diff --git a/README.md b/README.md index 652a4f2..0a057ba 100644 --- a/README.md +++ b/README.md @@ -65,18 +65,6 @@ Migration: Existing v0.3 collections are not offered migration. -## Runtime integration - -Companion plugins can access the selected mdbase runtime host through: - -```ts -app.plugins.getPlugin("mdbase-obsidian")?.api.runtime -``` - -The host remains default-deny. In v0.3 collections it validates and loads the -selected `runtime.policy` record and fails closed for missing, invalid, -disabled, or out-of-vault policies. - ## Application interoperability The plugin also hosts local application interoperability for companion plugins: @@ -98,7 +86,9 @@ records the exact contract version and digest plus application and implementation identity. The bridge is cooperative, same-process transport for Obsidian plugins. It does -not claim durable delivery or cross-device execution. +not claim to be a durable runtime: workflows, scheduling, retries, recovery, +and runtime-policy admission belong to a Runtime 0.2 host such as Connect. It +does not claim durable delivery or cross-device execution. ## Development diff --git a/main.js b/main.js index ae07a48..e67ea7c 100644 --- a/main.js +++ b/main.js @@ -3,96 +3,96 @@ THIS IS A GENERATED/BUNDLED FILE BY ESBUILD if you want to view the source, please visit the github repository of this plugin */ -var y_=Object.create;var gn=Object.defineProperty;var g_=Object.getOwnPropertyDescriptor;var b_=Object.getOwnPropertyNames;var __=Object.getPrototypeOf,v_=Object.prototype.hasOwnProperty;var w_=(r,e,t)=>e in r?gn(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var $=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),$_=(r,e)=>{for(var t in e)gn(r,t,{get:e[t],enumerable:!0})},Pf=(r,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of b_(e))!v_.call(r,n)&&n!==t&&gn(r,n,{get:()=>e[n],enumerable:!(i=g_(e,n))||i.enumerable});return r};var ft=(r,e,t)=>(t=r!=null?y_(__(r)):{},Pf(e||!r||!r.__esModule?gn(t,"default",{value:r,enumerable:!0}):t,r)),S_=r=>Pf(gn({},"__esModule",{value:!0}),r);var I=(r,e,t)=>w_(r,typeof e!="symbol"?e+"":e,t);var vn=$(ne=>{"use strict";Object.defineProperty(ne,"__esModule",{value:!0});ne.regexpCode=ne.getEsmExportName=ne.getProperty=ne.safeStringify=ne.stringify=ne.strConcat=ne.addCodeArg=ne.str=ne._=ne.nil=ne._Code=ne.Name=ne.IDENTIFIER=ne._CodeOrName=void 0;var bn=class{};ne._CodeOrName=bn;ne.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Wr=class extends bn{constructor(e){if(super(),!ne.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};ne.Name=Wr;var pt=class extends bn{constructor(e){super(),this._items=typeof e=="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((t,i)=>`${t}${i}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((t,i)=>(i instanceof Wr&&(t[i.str]=(t[i.str]||0)+1),t),{})}};ne._Code=pt;ne.nil=new pt("");function xf(r,...e){let t=[r[0]],i=0;for(;i{"use strict";Object.defineProperty(Qe,"__esModule",{value:!0});Qe.ValueScope=Qe.ValueScopeName=Qe.Scope=Qe.varKinds=Qe.UsedValueState=void 0;var Ze=vn(),sc=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},Js;(function(r){r[r.Started=0]="Started",r[r.Completed=1]="Completed"})(Js||(Qe.UsedValueState=Js={}));Qe.varKinds={const:new Ze.Name("const"),let:new Ze.Name("let"),var:new Ze.Name("var")};var Ys=class{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t}toName(e){return e instanceof Ze.Name?e:this.name(e)}name(e){return new Ze.Name(this._newName(e))}_newName(e){let t=this._names[e]||this._nameGroup(e);return`${e}${t.index++}`}_nameGroup(e){var t,i;if(!((i=(t=this._parent)===null||t===void 0?void 0:t._prefixes)===null||i===void 0)&&i.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};Qe.Scope=Ys;var Xs=class extends Ze.Name{constructor(e,t){super(t),this.prefix=e}setValue(e,{property:t,itemIndex:i}){this.value=e,this.scopePath=(0,Ze._)`.${new Ze.Name(t)}[${i}]`}};Qe.ValueScopeName=Xs;var O_=(0,Ze._)`\n`,oc=class extends Ys{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?O_:Ze.nil}}get(){return this._scope}name(e){return new Xs(e,this._newName(e))}value(e,t){var i;if(t.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let n=this.toName(e),{prefix:s}=n,o=(i=t.key)!==null&&i!==void 0?i:t.ref,a=this._values[s];if(a){let u=a.get(o);if(u)return u}else a=this._values[s]=new Map;a.set(o,n);let c=this._scope[s]||(this._scope[s]=[]),l=c.length;return c[l]=t.ref,n.setValue(t,{property:s,itemIndex:l}),n}getValue(e,t){let i=this._values[e];if(i)return i.get(t)}scopeRefs(e,t=this._values){return this._reduceValues(t,i=>{if(i.scopePath===void 0)throw new Error(`CodeGen: name "${i}" has no value`);return(0,Ze._)`${e}${i.scopePath}`})}scopeCode(e=this._values,t,i){return this._reduceValues(e,n=>{if(n.value===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return n.value.code},t,i)}_reduceValues(e,t,i={},n){let s=Ze.nil;for(let o in e){let a=e[o];if(!a)continue;let c=i[o]=i[o]||new Map;a.forEach(l=>{if(c.has(l))return;c.set(l,Js.Started);let u=t(l);if(u){let d=this.opts.es5?Qe.varKinds.var:Qe.varKinds.const;s=(0,Ze._)`${s}${d} ${l} = ${u};${this.opts._n}`}else if(u=n==null?void 0:n(l))s=(0,Ze._)`${s}${u}${this.opts._n}`;else throw new sc(l);c.set(l,Js.Completed)})}return s}};Qe.ValueScope=oc});var z=$(W=>{"use strict";Object.defineProperty(W,"__esModule",{value:!0});W.or=W.and=W.not=W.CodeGen=W.operators=W.varKinds=W.ValueScopeName=W.ValueScope=W.Scope=W.Name=W.regexpCode=W.stringify=W.getProperty=W.nil=W.strConcat=W.str=W._=void 0;var te=vn(),St=ac(),Sr=vn();Object.defineProperty(W,"_",{enumerable:!0,get:function(){return Sr._}});Object.defineProperty(W,"str",{enumerable:!0,get:function(){return Sr.str}});Object.defineProperty(W,"strConcat",{enumerable:!0,get:function(){return Sr.strConcat}});Object.defineProperty(W,"nil",{enumerable:!0,get:function(){return Sr.nil}});Object.defineProperty(W,"getProperty",{enumerable:!0,get:function(){return Sr.getProperty}});Object.defineProperty(W,"stringify",{enumerable:!0,get:function(){return Sr.stringify}});Object.defineProperty(W,"regexpCode",{enumerable:!0,get:function(){return Sr.regexpCode}});Object.defineProperty(W,"Name",{enumerable:!0,get:function(){return Sr.Name}});var to=ac();Object.defineProperty(W,"Scope",{enumerable:!0,get:function(){return to.Scope}});Object.defineProperty(W,"ValueScope",{enumerable:!0,get:function(){return to.ValueScope}});Object.defineProperty(W,"ValueScopeName",{enumerable:!0,get:function(){return to.ValueScopeName}});Object.defineProperty(W,"varKinds",{enumerable:!0,get:function(){return to.varKinds}});W.operators={GT:new te._Code(">"),GTE:new te._Code(">="),LT:new te._Code("<"),LTE:new te._Code("<="),EQ:new te._Code("==="),NEQ:new te._Code("!=="),NOT:new te._Code("!"),OR:new te._Code("||"),AND:new te._Code("&&"),ADD:new te._Code("+")};var nr=class{optimizeNodes(){return this}optimizeNames(e,t){return this}},cc=class extends nr{constructor(e,t,i){super(),this.varKind=e,this.name=t,this.rhs=i}render({es5:e,_n:t}){let i=e?St.varKinds.var:this.varKind,n=this.rhs===void 0?"":` = ${this.rhs}`;return`${i} ${this.name}${n};`+t}optimizeNames(e,t){if(e[this.name.str])return this.rhs&&(this.rhs=$i(this.rhs,e,t)),this}get names(){return this.rhs instanceof te._CodeOrName?this.rhs.names:{}}},Zs=class extends nr{constructor(e,t,i){super(),this.lhs=e,this.rhs=t,this.sideEffects=i}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,t){if(!(this.lhs instanceof te.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=$i(this.rhs,e,t),this}get names(){let e=this.lhs instanceof te.Name?{}:{...this.lhs.names};return eo(e,this.rhs)}},lc=class extends Zs{constructor(e,t,i,n){super(e,i,n),this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},dc=class extends nr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},uc=class extends nr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},fc=class extends nr{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},pc=class extends nr{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,t){return this.code=$i(this.code,e,t),this}get names(){return this.code instanceof te._CodeOrName?this.code.names:{}}},wn=class extends nr{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((t,i)=>t+i.render(e),"")}optimizeNodes(){let{nodes:e}=this,t=e.length;for(;t--;){let i=e[t].optimizeNodes();Array.isArray(i)?e.splice(t,1,...i):i?e[t]=i:e.splice(t,1)}return e.length>0?this:void 0}optimizeNames(e,t){let{nodes:i}=this,n=i.length;for(;n--;){let s=i[n];s.optimizeNames(e,t)||(C_(e,s.names),i.splice(n,1))}return i.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>Xr(e,t.names),{})}},sr=class extends wn{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},hc=class extends wn{},wi=class extends sr{};wi.kind="else";var Jr=class r extends sr{constructor(e,t){super(t),this.condition=e}render(e){let t=`if(${this.condition})`+super.render(e);return this.else&&(t+="else "+this.else.render(e)),t}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let t=this.else;if(t){let i=t.optimizeNodes();t=this.else=Array.isArray(i)?new wi(i):i}if(t)return e===!1?t instanceof r?t:t.nodes:this.nodes.length?this:new r(Rf(e),t instanceof r?[t]:t.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,t){var i;if(this.else=(i=this.else)===null||i===void 0?void 0:i.optimizeNames(e,t),!!(super.optimizeNames(e,t)||this.else))return this.condition=$i(this.condition,e,t),this}get names(){let e=super.names;return eo(e,this.condition),this.else&&Xr(e,this.else.names),e}};Jr.kind="if";var Yr=class extends sr{};Yr.kind="for";var mc=class extends Yr{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iteration=$i(this.iteration,e,t),this}get names(){return Xr(super.names,this.iteration.names)}},yc=class extends Yr{constructor(e,t,i,n){super(),this.varKind=e,this.name=t,this.from=i,this.to=n}render(e){let t=e.es5?St.varKinds.var:this.varKind,{name:i,from:n,to:s}=this;return`for(${t} ${i}=${n}; ${i}<${s}; ${i}++)`+super.render(e)}get names(){let e=eo(super.names,this.from);return eo(e,this.to)}},Qs=class extends Yr{constructor(e,t,i,n){super(),this.loop=e,this.varKind=t,this.name=i,this.iterable=n}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iterable=$i(this.iterable,e,t),this}get names(){return Xr(super.names,this.iterable.names)}},$n=class extends sr{constructor(e,t,i){super(),this.name=e,this.args=t,this.async=i}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};$n.kind="func";var Sn=class extends wn{render(e){return"return "+super.render(e)}};Sn.kind="return";var gc=class extends sr{render(e){let t="try"+super.render(e);return this.catch&&(t+=this.catch.render(e)),this.finally&&(t+=this.finally.render(e)),t}optimizeNodes(){var e,t;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(t=this.finally)===null||t===void 0||t.optimizeNodes(),this}optimizeNames(e,t){var i,n;return super.optimizeNames(e,t),(i=this.catch)===null||i===void 0||i.optimizeNames(e,t),(n=this.finally)===null||n===void 0||n.optimizeNames(e,t),this}get names(){let e=super.names;return this.catch&&Xr(e,this.catch.names),this.finally&&Xr(e,this.finally.names),e}},En=class extends sr{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};En.kind="catch";var An=class extends sr{render(e){return"finally"+super.render(e)}};An.kind="finally";var bc=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?` -`:""},this._extScope=e,this._scope=new St.Scope({parent:e}),this._nodes=[new hc]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,t){let i=this._extScope.value(e,t);return(this._values[i.prefix]||(this._values[i.prefix]=new Set)).add(i),i}getScopeValue(e,t){return this._extScope.getValue(e,t)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,t,i,n){let s=this._scope.toName(t);return i!==void 0&&n&&(this._constants[s.str]=i),this._leafNode(new cc(e,s,i)),s}const(e,t,i){return this._def(St.varKinds.const,e,t,i)}let(e,t,i){return this._def(St.varKinds.let,e,t,i)}var(e,t,i){return this._def(St.varKinds.var,e,t,i)}assign(e,t,i){return this._leafNode(new Zs(e,t,i))}add(e,t){return this._leafNode(new lc(e,W.operators.ADD,t))}code(e){return typeof e=="function"?e():e!==te.nil&&this._leafNode(new pc(e)),this}object(...e){let t=["{"];for(let[i,n]of e)t.length>1&&t.push(","),t.push(i),(i!==n||this.opts.es5)&&(t.push(":"),(0,te.addCodeArg)(t,n));return t.push("}"),new te._Code(t)}if(e,t,i){if(this._blockNode(new Jr(e)),t&&i)this.code(t).else().code(i).endIf();else if(t)this.code(t).endIf();else if(i)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new Jr(e))}else(){return this._elseNode(new wi)}endIf(){return this._endBlockNode(Jr,wi)}_for(e,t){return this._blockNode(e),t&&this.code(t).endFor(),this}for(e,t){return this._for(new mc(e),t)}forRange(e,t,i,n,s=this.opts.es5?St.varKinds.var:St.varKinds.let){let o=this._scope.toName(e);return this._for(new yc(s,o,t,i),()=>n(o))}forOf(e,t,i,n=St.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let o=t instanceof te.Name?t:this.var("_arr",t);return this.forRange("_i",0,(0,te._)`${o}.length`,a=>{this.var(s,(0,te._)`${o}[${a}]`),i(s)})}return this._for(new Qs("of",n,s,t),()=>i(s))}forIn(e,t,i,n=this.opts.es5?St.varKinds.var:St.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,te._)`Object.keys(${t})`,i);let s=this._scope.toName(e);return this._for(new Qs("in",n,s,t),()=>i(s))}endFor(){return this._endBlockNode(Yr)}label(e){return this._leafNode(new dc(e))}break(e){return this._leafNode(new uc(e))}return(e){let t=new Sn;if(this._blockNode(t),this.code(e),t.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Sn)}try(e,t,i){if(!t&&!i)throw new Error('CodeGen: "try" without "catch" and "finally"');let n=new gc;if(this._blockNode(n),this.code(e),t){let s=this.name("e");this._currNode=n.catch=new En(s),t(s)}return i&&(this._currNode=n.finally=new An,this.code(i)),this._endBlockNode(En,An)}throw(e){return this._leafNode(new fc(e))}block(e,t){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(t),this}endBlock(e){let t=this._blockStarts.pop();if(t===void 0)throw new Error("CodeGen: not in self-balancing block");let i=this._nodes.length-t;if(i<0||e!==void 0&&i!==e)throw new Error(`CodeGen: wrong number of nodes: ${i} vs ${e} expected`);return this._nodes.length=t,this}func(e,t=te.nil,i,n){return this._blockNode(new $n(e,t,i)),n&&this.code(n).endFunc(),this}endFunc(){return this._endBlockNode($n)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,t){let i=this._currNode;if(i instanceof e||t&&i instanceof t)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${t?`${e.kind}/${t.kind}`:e.kind}"`)}_elseNode(e){let t=this._currNode;if(!(t instanceof Jr))throw new Error('CodeGen: "else" without "if"');return this._currNode=t.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let t=this._nodes;t[t.length-1]=e}};W.CodeGen=bc;function Xr(r,e){for(let t in e)r[t]=(r[t]||0)+(e[t]||0);return r}function eo(r,e){return e instanceof te._CodeOrName?Xr(r,e.names):r}function $i(r,e,t){if(r instanceof te.Name)return i(r);if(!n(r))return r;return new te._Code(r._items.reduce((s,o)=>(o instanceof te.Name&&(o=i(o)),o instanceof te._Code?s.push(...o._items):s.push(o),s),[]));function i(s){let o=t[s.str];return o===void 0||e[s.str]!==1?s:(delete e[s.str],o)}function n(s){return s instanceof te._Code&&s._items.some(o=>o instanceof te.Name&&e[o.str]===1&&t[o.str]!==void 0)}}function C_(r,e){for(let t in e)r[t]=(r[t]||0)-(e[t]||0)}function Rf(r){return typeof r=="boolean"||typeof r=="number"||r===null?!r:(0,te._)`!${_c(r)}`}W.not=Rf;var N_=Tf(W.operators.AND);function M_(...r){return r.reduce(N_)}W.and=M_;var q_=Tf(W.operators.OR);function L_(...r){return r.reduce(q_)}W.or=L_;function Tf(r){return(e,t)=>e===te.nil?t:t===te.nil?e:(0,te._)`${_c(e)} ${r} ${_c(t)}`}function _c(r){return r instanceof te.Name?r:(0,te._)`(${r})`}});var Y=$(J=>{"use strict";Object.defineProperty(J,"__esModule",{value:!0});J.checkStrictMode=J.getErrorPath=J.Type=J.useFunc=J.setEvaluated=J.evaluatedPropsToName=J.mergeEvaluated=J.eachItem=J.unescapeJsonPointer=J.escapeJsonPointer=J.escapeFragment=J.unescapeFragment=J.schemaRefOrVal=J.schemaHasRulesButRef=J.schemaHasRules=J.checkUnknownRules=J.alwaysValidSchema=J.toHash=void 0;var de=z(),j_=vn();function D_(r){let e={};for(let t of r)e[t]=!0;return e}J.toHash=D_;function F_(r,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(Nf(r,e),!Mf(e,r.self.RULES.all))}J.alwaysValidSchema=F_;function Nf(r,e=r.schema){let{opts:t,self:i}=r;if(!t.strictSchema||typeof e=="boolean")return;let n=i.RULES.keywords;for(let s in e)n[s]||jf(r,`unknown keyword: "${s}"`)}J.checkUnknownRules=Nf;function Mf(r,e){if(typeof r=="boolean")return!r;for(let t in r)if(e[t])return!0;return!1}J.schemaHasRules=Mf;function V_(r,e){if(typeof r=="boolean")return!r;for(let t in r)if(t!=="$ref"&&e.all[t])return!0;return!1}J.schemaHasRulesButRef=V_;function U_({topSchemaRef:r,schemaPath:e},t,i,n){if(!n){if(typeof t=="number"||typeof t=="boolean")return t;if(typeof t=="string")return(0,de._)`${t}`}return(0,de._)`${r}${e}${(0,de.getProperty)(i)}`}J.schemaRefOrVal=U_;function z_(r){return qf(decodeURIComponent(r))}J.unescapeFragment=z_;function B_(r){return encodeURIComponent(wc(r))}J.escapeFragment=B_;function wc(r){return typeof r=="number"?`${r}`:r.replace(/~/g,"~0").replace(/\//g,"~1")}J.escapeJsonPointer=wc;function qf(r){return r.replace(/~1/g,"/").replace(/~0/g,"~")}J.unescapeJsonPointer=qf;function H_(r,e){if(Array.isArray(r))for(let t of r)e(t);else e(r)}J.eachItem=H_;function Of({mergeNames:r,mergeToName:e,mergeValues:t,resultToName:i}){return(n,s,o,a)=>{let c=o===void 0?s:o instanceof de.Name?(s instanceof de.Name?r(n,s,o):e(n,s,o),o):s instanceof de.Name?(e(n,o,s),s):t(s,o);return a===de.Name&&!(c instanceof de.Name)?i(n,c):c}}J.mergeEvaluated={props:Of({mergeNames:(r,e,t)=>r.if((0,de._)`${t} !== true && ${e} !== undefined`,()=>{r.if((0,de._)`${e} === true`,()=>r.assign(t,!0),()=>r.assign(t,(0,de._)`${t} || {}`).code((0,de._)`Object.assign(${t}, ${e})`))}),mergeToName:(r,e,t)=>r.if((0,de._)`${t} !== true`,()=>{e===!0?r.assign(t,!0):(r.assign(t,(0,de._)`${t} || {}`),$c(r,t,e))}),mergeValues:(r,e)=>r===!0?!0:{...r,...e},resultToName:Lf}),items:Of({mergeNames:(r,e,t)=>r.if((0,de._)`${t} !== true && ${e} !== undefined`,()=>r.assign(t,(0,de._)`${e} === true ? true : ${t} > ${e} ? ${t} : ${e}`)),mergeToName:(r,e,t)=>r.if((0,de._)`${t} !== true`,()=>r.assign(t,e===!0?!0:(0,de._)`${t} > ${e} ? ${t} : ${e}`)),mergeValues:(r,e)=>r===!0?!0:Math.max(r,e),resultToName:(r,e)=>r.var("items",e)})};function Lf(r,e){if(e===!0)return r.var("props",!0);let t=r.var("props",(0,de._)`{}`);return e!==void 0&&$c(r,t,e),t}J.evaluatedPropsToName=Lf;function $c(r,e,t){Object.keys(t).forEach(i=>r.assign((0,de._)`${e}${(0,de.getProperty)(i)}`,!0))}J.setEvaluated=$c;var Cf={};function K_(r,e){return r.scopeValue("func",{ref:e,code:Cf[e.code]||(Cf[e.code]=new j_._Code(e.code))})}J.useFunc=K_;var vc;(function(r){r[r.Num=0]="Num",r[r.Str=1]="Str"})(vc||(J.Type=vc={}));function G_(r,e,t){if(r instanceof de.Name){let i=e===vc.Num;return t?i?(0,de._)`"[" + ${r} + "]"`:(0,de._)`"['" + ${r} + "']"`:i?(0,de._)`"/" + ${r}`:(0,de._)`"/" + ${r}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return t?(0,de.getProperty)(r).toString():"/"+wc(r)}J.getErrorPath=G_;function jf(r,e,t=r.opts.strictSchema){if(t){if(e=`strict mode: ${e}`,t===!0)throw new Error(e);r.self.logger.warn(e)}}J.checkStrictMode=jf});var ht=$(Sc=>{"use strict";Object.defineProperty(Sc,"__esModule",{value:!0});var De=z(),W_={data:new De.Name("data"),valCxt:new De.Name("valCxt"),instancePath:new De.Name("instancePath"),parentData:new De.Name("parentData"),parentDataProperty:new De.Name("parentDataProperty"),rootData:new De.Name("rootData"),dynamicAnchors:new De.Name("dynamicAnchors"),vErrors:new De.Name("vErrors"),errors:new De.Name("errors"),this:new De.Name("this"),self:new De.Name("self"),scope:new De.Name("scope"),json:new De.Name("json"),jsonPos:new De.Name("jsonPos"),jsonLen:new De.Name("jsonLen"),jsonPart:new De.Name("jsonPart")};Sc.default=W_});var kn=$(Fe=>{"use strict";Object.defineProperty(Fe,"__esModule",{value:!0});Fe.extendErrors=Fe.resetErrorsCount=Fe.reportExtraError=Fe.reportError=Fe.keyword$DataError=Fe.keywordError=void 0;var ie=z(),ro=Y(),Ke=ht();Fe.keywordError={message:({keyword:r})=>(0,ie.str)`must pass "${r}" keyword validation`};Fe.keyword$DataError={message:({keyword:r,schemaType:e})=>e?(0,ie.str)`"${r}" keyword must be ${e} ($data)`:(0,ie.str)`"${r}" keyword is invalid ($data)`};function J_(r,e=Fe.keywordError,t,i){let{it:n}=r,{gen:s,compositeRule:o,allErrors:a}=n,c=Vf(r,e,t);(i!=null?i:o||a)?Df(s,c):Ff(n,(0,ie._)`[${c}]`)}Fe.reportError=J_;function Y_(r,e=Fe.keywordError,t){let{it:i}=r,{gen:n,compositeRule:s,allErrors:o}=i,a=Vf(r,e,t);Df(n,a),s||o||Ff(i,Ke.default.vErrors)}Fe.reportExtraError=Y_;function X_(r,e){r.assign(Ke.default.errors,e),r.if((0,ie._)`${Ke.default.vErrors} !== null`,()=>r.if(e,()=>r.assign((0,ie._)`${Ke.default.vErrors}.length`,e),()=>r.assign(Ke.default.vErrors,null)))}Fe.resetErrorsCount=X_;function Z_({gen:r,keyword:e,schemaValue:t,data:i,errsCount:n,it:s}){if(n===void 0)throw new Error("ajv implementation error");let o=r.name("err");r.forRange("i",n,Ke.default.errors,a=>{r.const(o,(0,ie._)`${Ke.default.vErrors}[${a}]`),r.if((0,ie._)`${o}.instancePath === undefined`,()=>r.assign((0,ie._)`${o}.instancePath`,(0,ie.strConcat)(Ke.default.instancePath,s.errorPath))),r.assign((0,ie._)`${o}.schemaPath`,(0,ie.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(r.assign((0,ie._)`${o}.schema`,t),r.assign((0,ie._)`${o}.data`,i))})}Fe.extendErrors=Z_;function Df(r,e){let t=r.const("err",e);r.if((0,ie._)`${Ke.default.vErrors} === null`,()=>r.assign(Ke.default.vErrors,(0,ie._)`[${t}]`),(0,ie._)`${Ke.default.vErrors}.push(${t})`),r.code((0,ie._)`${Ke.default.errors}++`)}function Ff(r,e){let{gen:t,validateName:i,schemaEnv:n}=r;n.$async?t.throw((0,ie._)`new ${r.ValidationError}(${e})`):(t.assign((0,ie._)`${i}.errors`,e),t.return(!1))}var Zr={keyword:new ie.Name("keyword"),schemaPath:new ie.Name("schemaPath"),params:new ie.Name("params"),propertyName:new ie.Name("propertyName"),message:new ie.Name("message"),schema:new ie.Name("schema"),parentSchema:new ie.Name("parentSchema")};function Vf(r,e,t){let{createErrors:i}=r.it;return i===!1?(0,ie._)`{}`:Q_(r,e,t)}function Q_(r,e,t={}){let{gen:i,it:n}=r,s=[ev(n,t),tv(r,t)];return rv(r,e,s),i.object(...s)}function ev({errorPath:r},{instancePath:e}){let t=e?(0,ie.str)`${r}${(0,ro.getErrorPath)(e,ro.Type.Str)}`:r;return[Ke.default.instancePath,(0,ie.strConcat)(Ke.default.instancePath,t)]}function tv({keyword:r,it:{errSchemaPath:e}},{schemaPath:t,parentSchema:i}){let n=i?e:(0,ie.str)`${e}/${r}`;return t&&(n=(0,ie.str)`${n}${(0,ro.getErrorPath)(t,ro.Type.Str)}`),[Zr.schemaPath,n]}function rv(r,{params:e,message:t},i){let{keyword:n,data:s,schemaValue:o,it:a}=r,{opts:c,propertyName:l,topSchemaRef:u,schemaPath:d}=a;i.push([Zr.keyword,n],[Zr.params,typeof e=="function"?e(r):e||(0,ie._)`{}`]),c.messages&&i.push([Zr.message,typeof t=="function"?t(r):t]),c.verbose&&i.push([Zr.schema,o],[Zr.parentSchema,(0,ie._)`${u}${d}`],[Ke.default.data,s]),l&&i.push([Zr.propertyName,l])}});var zf=$(Si=>{"use strict";Object.defineProperty(Si,"__esModule",{value:!0});Si.boolOrEmptySchema=Si.topBoolOrEmptySchema=void 0;var iv=kn(),nv=z(),sv=ht(),ov={message:"boolean schema is false"};function av(r){let{gen:e,schema:t,validateName:i}=r;t===!1?Uf(r,!1):typeof t=="object"&&t.$async===!0?e.return(sv.default.data):(e.assign((0,nv._)`${i}.errors`,null),e.return(!0))}Si.topBoolOrEmptySchema=av;function cv(r,e){let{gen:t,schema:i}=r;i===!1?(t.var(e,!1),Uf(r)):t.var(e,!0)}Si.boolOrEmptySchema=cv;function Uf(r,e){let{gen:t,data:i}=r,n={gen:t,keyword:"false schema",data:i,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:r};(0,iv.reportError)(n,ov,void 0,e)}});var Ec=$(Ei=>{"use strict";Object.defineProperty(Ei,"__esModule",{value:!0});Ei.getRules=Ei.isJSONType=void 0;var lv=["string","number","integer","boolean","null","object","array"],dv=new Set(lv);function uv(r){return typeof r=="string"&&dv.has(r)}Ei.isJSONType=uv;function fv(){let r={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...r,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},r.number,r.string,r.array,r.object],post:{rules:[]},all:{},keywords:{}}}Ei.getRules=fv});var Ac=$(Er=>{"use strict";Object.defineProperty(Er,"__esModule",{value:!0});Er.shouldUseRule=Er.shouldUseGroup=Er.schemaHasRulesForType=void 0;function pv({schema:r,self:e},t){let i=e.RULES.types[t];return i&&i!==!0&&Bf(r,i)}Er.schemaHasRulesForType=pv;function Bf(r,e){return e.rules.some(t=>Hf(r,t))}Er.shouldUseGroup=Bf;function Hf(r,e){var t;return r[e.keyword]!==void 0||((t=e.definition.implements)===null||t===void 0?void 0:t.some(i=>r[i]!==void 0))}Er.shouldUseRule=Hf});var Pn=$(Ve=>{"use strict";Object.defineProperty(Ve,"__esModule",{value:!0});Ve.reportTypeError=Ve.checkDataTypes=Ve.checkDataType=Ve.coerceAndCheckDataType=Ve.getJSONTypes=Ve.getSchemaTypes=Ve.DataType=void 0;var hv=Ec(),mv=Ac(),yv=kn(),H=z(),Kf=Y(),Ai;(function(r){r[r.Correct=0]="Correct",r[r.Wrong=1]="Wrong"})(Ai||(Ve.DataType=Ai={}));function gv(r){let e=Gf(r.type);if(e.includes("null")){if(r.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&r.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');r.nullable===!0&&e.push("null")}return e}Ve.getSchemaTypes=gv;function Gf(r){let e=Array.isArray(r)?r:r?[r]:[];if(e.every(hv.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}Ve.getJSONTypes=Gf;function bv(r,e){let{gen:t,data:i,opts:n}=r,s=_v(e,n.coerceTypes),o=e.length>0&&!(s.length===0&&e.length===1&&(0,mv.schemaHasRulesForType)(r,e[0]));if(o){let a=Pc(e,i,n.strictNumbers,Ai.Wrong);t.if(a,()=>{s.length?vv(r,e,s):xc(r)})}return o}Ve.coerceAndCheckDataType=bv;var Wf=new Set(["string","number","integer","boolean","null"]);function _v(r,e){return e?r.filter(t=>Wf.has(t)||e==="array"&&t==="array"):[]}function vv(r,e,t){let{gen:i,data:n,opts:s}=r,o=i.let("dataType",(0,H._)`typeof ${n}`),a=i.let("coerced",(0,H._)`undefined`);s.coerceTypes==="array"&&i.if((0,H._)`${o} == 'object' && Array.isArray(${n}) && ${n}.length == 1`,()=>i.assign(n,(0,H._)`${n}[0]`).assign(o,(0,H._)`typeof ${n}`).if(Pc(e,n,s.strictNumbers),()=>i.assign(a,n))),i.if((0,H._)`${a} !== undefined`);for(let l of t)(Wf.has(l)||l==="array"&&s.coerceTypes==="array")&&c(l);i.else(),xc(r),i.endIf(),i.if((0,H._)`${a} !== undefined`,()=>{i.assign(n,a),wv(r,a)});function c(l){switch(l){case"string":i.elseIf((0,H._)`${o} == "number" || ${o} == "boolean"`).assign(a,(0,H._)`"" + ${n}`).elseIf((0,H._)`${n} === null`).assign(a,(0,H._)`""`);return;case"number":i.elseIf((0,H._)`${o} == "boolean" || ${n} === null - || (${o} == "string" && ${n} && ${n} == +${n})`).assign(a,(0,H._)`+${n}`);return;case"integer":i.elseIf((0,H._)`${o} === "boolean" || ${n} === null - || (${o} === "string" && ${n} && ${n} == +${n} && !(${n} % 1))`).assign(a,(0,H._)`+${n}`);return;case"boolean":i.elseIf((0,H._)`${n} === "false" || ${n} === 0 || ${n} === null`).assign(a,!1).elseIf((0,H._)`${n} === "true" || ${n} === 1`).assign(a,!0);return;case"null":i.elseIf((0,H._)`${n} === "" || ${n} === 0 || ${n} === false`),i.assign(a,null);return;case"array":i.elseIf((0,H._)`${o} === "string" || ${o} === "number" - || ${o} === "boolean" || ${n} === null`).assign(a,(0,H._)`[${n}]`)}}}function wv({gen:r,parentData:e,parentDataProperty:t},i){r.if((0,H._)`${e} !== undefined`,()=>r.assign((0,H._)`${e}[${t}]`,i))}function kc(r,e,t,i=Ai.Correct){let n=i===Ai.Correct?H.operators.EQ:H.operators.NEQ,s;switch(r){case"null":return(0,H._)`${e} ${n} null`;case"array":s=(0,H._)`Array.isArray(${e})`;break;case"object":s=(0,H._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=o((0,H._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=o();break;default:return(0,H._)`typeof ${e} ${n} ${r}`}return i===Ai.Correct?s:(0,H.not)(s);function o(a=H.nil){return(0,H.and)((0,H._)`typeof ${e} == "number"`,a,t?(0,H._)`isFinite(${e})`:H.nil)}}Ve.checkDataType=kc;function Pc(r,e,t,i){if(r.length===1)return kc(r[0],e,t,i);let n,s=(0,Kf.toHash)(r);if(s.array&&s.object){let o=(0,H._)`typeof ${e} != "object"`;n=s.null?o:(0,H._)`!${e} || ${o}`,delete s.null,delete s.array,delete s.object}else n=H.nil;s.number&&delete s.integer;for(let o in s)n=(0,H.and)(n,kc(o,e,t,i));return n}Ve.checkDataTypes=Pc;var $v={message:({schema:r})=>`must be ${r}`,params:({schema:r,schemaValue:e})=>typeof r=="string"?(0,H._)`{type: ${r}}`:(0,H._)`{type: ${e}}`};function xc(r){let e=Sv(r);(0,yv.reportError)(e,$v)}Ve.reportTypeError=xc;function Sv(r){let{gen:e,data:t,schema:i}=r,n=(0,Kf.schemaRefOrVal)(r,i,"type");return{gen:e,keyword:"type",data:t,schema:i.type,schemaCode:n,schemaValue:n,parentSchema:i,params:{},it:r}}});var Yf=$(io=>{"use strict";Object.defineProperty(io,"__esModule",{value:!0});io.assignDefaults=void 0;var ki=z(),Ev=Y();function Av(r,e){let{properties:t,items:i}=r.schema;if(e==="object"&&t)for(let n in t)Jf(r,n,t[n].default);else e==="array"&&Array.isArray(i)&&i.forEach((n,s)=>Jf(r,s,n.default))}io.assignDefaults=Av;function Jf(r,e,t){let{gen:i,compositeRule:n,data:s,opts:o}=r;if(t===void 0)return;let a=(0,ki._)`${s}${(0,ki.getProperty)(e)}`;if(n){(0,Ev.checkStrictMode)(r,`default is ignored for: ${a}`);return}let c=(0,ki._)`${a} === undefined`;o.useDefaults==="empty"&&(c=(0,ki._)`${c} || ${a} === null || ${a} === ""`),i.if(c,(0,ki._)`${a} = ${(0,ki.stringify)(t)}`)}});var mt=$(ce=>{"use strict";Object.defineProperty(ce,"__esModule",{value:!0});ce.validateUnion=ce.validateArray=ce.usePattern=ce.callValidateCode=ce.schemaProperties=ce.allSchemaProperties=ce.noPropertyInData=ce.propertyInData=ce.isOwnProperty=ce.hasPropFunc=ce.reportMissingProp=ce.checkMissingProp=ce.checkReportMissingProp=void 0;var he=z(),Ic=Y(),Ar=ht(),kv=Y();function Pv(r,e){let{gen:t,data:i,it:n}=r;t.if(Tc(t,i,e,n.opts.ownProperties),()=>{r.setParams({missingProperty:(0,he._)`${e}`},!0),r.error()})}ce.checkReportMissingProp=Pv;function xv({gen:r,data:e,it:{opts:t}},i,n){return(0,he.or)(...i.map(s=>(0,he.and)(Tc(r,e,s,t.ownProperties),(0,he._)`${n} = ${s}`)))}ce.checkMissingProp=xv;function Iv(r,e){r.setParams({missingProperty:e},!0),r.error()}ce.reportMissingProp=Iv;function Xf(r){return r.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,he._)`Object.prototype.hasOwnProperty`})}ce.hasPropFunc=Xf;function Rc(r,e,t){return(0,he._)`${Xf(r)}.call(${e}, ${t})`}ce.isOwnProperty=Rc;function Rv(r,e,t,i){let n=(0,he._)`${e}${(0,he.getProperty)(t)} !== undefined`;return i?(0,he._)`${n} && ${Rc(r,e,t)}`:n}ce.propertyInData=Rv;function Tc(r,e,t,i){let n=(0,he._)`${e}${(0,he.getProperty)(t)} === undefined`;return i?(0,he.or)(n,(0,he.not)(Rc(r,e,t))):n}ce.noPropertyInData=Tc;function Zf(r){return r?Object.keys(r).filter(e=>e!=="__proto__"):[]}ce.allSchemaProperties=Zf;function Tv(r,e){return Zf(e).filter(t=>!(0,Ic.alwaysValidSchema)(r,e[t]))}ce.schemaProperties=Tv;function Ov({schemaCode:r,data:e,it:{gen:t,topSchemaRef:i,schemaPath:n,errorPath:s},it:o},a,c,l){let u=l?(0,he._)`${r}, ${e}, ${i}${n}`:e,d=[[Ar.default.instancePath,(0,he.strConcat)(Ar.default.instancePath,s)],[Ar.default.parentData,o.parentData],[Ar.default.parentDataProperty,o.parentDataProperty],[Ar.default.rootData,Ar.default.rootData]];o.opts.dynamicRef&&d.push([Ar.default.dynamicAnchors,Ar.default.dynamicAnchors]);let f=(0,he._)`${u}, ${t.object(...d)}`;return c!==he.nil?(0,he._)`${a}.call(${c}, ${f})`:(0,he._)`${a}(${f})`}ce.callValidateCode=Ov;var Cv=(0,he._)`new RegExp`;function Nv({gen:r,it:{opts:e}},t){let i=e.unicodeRegExp?"u":"",{regExp:n}=e.code,s=n(t,i);return r.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,he._)`${n.code==="new RegExp"?Cv:(0,kv.useFunc)(r,n)}(${t}, ${i})`})}ce.usePattern=Nv;function Mv(r){let{gen:e,data:t,keyword:i,it:n}=r,s=e.name("valid");if(n.allErrors){let a=e.let("valid",!0);return o(()=>e.assign(a,!1)),a}return e.var(s,!0),o(()=>e.break()),s;function o(a){let c=e.const("len",(0,he._)`${t}.length`);e.forRange("i",0,c,l=>{r.subschema({keyword:i,dataProp:l,dataPropType:Ic.Type.Num},s),e.if((0,he.not)(s),a)})}}ce.validateArray=Mv;function qv(r){let{gen:e,schema:t,keyword:i,it:n}=r;if(!Array.isArray(t))throw new Error("ajv implementation error");if(t.some(c=>(0,Ic.alwaysValidSchema)(n,c))&&!n.opts.unevaluated)return;let o=e.let("valid",!1),a=e.name("_valid");e.block(()=>t.forEach((c,l)=>{let u=r.subschema({keyword:i,schemaProp:l,compositeRule:!0},a);e.assign(o,(0,he._)`${o} || ${a}`),r.mergeValidEvaluated(u,a)||e.if((0,he.not)(o))})),r.result(o,()=>r.reset(),()=>r.error(!0))}ce.validateUnion=qv});var tp=$(zt=>{"use strict";Object.defineProperty(zt,"__esModule",{value:!0});zt.validateKeywordUsage=zt.validSchemaType=zt.funcKeywordCode=zt.macroKeywordCode=void 0;var Ge=z(),Qr=ht(),Lv=mt(),jv=kn();function Dv(r,e){let{gen:t,keyword:i,schema:n,parentSchema:s,it:o}=r,a=e.macro.call(o.self,n,s,o),c=ep(t,i,a);o.opts.validateSchema!==!1&&o.self.validateSchema(a,!0);let l=t.name("valid");r.subschema({schema:a,schemaPath:Ge.nil,errSchemaPath:`${o.errSchemaPath}/${i}`,topSchemaRef:c,compositeRule:!0},l),r.pass(l,()=>r.error(!0))}zt.macroKeywordCode=Dv;function Fv(r,e){var t;let{gen:i,keyword:n,schema:s,parentSchema:o,$data:a,it:c}=r;Uv(c,e);let l=!a&&e.compile?e.compile.call(c.self,s,o,c):e.validate,u=ep(i,n,l),d=i.let("valid");r.block$data(d,f),r.ok((t=e.valid)!==null&&t!==void 0?t:d);function f(){if(e.errors===!1)h(),e.modifying&&Qf(r),y(()=>r.error());else{let b=e.async?p():m();e.modifying&&Qf(r),y(()=>Vv(r,b))}}function p(){let b=i.let("ruleErrs",null);return i.try(()=>h((0,Ge._)`await `),g=>i.assign(d,!1).if((0,Ge._)`${g} instanceof ${c.ValidationError}`,()=>i.assign(b,(0,Ge._)`${g}.errors`),()=>i.throw(g))),b}function m(){let b=(0,Ge._)`${u}.errors`;return i.assign(b,null),h(Ge.nil),b}function h(b=e.async?(0,Ge._)`await `:Ge.nil){let g=c.opts.passContext?Qr.default.this:Qr.default.self,_=!("compile"in e&&!a||e.schema===!1);i.assign(d,(0,Ge._)`${b}${(0,Lv.callValidateCode)(r,u,g,_)}`,e.modifying)}function y(b){var g;i.if((0,Ge.not)((g=e.valid)!==null&&g!==void 0?g:d),b)}}zt.funcKeywordCode=Fv;function Qf(r){let{gen:e,data:t,it:i}=r;e.if(i.parentData,()=>e.assign(t,(0,Ge._)`${i.parentData}[${i.parentDataProperty}]`))}function Vv(r,e){let{gen:t}=r;t.if((0,Ge._)`Array.isArray(${e})`,()=>{t.assign(Qr.default.vErrors,(0,Ge._)`${Qr.default.vErrors} === null ? ${e} : ${Qr.default.vErrors}.concat(${e})`).assign(Qr.default.errors,(0,Ge._)`${Qr.default.vErrors}.length`),(0,jv.extendErrors)(r)},()=>r.error())}function Uv({schemaEnv:r},e){if(e.async&&!r.$async)throw new Error("async keyword in sync schema")}function ep(r,e,t){if(t===void 0)throw new Error(`keyword "${e}" failed to compile`);return r.scopeValue("keyword",typeof t=="function"?{ref:t}:{ref:t,code:(0,Ge.stringify)(t)})}function zv(r,e,t=!1){return!e.length||e.some(i=>i==="array"?Array.isArray(r):i==="object"?r&&typeof r=="object"&&!Array.isArray(r):typeof r==i||t&&typeof r=="undefined")}zt.validSchemaType=zv;function Bv({schema:r,opts:e,self:t,errSchemaPath:i},n,s){if(Array.isArray(n.keyword)?!n.keyword.includes(s):n.keyword!==s)throw new Error("ajv implementation error");let o=n.dependencies;if(o!=null&&o.some(a=>!Object.prototype.hasOwnProperty.call(r,a)))throw new Error(`parent schema must have dependencies of ${s}: ${o.join(",")}`);if(n.validateSchema&&!n.validateSchema(r[s])){let c=`keyword "${s}" value is invalid at path "${i}": `+t.errorsText(n.validateSchema.errors);if(e.validateSchema==="log")t.logger.error(c);else throw new Error(c)}}zt.validateKeywordUsage=Bv});var ip=$(kr=>{"use strict";Object.defineProperty(kr,"__esModule",{value:!0});kr.extendSubschemaMode=kr.extendSubschemaData=kr.getSubschema=void 0;var Bt=z(),rp=Y();function Hv(r,{keyword:e,schemaProp:t,schema:i,schemaPath:n,errSchemaPath:s,topSchemaRef:o}){if(e!==void 0&&i!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let a=r.schema[e];return t===void 0?{schema:a,schemaPath:(0,Bt._)`${r.schemaPath}${(0,Bt.getProperty)(e)}`,errSchemaPath:`${r.errSchemaPath}/${e}`}:{schema:a[t],schemaPath:(0,Bt._)`${r.schemaPath}${(0,Bt.getProperty)(e)}${(0,Bt.getProperty)(t)}`,errSchemaPath:`${r.errSchemaPath}/${e}/${(0,rp.escapeFragment)(t)}`}}if(i!==void 0){if(n===void 0||s===void 0||o===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:i,schemaPath:n,topSchemaRef:o,errSchemaPath:s}}throw new Error('either "keyword" or "schema" must be passed')}kr.getSubschema=Hv;function Kv(r,e,{dataProp:t,dataPropType:i,data:n,dataTypes:s,propertyName:o}){if(n!==void 0&&t!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(t!==void 0){let{errorPath:l,dataPathArr:u,opts:d}=e,f=a.let("data",(0,Bt._)`${e.data}${(0,Bt.getProperty)(t)}`,!0);c(f),r.errorPath=(0,Bt.str)`${l}${(0,rp.getErrorPath)(t,i,d.jsPropertySyntax)}`,r.parentDataProperty=(0,Bt._)`${t}`,r.dataPathArr=[...u,r.parentDataProperty]}if(n!==void 0){let l=n instanceof Bt.Name?n:a.let("data",n,!0);c(l),o!==void 0&&(r.propertyName=o)}s&&(r.dataTypes=s);function c(l){r.data=l,r.dataLevel=e.dataLevel+1,r.dataTypes=[],e.definedProperties=new Set,r.parentData=e.data,r.dataNames=[...e.dataNames,l]}}kr.extendSubschemaData=Kv;function Gv(r,{jtdDiscriminator:e,jtdMetadata:t,compositeRule:i,createErrors:n,allErrors:s}){i!==void 0&&(r.compositeRule=i),n!==void 0&&(r.createErrors=n),s!==void 0&&(r.allErrors=s),r.jtdDiscriminator=e,r.jtdMetadata=t}kr.extendSubschemaMode=Gv});var Oc=$(($O,np)=>{"use strict";np.exports=function r(e,t){if(e===t)return!0;if(e&&t&&typeof e=="object"&&typeof t=="object"){if(e.constructor!==t.constructor)return!1;var i,n,s;if(Array.isArray(e)){if(i=e.length,i!=t.length)return!1;for(n=i;n--!==0;)if(!r(e[n],t[n]))return!1;return!0}if(e.constructor===RegExp)return e.source===t.source&&e.flags===t.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===t.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===t.toString();if(s=Object.keys(e),i=s.length,i!==Object.keys(t).length)return!1;for(n=i;n--!==0;)if(!Object.prototype.hasOwnProperty.call(t,s[n]))return!1;for(n=i;n--!==0;){var o=s[n];if(!r(e[o],t[o]))return!1}return!0}return e!==e&&t!==t}});var op=$((SO,sp)=>{"use strict";var Pr=sp.exports=function(r,e,t){typeof e=="function"&&(t=e,e={}),t=e.cb||t;var i=typeof t=="function"?t:t.pre||function(){},n=t.post||function(){};no(e,i,n,r,"",r)};Pr.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Pr.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Pr.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Pr.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function no(r,e,t,i,n,s,o,a,c,l){if(i&&typeof i=="object"&&!Array.isArray(i)){e(i,n,s,o,a,c,l);for(var u in i){var d=i[u];if(Array.isArray(d)){if(u in Pr.arrayKeywords)for(var f=0;f{"use strict";Object.defineProperty(et,"__esModule",{value:!0});et.getSchemaRefs=et.resolveUrl=et.normalizeId=et._getFullPath=et.getFullPath=et.inlineRef=void 0;var Jv=Y(),Yv=Oc(),Xv=op(),Zv=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function Qv(r,e=!0){return typeof r=="boolean"?!0:e===!0?!Cc(r):e?ap(r)<=e:!1}et.inlineRef=Qv;var ew=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Cc(r){for(let e in r){if(ew.has(e))return!0;let t=r[e];if(Array.isArray(t)&&t.some(Cc)||typeof t=="object"&&Cc(t))return!0}return!1}function ap(r){let e=0;for(let t in r){if(t==="$ref")return 1/0;if(e++,!Zv.has(t)&&(typeof r[t]=="object"&&(0,Jv.eachItem)(r[t],i=>e+=ap(i)),e===1/0))return 1/0}return e}function cp(r,e="",t){t!==!1&&(e=Pi(e));let i=r.parse(e);return lp(r,i)}et.getFullPath=cp;function lp(r,e){return r.serialize(e).split("#")[0]+"#"}et._getFullPath=lp;var tw=/#\/?$/;function Pi(r){return r?r.replace(tw,""):""}et.normalizeId=Pi;function rw(r,e,t){return t=Pi(t),r.resolve(e,t)}et.resolveUrl=rw;var iw=/^[a-z_][-a-z0-9._]*$/i;function nw(r,e){if(typeof r=="boolean")return{};let{schemaId:t,uriResolver:i}=this.opts,n=Pi(r[t]||e),s={"":n},o=cp(i,n,!1),a={},c=new Set;return Xv(r,{allKeys:!0},(d,f,p,m)=>{if(m===void 0)return;let h=o+f,y=s[m];typeof d[t]=="string"&&(y=b.call(this,d[t])),g.call(this,d.$anchor),g.call(this,d.$dynamicAnchor),s[f]=y;function b(_){let S=this.opts.uriResolver.resolve;if(_=Pi(y?S(y,_):_),c.has(_))throw u(_);c.add(_);let v=this.refs[_];return typeof v=="string"&&(v=this.refs[v]),typeof v=="object"?l(d,v.schema,_):_!==Pi(h)&&(_[0]==="#"?(l(d,a[_],_),a[_]=d):this.refs[_]=h),_}function g(_){if(typeof _=="string"){if(!iw.test(_))throw new Error(`invalid anchor "${_}"`);b.call(this,`#${_}`)}}}),a;function l(d,f,p){if(f!==void 0&&!Yv(d,f))throw u(p)}function u(d){return new Error(`reference "${d}" resolves to more than one schema`)}}et.getSchemaRefs=nw});var xi=$(xr=>{"use strict";Object.defineProperty(xr,"__esModule",{value:!0});xr.getData=xr.KeywordCxt=xr.validateFunctionCode=void 0;var hp=zf(),dp=Pn(),Mc=Ac(),so=Pn(),sw=Yf(),Rn=tp(),Nc=ip(),D=z(),U=ht(),ow=xn(),or=Y(),In=kn();function aw(r){if(gp(r)&&(bp(r),yp(r))){dw(r);return}mp(r,()=>(0,hp.topBoolOrEmptySchema)(r))}xr.validateFunctionCode=aw;function mp({gen:r,validateName:e,schema:t,schemaEnv:i,opts:n},s){n.code.es5?r.func(e,(0,D._)`${U.default.data}, ${U.default.valCxt}`,i.$async,()=>{r.code((0,D._)`"use strict"; ${up(t,n)}`),lw(r,n),r.code(s)}):r.func(e,(0,D._)`${U.default.data}, ${cw(n)}`,i.$async,()=>r.code(up(t,n)).code(s))}function cw(r){return(0,D._)`{${U.default.instancePath}="", ${U.default.parentData}, ${U.default.parentDataProperty}, ${U.default.rootData}=${U.default.data}${r.dynamicRef?(0,D._)`, ${U.default.dynamicAnchors}={}`:D.nil}}={}`}function lw(r,e){r.if(U.default.valCxt,()=>{r.var(U.default.instancePath,(0,D._)`${U.default.valCxt}.${U.default.instancePath}`),r.var(U.default.parentData,(0,D._)`${U.default.valCxt}.${U.default.parentData}`),r.var(U.default.parentDataProperty,(0,D._)`${U.default.valCxt}.${U.default.parentDataProperty}`),r.var(U.default.rootData,(0,D._)`${U.default.valCxt}.${U.default.rootData}`),e.dynamicRef&&r.var(U.default.dynamicAnchors,(0,D._)`${U.default.valCxt}.${U.default.dynamicAnchors}`)},()=>{r.var(U.default.instancePath,(0,D._)`""`),r.var(U.default.parentData,(0,D._)`undefined`),r.var(U.default.parentDataProperty,(0,D._)`undefined`),r.var(U.default.rootData,U.default.data),e.dynamicRef&&r.var(U.default.dynamicAnchors,(0,D._)`{}`)})}function dw(r){let{schema:e,opts:t,gen:i}=r;mp(r,()=>{t.$comment&&e.$comment&&vp(r),mw(r),i.let(U.default.vErrors,null),i.let(U.default.errors,0),t.unevaluated&&uw(r),_p(r),bw(r)})}function uw(r){let{gen:e,validateName:t}=r;r.evaluated=e.const("evaluated",(0,D._)`${t}.evaluated`),e.if((0,D._)`${r.evaluated}.dynamicProps`,()=>e.assign((0,D._)`${r.evaluated}.props`,(0,D._)`undefined`)),e.if((0,D._)`${r.evaluated}.dynamicItems`,()=>e.assign((0,D._)`${r.evaluated}.items`,(0,D._)`undefined`))}function up(r,e){let t=typeof r=="object"&&r[e.schemaId];return t&&(e.code.source||e.code.process)?(0,D._)`/*# sourceURL=${t} */`:D.nil}function fw(r,e){if(gp(r)&&(bp(r),yp(r))){pw(r,e);return}(0,hp.boolOrEmptySchema)(r,e)}function yp({schema:r,self:e}){if(typeof r=="boolean")return!r;for(let t in r)if(e.RULES.all[t])return!0;return!1}function gp(r){return typeof r.schema!="boolean"}function pw(r,e){let{schema:t,gen:i,opts:n}=r;n.$comment&&t.$comment&&vp(r),yw(r),gw(r);let s=i.const("_errs",U.default.errors);_p(r,s),i.var(e,(0,D._)`${s} === ${U.default.errors}`)}function bp(r){(0,or.checkUnknownRules)(r),hw(r)}function _p(r,e){if(r.opts.jtd)return fp(r,[],!1,e);let t=(0,dp.getSchemaTypes)(r.schema),i=(0,dp.coerceAndCheckDataType)(r,t);fp(r,t,!i,e)}function hw(r){let{schema:e,errSchemaPath:t,opts:i,self:n}=r;e.$ref&&i.ignoreKeywordsWithRef&&(0,or.schemaHasRulesButRef)(e,n.RULES)&&n.logger.warn(`$ref: keywords ignored in schema at path "${t}"`)}function mw(r){let{schema:e,opts:t}=r;e.default!==void 0&&t.useDefaults&&t.strictSchema&&(0,or.checkStrictMode)(r,"default is ignored in the schema root")}function yw(r){let e=r.schema[r.opts.schemaId];e&&(r.baseId=(0,ow.resolveUrl)(r.opts.uriResolver,r.baseId,e))}function gw(r){if(r.schema.$async&&!r.schemaEnv.$async)throw new Error("async schema in sync schema")}function vp({gen:r,schemaEnv:e,schema:t,errSchemaPath:i,opts:n}){let s=t.$comment;if(n.$comment===!0)r.code((0,D._)`${U.default.self}.logger.log(${s})`);else if(typeof n.$comment=="function"){let o=(0,D.str)`${i}/$comment`,a=r.scopeValue("root",{ref:e.root});r.code((0,D._)`${U.default.self}.opts.$comment(${s}, ${o}, ${a}.schema)`)}}function bw(r){let{gen:e,schemaEnv:t,validateName:i,ValidationError:n,opts:s}=r;t.$async?e.if((0,D._)`${U.default.errors} === 0`,()=>e.return(U.default.data),()=>e.throw((0,D._)`new ${n}(${U.default.vErrors})`)):(e.assign((0,D._)`${i}.errors`,U.default.vErrors),s.unevaluated&&_w(r),e.return((0,D._)`${U.default.errors} === 0`))}function _w({gen:r,evaluated:e,props:t,items:i}){t instanceof D.Name&&r.assign((0,D._)`${e}.props`,t),i instanceof D.Name&&r.assign((0,D._)`${e}.items`,i)}function fp(r,e,t,i){let{gen:n,schema:s,data:o,allErrors:a,opts:c,self:l}=r,{RULES:u}=l;if(s.$ref&&(c.ignoreKeywordsWithRef||!(0,or.schemaHasRulesButRef)(s,u))){n.block(()=>$p(r,"$ref",u.all.$ref.definition));return}c.jtd||vw(r,e),n.block(()=>{for(let f of u.rules)d(f);d(u.post)});function d(f){(0,Mc.shouldUseGroup)(s,f)&&(f.type?(n.if((0,so.checkDataType)(f.type,o,c.strictNumbers)),pp(r,f),e.length===1&&e[0]===f.type&&t&&(n.else(),(0,so.reportTypeError)(r)),n.endIf()):pp(r,f),a||n.if((0,D._)`${U.default.errors} === ${i||0}`))}}function pp(r,e){let{gen:t,schema:i,opts:{useDefaults:n}}=r;n&&(0,sw.assignDefaults)(r,e.type),t.block(()=>{for(let s of e.rules)(0,Mc.shouldUseRule)(i,s)&&$p(r,s.keyword,s.definition,e.type)})}function vw(r,e){r.schemaEnv.meta||!r.opts.strictTypes||(ww(r,e),r.opts.allowUnionTypes||$w(r,e),Sw(r,r.dataTypes))}function ww(r,e){if(e.length){if(!r.dataTypes.length){r.dataTypes=e;return}e.forEach(t=>{wp(r.dataTypes,t)||qc(r,`type "${t}" not allowed by context "${r.dataTypes.join(",")}"`)}),Aw(r,e)}}function $w(r,e){e.length>1&&!(e.length===2&&e.includes("null"))&&qc(r,"use allowUnionTypes to allow union type keyword")}function Sw(r,e){let t=r.self.RULES.all;for(let i in t){let n=t[i];if(typeof n=="object"&&(0,Mc.shouldUseRule)(r.schema,n)){let{type:s}=n.definition;s.length&&!s.some(o=>Ew(e,o))&&qc(r,`missing type "${s.join(",")}" for keyword "${i}"`)}}}function Ew(r,e){return r.includes(e)||e==="number"&&r.includes("integer")}function wp(r,e){return r.includes(e)||e==="integer"&&r.includes("number")}function Aw(r,e){let t=[];for(let i of r.dataTypes)wp(e,i)?t.push(i):e.includes("integer")&&i==="number"&&t.push("integer");r.dataTypes=t}function qc(r,e){let t=r.schemaEnv.baseId+r.errSchemaPath;e+=` at "${t}" (strictTypes)`,(0,or.checkStrictMode)(r,e,r.opts.strictTypes)}var oo=class{constructor(e,t,i){if((0,Rn.validateKeywordUsage)(e,t,i),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=i,this.data=e.data,this.schema=e.schema[i],this.$data=t.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,or.schemaRefOrVal)(e,this.schema,i,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",Sp(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,Rn.validSchemaType)(this.schema,t.schemaType,t.allowUndefined))throw new Error(`${i} value must be ${JSON.stringify(t.schemaType)}`);("code"in t?t.trackErrors:t.errors!==!1)&&(this.errsCount=e.gen.const("_errs",U.default.errors))}result(e,t,i){this.failResult((0,D.not)(e),t,i)}failResult(e,t,i){this.gen.if(e),i?i():this.error(),t?(this.gen.else(),t(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,t){this.failResult((0,D.not)(e),void 0,t)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:t}=this;this.fail((0,D._)`${t} !== undefined && (${(0,D.or)(this.invalid$data(),e)})`)}error(e,t,i){if(t){this.setParams(t),this._error(e,i),this.setParams({});return}this._error(e,i)}_error(e,t){(e?In.reportExtraError:In.reportError)(this,this.def.error,t)}$dataError(){(0,In.reportError)(this,this.def.$dataError||In.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,In.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,t){t?Object.assign(this.params,e):this.params=e}block$data(e,t,i=D.nil){this.gen.block(()=>{this.check$data(e,i),t()})}check$data(e=D.nil,t=D.nil){if(!this.$data)return;let{gen:i,schemaCode:n,schemaType:s,def:o}=this;i.if((0,D.or)((0,D._)`${n} === undefined`,t)),e!==D.nil&&i.assign(e,!0),(s.length||o.validateSchema)&&(i.elseIf(this.invalid$data()),this.$dataError(),e!==D.nil&&i.assign(e,!1)),i.else()}invalid$data(){let{gen:e,schemaCode:t,schemaType:i,def:n,it:s}=this;return(0,D.or)(o(),a());function o(){if(i.length){if(!(t instanceof D.Name))throw new Error("ajv implementation error");let c=Array.isArray(i)?i:[i];return(0,D._)`${(0,so.checkDataTypes)(c,t,s.opts.strictNumbers,so.DataType.Wrong)}`}return D.nil}function a(){if(n.validateSchema){let c=e.scopeValue("validate$data",{ref:n.validateSchema});return(0,D._)`!${c}(${t})`}return D.nil}}subschema(e,t){let i=(0,Nc.getSubschema)(this.it,e);(0,Nc.extendSubschemaData)(i,this.it,e),(0,Nc.extendSubschemaMode)(i,e);let n={...this.it,...i,items:void 0,props:void 0};return fw(n,t),n}mergeEvaluated(e,t){let{it:i,gen:n}=this;i.opts.unevaluated&&(i.props!==!0&&e.props!==void 0&&(i.props=or.mergeEvaluated.props(n,e.props,i.props,t)),i.items!==!0&&e.items!==void 0&&(i.items=or.mergeEvaluated.items(n,e.items,i.items,t)))}mergeValidEvaluated(e,t){let{it:i,gen:n}=this;if(i.opts.unevaluated&&(i.props!==!0||i.items!==!0))return n.if(t,()=>this.mergeEvaluated(e,D.Name)),!0}};xr.KeywordCxt=oo;function $p(r,e,t,i){let n=new oo(r,t,e);"code"in t?t.code(n,i):n.$data&&t.validate?(0,Rn.funcKeywordCode)(n,t):"macro"in t?(0,Rn.macroKeywordCode)(n,t):(t.compile||t.validate)&&(0,Rn.funcKeywordCode)(n,t)}var kw=/^\/(?:[^~]|~0|~1)*$/,Pw=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Sp(r,{dataLevel:e,dataNames:t,dataPathArr:i}){let n,s;if(r==="")return U.default.rootData;if(r[0]==="/"){if(!kw.test(r))throw new Error(`Invalid JSON-pointer: ${r}`);n=r,s=U.default.rootData}else{let l=Pw.exec(r);if(!l)throw new Error(`Invalid JSON-pointer: ${r}`);let u=+l[1];if(n=l[2],n==="#"){if(u>=e)throw new Error(c("property/index",u));return i[e-u]}if(u>e)throw new Error(c("data",u));if(s=t[e-u],!n)return s}let o=s,a=n.split("/");for(let l of a)l&&(s=(0,D._)`${s}${(0,D.getProperty)((0,or.unescapeJsonPointer)(l))}`,o=(0,D._)`${o} && ${s}`);return o;function c(l,u){return`Cannot access ${l} ${u} levels up, current level is ${e}`}}xr.getData=Sp});var Tn=$(jc=>{"use strict";Object.defineProperty(jc,"__esModule",{value:!0});var Lc=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};jc.default=Lc});var Ii=$(Vc=>{"use strict";Object.defineProperty(Vc,"__esModule",{value:!0});var Dc=xn(),Fc=class extends Error{constructor(e,t,i,n){super(n||`can't resolve reference ${i} from id ${t}`),this.missingRef=(0,Dc.resolveUrl)(e,t,i),this.missingSchema=(0,Dc.normalizeId)((0,Dc.getFullPath)(e,this.missingRef))}};Vc.default=Fc});var On=$(yt=>{"use strict";Object.defineProperty(yt,"__esModule",{value:!0});yt.resolveSchema=yt.getCompilingSchema=yt.resolveRef=yt.compileSchema=yt.SchemaEnv=void 0;var Et=z(),xw=Tn(),ei=ht(),At=xn(),Ep=Y(),Iw=xi(),Ri=class{constructor(e){var t;this.refs={},this.dynamicAnchors={};let i;typeof e.schema=="object"&&(i=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,At.normalizeId)(i==null?void 0:i[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=i==null?void 0:i.$async,this.refs={}}};yt.SchemaEnv=Ri;function zc(r){let e=Ap.call(this,r);if(e)return e;let t=(0,At.getFullPath)(this.opts.uriResolver,r.root.baseId),{es5:i,lines:n}=this.opts.code,{ownProperties:s}=this.opts,o=new Et.CodeGen(this.scope,{es5:i,lines:n,ownProperties:s}),a;r.$async&&(a=o.scopeValue("Error",{ref:xw.default,code:(0,Et._)`require("ajv/dist/runtime/validation_error").default`}));let c=o.scopeName("validate");r.validateName=c;let l={gen:o,allErrors:this.opts.allErrors,data:ei.default.data,parentData:ei.default.parentData,parentDataProperty:ei.default.parentDataProperty,dataNames:[ei.default.data],dataPathArr:[Et.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:o.scopeValue("schema",this.opts.code.source===!0?{ref:r.schema,code:(0,Et.stringify)(r.schema)}:{ref:r.schema}),validateName:c,ValidationError:a,schema:r.schema,schemaEnv:r,rootId:t,baseId:r.baseId||t,schemaPath:Et.nil,errSchemaPath:r.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Et._)`""`,opts:this.opts,self:this},u;try{this._compilations.add(r),(0,Iw.validateFunctionCode)(l),o.optimize(this.opts.code.optimize);let d=o.toString();u=`${o.scopeRefs(ei.default.scope)}return ${d}`,this.opts.code.process&&(u=this.opts.code.process(u,r));let p=new Function(`${ei.default.self}`,`${ei.default.scope}`,u)(this,this.scope.get());if(this.scope.value(c,{ref:p}),p.errors=null,p.schema=r.schema,p.schemaEnv=r,r.$async&&(p.$async=!0),this.opts.code.source===!0&&(p.source={validateName:c,validateCode:d,scopeValues:o._values}),this.opts.unevaluated){let{props:m,items:h}=l;p.evaluated={props:m instanceof Et.Name?void 0:m,items:h instanceof Et.Name?void 0:h,dynamicProps:m instanceof Et.Name,dynamicItems:h instanceof Et.Name},p.source&&(p.source.evaluated=(0,Et.stringify)(p.evaluated))}return r.validate=p,r}catch(d){throw delete r.validate,delete r.validateName,u&&this.logger.error("Error compiling schema, function code:",u),d}finally{this._compilations.delete(r)}}yt.compileSchema=zc;function Rw(r,e,t){var i;t=(0,At.resolveUrl)(this.opts.uriResolver,e,t);let n=r.refs[t];if(n)return n;let s=Cw.call(this,r,t);if(s===void 0){let o=(i=r.localRefs)===null||i===void 0?void 0:i[t],{schemaId:a}=this.opts;o&&(s=new Ri({schema:o,schemaId:a,root:r,baseId:e}))}if(s!==void 0)return r.refs[t]=Tw.call(this,s)}yt.resolveRef=Rw;function Tw(r){return(0,At.inlineRef)(r.schema,this.opts.inlineRefs)?r.schema:r.validate?r:zc.call(this,r)}function Ap(r){for(let e of this._compilations)if(Ow(e,r))return e}yt.getCompilingSchema=Ap;function Ow(r,e){return r.schema===e.schema&&r.root===e.root&&r.baseId===e.baseId}function Cw(r,e){let t;for(;typeof(t=this.refs[e])=="string";)e=t;return t||this.schemas[e]||ao.call(this,r,e)}function ao(r,e){let t=this.opts.uriResolver.parse(e),i=(0,At._getFullPath)(this.opts.uriResolver,t),n=(0,At.getFullPath)(this.opts.uriResolver,r.baseId,void 0);if(Object.keys(r.schema).length>0&&i===n)return Uc.call(this,t,r);let s=(0,At.normalizeId)(i),o=this.refs[s]||this.schemas[s];if(typeof o=="string"){let a=ao.call(this,r,o);return typeof(a==null?void 0:a.schema)!="object"?void 0:Uc.call(this,t,a)}if(typeof(o==null?void 0:o.schema)=="object"){if(o.validate||zc.call(this,o),s===(0,At.normalizeId)(e)){let{schema:a}=o,{schemaId:c}=this.opts,l=a[c];return l&&(n=(0,At.resolveUrl)(this.opts.uriResolver,n,l)),new Ri({schema:a,schemaId:c,root:r,baseId:n})}return Uc.call(this,t,o)}}yt.resolveSchema=ao;var Nw=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Uc(r,{baseId:e,schema:t,root:i}){var n;if(((n=r.fragment)===null||n===void 0?void 0:n[0])!=="/")return;for(let a of r.fragment.slice(1).split("/")){if(typeof t=="boolean")return;let c=t[(0,Ep.unescapeFragment)(a)];if(c===void 0)return;t=c;let l=typeof t=="object"&&t[this.opts.schemaId];!Nw.has(a)&&l&&(e=(0,At.resolveUrl)(this.opts.uriResolver,e,l))}let s;if(typeof t!="boolean"&&t.$ref&&!(0,Ep.schemaHasRulesButRef)(t,this.RULES)){let a=(0,At.resolveUrl)(this.opts.uriResolver,e,t.$ref);s=ao.call(this,i,a)}let{schemaId:o}=this.opts;if(s=s||new Ri({schema:t,schemaId:o,root:i,baseId:e}),s.schema!==s.root.schema)return s}});var kp=$((IO,Mw)=>{Mw.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 Kc=$((RO,Op)=>{"use strict";var qw=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),xp=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u),Bc=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),Ip=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),Lw=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function Hc(r){let e="",t=0,i=0;for(i=0;i=48&&t<=57||t>=65&&t<=70||t>=97&&t<=102))return"";e+=r[i];break}for(i+=1;i=48&&t<=57||t>=65&&t<=70||t>=97&&t<=102))return"";e+=r[i]}return e}var jw=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function Pp(r){return r.length=0,!0}function Dw(r,e,t){if(r.length){let i=Hc(r);if(i!=="")e.push(i);else return t.error=!0,!1;r.length=0}return!0}function Fw(r){let e=0,t={error:!1,address:"",zone:""},i=[],n=[],s=!1,o=!1,a=Dw;for(let c=0;c7){t.error=!0;break}c>0&&r[c-1]===":"&&(s=!0),i.push(":");continue}else if(l==="%"){if(!a(n,i,t))break;a=Pp}else{n.push(l);continue}}return n.length&&(a===Pp?t.zone=n.join(""):o?i.push(n.join("")):i.push(Hc(n))),t.address=i.join(""),t}function Rp(r){if(Vw(r,":")<2)return{host:r,isIPV6:!1};let e=Fw(r);if(e.error)return{host:r,isIPV6:!1};{let t=e.address,i=e.address;return e.zone&&(t+="%"+e.zone,i+="%25"+e.zone),{host:t,isIPV6:!0,escapedHost:i}}}function Vw(r,e){let t=0;for(let i=0;izw[i])}function Kw(r,e=!1){if(r.indexOf("%")===-1)return r;let t="";for(let i=0;i{"use strict";var{isUUID:Yw}=Kc(),Xw=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,Zw=["http","https","ws","wss","urn","urn:uuid"];function Qw(r){return Zw.indexOf(r)!==-1}function Gc(r){return r.secure===!0?!0:r.secure===!1?!1:r.scheme?r.scheme.length===3&&(r.scheme[0]==="w"||r.scheme[0]==="W")&&(r.scheme[1]==="s"||r.scheme[1]==="S")&&(r.scheme[2]==="s"||r.scheme[2]==="S"):!1}function Cp(r){return r.host||(r.error=r.error||"HTTP URIs must have a host."),r}function Np(r){let e=String(r.scheme).toLowerCase()==="https";return(r.port===(e?443:80)||r.port==="")&&(r.port=void 0),r.path||(r.path="/"),r}function e$(r){return r.secure=Gc(r),r.resourceName=(r.path||"/")+(r.query?"?"+r.query:""),r.path=void 0,r.query=void 0,r}function t$(r){if((r.port===(Gc(r)?443:80)||r.port==="")&&(r.port=void 0),typeof r.secure=="boolean"&&(r.scheme=r.secure?"wss":"ws",r.secure=void 0),r.resourceName){let[e,t]=r.resourceName.split("?");r.path=e&&e!=="/"?e:void 0,r.query=t,r.resourceName=void 0}return r.fragment=void 0,r}function r$(r,e){if(!r.path)return r.error="URN can not be parsed",r;let t=r.path.match(Xw);if(t){let i=e.scheme||r.scheme||"urn";r.nid=t[1].toLowerCase(),r.nss=t[2];let n=`${i}:${e.nid||r.nid}`,s=Wc(n);r.path=void 0,s&&(r=s.parse(r,e))}else r.error=r.error||"URN can not be parsed.";return r}function i$(r,e){if(r.nid===void 0)throw new Error("URN without nid cannot be serialized");let t=e.scheme||r.scheme||"urn",i=r.nid.toLowerCase(),n=`${t}:${e.nid||i}`,s=Wc(n);s&&(r=s.serialize(r,e));let o=r,a=r.nss;return o.path=`${i||e.nid}:${a}`,e.skipEscape=!0,o}function n$(r,e){let t=r;return t.uuid=t.nss,t.nss=void 0,!e.tolerant&&(!t.uuid||!Yw(t.uuid))&&(t.error=t.error||"UUID is not valid."),t}function s$(r){let e=r;return e.nss=(r.uuid||"").toLowerCase(),e}var Mp={scheme:"http",domainHost:!0,parse:Cp,serialize:Np},o$={scheme:"https",domainHost:Mp.domainHost,parse:Cp,serialize:Np},co={scheme:"ws",domainHost:!0,parse:e$,serialize:t$},a$={scheme:"wss",domainHost:co.domainHost,parse:co.parse,serialize:co.serialize},c$={scheme:"urn",parse:r$,serialize:i$,skipNormalize:!0},l$={scheme:"urn:uuid",parse:n$,serialize:s$,skipNormalize:!0},lo={http:Mp,https:o$,ws:co,wss:a$,urn:c$,"urn:uuid":l$};Object.setPrototypeOf(lo,null);function Wc(r){return r&&(lo[r]||lo[r.toLowerCase()])||void 0}qp.exports={wsIsSecure:Gc,SCHEMES:lo,isValidSchemeName:Qw,getSchemeHandler:Wc}});var zp=$((OO,uo)=>{"use strict";var{normalizeIPv6:d$,removeDotSegments:Cn,recomposeAuthority:u$,normalizePercentEncoding:f$,normalizePathEncoding:p$,escapePreservingEscapes:h$,reescapeHostDelimiters:m$,isIPv4:y$,nonSimpleDomain:g$}=Kc(),{SCHEMES:b$,getSchemeHandler:Dp}=Lp();function _$(r,e){return typeof r=="string"?r=A$(r,e):typeof r=="object"&&(r=Ti(ti(r,e),e)),r}function v$(r,e,t){let i=t?Object.assign({scheme:"null"},t):{scheme:"null"},n=Fp(Ti(r,i),Ti(e,i),i,!0);return i.skipEscape=!0,ti(n,i)}function Fp(r,e,t,i){let n={};return i||(r=Ti(ti(r,t),t),e=Ti(ti(e,t),t)),t=t||{},!t.tolerant&&e.scheme?(n.scheme=e.scheme,n.userinfo=e.userinfo,n.host=e.host,n.port=e.port,n.path=Cn(e.path||""),n.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(n.userinfo=e.userinfo,n.host=e.host,n.port=e.port,n.path=Cn(e.path||""),n.query=e.query):(e.path?(e.path[0]==="/"?n.path=Cn(e.path):((r.userinfo!==void 0||r.host!==void 0||r.port!==void 0)&&!r.path?n.path="/"+e.path:r.path?n.path=r.path.slice(0,r.path.lastIndexOf("/")+1)+e.path:n.path=e.path,n.path=Cn(n.path)),n.query=e.query):(n.path=r.path,e.query!==void 0?n.query=e.query:n.query=r.query),n.userinfo=r.userinfo,n.host=r.host,n.port=r.port),n.scheme=r.scheme),n.fragment=e.fragment,n}function w$(r,e,t){let i=jp(r,t),n=jp(e,t);return i!==void 0&&n!==void 0&&i.toLowerCase()===n.toLowerCase()}function ti(r,e){let t={host:r.host,scheme:r.scheme,userinfo:r.userinfo,port:r.port,path:r.path,query:r.query,nid:r.nid,nss:r.nss,uuid:r.uuid,fragment:r.fragment,reference:r.reference,resourceName:r.resourceName,secure:r.secure,error:""},i=Object.assign({},e),n=[],s=Dp(i.scheme||t.scheme);s&&s.serialize&&s.serialize(t,i),t.path!==void 0&&(i.skipEscape?t.path=f$(t.path):(t.path=h$(t.path),t.scheme!==void 0&&(t.path=t.path.split("%3A").join(":")))),i.reference!=="suffix"&&t.scheme&&n.push(t.scheme,":");let o=u$(t);if(o!==void 0&&(i.reference!=="suffix"&&n.push("//"),n.push(o),t.path&&t.path[0]!=="/"&&n.push("/")),t.path!==void 0){let a=t.path;!i.absolutePath&&(!s||!s.absolutePath)&&(a=Cn(a)),o===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),n.push(a)}return t.query!==void 0&&n.push("?",t.query),t.fragment!==void 0&&n.push("#",t.fragment),n.join("")}var $$=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,S$=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/;function E$(r,e){if(e[2]!==void 0&&r.path&&r.path[0]!=="/")return'URI path must start with "/" when authority is present.';if(typeof r.port=="number"&&(r.port<0||r.port>65535))return"URI port is malformed."}function Vp(r,e){let t=Object.assign({},e),i={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},n=!1,s=!1;t.reference==="suffix"&&(t.scheme?r=t.scheme+":"+r:r="//"+r);let o=r.match(S$);o!==null&&o[1].indexOf("\\")!==-1&&(i.error="URI authority must not contain a literal backslash.",n=!0);let a=r.match($$);if(a){i.scheme=a[1],i.userinfo=a[3],i.host=a[4],i.port=parseInt(a[5],10),i.path=a[6]||"",i.query=a[7],i.fragment=a[8],isNaN(i.port)&&(i.port=a[5]);let c=E$(i,a);if(c!==void 0&&(i.error=i.error||c,n=!0),i.host)if(y$(i.host)===!1){let d=d$(i.host);i.host=d.host.toLowerCase(),s=d.isIPV6}else s=!0;i.scheme===void 0&&i.userinfo===void 0&&i.host===void 0&&i.port===void 0&&i.query===void 0&&!i.path?i.reference="same-document":i.scheme===void 0?i.reference="relative":i.fragment===void 0?i.reference="absolute":i.reference="uri",t.reference&&t.reference!=="suffix"&&t.reference!==i.reference&&(i.error=i.error||"URI is not a "+t.reference+" reference.");let l=Dp(t.scheme||i.scheme);if(!t.unicodeSupport&&(!l||!l.unicodeSupport)&&i.host&&(t.domainHost||l&&l.domainHost)&&s===!1&&g$(i.host))try{i.host=new URL("http://"+i.host).hostname}catch(u){i.error=i.error||"Host's domain name can not be converted to ASCII: "+u}if((!l||l&&!l.skipNormalize)&&(r.indexOf("%")!==-1&&(i.scheme!==void 0&&(i.scheme=unescape(i.scheme)),i.host!==void 0&&(i.host=m$(unescape(i.host),s))),i.path&&(i.path=p$(i.path)),i.fragment))try{i.fragment=encodeURI(decodeURIComponent(i.fragment))}catch(u){i.error=i.error||"URI malformed"}l&&l.parse&&l.parse(i,t)}else i.error=i.error||"URI can not be parsed.";return{parsed:i,malformedAuthorityOrPort:n}}function Ti(r,e){return Vp(r,e).parsed}function A$(r,e){return Up(r,e).normalized}function Up(r,e){let{parsed:t,malformedAuthorityOrPort:i}=Vp(r,e);return{normalized:i?r:ti(t,e),malformedAuthorityOrPort:i}}function jp(r,e){if(typeof r=="string"){let{normalized:t,malformedAuthorityOrPort:i}=Up(r,e);return i?void 0:t}if(typeof r=="object")return ti(r,e)}var Jc={SCHEMES:b$,normalize:_$,resolve:v$,resolveComponent:Fp,equal:w$,serialize:ti,parse:Ti};uo.exports=Jc;uo.exports.default=Jc;uo.exports.fastUri=Jc});var Hp=$(Yc=>{"use strict";Object.defineProperty(Yc,"__esModule",{value:!0});var Bp=zp();Bp.code='require("ajv/dist/runtime/uri").default';Yc.default=Bp});var Qc=$(Me=>{"use strict";Object.defineProperty(Me,"__esModule",{value:!0});Me.CodeGen=Me.Name=Me.nil=Me.stringify=Me.str=Me._=Me.KeywordCxt=void 0;var k$=xi();Object.defineProperty(Me,"KeywordCxt",{enumerable:!0,get:function(){return k$.KeywordCxt}});var Oi=z();Object.defineProperty(Me,"_",{enumerable:!0,get:function(){return Oi._}});Object.defineProperty(Me,"str",{enumerable:!0,get:function(){return Oi.str}});Object.defineProperty(Me,"stringify",{enumerable:!0,get:function(){return Oi.stringify}});Object.defineProperty(Me,"nil",{enumerable:!0,get:function(){return Oi.nil}});Object.defineProperty(Me,"Name",{enumerable:!0,get:function(){return Oi.Name}});Object.defineProperty(Me,"CodeGen",{enumerable:!0,get:function(){return Oi.CodeGen}});var P$=Tn(),Yp=Ii(),x$=Ec(),Nn=On(),I$=z(),Mn=xn(),fo=Pn(),Zc=Y(),Kp=kp(),R$=Hp(),Xp=(r,e)=>new RegExp(r,e);Xp.code="new RegExp";var T$=["removeAdditional","useDefaults","coerceTypes"],O$=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),C$={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."},N$={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Gp=200;function M$(r){var e,t,i,n,s,o,a,c,l,u,d,f,p,m,h,y,b,g,_,S,v,P,x,E,R;let w=r.strict,F=(e=r.code)===null||e===void 0?void 0:e.optimize,V=F===!0||F===void 0?1:F||0,G=(i=(t=r.code)===null||t===void 0?void 0:t.regExp)!==null&&i!==void 0?i:Xp,A=(n=r.uriResolver)!==null&&n!==void 0?n:R$.default;return{strictSchema:(o=(s=r.strictSchema)!==null&&s!==void 0?s:w)!==null&&o!==void 0?o:!0,strictNumbers:(c=(a=r.strictNumbers)!==null&&a!==void 0?a:w)!==null&&c!==void 0?c:!0,strictTypes:(u=(l=r.strictTypes)!==null&&l!==void 0?l:w)!==null&&u!==void 0?u:"log",strictTuples:(f=(d=r.strictTuples)!==null&&d!==void 0?d:w)!==null&&f!==void 0?f:"log",strictRequired:(m=(p=r.strictRequired)!==null&&p!==void 0?p:w)!==null&&m!==void 0?m:!1,code:r.code?{...r.code,optimize:V,regExp:G}:{optimize:V,regExp:G},loopRequired:(h=r.loopRequired)!==null&&h!==void 0?h:Gp,loopEnum:(y=r.loopEnum)!==null&&y!==void 0?y:Gp,meta:(b=r.meta)!==null&&b!==void 0?b:!0,messages:(g=r.messages)!==null&&g!==void 0?g:!0,inlineRefs:(_=r.inlineRefs)!==null&&_!==void 0?_:!0,schemaId:(S=r.schemaId)!==null&&S!==void 0?S:"$id",addUsedSchema:(v=r.addUsedSchema)!==null&&v!==void 0?v:!0,validateSchema:(P=r.validateSchema)!==null&&P!==void 0?P:!0,validateFormats:(x=r.validateFormats)!==null&&x!==void 0?x:!0,unicodeRegExp:(E=r.unicodeRegExp)!==null&&E!==void 0?E:!0,int32range:(R=r.int32range)!==null&&R!==void 0?R:!0,uriResolver:A}}var qn=class{constructor(e={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...M$(e)};let{es5:t,lines:i}=this.opts.code;this.scope=new I$.ValueScope({scope:{},prefixes:O$,es5:t,lines:i}),this.logger=V$(e.logger);let n=e.validateFormats;e.validateFormats=!1,this.RULES=(0,x$.getRules)(),Wp.call(this,C$,e,"NOT SUPPORTED"),Wp.call(this,N$,e,"DEPRECATED","warn"),this._metaOpts=D$.call(this),e.formats&&L$.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&j$.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),q$.call(this),e.validateFormats=n}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:t,schemaId:i}=this.opts,n=Kp;i==="id"&&(n={...Kp},n.id=n.$id,delete n.$id),t&&e&&this.addMetaSchema(n,n[i],!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 i;if(typeof e=="string"){if(i=this.getSchema(e),!i)throw new Error(`no schema with key or ref "${e}"`)}else i=this.compile(e);let n=i(t);return"$async"in i||(this.errors=i.errors),n}compile(e,t){let i=this._addSchema(e,t);return i.validate||this._compileSchemaEnv(i)}compileAsync(e,t){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:i}=this.opts;return n.call(this,e,t);async function n(u,d){await s.call(this,u.$schema);let f=this._addSchema(u,d);return f.validate||o.call(this,f)}async function s(u){u&&!this.getSchema(u)&&await n.call(this,{$ref:u},!0)}async function o(u){try{return this._compileSchemaEnv(u)}catch(d){if(!(d instanceof Yp.default))throw d;return a.call(this,d),await c.call(this,d.missingSchema),o.call(this,u)}}function a({missingSchema:u,missingRef:d}){if(this.refs[u])throw new Error(`AnySchema ${u} is loaded but ${d} cannot be resolved`)}async function c(u){let d=await l.call(this,u);this.refs[u]||await s.call(this,d.$schema),this.refs[u]||this.addSchema(d,u,t)}async function l(u){let d=this._loading[u];if(d)return d;try{return await(this._loading[u]=i(u))}finally{delete this._loading[u]}}}addSchema(e,t,i,n=this.opts.validateSchema){if(Array.isArray(e)){for(let o of e)this.addSchema(o,void 0,i,n);return this}let s;if(typeof e=="object"){let{schemaId:o}=this.opts;if(s=e[o],s!==void 0&&typeof s!="string")throw new Error(`schema ${o} must be string`)}return t=(0,Mn.normalizeId)(t||s),this._checkUnique(t),this.schemas[t]=this._addSchema(e,i,t,n,!0),this}addMetaSchema(e,t,i=this.opts.validateSchema){return this.addSchema(e,t,!0,i),this}validateSchema(e,t){if(typeof e=="boolean")return!0;let i;if(i=e.$schema,i!==void 0&&typeof i!="string")throw new Error("$schema must be a string");if(i=i||this.opts.defaultMeta||this.defaultMeta(),!i)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let n=this.validate(i,e);if(!n&&t){let s="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(s);else throw new Error(s)}return n}getSchema(e){let t;for(;typeof(t=Jp.call(this,e))=="string";)e=t;if(t===void 0){let{schemaId:i}=this.opts,n=new Nn.SchemaEnv({schema:{},schemaId:i});if(t=Nn.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=Jp.call(this,e);return typeof t=="object"&&this._cache.delete(t.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let t=e;this._cache.delete(t);let i=e[this.opts.schemaId];return i&&(i=(0,Mn.normalizeId)(i),delete this.schemas[i],delete this.refs[i]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let t of e)this.addKeyword(t);return this}addKeyword(e,t){let i;if(typeof e=="string")i=e,typeof t=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),t.keyword=i);else if(typeof e=="object"&&t===void 0){if(t=e,i=t.keyword,Array.isArray(i)&&!i.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(z$.call(this,i,t),!t)return(0,Zc.eachItem)(i,s=>Xc.call(this,s)),this;H$.call(this,t);let n={...t,type:(0,fo.getJSONTypes)(t.type),schemaType:(0,fo.getJSONTypes)(t.schemaType)};return(0,Zc.eachItem)(i,n.type.length===0?s=>Xc.call(this,s,n):s=>n.type.forEach(o=>Xc.call(this,s,n,o))),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 i of t.rules){let n=i.rules.findIndex(s=>s.keyword===e);n>=0&&i.rules.splice(n,1)}return this}addFormat(e,t){return typeof t=="string"&&(t=new RegExp(t)),this.formats[e]=t,this}errorsText(e=this.errors,{separator:t=", ",dataVar:i="data"}={}){return!e||e.length===0?"No errors":e.map(n=>`${i}${n.instancePath} ${n.message}`).reduce((n,s)=>n+t+s)}$dataMetaSchema(e,t){let i=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let n of t){let s=n.split("/").slice(1),o=e;for(let a of s)o=o[a];for(let a in i){let c=i[a];if(typeof c!="object")continue;let{$data:l}=c.definition,u=o[a];l&&u&&(o[a]=Zp(u))}}return e}_removeAllSchemas(e,t){for(let i in e){let n=e[i];(!t||t.test(i))&&(typeof n=="string"?delete e[i]:n&&!n.meta&&(this._cache.delete(n.schema),delete e[i]))}}_addSchema(e,t,i,n=this.opts.validateSchema,s=this.opts.addUsedSchema){let o,{schemaId:a}=this.opts;if(typeof e=="object")o=e[a];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof e!="boolean")throw new Error("schema must be object or boolean")}let c=this._cache.get(e);if(c!==void 0)return c;i=(0,Mn.normalizeId)(o||i);let l=Mn.getSchemaRefs.call(this,e,i);return c=new Nn.SchemaEnv({schema:e,schemaId:a,meta:t,baseId:i,localRefs:l}),this._cache.set(c.schema,c),s&&!i.startsWith("#")&&(i&&this._checkUnique(i),this.refs[i]=c),n&&this.validateSchema(e,!0),c}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):Nn.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let t=this.opts;this.opts=this._metaOpts;try{Nn.compileSchema.call(this,e)}finally{this.opts=t}}};qn.ValidationError=P$.default;qn.MissingRefError=Yp.default;Me.default=qn;function Wp(r,e,t,i="error"){for(let n in r){let s=n;s in e&&this.logger[i](`${t}: option ${n}. ${r[s]}`)}}function Jp(r){return r=(0,Mn.normalizeId)(r),this.schemas[r]||this.refs[r]}function q$(){let r=this.opts.schemas;if(r)if(Array.isArray(r))this.addSchema(r);else for(let e in r)this.addSchema(r[e],e)}function L$(){for(let r in this.opts.formats){let e=this.opts.formats[r];e&&this.addFormat(r,e)}}function j$(r){if(Array.isArray(r)){this.addVocabulary(r);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let e in r){let t=r[e];t.keyword||(t.keyword=e),this.addKeyword(t)}}function D$(){let r={...this.opts};for(let e of T$)delete r[e];return r}var F$={log(){},warn(){},error(){}};function V$(r){if(r===!1)return F$;if(r===void 0)return console;if(r.log&&r.warn&&r.error)return r;throw new Error("logger must implement log, warn and error methods")}var U$=/^[a-z_$][a-z0-9_$:-]*$/i;function z$(r,e){let{RULES:t}=this;if((0,Zc.eachItem)(r,i=>{if(t.keywords[i])throw new Error(`Keyword ${i} is already defined`);if(!U$.test(i))throw new Error(`Keyword ${i} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function Xc(r,e,t){var i;let n=e==null?void 0:e.post;if(t&&n)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:s}=this,o=n?s.post:s.rules.find(({type:c})=>c===t);if(o||(o={type:t,rules:[]},s.rules.push(o)),s.keywords[r]=!0,!e)return;let a={keyword:r,definition:{...e,type:(0,fo.getJSONTypes)(e.type),schemaType:(0,fo.getJSONTypes)(e.schemaType)}};e.before?B$.call(this,o,a,e.before):o.rules.push(a),s.all[r]=a,(i=e.implements)===null||i===void 0||i.forEach(c=>this.addKeyword(c))}function B$(r,e,t){let i=r.rules.findIndex(n=>n.keyword===t);i>=0?r.rules.splice(i,0,e):(r.rules.push(e),this.logger.warn(`rule ${t} is not defined`))}function H$(r){let{metaSchema:e}=r;e!==void 0&&(r.$data&&this.opts.$data&&(e=Zp(e)),r.validateSchema=this.compile(e,!0))}var K$={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Zp(r){return{anyOf:[r,K$]}}});var Qp=$(el=>{"use strict";Object.defineProperty(el,"__esModule",{value:!0});var G$={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};el.default=G$});var mo=$(ri=>{"use strict";Object.defineProperty(ri,"__esModule",{value:!0});ri.callRef=ri.getValidate=void 0;var W$=Ii(),eh=mt(),tt=z(),Ci=ht(),th=On(),po=Y(),J$={keyword:"$ref",schemaType:"string",code(r){let{gen:e,schema:t,it:i}=r,{baseId:n,schemaEnv:s,validateName:o,opts:a,self:c}=i,{root:l}=s;if((t==="#"||t==="#/")&&n===l.baseId)return d();let u=th.resolveRef.call(c,l,n,t);if(u===void 0)throw new W$.default(i.opts.uriResolver,n,t);if(u instanceof th.SchemaEnv)return f(u);return p(u);function d(){if(s===l)return ho(r,o,s,s.$async);let m=e.scopeValue("root",{ref:l});return ho(r,(0,tt._)`${m}.validate`,l,l.$async)}function f(m){let h=rh(r,m);ho(r,h,m,m.$async)}function p(m){let h=e.scopeValue("schema",a.code.source===!0?{ref:m,code:(0,tt.stringify)(m)}:{ref:m}),y=e.name("valid"),b=r.subschema({schema:m,dataTypes:[],schemaPath:tt.nil,topSchemaRef:h,errSchemaPath:t},y);r.mergeEvaluated(b),r.ok(y)}}};function rh(r,e){let{gen:t}=r;return e.validate?t.scopeValue("validate",{ref:e.validate}):(0,tt._)`${t.scopeValue("wrapper",{ref:e})}.validate`}ri.getValidate=rh;function ho(r,e,t,i){let{gen:n,it:s}=r,{allErrors:o,schemaEnv:a,opts:c}=s,l=c.passContext?Ci.default.this:tt.nil;i?u():d();function u(){if(!a.$async)throw new Error("async schema referenced by sync schema");let m=n.let("valid");n.try(()=>{n.code((0,tt._)`await ${(0,eh.callValidateCode)(r,e,l)}`),p(e),o||n.assign(m,!0)},h=>{n.if((0,tt._)`!(${h} instanceof ${s.ValidationError})`,()=>n.throw(h)),f(h),o||n.assign(m,!1)}),r.ok(m)}function d(){r.result((0,eh.callValidateCode)(r,e,l),()=>p(e),()=>f(e))}function f(m){let h=(0,tt._)`${m}.errors`;n.assign(Ci.default.vErrors,(0,tt._)`${Ci.default.vErrors} === null ? ${h} : ${Ci.default.vErrors}.concat(${h})`),n.assign(Ci.default.errors,(0,tt._)`${Ci.default.vErrors}.length`)}function p(m){var h;if(!s.opts.unevaluated)return;let y=(h=t==null?void 0:t.validate)===null||h===void 0?void 0:h.evaluated;if(s.props!==!0)if(y&&!y.dynamicProps)y.props!==void 0&&(s.props=po.mergeEvaluated.props(n,y.props,s.props));else{let b=n.var("props",(0,tt._)`${m}.evaluated.props`);s.props=po.mergeEvaluated.props(n,b,s.props,tt.Name)}if(s.items!==!0)if(y&&!y.dynamicItems)y.items!==void 0&&(s.items=po.mergeEvaluated.items(n,y.items,s.items));else{let b=n.var("items",(0,tt._)`${m}.evaluated.items`);s.items=po.mergeEvaluated.items(n,b,s.items,tt.Name)}}}ri.callRef=ho;ri.default=J$});var rl=$(tl=>{"use strict";Object.defineProperty(tl,"__esModule",{value:!0});var Y$=Qp(),X$=mo(),Z$=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",Y$.default,X$.default];tl.default=Z$});var ih=$(il=>{"use strict";Object.defineProperty(il,"__esModule",{value:!0});var yo=z(),Ir=yo.operators,go={maximum:{okStr:"<=",ok:Ir.LTE,fail:Ir.GT},minimum:{okStr:">=",ok:Ir.GTE,fail:Ir.LT},exclusiveMaximum:{okStr:"<",ok:Ir.LT,fail:Ir.GTE},exclusiveMinimum:{okStr:">",ok:Ir.GT,fail:Ir.LTE}},Q$={message:({keyword:r,schemaCode:e})=>(0,yo.str)`must be ${go[r].okStr} ${e}`,params:({keyword:r,schemaCode:e})=>(0,yo._)`{comparison: ${go[r].okStr}, limit: ${e}}`},eS={keyword:Object.keys(go),type:"number",schemaType:"number",$data:!0,error:Q$,code(r){let{keyword:e,data:t,schemaCode:i}=r;r.fail$data((0,yo._)`${t} ${go[e].fail} ${i} || isNaN(${t})`)}};il.default=eS});var nh=$(nl=>{"use strict";Object.defineProperty(nl,"__esModule",{value:!0});var Ln=z(),tS={message:({schemaCode:r})=>(0,Ln.str)`must be multiple of ${r}`,params:({schemaCode:r})=>(0,Ln._)`{multipleOf: ${r}}`},rS={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:tS,code(r){let{gen:e,data:t,schemaCode:i,it:n}=r,s=n.opts.multipleOfPrecision,o=e.let("res"),a=s?(0,Ln._)`Math.abs(Math.round(${o}) - ${o}) > 1e-${s}`:(0,Ln._)`${o} !== parseInt(${o})`;r.fail$data((0,Ln._)`(${i} === 0 || (${o} = ${t}/${i}, ${a}))`)}};nl.default=rS});var oh=$(sl=>{"use strict";Object.defineProperty(sl,"__esModule",{value:!0});function sh(r){let e=r.length,t=0,i=0,n;for(;i=55296&&n<=56319&&i{"use strict";Object.defineProperty(ol,"__esModule",{value:!0});var ii=z(),iS=Y(),nS=oh(),sS={message({keyword:r,schemaCode:e}){let t=r==="maxLength"?"more":"fewer";return(0,ii.str)`must NOT have ${t} than ${e} characters`},params:({schemaCode:r})=>(0,ii._)`{limit: ${r}}`},oS={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:sS,code(r){let{keyword:e,data:t,schemaCode:i,it:n}=r,s=e==="maxLength"?ii.operators.GT:ii.operators.LT,o=n.opts.unicode===!1?(0,ii._)`${t}.length`:(0,ii._)`${(0,iS.useFunc)(r.gen,nS.default)}(${t})`;r.fail$data((0,ii._)`${o} ${s} ${i}`)}};ol.default=oS});var ch=$(al=>{"use strict";Object.defineProperty(al,"__esModule",{value:!0});var aS=mt(),cS=Y(),Ni=z(),lS={message:({schemaCode:r})=>(0,Ni.str)`must match pattern "${r}"`,params:({schemaCode:r})=>(0,Ni._)`{pattern: ${r}}`},dS={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:lS,code(r){let{gen:e,data:t,$data:i,schema:n,schemaCode:s,it:o}=r,a=o.opts.unicodeRegExp?"u":"";if(i){let{regExp:c}=o.opts.code,l=c.code==="new RegExp"?(0,Ni._)`new RegExp`:(0,cS.useFunc)(e,c),u=e.let("valid");e.try(()=>e.assign(u,(0,Ni._)`${l}(${s}, ${a}).test(${t})`),()=>e.assign(u,!1)),r.fail$data((0,Ni._)`!${u}`)}else{let c=(0,aS.usePattern)(r,n);r.fail$data((0,Ni._)`!${c}.test(${t})`)}}};al.default=dS});var lh=$(cl=>{"use strict";Object.defineProperty(cl,"__esModule",{value:!0});var jn=z(),uS={message({keyword:r,schemaCode:e}){let t=r==="maxProperties"?"more":"fewer";return(0,jn.str)`must NOT have ${t} than ${e} properties`},params:({schemaCode:r})=>(0,jn._)`{limit: ${r}}`},fS={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:uS,code(r){let{keyword:e,data:t,schemaCode:i}=r,n=e==="maxProperties"?jn.operators.GT:jn.operators.LT;r.fail$data((0,jn._)`Object.keys(${t}).length ${n} ${i}`)}};cl.default=fS});var dh=$(ll=>{"use strict";Object.defineProperty(ll,"__esModule",{value:!0});var Dn=mt(),Fn=z(),pS=Y(),hS={message:({params:{missingProperty:r}})=>(0,Fn.str)`must have required property '${r}'`,params:({params:{missingProperty:r}})=>(0,Fn._)`{missingProperty: ${r}}`},mS={keyword:"required",type:"object",schemaType:"array",$data:!0,error:hS,code(r){let{gen:e,schema:t,schemaCode:i,data:n,$data:s,it:o}=r,{opts:a}=o;if(!s&&t.length===0)return;let c=t.length>=a.loopRequired;if(o.allErrors?l():u(),a.strictRequired){let p=r.parentSchema.properties,{definedProperties:m}=r.it;for(let h of t)if((p==null?void 0:p[h])===void 0&&!m.has(h)){let y=o.schemaEnv.baseId+o.errSchemaPath,b=`required property "${h}" is not defined at "${y}" (strictRequired)`;(0,pS.checkStrictMode)(o,b,o.opts.strictRequired)}}function l(){if(c||s)r.block$data(Fn.nil,d);else for(let p of t)(0,Dn.checkReportMissingProp)(r,p)}function u(){let p=e.let("missing");if(c||s){let m=e.let("valid",!0);r.block$data(m,()=>f(p,m)),r.ok(m)}else e.if((0,Dn.checkMissingProp)(r,t,p)),(0,Dn.reportMissingProp)(r,p),e.else()}function d(){e.forOf("prop",i,p=>{r.setParams({missingProperty:p}),e.if((0,Dn.noPropertyInData)(e,n,p,a.ownProperties),()=>r.error())})}function f(p,m){r.setParams({missingProperty:p}),e.forOf(p,i,()=>{e.assign(m,(0,Dn.propertyInData)(e,n,p,a.ownProperties)),e.if((0,Fn.not)(m),()=>{r.error(),e.break()})},Fn.nil)}}};ll.default=mS});var uh=$(dl=>{"use strict";Object.defineProperty(dl,"__esModule",{value:!0});var Vn=z(),yS={message({keyword:r,schemaCode:e}){let t=r==="maxItems"?"more":"fewer";return(0,Vn.str)`must NOT have ${t} than ${e} items`},params:({schemaCode:r})=>(0,Vn._)`{limit: ${r}}`},gS={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:yS,code(r){let{keyword:e,data:t,schemaCode:i}=r,n=e==="maxItems"?Vn.operators.GT:Vn.operators.LT;r.fail$data((0,Vn._)`${t}.length ${n} ${i}`)}};dl.default=gS});var bo=$(ul=>{"use strict";Object.defineProperty(ul,"__esModule",{value:!0});var fh=Oc();fh.code='require("ajv/dist/runtime/equal").default';ul.default=fh});var ph=$(pl=>{"use strict";Object.defineProperty(pl,"__esModule",{value:!0});var fl=Pn(),qe=z(),bS=Y(),_S=bo(),vS={message:({params:{i:r,j:e}})=>(0,qe.str)`must NOT have duplicate items (items ## ${e} and ${r} are identical)`,params:({params:{i:r,j:e}})=>(0,qe._)`{i: ${r}, j: ${e}}`},wS={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:vS,code(r){let{gen:e,data:t,$data:i,schema:n,parentSchema:s,schemaCode:o,it:a}=r;if(!i&&!n)return;let c=e.let("valid"),l=s.items?(0,fl.getSchemaTypes)(s.items):[];r.block$data(c,u,(0,qe._)`${o} === false`),r.ok(c);function u(){let m=e.let("i",(0,qe._)`${t}.length`),h=e.let("j");r.setParams({i:m,j:h}),e.assign(c,!0),e.if((0,qe._)`${m} > 1`,()=>(d()?f:p)(m,h))}function d(){return l.length>0&&!l.some(m=>m==="object"||m==="array")}function f(m,h){let y=e.name("item"),b=(0,fl.checkDataTypes)(l,y,a.opts.strictNumbers,fl.DataType.Wrong),g=e.const("indices",(0,qe._)`{}`);e.for((0,qe._)`;${m}--;`,()=>{e.let(y,(0,qe._)`${t}[${m}]`),e.if(b,(0,qe._)`continue`),l.length>1&&e.if((0,qe._)`typeof ${y} == "string"`,(0,qe._)`${y} += "_"`),e.if((0,qe._)`typeof ${g}[${y}] == "number"`,()=>{e.assign(h,(0,qe._)`${g}[${y}]`),r.error(),e.assign(c,!1).break()}).code((0,qe._)`${g}[${y}] = ${m}`)})}function p(m,h){let y=(0,bS.useFunc)(e,_S.default),b=e.name("outer");e.label(b).for((0,qe._)`;${m}--;`,()=>e.for((0,qe._)`${h} = ${m}; ${h}--;`,()=>e.if((0,qe._)`${y}(${t}[${m}], ${t}[${h}])`,()=>{r.error(),e.assign(c,!1).break(b)})))}}};pl.default=wS});var hh=$(ml=>{"use strict";Object.defineProperty(ml,"__esModule",{value:!0});var hl=z(),$S=Y(),SS=bo(),ES={message:"must be equal to constant",params:({schemaCode:r})=>(0,hl._)`{allowedValue: ${r}}`},AS={keyword:"const",$data:!0,error:ES,code(r){let{gen:e,data:t,$data:i,schemaCode:n,schema:s}=r;i||s&&typeof s=="object"?r.fail$data((0,hl._)`!${(0,$S.useFunc)(e,SS.default)}(${t}, ${n})`):r.fail((0,hl._)`${s} !== ${t}`)}};ml.default=AS});var mh=$(yl=>{"use strict";Object.defineProperty(yl,"__esModule",{value:!0});var Un=z(),kS=Y(),PS=bo(),xS={message:"must be equal to one of the allowed values",params:({schemaCode:r})=>(0,Un._)`{allowedValues: ${r}}`},IS={keyword:"enum",schemaType:"array",$data:!0,error:xS,code(r){let{gen:e,data:t,$data:i,schema:n,schemaCode:s,it:o}=r;if(!i&&n.length===0)throw new Error("enum must have non-empty array");let a=n.length>=o.opts.loopEnum,c,l=()=>c!=null?c:c=(0,kS.useFunc)(e,PS.default),u;if(a||i)u=e.let("valid"),r.block$data(u,d);else{if(!Array.isArray(n))throw new Error("ajv implementation error");let p=e.const("vSchema",s);u=(0,Un.or)(...n.map((m,h)=>f(p,h)))}r.pass(u);function d(){e.assign(u,!1),e.forOf("v",s,p=>e.if((0,Un._)`${l()}(${t}, ${p})`,()=>e.assign(u,!0).break()))}function f(p,m){let h=n[m];return typeof h=="object"&&h!==null?(0,Un._)`${l()}(${t}, ${p}[${m}])`:(0,Un._)`${t} === ${h}`}}};yl.default=IS});var bl=$(gl=>{"use strict";Object.defineProperty(gl,"__esModule",{value:!0});var RS=ih(),TS=nh(),OS=ah(),CS=ch(),NS=lh(),MS=dh(),qS=uh(),LS=ph(),jS=hh(),DS=mh(),FS=[RS.default,TS.default,OS.default,CS.default,NS.default,MS.default,qS.default,LS.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},jS.default,DS.default];gl.default=FS});var vl=$(zn=>{"use strict";Object.defineProperty(zn,"__esModule",{value:!0});zn.validateAdditionalItems=void 0;var ni=z(),_l=Y(),VS={message:({params:{len:r}})=>(0,ni.str)`must NOT have more than ${r} items`,params:({params:{len:r}})=>(0,ni._)`{limit: ${r}}`},US={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:VS,code(r){let{parentSchema:e,it:t}=r,{items:i}=e;if(!Array.isArray(i)){(0,_l.checkStrictMode)(t,'"additionalItems" is ignored when "items" is not an array of schemas');return}yh(r,i)}};function yh(r,e){let{gen:t,schema:i,data:n,keyword:s,it:o}=r;o.items=!0;let a=t.const("len",(0,ni._)`${n}.length`);if(i===!1)r.setParams({len:e.length}),r.pass((0,ni._)`${a} <= ${e.length}`);else if(typeof i=="object"&&!(0,_l.alwaysValidSchema)(o,i)){let l=t.var("valid",(0,ni._)`${a} <= ${e.length}`);t.if((0,ni.not)(l),()=>c(l)),r.ok(l)}function c(l){t.forRange("i",e.length,a,u=>{r.subschema({keyword:s,dataProp:u,dataPropType:_l.Type.Num},l),o.allErrors||t.if((0,ni.not)(l),()=>t.break())})}}zn.validateAdditionalItems=yh;zn.default=US});var wl=$(Bn=>{"use strict";Object.defineProperty(Bn,"__esModule",{value:!0});Bn.validateTuple=void 0;var gh=z(),_o=Y(),zS=mt(),BS={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(r){let{schema:e,it:t}=r;if(Array.isArray(e))return bh(r,"additionalItems",e);t.items=!0,!(0,_o.alwaysValidSchema)(t,e)&&r.ok((0,zS.validateArray)(r))}};function bh(r,e,t=r.schema){let{gen:i,parentSchema:n,data:s,keyword:o,it:a}=r;u(n),a.opts.unevaluated&&t.length&&a.items!==!0&&(a.items=_o.mergeEvaluated.items(i,t.length,a.items));let c=i.name("valid"),l=i.const("len",(0,gh._)`${s}.length`);t.forEach((d,f)=>{(0,_o.alwaysValidSchema)(a,d)||(i.if((0,gh._)`${l} > ${f}`,()=>r.subschema({keyword:o,schemaProp:f,dataProp:f},c)),r.ok(c))});function u(d){let{opts:f,errSchemaPath:p}=a,m=t.length,h=m===d.minItems&&(m===d.maxItems||d[e]===!1);if(f.strictTuples&&!h){let y=`"${o}" is ${m}-tuple, but minItems or maxItems/${e} are not specified or different at path "${p}"`;(0,_o.checkStrictMode)(a,y,f.strictTuples)}}}Bn.validateTuple=bh;Bn.default=BS});var _h=$($l=>{"use strict";Object.defineProperty($l,"__esModule",{value:!0});var HS=wl(),KS={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:r=>(0,HS.validateTuple)(r,"items")};$l.default=KS});var wh=$(Sl=>{"use strict";Object.defineProperty(Sl,"__esModule",{value:!0});var vh=z(),GS=Y(),WS=mt(),JS=vl(),YS={message:({params:{len:r}})=>(0,vh.str)`must NOT have more than ${r} items`,params:({params:{len:r}})=>(0,vh._)`{limit: ${r}}`},XS={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:YS,code(r){let{schema:e,parentSchema:t,it:i}=r,{prefixItems:n}=t;i.items=!0,!(0,GS.alwaysValidSchema)(i,e)&&(n?(0,JS.validateAdditionalItems)(r,n):r.ok((0,WS.validateArray)(r)))}};Sl.default=XS});var $h=$(El=>{"use strict";Object.defineProperty(El,"__esModule",{value:!0});var gt=z(),vo=Y(),ZS={message:({params:{min:r,max:e}})=>e===void 0?(0,gt.str)`must contain at least ${r} valid item(s)`:(0,gt.str)`must contain at least ${r} and no more than ${e} valid item(s)`,params:({params:{min:r,max:e}})=>e===void 0?(0,gt._)`{minContains: ${r}}`:(0,gt._)`{minContains: ${r}, maxContains: ${e}}`},QS={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:ZS,code(r){let{gen:e,schema:t,parentSchema:i,data:n,it:s}=r,o,a,{minContains:c,maxContains:l}=i;s.opts.next?(o=c===void 0?1:c,a=l):o=1;let u=e.const("len",(0,gt._)`${n}.length`);if(r.setParams({min:o,max:a}),a===void 0&&o===0){(0,vo.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&o>a){(0,vo.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),r.fail();return}if((0,vo.alwaysValidSchema)(s,t)){let h=(0,gt._)`${u} >= ${o}`;a!==void 0&&(h=(0,gt._)`${h} && ${u} <= ${a}`),r.pass(h);return}s.items=!0;let d=e.name("valid");a===void 0&&o===1?p(d,()=>e.if(d,()=>e.break())):o===0?(e.let(d,!0),a!==void 0&&e.if((0,gt._)`${n}.length > 0`,f)):(e.let(d,!1),f()),r.result(d,()=>r.reset());function f(){let h=e.name("_valid"),y=e.let("count",0);p(h,()=>e.if(h,()=>m(y)))}function p(h,y){e.forRange("i",0,u,b=>{r.subschema({keyword:"contains",dataProp:b,dataPropType:vo.Type.Num,compositeRule:!0},h),y()})}function m(h){e.code((0,gt._)`${h}++`),a===void 0?e.if((0,gt._)`${h} >= ${o}`,()=>e.assign(d,!0).break()):(e.if((0,gt._)`${h} > ${a}`,()=>e.assign(d,!1).break()),o===1?e.assign(d,!0):e.if((0,gt._)`${h} >= ${o}`,()=>e.assign(d,!0)))}}};El.default=QS});var wo=$(Ht=>{"use strict";Object.defineProperty(Ht,"__esModule",{value:!0});Ht.validateSchemaDeps=Ht.validatePropertyDeps=Ht.error=void 0;var Al=z(),eE=Y(),Hn=mt();Ht.error={message:({params:{property:r,depsCount:e,deps:t}})=>{let i=e===1?"property":"properties";return(0,Al.str)`must have ${i} ${t} when property ${r} is present`},params:({params:{property:r,depsCount:e,deps:t,missingProperty:i}})=>(0,Al._)`{property: ${r}, - missingProperty: ${i}, +var U0=Object.create;var fs=Object.defineProperty;var B0=Object.getOwnPropertyDescriptor;var H0=Object.getOwnPropertyNames;var z0=Object.getPrototypeOf,K0=Object.prototype.hasOwnProperty;var G0=(r,e,t)=>e in r?fs(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var $=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),W0=(r,e)=>{for(var t in e)fs(r,t,{get:e[t],enumerable:!0})},af=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of H0(e))!K0.call(r,s)&&s!==t&&fs(r,s,{get:()=>e[s],enumerable:!(n=B0(e,s))||n.enumerable});return r};var Hr=(r,e,t)=>(t=r!=null?U0(z0(r)):{},af(e||!r||!r.__esModule?fs(t,"default",{value:r,enumerable:!0}):t,r)),J0=r=>af(fs({},"__esModule",{value:!0}),r);var P=(r,e,t)=>G0(r,typeof e!="symbol"?e+"":e,t);var ys=$(se=>{"use strict";Object.defineProperty(se,"__esModule",{value:!0});se.regexpCode=se.getEsmExportName=se.getProperty=se.safeStringify=se.stringify=se.strConcat=se.addCodeArg=se.str=se._=se.nil=se._Code=se.Name=se.IDENTIFIER=se._CodeOrName=void 0;var hs=class{};se._CodeOrName=hs;se.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var zr=class extends hs{constructor(e){if(super(),!se.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};se.Name=zr;var ut=class extends hs{constructor(e){super(),this._items=typeof e=="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((t,n)=>`${t}${n}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((t,n)=>(n instanceof zr&&(t[n.str]=(t[n.str]||0)+1),t),{})}};se._Code=ut;se.nil=new ut("");function cf(r,...e){let t=[r[0]],n=0;for(;n{"use strict";Object.defineProperty(Xe,"__esModule",{value:!0});Xe.ValueScope=Xe.ValueScopeName=Xe.Scope=Xe.varKinds=Xe.UsedValueState=void 0;var Ye=ys(),Ha=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},ji;(function(r){r[r.Started=0]="Started",r[r.Completed=1]="Completed"})(ji||(Xe.UsedValueState=ji={}));Xe.varKinds={const:new Ye.Name("const"),let:new Ye.Name("let"),var:new Ye.Name("var")};var Fi=class{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t}toName(e){return e instanceof Ye.Name?e:this.name(e)}name(e){return new Ye.Name(this._newName(e))}_newName(e){let t=this._names[e]||this._nameGroup(e);return`${e}${t.index++}`}_nameGroup(e){var t,n;if(!((n=(t=this._parent)===null||t===void 0?void 0:t._prefixes)===null||n===void 0)&&n.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};Xe.Scope=Fi;var Vi=class extends Ye.Name{constructor(e,t){super(t),this.prefix=e}setValue(e,{property:t,itemIndex:n}){this.value=e,this.scopePath=(0,Ye._)`.${new Ye.Name(t)}[${n}]`}};Xe.ValueScopeName=Vi;var sw=(0,Ye._)`\n`,za=class extends Fi{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?sw:Ye.nil}}get(){return this._scope}name(e){return new Vi(e,this._newName(e))}value(e,t){var n;if(t.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let s=this.toName(e),{prefix:i}=s,o=(n=t.key)!==null&&n!==void 0?n:t.ref,a=this._values[i];if(a){let u=a.get(o);if(u)return u}else a=this._values[i]=new Map;a.set(o,s);let c=this._scope[i]||(this._scope[i]=[]),l=c.length;return c[l]=t.ref,s.setValue(t,{property:i,itemIndex:l}),s}getValue(e,t){let n=this._values[e];if(n)return n.get(t)}scopeRefs(e,t=this._values){return this._reduceValues(t,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,Ye._)`${e}${n.scopePath}`})}scopeCode(e=this._values,t,n){return this._reduceValues(e,s=>{if(s.value===void 0)throw new Error(`CodeGen: name "${s}" has no value`);return s.value.code},t,n)}_reduceValues(e,t,n={},s){let i=Ye.nil;for(let o in e){let a=e[o];if(!a)continue;let c=n[o]=n[o]||new Map;a.forEach(l=>{if(c.has(l))return;c.set(l,ji.Started);let u=t(l);if(u){let d=this.opts.es5?Xe.varKinds.var:Xe.varKinds.const;i=(0,Ye._)`${i}${d} ${l} = ${u};${this.opts._n}`}else if(u=s==null?void 0:s(l))i=(0,Ye._)`${i}${u}${this.opts._n}`;else throw new Ha(l);c.set(l,ji.Completed)})}return i}};Xe.ValueScope=za});var B=$(W=>{"use strict";Object.defineProperty(W,"__esModule",{value:!0});W.or=W.and=W.not=W.CodeGen=W.operators=W.varKinds=W.ValueScopeName=W.ValueScope=W.Scope=W.Name=W.regexpCode=W.stringify=W.getProperty=W.nil=W.strConcat=W.str=W._=void 0;var te=ys(),vt=Ka(),vr=ys();Object.defineProperty(W,"_",{enumerable:!0,get:function(){return vr._}});Object.defineProperty(W,"str",{enumerable:!0,get:function(){return vr.str}});Object.defineProperty(W,"strConcat",{enumerable:!0,get:function(){return vr.strConcat}});Object.defineProperty(W,"nil",{enumerable:!0,get:function(){return vr.nil}});Object.defineProperty(W,"getProperty",{enumerable:!0,get:function(){return vr.getProperty}});Object.defineProperty(W,"stringify",{enumerable:!0,get:function(){return vr.stringify}});Object.defineProperty(W,"regexpCode",{enumerable:!0,get:function(){return vr.regexpCode}});Object.defineProperty(W,"Name",{enumerable:!0,get:function(){return vr.Name}});var zi=Ka();Object.defineProperty(W,"Scope",{enumerable:!0,get:function(){return zi.Scope}});Object.defineProperty(W,"ValueScope",{enumerable:!0,get:function(){return zi.ValueScope}});Object.defineProperty(W,"ValueScopeName",{enumerable:!0,get:function(){return zi.ValueScopeName}});Object.defineProperty(W,"varKinds",{enumerable:!0,get:function(){return zi.varKinds}});W.operators={GT:new te._Code(">"),GTE:new te._Code(">="),LT:new te._Code("<"),LTE:new te._Code("<="),EQ:new te._Code("==="),NEQ:new te._Code("!=="),NOT:new te._Code("!"),OR:new te._Code("||"),AND:new te._Code("&&"),ADD:new te._Code("+")};var rr=class{optimizeNodes(){return this}optimizeNames(e,t){return this}},Ga=class extends rr{constructor(e,t,n){super(),this.varKind=e,this.name=t,this.rhs=n}render({es5:e,_n:t}){let n=e?vt.varKinds.var:this.varKind,s=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${s};`+t}optimizeNames(e,t){if(e[this.name.str])return this.rhs&&(this.rhs=bn(this.rhs,e,t)),this}get names(){return this.rhs instanceof te._CodeOrName?this.rhs.names:{}}},Ui=class extends rr{constructor(e,t,n){super(),this.lhs=e,this.rhs=t,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,t){if(!(this.lhs instanceof te.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=bn(this.rhs,e,t),this}get names(){let e=this.lhs instanceof te.Name?{}:{...this.lhs.names};return Hi(e,this.rhs)}},Wa=class extends Ui{constructor(e,t,n,s){super(e,n,s),this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Ja=class extends rr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Ya=class extends rr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Xa=class extends rr{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Qa=class extends rr{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,t){return this.code=bn(this.code,e,t),this}get names(){return this.code instanceof te._CodeOrName?this.code.names:{}}},gs=class extends rr{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((t,n)=>t+n.render(e),"")}optimizeNodes(){let{nodes:e}=this,t=e.length;for(;t--;){let n=e[t].optimizeNodes();Array.isArray(n)?e.splice(t,1,...n):n?e[t]=n:e.splice(t,1)}return e.length>0?this:void 0}optimizeNames(e,t){let{nodes:n}=this,s=n.length;for(;s--;){let i=n[s];i.optimizeNames(e,t)||(iw(e,i.names),n.splice(s,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>Wr(e,t.names),{})}},nr=class extends gs{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Za=class extends gs{},gn=class extends nr{};gn.kind="else";var Kr=class r extends nr{constructor(e,t){super(t),this.condition=e}render(e){let t=`if(${this.condition})`+super.render(e);return this.else&&(t+="else "+this.else.render(e)),t}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let t=this.else;if(t){let n=t.optimizeNodes();t=this.else=Array.isArray(n)?new gn(n):n}if(t)return e===!1?t instanceof r?t:t.nodes:this.nodes.length?this:new r(df(e),t instanceof r?[t]:t.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,t){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(e,t),!!(super.optimizeNames(e,t)||this.else))return this.condition=bn(this.condition,e,t),this}get names(){let e=super.names;return Hi(e,this.condition),this.else&&Wr(e,this.else.names),e}};Kr.kind="if";var Gr=class extends nr{};Gr.kind="for";var ec=class extends Gr{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iteration=bn(this.iteration,e,t),this}get names(){return Wr(super.names,this.iteration.names)}},tc=class extends Gr{constructor(e,t,n,s){super(),this.varKind=e,this.name=t,this.from=n,this.to=s}render(e){let t=e.es5?vt.varKinds.var:this.varKind,{name:n,from:s,to:i}=this;return`for(${t} ${n}=${s}; ${n}<${i}; ${n}++)`+super.render(e)}get names(){let e=Hi(super.names,this.from);return Hi(e,this.to)}},Bi=class extends Gr{constructor(e,t,n,s){super(),this.loop=e,this.varKind=t,this.name=n,this.iterable=s}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iterable=bn(this.iterable,e,t),this}get names(){return Wr(super.names,this.iterable.names)}},bs=class extends nr{constructor(e,t,n){super(),this.name=e,this.args=t,this.async=n}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};bs.kind="func";var ws=class extends gs{render(e){return"return "+super.render(e)}};ws.kind="return";var rc=class extends nr{render(e){let t="try"+super.render(e);return this.catch&&(t+=this.catch.render(e)),this.finally&&(t+=this.finally.render(e)),t}optimizeNodes(){var e,t;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(t=this.finally)===null||t===void 0||t.optimizeNodes(),this}optimizeNames(e,t){var n,s;return super.optimizeNames(e,t),(n=this.catch)===null||n===void 0||n.optimizeNames(e,t),(s=this.finally)===null||s===void 0||s.optimizeNames(e,t),this}get names(){let e=super.names;return this.catch&&Wr(e,this.catch.names),this.finally&&Wr(e,this.finally.names),e}},_s=class extends nr{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};_s.kind="catch";var vs=class extends nr{render(e){return"finally"+super.render(e)}};vs.kind="finally";var nc=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?` +`:""},this._extScope=e,this._scope=new vt.Scope({parent:e}),this._nodes=[new Za]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,t){let n=this._extScope.value(e,t);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,t){return this._extScope.getValue(e,t)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,t,n,s){let i=this._scope.toName(t);return n!==void 0&&s&&(this._constants[i.str]=n),this._leafNode(new Ga(e,i,n)),i}const(e,t,n){return this._def(vt.varKinds.const,e,t,n)}let(e,t,n){return this._def(vt.varKinds.let,e,t,n)}var(e,t,n){return this._def(vt.varKinds.var,e,t,n)}assign(e,t,n){return this._leafNode(new Ui(e,t,n))}add(e,t){return this._leafNode(new Wa(e,W.operators.ADD,t))}code(e){return typeof e=="function"?e():e!==te.nil&&this._leafNode(new Qa(e)),this}object(...e){let t=["{"];for(let[n,s]of e)t.length>1&&t.push(","),t.push(n),(n!==s||this.opts.es5)&&(t.push(":"),(0,te.addCodeArg)(t,s));return t.push("}"),new te._Code(t)}if(e,t,n){if(this._blockNode(new Kr(e)),t&&n)this.code(t).else().code(n).endIf();else if(t)this.code(t).endIf();else if(n)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new Kr(e))}else(){return this._elseNode(new gn)}endIf(){return this._endBlockNode(Kr,gn)}_for(e,t){return this._blockNode(e),t&&this.code(t).endFor(),this}for(e,t){return this._for(new ec(e),t)}forRange(e,t,n,s,i=this.opts.es5?vt.varKinds.var:vt.varKinds.let){let o=this._scope.toName(e);return this._for(new tc(i,o,t,n),()=>s(o))}forOf(e,t,n,s=vt.varKinds.const){let i=this._scope.toName(e);if(this.opts.es5){let o=t instanceof te.Name?t:this.var("_arr",t);return this.forRange("_i",0,(0,te._)`${o}.length`,a=>{this.var(i,(0,te._)`${o}[${a}]`),n(i)})}return this._for(new Bi("of",s,i,t),()=>n(i))}forIn(e,t,n,s=this.opts.es5?vt.varKinds.var:vt.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,te._)`Object.keys(${t})`,n);let i=this._scope.toName(e);return this._for(new Bi("in",s,i,t),()=>n(i))}endFor(){return this._endBlockNode(Gr)}label(e){return this._leafNode(new Ja(e))}break(e){return this._leafNode(new Ya(e))}return(e){let t=new ws;if(this._blockNode(t),this.code(e),t.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(ws)}try(e,t,n){if(!t&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let s=new rc;if(this._blockNode(s),this.code(e),t){let i=this.name("e");this._currNode=s.catch=new _s(i),t(i)}return n&&(this._currNode=s.finally=new vs,this.code(n)),this._endBlockNode(_s,vs)}throw(e){return this._leafNode(new Xa(e))}block(e,t){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(t),this}endBlock(e){let t=this._blockStarts.pop();if(t===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-t;if(n<0||e!==void 0&&n!==e)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=t,this}func(e,t=te.nil,n,s){return this._blockNode(new bs(e,t,n)),s&&this.code(s).endFunc(),this}endFunc(){return this._endBlockNode(bs)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,t){let n=this._currNode;if(n instanceof e||t&&n instanceof t)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${t?`${e.kind}/${t.kind}`:e.kind}"`)}_elseNode(e){let t=this._currNode;if(!(t instanceof Kr))throw new Error('CodeGen: "else" without "if"');return this._currNode=t.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let t=this._nodes;t[t.length-1]=e}};W.CodeGen=nc;function Wr(r,e){for(let t in e)r[t]=(r[t]||0)+(e[t]||0);return r}function Hi(r,e){return e instanceof te._CodeOrName?Wr(r,e.names):r}function bn(r,e,t){if(r instanceof te.Name)return n(r);if(!s(r))return r;return new te._Code(r._items.reduce((i,o)=>(o instanceof te.Name&&(o=n(o)),o instanceof te._Code?i.push(...o._items):i.push(o),i),[]));function n(i){let o=t[i.str];return o===void 0||e[i.str]!==1?i:(delete e[i.str],o)}function s(i){return i instanceof te._Code&&i._items.some(o=>o instanceof te.Name&&e[o.str]===1&&t[o.str]!==void 0)}}function iw(r,e){for(let t in e)r[t]=(r[t]||0)-(e[t]||0)}function df(r){return typeof r=="boolean"||typeof r=="number"||r===null?!r:(0,te._)`!${sc(r)}`}W.not=df;var ow=uf(W.operators.AND);function aw(...r){return r.reduce(ow)}W.and=aw;var cw=uf(W.operators.OR);function lw(...r){return r.reduce(cw)}W.or=lw;function uf(r){return(e,t)=>e===te.nil?t:t===te.nil?e:(0,te._)`${sc(e)} ${r} ${sc(t)}`}function sc(r){return r instanceof te.Name?r:(0,te._)`(${r})`}});var Y=$(J=>{"use strict";Object.defineProperty(J,"__esModule",{value:!0});J.checkStrictMode=J.getErrorPath=J.Type=J.useFunc=J.setEvaluated=J.evaluatedPropsToName=J.mergeEvaluated=J.eachItem=J.unescapeJsonPointer=J.escapeJsonPointer=J.escapeFragment=J.unescapeFragment=J.schemaRefOrVal=J.schemaHasRulesButRef=J.schemaHasRules=J.checkUnknownRules=J.alwaysValidSchema=J.toHash=void 0;var de=B(),dw=ys();function uw(r){let e={};for(let t of r)e[t]=!0;return e}J.toHash=uw;function fw(r,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(hf(r,e),!mf(e,r.self.RULES.all))}J.alwaysValidSchema=fw;function hf(r,e=r.schema){let{opts:t,self:n}=r;if(!t.strictSchema||typeof e=="boolean")return;let s=n.RULES.keywords;for(let i in e)s[i]||bf(r,`unknown keyword: "${i}"`)}J.checkUnknownRules=hf;function mf(r,e){if(typeof r=="boolean")return!r;for(let t in r)if(e[t])return!0;return!1}J.schemaHasRules=mf;function pw(r,e){if(typeof r=="boolean")return!r;for(let t in r)if(t!=="$ref"&&e.all[t])return!0;return!1}J.schemaHasRulesButRef=pw;function hw({topSchemaRef:r,schemaPath:e},t,n,s){if(!s){if(typeof t=="number"||typeof t=="boolean")return t;if(typeof t=="string")return(0,de._)`${t}`}return(0,de._)`${r}${e}${(0,de.getProperty)(n)}`}J.schemaRefOrVal=hw;function mw(r){return yf(decodeURIComponent(r))}J.unescapeFragment=mw;function yw(r){return encodeURIComponent(oc(r))}J.escapeFragment=yw;function oc(r){return typeof r=="number"?`${r}`:r.replace(/~/g,"~0").replace(/\//g,"~1")}J.escapeJsonPointer=oc;function yf(r){return r.replace(/~1/g,"/").replace(/~0/g,"~")}J.unescapeJsonPointer=yf;function gw(r,e){if(Array.isArray(r))for(let t of r)e(t);else e(r)}J.eachItem=gw;function ff({mergeNames:r,mergeToName:e,mergeValues:t,resultToName:n}){return(s,i,o,a)=>{let c=o===void 0?i:o instanceof de.Name?(i instanceof de.Name?r(s,i,o):e(s,i,o),o):i instanceof de.Name?(e(s,o,i),i):t(i,o);return a===de.Name&&!(c instanceof de.Name)?n(s,c):c}}J.mergeEvaluated={props:ff({mergeNames:(r,e,t)=>r.if((0,de._)`${t} !== true && ${e} !== undefined`,()=>{r.if((0,de._)`${e} === true`,()=>r.assign(t,!0),()=>r.assign(t,(0,de._)`${t} || {}`).code((0,de._)`Object.assign(${t}, ${e})`))}),mergeToName:(r,e,t)=>r.if((0,de._)`${t} !== true`,()=>{e===!0?r.assign(t,!0):(r.assign(t,(0,de._)`${t} || {}`),ac(r,t,e))}),mergeValues:(r,e)=>r===!0?!0:{...r,...e},resultToName:gf}),items:ff({mergeNames:(r,e,t)=>r.if((0,de._)`${t} !== true && ${e} !== undefined`,()=>r.assign(t,(0,de._)`${e} === true ? true : ${t} > ${e} ? ${t} : ${e}`)),mergeToName:(r,e,t)=>r.if((0,de._)`${t} !== true`,()=>r.assign(t,e===!0?!0:(0,de._)`${t} > ${e} ? ${t} : ${e}`)),mergeValues:(r,e)=>r===!0?!0:Math.max(r,e),resultToName:(r,e)=>r.var("items",e)})};function gf(r,e){if(e===!0)return r.var("props",!0);let t=r.var("props",(0,de._)`{}`);return e!==void 0&&ac(r,t,e),t}J.evaluatedPropsToName=gf;function ac(r,e,t){Object.keys(t).forEach(n=>r.assign((0,de._)`${e}${(0,de.getProperty)(n)}`,!0))}J.setEvaluated=ac;var pf={};function bw(r,e){return r.scopeValue("func",{ref:e,code:pf[e.code]||(pf[e.code]=new dw._Code(e.code))})}J.useFunc=bw;var ic;(function(r){r[r.Num=0]="Num",r[r.Str=1]="Str"})(ic||(J.Type=ic={}));function ww(r,e,t){if(r instanceof de.Name){let n=e===ic.Num;return t?n?(0,de._)`"[" + ${r} + "]"`:(0,de._)`"['" + ${r} + "']"`:n?(0,de._)`"/" + ${r}`:(0,de._)`"/" + ${r}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return t?(0,de.getProperty)(r).toString():"/"+oc(r)}J.getErrorPath=ww;function bf(r,e,t=r.opts.strictSchema){if(t){if(e=`strict mode: ${e}`,t===!0)throw new Error(e);r.self.logger.warn(e)}}J.checkStrictMode=bf});var ft=$(cc=>{"use strict";Object.defineProperty(cc,"__esModule",{value:!0});var De=B(),_w={data:new De.Name("data"),valCxt:new De.Name("valCxt"),instancePath:new De.Name("instancePath"),parentData:new De.Name("parentData"),parentDataProperty:new De.Name("parentDataProperty"),rootData:new De.Name("rootData"),dynamicAnchors:new De.Name("dynamicAnchors"),vErrors:new De.Name("vErrors"),errors:new De.Name("errors"),this:new De.Name("this"),self:new De.Name("self"),scope:new De.Name("scope"),json:new De.Name("json"),jsonPos:new De.Name("jsonPos"),jsonLen:new De.Name("jsonLen"),jsonPart:new De.Name("jsonPart")};cc.default=_w});var $s=$(je=>{"use strict";Object.defineProperty(je,"__esModule",{value:!0});je.extendErrors=je.resetErrorsCount=je.reportExtraError=je.reportError=je.keyword$DataError=je.keywordError=void 0;var ne=B(),Ki=Y(),He=ft();je.keywordError={message:({keyword:r})=>(0,ne.str)`must pass "${r}" keyword validation`};je.keyword$DataError={message:({keyword:r,schemaType:e})=>e?(0,ne.str)`"${r}" keyword must be ${e} ($data)`:(0,ne.str)`"${r}" keyword is invalid ($data)`};function vw(r,e=je.keywordError,t,n){let{it:s}=r,{gen:i,compositeRule:o,allErrors:a}=s,c=vf(r,e,t);(n!=null?n:o||a)?wf(i,c):_f(s,(0,ne._)`[${c}]`)}je.reportError=vw;function $w(r,e=je.keywordError,t){let{it:n}=r,{gen:s,compositeRule:i,allErrors:o}=n,a=vf(r,e,t);wf(s,a),i||o||_f(n,He.default.vErrors)}je.reportExtraError=$w;function Sw(r,e){r.assign(He.default.errors,e),r.if((0,ne._)`${He.default.vErrors} !== null`,()=>r.if(e,()=>r.assign((0,ne._)`${He.default.vErrors}.length`,e),()=>r.assign(He.default.vErrors,null)))}je.resetErrorsCount=Sw;function Ew({gen:r,keyword:e,schemaValue:t,data:n,errsCount:s,it:i}){if(s===void 0)throw new Error("ajv implementation error");let o=r.name("err");r.forRange("i",s,He.default.errors,a=>{r.const(o,(0,ne._)`${He.default.vErrors}[${a}]`),r.if((0,ne._)`${o}.instancePath === undefined`,()=>r.assign((0,ne._)`${o}.instancePath`,(0,ne.strConcat)(He.default.instancePath,i.errorPath))),r.assign((0,ne._)`${o}.schemaPath`,(0,ne.str)`${i.errSchemaPath}/${e}`),i.opts.verbose&&(r.assign((0,ne._)`${o}.schema`,t),r.assign((0,ne._)`${o}.data`,n))})}je.extendErrors=Ew;function wf(r,e){let t=r.const("err",e);r.if((0,ne._)`${He.default.vErrors} === null`,()=>r.assign(He.default.vErrors,(0,ne._)`[${t}]`),(0,ne._)`${He.default.vErrors}.push(${t})`),r.code((0,ne._)`${He.default.errors}++`)}function _f(r,e){let{gen:t,validateName:n,schemaEnv:s}=r;s.$async?t.throw((0,ne._)`new ${r.ValidationError}(${e})`):(t.assign((0,ne._)`${n}.errors`,e),t.return(!1))}var Jr={keyword:new ne.Name("keyword"),schemaPath:new ne.Name("schemaPath"),params:new ne.Name("params"),propertyName:new ne.Name("propertyName"),message:new ne.Name("message"),schema:new ne.Name("schema"),parentSchema:new ne.Name("parentSchema")};function vf(r,e,t){let{createErrors:n}=r.it;return n===!1?(0,ne._)`{}`:Aw(r,e,t)}function Aw(r,e,t={}){let{gen:n,it:s}=r,i=[kw(s,t),xw(r,t)];return Iw(r,e,i),n.object(...i)}function kw({errorPath:r},{instancePath:e}){let t=e?(0,ne.str)`${r}${(0,Ki.getErrorPath)(e,Ki.Type.Str)}`:r;return[He.default.instancePath,(0,ne.strConcat)(He.default.instancePath,t)]}function xw({keyword:r,it:{errSchemaPath:e}},{schemaPath:t,parentSchema:n}){let s=n?e:(0,ne.str)`${e}/${r}`;return t&&(s=(0,ne.str)`${s}${(0,Ki.getErrorPath)(t,Ki.Type.Str)}`),[Jr.schemaPath,s]}function Iw(r,{params:e,message:t},n){let{keyword:s,data:i,schemaValue:o,it:a}=r,{opts:c,propertyName:l,topSchemaRef:u,schemaPath:d}=a;n.push([Jr.keyword,s],[Jr.params,typeof e=="function"?e(r):e||(0,ne._)`{}`]),c.messages&&n.push([Jr.message,typeof t=="function"?t(r):t]),c.verbose&&n.push([Jr.schema,o],[Jr.parentSchema,(0,ne._)`${u}${d}`],[He.default.data,i]),l&&n.push([Jr.propertyName,l])}});var Sf=$(wn=>{"use strict";Object.defineProperty(wn,"__esModule",{value:!0});wn.boolOrEmptySchema=wn.topBoolOrEmptySchema=void 0;var Tw=$s(),Pw=B(),Ow=ft(),Rw={message:"boolean schema is false"};function Cw(r){let{gen:e,schema:t,validateName:n}=r;t===!1?$f(r,!1):typeof t=="object"&&t.$async===!0?e.return(Ow.default.data):(e.assign((0,Pw._)`${n}.errors`,null),e.return(!0))}wn.topBoolOrEmptySchema=Cw;function Nw(r,e){let{gen:t,schema:n}=r;n===!1?(t.var(e,!1),$f(r)):t.var(e,!0)}wn.boolOrEmptySchema=Nw;function $f(r,e){let{gen:t,data:n}=r,s={gen:t,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:r};(0,Tw.reportError)(s,Rw,void 0,e)}});var lc=$(_n=>{"use strict";Object.defineProperty(_n,"__esModule",{value:!0});_n.getRules=_n.isJSONType=void 0;var Mw=["string","number","integer","boolean","null","object","array"],Lw=new Set(Mw);function qw(r){return typeof r=="string"&&Lw.has(r)}_n.isJSONType=qw;function Dw(){let r={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...r,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},r.number,r.string,r.array,r.object],post:{rules:[]},all:{},keywords:{}}}_n.getRules=Dw});var dc=$($r=>{"use strict";Object.defineProperty($r,"__esModule",{value:!0});$r.shouldUseRule=$r.shouldUseGroup=$r.schemaHasRulesForType=void 0;function jw({schema:r,self:e},t){let n=e.RULES.types[t];return n&&n!==!0&&Ef(r,n)}$r.schemaHasRulesForType=jw;function Ef(r,e){return e.rules.some(t=>Af(r,t))}$r.shouldUseGroup=Ef;function Af(r,e){var t;return r[e.keyword]!==void 0||((t=e.definition.implements)===null||t===void 0?void 0:t.some(n=>r[n]!==void 0))}$r.shouldUseRule=Af});var Ss=$(Fe=>{"use strict";Object.defineProperty(Fe,"__esModule",{value:!0});Fe.reportTypeError=Fe.checkDataTypes=Fe.checkDataType=Fe.coerceAndCheckDataType=Fe.getJSONTypes=Fe.getSchemaTypes=Fe.DataType=void 0;var Fw=lc(),Vw=dc(),Uw=$s(),z=B(),kf=Y(),vn;(function(r){r[r.Correct=0]="Correct",r[r.Wrong=1]="Wrong"})(vn||(Fe.DataType=vn={}));function Bw(r){let e=xf(r.type);if(e.includes("null")){if(r.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&r.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');r.nullable===!0&&e.push("null")}return e}Fe.getSchemaTypes=Bw;function xf(r){let e=Array.isArray(r)?r:r?[r]:[];if(e.every(Fw.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}Fe.getJSONTypes=xf;function Hw(r,e){let{gen:t,data:n,opts:s}=r,i=zw(e,s.coerceTypes),o=e.length>0&&!(i.length===0&&e.length===1&&(0,Vw.schemaHasRulesForType)(r,e[0]));if(o){let a=fc(e,n,s.strictNumbers,vn.Wrong);t.if(a,()=>{i.length?Kw(r,e,i):pc(r)})}return o}Fe.coerceAndCheckDataType=Hw;var If=new Set(["string","number","integer","boolean","null"]);function zw(r,e){return e?r.filter(t=>If.has(t)||e==="array"&&t==="array"):[]}function Kw(r,e,t){let{gen:n,data:s,opts:i}=r,o=n.let("dataType",(0,z._)`typeof ${s}`),a=n.let("coerced",(0,z._)`undefined`);i.coerceTypes==="array"&&n.if((0,z._)`${o} == 'object' && Array.isArray(${s}) && ${s}.length == 1`,()=>n.assign(s,(0,z._)`${s}[0]`).assign(o,(0,z._)`typeof ${s}`).if(fc(e,s,i.strictNumbers),()=>n.assign(a,s))),n.if((0,z._)`${a} !== undefined`);for(let l of t)(If.has(l)||l==="array"&&i.coerceTypes==="array")&&c(l);n.else(),pc(r),n.endIf(),n.if((0,z._)`${a} !== undefined`,()=>{n.assign(s,a),Gw(r,a)});function c(l){switch(l){case"string":n.elseIf((0,z._)`${o} == "number" || ${o} == "boolean"`).assign(a,(0,z._)`"" + ${s}`).elseIf((0,z._)`${s} === null`).assign(a,(0,z._)`""`);return;case"number":n.elseIf((0,z._)`${o} == "boolean" || ${s} === null + || (${o} == "string" && ${s} && ${s} == +${s})`).assign(a,(0,z._)`+${s}`);return;case"integer":n.elseIf((0,z._)`${o} === "boolean" || ${s} === null + || (${o} === "string" && ${s} && ${s} == +${s} && !(${s} % 1))`).assign(a,(0,z._)`+${s}`);return;case"boolean":n.elseIf((0,z._)`${s} === "false" || ${s} === 0 || ${s} === null`).assign(a,!1).elseIf((0,z._)`${s} === "true" || ${s} === 1`).assign(a,!0);return;case"null":n.elseIf((0,z._)`${s} === "" || ${s} === 0 || ${s} === false`),n.assign(a,null);return;case"array":n.elseIf((0,z._)`${o} === "string" || ${o} === "number" + || ${o} === "boolean" || ${s} === null`).assign(a,(0,z._)`[${s}]`)}}}function Gw({gen:r,parentData:e,parentDataProperty:t},n){r.if((0,z._)`${e} !== undefined`,()=>r.assign((0,z._)`${e}[${t}]`,n))}function uc(r,e,t,n=vn.Correct){let s=n===vn.Correct?z.operators.EQ:z.operators.NEQ,i;switch(r){case"null":return(0,z._)`${e} ${s} null`;case"array":i=(0,z._)`Array.isArray(${e})`;break;case"object":i=(0,z._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":i=o((0,z._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":i=o();break;default:return(0,z._)`typeof ${e} ${s} ${r}`}return n===vn.Correct?i:(0,z.not)(i);function o(a=z.nil){return(0,z.and)((0,z._)`typeof ${e} == "number"`,a,t?(0,z._)`isFinite(${e})`:z.nil)}}Fe.checkDataType=uc;function fc(r,e,t,n){if(r.length===1)return uc(r[0],e,t,n);let s,i=(0,kf.toHash)(r);if(i.array&&i.object){let o=(0,z._)`typeof ${e} != "object"`;s=i.null?o:(0,z._)`!${e} || ${o}`,delete i.null,delete i.array,delete i.object}else s=z.nil;i.number&&delete i.integer;for(let o in i)s=(0,z.and)(s,uc(o,e,t,n));return s}Fe.checkDataTypes=fc;var Ww={message:({schema:r})=>`must be ${r}`,params:({schema:r,schemaValue:e})=>typeof r=="string"?(0,z._)`{type: ${r}}`:(0,z._)`{type: ${e}}`};function pc(r){let e=Jw(r);(0,Uw.reportError)(e,Ww)}Fe.reportTypeError=pc;function Jw(r){let{gen:e,data:t,schema:n}=r,s=(0,kf.schemaRefOrVal)(r,n,"type");return{gen:e,keyword:"type",data:t,schema:n.type,schemaCode:s,schemaValue:s,parentSchema:n,params:{},it:r}}});var Pf=$(Gi=>{"use strict";Object.defineProperty(Gi,"__esModule",{value:!0});Gi.assignDefaults=void 0;var $n=B(),Yw=Y();function Xw(r,e){let{properties:t,items:n}=r.schema;if(e==="object"&&t)for(let s in t)Tf(r,s,t[s].default);else e==="array"&&Array.isArray(n)&&n.forEach((s,i)=>Tf(r,i,s.default))}Gi.assignDefaults=Xw;function Tf(r,e,t){let{gen:n,compositeRule:s,data:i,opts:o}=r;if(t===void 0)return;let a=(0,$n._)`${i}${(0,$n.getProperty)(e)}`;if(s){(0,Yw.checkStrictMode)(r,`default is ignored for: ${a}`);return}let c=(0,$n._)`${a} === undefined`;o.useDefaults==="empty"&&(c=(0,$n._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,$n._)`${a} = ${(0,$n.stringify)(t)}`)}});var pt=$(ce=>{"use strict";Object.defineProperty(ce,"__esModule",{value:!0});ce.validateUnion=ce.validateArray=ce.usePattern=ce.callValidateCode=ce.schemaProperties=ce.allSchemaProperties=ce.noPropertyInData=ce.propertyInData=ce.isOwnProperty=ce.hasPropFunc=ce.reportMissingProp=ce.checkMissingProp=ce.checkReportMissingProp=void 0;var he=B(),hc=Y(),Sr=ft(),Qw=Y();function Zw(r,e){let{gen:t,data:n,it:s}=r;t.if(yc(t,n,e,s.opts.ownProperties),()=>{r.setParams({missingProperty:(0,he._)`${e}`},!0),r.error()})}ce.checkReportMissingProp=Zw;function e_({gen:r,data:e,it:{opts:t}},n,s){return(0,he.or)(...n.map(i=>(0,he.and)(yc(r,e,i,t.ownProperties),(0,he._)`${s} = ${i}`)))}ce.checkMissingProp=e_;function t_(r,e){r.setParams({missingProperty:e},!0),r.error()}ce.reportMissingProp=t_;function Of(r){return r.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,he._)`Object.prototype.hasOwnProperty`})}ce.hasPropFunc=Of;function mc(r,e,t){return(0,he._)`${Of(r)}.call(${e}, ${t})`}ce.isOwnProperty=mc;function r_(r,e,t,n){let s=(0,he._)`${e}${(0,he.getProperty)(t)} !== undefined`;return n?(0,he._)`${s} && ${mc(r,e,t)}`:s}ce.propertyInData=r_;function yc(r,e,t,n){let s=(0,he._)`${e}${(0,he.getProperty)(t)} === undefined`;return n?(0,he.or)(s,(0,he.not)(mc(r,e,t))):s}ce.noPropertyInData=yc;function Rf(r){return r?Object.keys(r).filter(e=>e!=="__proto__"):[]}ce.allSchemaProperties=Rf;function n_(r,e){return Rf(e).filter(t=>!(0,hc.alwaysValidSchema)(r,e[t]))}ce.schemaProperties=n_;function s_({schemaCode:r,data:e,it:{gen:t,topSchemaRef:n,schemaPath:s,errorPath:i},it:o},a,c,l){let u=l?(0,he._)`${r}, ${e}, ${n}${s}`:e,d=[[Sr.default.instancePath,(0,he.strConcat)(Sr.default.instancePath,i)],[Sr.default.parentData,o.parentData],[Sr.default.parentDataProperty,o.parentDataProperty],[Sr.default.rootData,Sr.default.rootData]];o.opts.dynamicRef&&d.push([Sr.default.dynamicAnchors,Sr.default.dynamicAnchors]);let f=(0,he._)`${u}, ${t.object(...d)}`;return c!==he.nil?(0,he._)`${a}.call(${c}, ${f})`:(0,he._)`${a}(${f})`}ce.callValidateCode=s_;var i_=(0,he._)`new RegExp`;function o_({gen:r,it:{opts:e}},t){let n=e.unicodeRegExp?"u":"",{regExp:s}=e.code,i=s(t,n);return r.scopeValue("pattern",{key:i.toString(),ref:i,code:(0,he._)`${s.code==="new RegExp"?i_:(0,Qw.useFunc)(r,s)}(${t}, ${n})`})}ce.usePattern=o_;function a_(r){let{gen:e,data:t,keyword:n,it:s}=r,i=e.name("valid");if(s.allErrors){let a=e.let("valid",!0);return o(()=>e.assign(a,!1)),a}return e.var(i,!0),o(()=>e.break()),i;function o(a){let c=e.const("len",(0,he._)`${t}.length`);e.forRange("i",0,c,l=>{r.subschema({keyword:n,dataProp:l,dataPropType:hc.Type.Num},i),e.if((0,he.not)(i),a)})}}ce.validateArray=a_;function c_(r){let{gen:e,schema:t,keyword:n,it:s}=r;if(!Array.isArray(t))throw new Error("ajv implementation error");if(t.some(c=>(0,hc.alwaysValidSchema)(s,c))&&!s.opts.unevaluated)return;let o=e.let("valid",!1),a=e.name("_valid");e.block(()=>t.forEach((c,l)=>{let u=r.subschema({keyword:n,schemaProp:l,compositeRule:!0},a);e.assign(o,(0,he._)`${o} || ${a}`),r.mergeValidEvaluated(u,a)||e.if((0,he.not)(o))})),r.result(o,()=>r.reset(),()=>r.error(!0))}ce.validateUnion=c_});var Mf=$(Vt=>{"use strict";Object.defineProperty(Vt,"__esModule",{value:!0});Vt.validateKeywordUsage=Vt.validSchemaType=Vt.funcKeywordCode=Vt.macroKeywordCode=void 0;var ze=B(),Yr=ft(),l_=pt(),d_=$s();function u_(r,e){let{gen:t,keyword:n,schema:s,parentSchema:i,it:o}=r,a=e.macro.call(o.self,s,i,o),c=Nf(t,n,a);o.opts.validateSchema!==!1&&o.self.validateSchema(a,!0);let l=t.name("valid");r.subschema({schema:a,schemaPath:ze.nil,errSchemaPath:`${o.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},l),r.pass(l,()=>r.error(!0))}Vt.macroKeywordCode=u_;function f_(r,e){var t;let{gen:n,keyword:s,schema:i,parentSchema:o,$data:a,it:c}=r;h_(c,e);let l=!a&&e.compile?e.compile.call(c.self,i,o,c):e.validate,u=Nf(n,s,l),d=n.let("valid");r.block$data(d,f),r.ok((t=e.valid)!==null&&t!==void 0?t:d);function f(){if(e.errors===!1)h(),e.modifying&&Cf(r),y(()=>r.error());else{let b=e.async?p():m();e.modifying&&Cf(r),y(()=>p_(r,b))}}function p(){let b=n.let("ruleErrs",null);return n.try(()=>h((0,ze._)`await `),g=>n.assign(d,!1).if((0,ze._)`${g} instanceof ${c.ValidationError}`,()=>n.assign(b,(0,ze._)`${g}.errors`),()=>n.throw(g))),b}function m(){let b=(0,ze._)`${u}.errors`;return n.assign(b,null),h(ze.nil),b}function h(b=e.async?(0,ze._)`await `:ze.nil){let g=c.opts.passContext?Yr.default.this:Yr.default.self,w=!("compile"in e&&!a||e.schema===!1);n.assign(d,(0,ze._)`${b}${(0,l_.callValidateCode)(r,u,g,w)}`,e.modifying)}function y(b){var g;n.if((0,ze.not)((g=e.valid)!==null&&g!==void 0?g:d),b)}}Vt.funcKeywordCode=f_;function Cf(r){let{gen:e,data:t,it:n}=r;e.if(n.parentData,()=>e.assign(t,(0,ze._)`${n.parentData}[${n.parentDataProperty}]`))}function p_(r,e){let{gen:t}=r;t.if((0,ze._)`Array.isArray(${e})`,()=>{t.assign(Yr.default.vErrors,(0,ze._)`${Yr.default.vErrors} === null ? ${e} : ${Yr.default.vErrors}.concat(${e})`).assign(Yr.default.errors,(0,ze._)`${Yr.default.vErrors}.length`),(0,d_.extendErrors)(r)},()=>r.error())}function h_({schemaEnv:r},e){if(e.async&&!r.$async)throw new Error("async keyword in sync schema")}function Nf(r,e,t){if(t===void 0)throw new Error(`keyword "${e}" failed to compile`);return r.scopeValue("keyword",typeof t=="function"?{ref:t}:{ref:t,code:(0,ze.stringify)(t)})}function m_(r,e,t=!1){return!e.length||e.some(n=>n==="array"?Array.isArray(r):n==="object"?r&&typeof r=="object"&&!Array.isArray(r):typeof r==n||t&&typeof r=="undefined")}Vt.validSchemaType=m_;function y_({schema:r,opts:e,self:t,errSchemaPath:n},s,i){if(Array.isArray(s.keyword)?!s.keyword.includes(i):s.keyword!==i)throw new Error("ajv implementation error");let o=s.dependencies;if(o!=null&&o.some(a=>!Object.prototype.hasOwnProperty.call(r,a)))throw new Error(`parent schema must have dependencies of ${i}: ${o.join(",")}`);if(s.validateSchema&&!s.validateSchema(r[i])){let c=`keyword "${i}" value is invalid at path "${n}": `+t.errorsText(s.validateSchema.errors);if(e.validateSchema==="log")t.logger.error(c);else throw new Error(c)}}Vt.validateKeywordUsage=y_});var qf=$(Er=>{"use strict";Object.defineProperty(Er,"__esModule",{value:!0});Er.extendSubschemaMode=Er.extendSubschemaData=Er.getSubschema=void 0;var Ut=B(),Lf=Y();function g_(r,{keyword:e,schemaProp:t,schema:n,schemaPath:s,errSchemaPath:i,topSchemaRef:o}){if(e!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let a=r.schema[e];return t===void 0?{schema:a,schemaPath:(0,Ut._)`${r.schemaPath}${(0,Ut.getProperty)(e)}`,errSchemaPath:`${r.errSchemaPath}/${e}`}:{schema:a[t],schemaPath:(0,Ut._)`${r.schemaPath}${(0,Ut.getProperty)(e)}${(0,Ut.getProperty)(t)}`,errSchemaPath:`${r.errSchemaPath}/${e}/${(0,Lf.escapeFragment)(t)}`}}if(n!==void 0){if(s===void 0||i===void 0||o===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:s,topSchemaRef:o,errSchemaPath:i}}throw new Error('either "keyword" or "schema" must be passed')}Er.getSubschema=g_;function b_(r,e,{dataProp:t,dataPropType:n,data:s,dataTypes:i,propertyName:o}){if(s!==void 0&&t!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(t!==void 0){let{errorPath:l,dataPathArr:u,opts:d}=e,f=a.let("data",(0,Ut._)`${e.data}${(0,Ut.getProperty)(t)}`,!0);c(f),r.errorPath=(0,Ut.str)`${l}${(0,Lf.getErrorPath)(t,n,d.jsPropertySyntax)}`,r.parentDataProperty=(0,Ut._)`${t}`,r.dataPathArr=[...u,r.parentDataProperty]}if(s!==void 0){let l=s instanceof Ut.Name?s:a.let("data",s,!0);c(l),o!==void 0&&(r.propertyName=o)}i&&(r.dataTypes=i);function c(l){r.data=l,r.dataLevel=e.dataLevel+1,r.dataTypes=[],e.definedProperties=new Set,r.parentData=e.data,r.dataNames=[...e.dataNames,l]}}Er.extendSubschemaData=b_;function w_(r,{jtdDiscriminator:e,jtdMetadata:t,compositeRule:n,createErrors:s,allErrors:i}){n!==void 0&&(r.compositeRule=n),s!==void 0&&(r.createErrors=s),i!==void 0&&(r.allErrors=i),r.jtdDiscriminator=e,r.jtdMetadata=t}Er.extendSubschemaMode=w_});var gc=$((UO,Df)=>{"use strict";Df.exports=function r(e,t){if(e===t)return!0;if(e&&t&&typeof e=="object"&&typeof t=="object"){if(e.constructor!==t.constructor)return!1;var n,s,i;if(Array.isArray(e)){if(n=e.length,n!=t.length)return!1;for(s=n;s--!==0;)if(!r(e[s],t[s]))return!1;return!0}if(e.constructor===RegExp)return e.source===t.source&&e.flags===t.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===t.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===t.toString();if(i=Object.keys(e),n=i.length,n!==Object.keys(t).length)return!1;for(s=n;s--!==0;)if(!Object.prototype.hasOwnProperty.call(t,i[s]))return!1;for(s=n;s--!==0;){var o=i[s];if(!r(e[o],t[o]))return!1}return!0}return e!==e&&t!==t}});var Ff=$((BO,jf)=>{"use strict";var Ar=jf.exports=function(r,e,t){typeof e=="function"&&(t=e,e={}),t=e.cb||t;var n=typeof t=="function"?t:t.pre||function(){},s=t.post||function(){};Wi(e,n,s,r,"",r)};Ar.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Ar.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Ar.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Ar.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function Wi(r,e,t,n,s,i,o,a,c,l){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,s,i,o,a,c,l);for(var u in n){var d=n[u];if(Array.isArray(d)){if(u in Ar.arrayKeywords)for(var f=0;f{"use strict";Object.defineProperty(Qe,"__esModule",{value:!0});Qe.getSchemaRefs=Qe.resolveUrl=Qe.normalizeId=Qe._getFullPath=Qe.getFullPath=Qe.inlineRef=void 0;var v_=Y(),$_=gc(),S_=Ff(),E_=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function A_(r,e=!0){return typeof r=="boolean"?!0:e===!0?!bc(r):e?Vf(r)<=e:!1}Qe.inlineRef=A_;var k_=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function bc(r){for(let e in r){if(k_.has(e))return!0;let t=r[e];if(Array.isArray(t)&&t.some(bc)||typeof t=="object"&&bc(t))return!0}return!1}function Vf(r){let e=0;for(let t in r){if(t==="$ref")return 1/0;if(e++,!E_.has(t)&&(typeof r[t]=="object"&&(0,v_.eachItem)(r[t],n=>e+=Vf(n)),e===1/0))return 1/0}return e}function Uf(r,e="",t){t!==!1&&(e=Sn(e));let n=r.parse(e);return Bf(r,n)}Qe.getFullPath=Uf;function Bf(r,e){return r.serialize(e).split("#")[0]+"#"}Qe._getFullPath=Bf;var x_=/#\/?$/;function Sn(r){return r?r.replace(x_,""):""}Qe.normalizeId=Sn;function I_(r,e,t){return t=Sn(t),r.resolve(e,t)}Qe.resolveUrl=I_;var T_=/^[a-z_][-a-z0-9._]*$/i;function P_(r,e){if(typeof r=="boolean")return{};let{schemaId:t,uriResolver:n}=this.opts,s=Sn(r[t]||e),i={"":s},o=Uf(n,s,!1),a={},c=new Set;return S_(r,{allKeys:!0},(d,f,p,m)=>{if(m===void 0)return;let h=o+f,y=i[m];typeof d[t]=="string"&&(y=b.call(this,d[t])),g.call(this,d.$anchor),g.call(this,d.$dynamicAnchor),i[f]=y;function b(w){let S=this.opts.uriResolver.resolve;if(w=Sn(y?S(y,w):w),c.has(w))throw u(w);c.add(w);let _=this.refs[w];return typeof _=="string"&&(_=this.refs[_]),typeof _=="object"?l(d,_.schema,w):w!==Sn(h)&&(w[0]==="#"?(l(d,a[w],w),a[w]=d):this.refs[w]=h),w}function g(w){if(typeof w=="string"){if(!T_.test(w))throw new Error(`invalid anchor "${w}"`);b.call(this,`#${w}`)}}}),a;function l(d,f,p){if(f!==void 0&&!$_(d,f))throw u(p)}function u(d){return new Error(`reference "${d}" resolves to more than one schema`)}}Qe.getSchemaRefs=P_});var En=$(kr=>{"use strict";Object.defineProperty(kr,"__esModule",{value:!0});kr.getData=kr.KeywordCxt=kr.validateFunctionCode=void 0;var Wf=Sf(),Hf=Ss(),_c=dc(),Ji=Ss(),O_=Pf(),ks=Mf(),wc=qf(),j=B(),U=ft(),R_=Es(),sr=Y(),As=$s();function C_(r){if(Xf(r)&&(Qf(r),Yf(r))){L_(r);return}Jf(r,()=>(0,Wf.topBoolOrEmptySchema)(r))}kr.validateFunctionCode=C_;function Jf({gen:r,validateName:e,schema:t,schemaEnv:n,opts:s},i){s.code.es5?r.func(e,(0,j._)`${U.default.data}, ${U.default.valCxt}`,n.$async,()=>{r.code((0,j._)`"use strict"; ${zf(t,s)}`),M_(r,s),r.code(i)}):r.func(e,(0,j._)`${U.default.data}, ${N_(s)}`,n.$async,()=>r.code(zf(t,s)).code(i))}function N_(r){return(0,j._)`{${U.default.instancePath}="", ${U.default.parentData}, ${U.default.parentDataProperty}, ${U.default.rootData}=${U.default.data}${r.dynamicRef?(0,j._)`, ${U.default.dynamicAnchors}={}`:j.nil}}={}`}function M_(r,e){r.if(U.default.valCxt,()=>{r.var(U.default.instancePath,(0,j._)`${U.default.valCxt}.${U.default.instancePath}`),r.var(U.default.parentData,(0,j._)`${U.default.valCxt}.${U.default.parentData}`),r.var(U.default.parentDataProperty,(0,j._)`${U.default.valCxt}.${U.default.parentDataProperty}`),r.var(U.default.rootData,(0,j._)`${U.default.valCxt}.${U.default.rootData}`),e.dynamicRef&&r.var(U.default.dynamicAnchors,(0,j._)`${U.default.valCxt}.${U.default.dynamicAnchors}`)},()=>{r.var(U.default.instancePath,(0,j._)`""`),r.var(U.default.parentData,(0,j._)`undefined`),r.var(U.default.parentDataProperty,(0,j._)`undefined`),r.var(U.default.rootData,U.default.data),e.dynamicRef&&r.var(U.default.dynamicAnchors,(0,j._)`{}`)})}function L_(r){let{schema:e,opts:t,gen:n}=r;Jf(r,()=>{t.$comment&&e.$comment&&ep(r),V_(r),n.let(U.default.vErrors,null),n.let(U.default.errors,0),t.unevaluated&&q_(r),Zf(r),H_(r)})}function q_(r){let{gen:e,validateName:t}=r;r.evaluated=e.const("evaluated",(0,j._)`${t}.evaluated`),e.if((0,j._)`${r.evaluated}.dynamicProps`,()=>e.assign((0,j._)`${r.evaluated}.props`,(0,j._)`undefined`)),e.if((0,j._)`${r.evaluated}.dynamicItems`,()=>e.assign((0,j._)`${r.evaluated}.items`,(0,j._)`undefined`))}function zf(r,e){let t=typeof r=="object"&&r[e.schemaId];return t&&(e.code.source||e.code.process)?(0,j._)`/*# sourceURL=${t} */`:j.nil}function D_(r,e){if(Xf(r)&&(Qf(r),Yf(r))){j_(r,e);return}(0,Wf.boolOrEmptySchema)(r,e)}function Yf({schema:r,self:e}){if(typeof r=="boolean")return!r;for(let t in r)if(e.RULES.all[t])return!0;return!1}function Xf(r){return typeof r.schema!="boolean"}function j_(r,e){let{schema:t,gen:n,opts:s}=r;s.$comment&&t.$comment&&ep(r),U_(r),B_(r);let i=n.const("_errs",U.default.errors);Zf(r,i),n.var(e,(0,j._)`${i} === ${U.default.errors}`)}function Qf(r){(0,sr.checkUnknownRules)(r),F_(r)}function Zf(r,e){if(r.opts.jtd)return Kf(r,[],!1,e);let t=(0,Hf.getSchemaTypes)(r.schema),n=(0,Hf.coerceAndCheckDataType)(r,t);Kf(r,t,!n,e)}function F_(r){let{schema:e,errSchemaPath:t,opts:n,self:s}=r;e.$ref&&n.ignoreKeywordsWithRef&&(0,sr.schemaHasRulesButRef)(e,s.RULES)&&s.logger.warn(`$ref: keywords ignored in schema at path "${t}"`)}function V_(r){let{schema:e,opts:t}=r;e.default!==void 0&&t.useDefaults&&t.strictSchema&&(0,sr.checkStrictMode)(r,"default is ignored in the schema root")}function U_(r){let e=r.schema[r.opts.schemaId];e&&(r.baseId=(0,R_.resolveUrl)(r.opts.uriResolver,r.baseId,e))}function B_(r){if(r.schema.$async&&!r.schemaEnv.$async)throw new Error("async schema in sync schema")}function ep({gen:r,schemaEnv:e,schema:t,errSchemaPath:n,opts:s}){let i=t.$comment;if(s.$comment===!0)r.code((0,j._)`${U.default.self}.logger.log(${i})`);else if(typeof s.$comment=="function"){let o=(0,j.str)`${n}/$comment`,a=r.scopeValue("root",{ref:e.root});r.code((0,j._)`${U.default.self}.opts.$comment(${i}, ${o}, ${a}.schema)`)}}function H_(r){let{gen:e,schemaEnv:t,validateName:n,ValidationError:s,opts:i}=r;t.$async?e.if((0,j._)`${U.default.errors} === 0`,()=>e.return(U.default.data),()=>e.throw((0,j._)`new ${s}(${U.default.vErrors})`)):(e.assign((0,j._)`${n}.errors`,U.default.vErrors),i.unevaluated&&z_(r),e.return((0,j._)`${U.default.errors} === 0`))}function z_({gen:r,evaluated:e,props:t,items:n}){t instanceof j.Name&&r.assign((0,j._)`${e}.props`,t),n instanceof j.Name&&r.assign((0,j._)`${e}.items`,n)}function Kf(r,e,t,n){let{gen:s,schema:i,data:o,allErrors:a,opts:c,self:l}=r,{RULES:u}=l;if(i.$ref&&(c.ignoreKeywordsWithRef||!(0,sr.schemaHasRulesButRef)(i,u))){s.block(()=>rp(r,"$ref",u.all.$ref.definition));return}c.jtd||K_(r,e),s.block(()=>{for(let f of u.rules)d(f);d(u.post)});function d(f){(0,_c.shouldUseGroup)(i,f)&&(f.type?(s.if((0,Ji.checkDataType)(f.type,o,c.strictNumbers)),Gf(r,f),e.length===1&&e[0]===f.type&&t&&(s.else(),(0,Ji.reportTypeError)(r)),s.endIf()):Gf(r,f),a||s.if((0,j._)`${U.default.errors} === ${n||0}`))}}function Gf(r,e){let{gen:t,schema:n,opts:{useDefaults:s}}=r;s&&(0,O_.assignDefaults)(r,e.type),t.block(()=>{for(let i of e.rules)(0,_c.shouldUseRule)(n,i)&&rp(r,i.keyword,i.definition,e.type)})}function K_(r,e){r.schemaEnv.meta||!r.opts.strictTypes||(G_(r,e),r.opts.allowUnionTypes||W_(r,e),J_(r,r.dataTypes))}function G_(r,e){if(e.length){if(!r.dataTypes.length){r.dataTypes=e;return}e.forEach(t=>{tp(r.dataTypes,t)||vc(r,`type "${t}" not allowed by context "${r.dataTypes.join(",")}"`)}),X_(r,e)}}function W_(r,e){e.length>1&&!(e.length===2&&e.includes("null"))&&vc(r,"use allowUnionTypes to allow union type keyword")}function J_(r,e){let t=r.self.RULES.all;for(let n in t){let s=t[n];if(typeof s=="object"&&(0,_c.shouldUseRule)(r.schema,s)){let{type:i}=s.definition;i.length&&!i.some(o=>Y_(e,o))&&vc(r,`missing type "${i.join(",")}" for keyword "${n}"`)}}}function Y_(r,e){return r.includes(e)||e==="number"&&r.includes("integer")}function tp(r,e){return r.includes(e)||e==="integer"&&r.includes("number")}function X_(r,e){let t=[];for(let n of r.dataTypes)tp(e,n)?t.push(n):e.includes("integer")&&n==="number"&&t.push("integer");r.dataTypes=t}function vc(r,e){let t=r.schemaEnv.baseId+r.errSchemaPath;e+=` at "${t}" (strictTypes)`,(0,sr.checkStrictMode)(r,e,r.opts.strictTypes)}var Yi=class{constructor(e,t,n){if((0,ks.validateKeywordUsage)(e,t,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=t.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,sr.schemaRefOrVal)(e,this.schema,n,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",np(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,ks.validSchemaType)(this.schema,t.schemaType,t.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(t.schemaType)}`);("code"in t?t.trackErrors:t.errors!==!1)&&(this.errsCount=e.gen.const("_errs",U.default.errors))}result(e,t,n){this.failResult((0,j.not)(e),t,n)}failResult(e,t,n){this.gen.if(e),n?n():this.error(),t?(this.gen.else(),t(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,t){this.failResult((0,j.not)(e),void 0,t)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:t}=this;this.fail((0,j._)`${t} !== undefined && (${(0,j.or)(this.invalid$data(),e)})`)}error(e,t,n){if(t){this.setParams(t),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,t){(e?As.reportExtraError:As.reportError)(this,this.def.error,t)}$dataError(){(0,As.reportError)(this,this.def.$dataError||As.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,As.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,t){t?Object.assign(this.params,e):this.params=e}block$data(e,t,n=j.nil){this.gen.block(()=>{this.check$data(e,n),t()})}check$data(e=j.nil,t=j.nil){if(!this.$data)return;let{gen:n,schemaCode:s,schemaType:i,def:o}=this;n.if((0,j.or)((0,j._)`${s} === undefined`,t)),e!==j.nil&&n.assign(e,!0),(i.length||o.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==j.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:t,schemaType:n,def:s,it:i}=this;return(0,j.or)(o(),a());function o(){if(n.length){if(!(t instanceof j.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,j._)`${(0,Ji.checkDataTypes)(c,t,i.opts.strictNumbers,Ji.DataType.Wrong)}`}return j.nil}function a(){if(s.validateSchema){let c=e.scopeValue("validate$data",{ref:s.validateSchema});return(0,j._)`!${c}(${t})`}return j.nil}}subschema(e,t){let n=(0,wc.getSubschema)(this.it,e);(0,wc.extendSubschemaData)(n,this.it,e),(0,wc.extendSubschemaMode)(n,e);let s={...this.it,...n,items:void 0,props:void 0};return D_(s,t),s}mergeEvaluated(e,t){let{it:n,gen:s}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=sr.mergeEvaluated.props(s,e.props,n.props,t)),n.items!==!0&&e.items!==void 0&&(n.items=sr.mergeEvaluated.items(s,e.items,n.items,t)))}mergeValidEvaluated(e,t){let{it:n,gen:s}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return s.if(t,()=>this.mergeEvaluated(e,j.Name)),!0}};kr.KeywordCxt=Yi;function rp(r,e,t,n){let s=new Yi(r,t,e);"code"in t?t.code(s,n):s.$data&&t.validate?(0,ks.funcKeywordCode)(s,t):"macro"in t?(0,ks.macroKeywordCode)(s,t):(t.compile||t.validate)&&(0,ks.funcKeywordCode)(s,t)}var Q_=/^\/(?:[^~]|~0|~1)*$/,Z_=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function np(r,{dataLevel:e,dataNames:t,dataPathArr:n}){let s,i;if(r==="")return U.default.rootData;if(r[0]==="/"){if(!Q_.test(r))throw new Error(`Invalid JSON-pointer: ${r}`);s=r,i=U.default.rootData}else{let l=Z_.exec(r);if(!l)throw new Error(`Invalid JSON-pointer: ${r}`);let u=+l[1];if(s=l[2],s==="#"){if(u>=e)throw new Error(c("property/index",u));return n[e-u]}if(u>e)throw new Error(c("data",u));if(i=t[e-u],!s)return i}let o=i,a=s.split("/");for(let l of a)l&&(i=(0,j._)`${i}${(0,j.getProperty)((0,sr.unescapeJsonPointer)(l))}`,o=(0,j._)`${o} && ${i}`);return o;function c(l,u){return`Cannot access ${l} ${u} levels up, current level is ${e}`}}kr.getData=np});var xs=$(Sc=>{"use strict";Object.defineProperty(Sc,"__esModule",{value:!0});var $c=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};Sc.default=$c});var An=$(kc=>{"use strict";Object.defineProperty(kc,"__esModule",{value:!0});var Ec=Es(),Ac=class extends Error{constructor(e,t,n,s){super(s||`can't resolve reference ${n} from id ${t}`),this.missingRef=(0,Ec.resolveUrl)(e,t,n),this.missingSchema=(0,Ec.normalizeId)((0,Ec.getFullPath)(e,this.missingRef))}};kc.default=Ac});var Is=$(ht=>{"use strict";Object.defineProperty(ht,"__esModule",{value:!0});ht.resolveSchema=ht.getCompilingSchema=ht.resolveRef=ht.compileSchema=ht.SchemaEnv=void 0;var $t=B(),ev=xs(),Xr=ft(),St=Es(),sp=Y(),tv=En(),kn=class{constructor(e){var t;this.refs={},this.dynamicAnchors={};let n;typeof e.schema=="object"&&(n=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,St.normalizeId)(n==null?void 0:n[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n==null?void 0:n.$async,this.refs={}}};ht.SchemaEnv=kn;function Ic(r){let e=ip.call(this,r);if(e)return e;let t=(0,St.getFullPath)(this.opts.uriResolver,r.root.baseId),{es5:n,lines:s}=this.opts.code,{ownProperties:i}=this.opts,o=new $t.CodeGen(this.scope,{es5:n,lines:s,ownProperties:i}),a;r.$async&&(a=o.scopeValue("Error",{ref:ev.default,code:(0,$t._)`require("ajv/dist/runtime/validation_error").default`}));let c=o.scopeName("validate");r.validateName=c;let l={gen:o,allErrors:this.opts.allErrors,data:Xr.default.data,parentData:Xr.default.parentData,parentDataProperty:Xr.default.parentDataProperty,dataNames:[Xr.default.data],dataPathArr:[$t.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:o.scopeValue("schema",this.opts.code.source===!0?{ref:r.schema,code:(0,$t.stringify)(r.schema)}:{ref:r.schema}),validateName:c,ValidationError:a,schema:r.schema,schemaEnv:r,rootId:t,baseId:r.baseId||t,schemaPath:$t.nil,errSchemaPath:r.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,$t._)`""`,opts:this.opts,self:this},u;try{this._compilations.add(r),(0,tv.validateFunctionCode)(l),o.optimize(this.opts.code.optimize);let d=o.toString();u=`${o.scopeRefs(Xr.default.scope)}return ${d}`,this.opts.code.process&&(u=this.opts.code.process(u,r));let p=new Function(`${Xr.default.self}`,`${Xr.default.scope}`,u)(this,this.scope.get());if(this.scope.value(c,{ref:p}),p.errors=null,p.schema=r.schema,p.schemaEnv=r,r.$async&&(p.$async=!0),this.opts.code.source===!0&&(p.source={validateName:c,validateCode:d,scopeValues:o._values}),this.opts.unevaluated){let{props:m,items:h}=l;p.evaluated={props:m instanceof $t.Name?void 0:m,items:h instanceof $t.Name?void 0:h,dynamicProps:m instanceof $t.Name,dynamicItems:h instanceof $t.Name},p.source&&(p.source.evaluated=(0,$t.stringify)(p.evaluated))}return r.validate=p,r}catch(d){throw delete r.validate,delete r.validateName,u&&this.logger.error("Error compiling schema, function code:",u),d}finally{this._compilations.delete(r)}}ht.compileSchema=Ic;function rv(r,e,t){var n;t=(0,St.resolveUrl)(this.opts.uriResolver,e,t);let s=r.refs[t];if(s)return s;let i=iv.call(this,r,t);if(i===void 0){let o=(n=r.localRefs)===null||n===void 0?void 0:n[t],{schemaId:a}=this.opts;o&&(i=new kn({schema:o,schemaId:a,root:r,baseId:e}))}if(i!==void 0)return r.refs[t]=nv.call(this,i)}ht.resolveRef=rv;function nv(r){return(0,St.inlineRef)(r.schema,this.opts.inlineRefs)?r.schema:r.validate?r:Ic.call(this,r)}function ip(r){for(let e of this._compilations)if(sv(e,r))return e}ht.getCompilingSchema=ip;function sv(r,e){return r.schema===e.schema&&r.root===e.root&&r.baseId===e.baseId}function iv(r,e){let t;for(;typeof(t=this.refs[e])=="string";)e=t;return t||this.schemas[e]||Xi.call(this,r,e)}function Xi(r,e){let t=this.opts.uriResolver.parse(e),n=(0,St._getFullPath)(this.opts.uriResolver,t),s=(0,St.getFullPath)(this.opts.uriResolver,r.baseId,void 0);if(Object.keys(r.schema).length>0&&n===s)return xc.call(this,t,r);let i=(0,St.normalizeId)(n),o=this.refs[i]||this.schemas[i];if(typeof o=="string"){let a=Xi.call(this,r,o);return typeof(a==null?void 0:a.schema)!="object"?void 0:xc.call(this,t,a)}if(typeof(o==null?void 0:o.schema)=="object"){if(o.validate||Ic.call(this,o),i===(0,St.normalizeId)(e)){let{schema:a}=o,{schemaId:c}=this.opts,l=a[c];return l&&(s=(0,St.resolveUrl)(this.opts.uriResolver,s,l)),new kn({schema:a,schemaId:c,root:r,baseId:s})}return xc.call(this,t,o)}}ht.resolveSchema=Xi;var ov=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function xc(r,{baseId:e,schema:t,root:n}){var s;if(((s=r.fragment)===null||s===void 0?void 0:s[0])!=="/")return;for(let a of r.fragment.slice(1).split("/")){if(typeof t=="boolean")return;let c=t[(0,sp.unescapeFragment)(a)];if(c===void 0)return;t=c;let l=typeof t=="object"&&t[this.opts.schemaId];!ov.has(a)&&l&&(e=(0,St.resolveUrl)(this.opts.uriResolver,e,l))}let i;if(typeof t!="boolean"&&t.$ref&&!(0,sp.schemaHasRulesButRef)(t,this.RULES)){let a=(0,St.resolveUrl)(this.opts.uriResolver,e,t.$ref);i=Xi.call(this,n,a)}let{schemaId:o}=this.opts;if(i=i||new kn({schema:t,schemaId:o,root:n,baseId:e}),i.schema!==i.root.schema)return i}});var op=$((JO,av)=>{av.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 Oc=$((YO,fp)=>{"use strict";var cv=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),cp=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u),Tc=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),lp=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),lv=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function Pc(r){let e="",t=0,n=0;for(n=0;n=48&&t<=57||t>=65&&t<=70||t>=97&&t<=102))return"";e+=r[n];break}for(n+=1;n=48&&t<=57||t>=65&&t<=70||t>=97&&t<=102))return"";e+=r[n]}return e}var dv=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function ap(r){return r.length=0,!0}function uv(r,e,t){if(r.length){let n=Pc(r);if(n!=="")e.push(n);else return t.error=!0,!1;r.length=0}return!0}function fv(r){let e=0,t={error:!1,address:"",zone:""},n=[],s=[],i=!1,o=!1,a=uv;for(let c=0;c7){t.error=!0;break}c>0&&r[c-1]===":"&&(i=!0),n.push(":");continue}else if(l==="%"){if(!a(s,n,t))break;a=ap}else{s.push(l);continue}}return s.length&&(a===ap?t.zone=s.join(""):o?n.push(s.join("")):n.push(Pc(s))),t.address=n.join(""),t}function dp(r){if(pv(r,":")<2)return{host:r,isIPV6:!1};let e=fv(r);if(e.error)return{host:r,isIPV6:!1};{let t=e.address,n=e.address;return e.zone&&(t+="%"+e.zone,n+="%25"+e.zone),{host:t,isIPV6:!0,escapedHost:n}}}function pv(r,e){let t=0;for(let n=0;nmv[n])}function bv(r,e=!1){if(r.indexOf("%")===-1)return r;let t="";for(let n=0;n{"use strict";var{isUUID:$v}=Oc(),Sv=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,Ev=["http","https","ws","wss","urn","urn:uuid"];function Av(r){return Ev.indexOf(r)!==-1}function Rc(r){return r.secure===!0?!0:r.secure===!1?!1:r.scheme?r.scheme.length===3&&(r.scheme[0]==="w"||r.scheme[0]==="W")&&(r.scheme[1]==="s"||r.scheme[1]==="S")&&(r.scheme[2]==="s"||r.scheme[2]==="S"):!1}function pp(r){return r.host||(r.error=r.error||"HTTP URIs must have a host."),r}function hp(r){let e=String(r.scheme).toLowerCase()==="https";return(r.port===(e?443:80)||r.port==="")&&(r.port=void 0),r.path||(r.path="/"),r}function kv(r){return r.secure=Rc(r),r.resourceName=(r.path||"/")+(r.query?"?"+r.query:""),r.path=void 0,r.query=void 0,r}function xv(r){if((r.port===(Rc(r)?443:80)||r.port==="")&&(r.port=void 0),typeof r.secure=="boolean"&&(r.scheme=r.secure?"wss":"ws",r.secure=void 0),r.resourceName){let[e,t]=r.resourceName.split("?");r.path=e&&e!=="/"?e:void 0,r.query=t,r.resourceName=void 0}return r.fragment=void 0,r}function Iv(r,e){if(!r.path)return r.error="URN can not be parsed",r;let t=r.path.match(Sv);if(t){let n=e.scheme||r.scheme||"urn";r.nid=t[1].toLowerCase(),r.nss=t[2];let s=`${n}:${e.nid||r.nid}`,i=Cc(s);r.path=void 0,i&&(r=i.parse(r,e))}else r.error=r.error||"URN can not be parsed.";return r}function Tv(r,e){if(r.nid===void 0)throw new Error("URN without nid cannot be serialized");let t=e.scheme||r.scheme||"urn",n=r.nid.toLowerCase(),s=`${t}:${e.nid||n}`,i=Cc(s);i&&(r=i.serialize(r,e));let o=r,a=r.nss;return o.path=`${n||e.nid}:${a}`,e.skipEscape=!0,o}function Pv(r,e){let t=r;return t.uuid=t.nss,t.nss=void 0,!e.tolerant&&(!t.uuid||!$v(t.uuid))&&(t.error=t.error||"UUID is not valid."),t}function Ov(r){let e=r;return e.nss=(r.uuid||"").toLowerCase(),e}var mp={scheme:"http",domainHost:!0,parse:pp,serialize:hp},Rv={scheme:"https",domainHost:mp.domainHost,parse:pp,serialize:hp},Qi={scheme:"ws",domainHost:!0,parse:kv,serialize:xv},Cv={scheme:"wss",domainHost:Qi.domainHost,parse:Qi.parse,serialize:Qi.serialize},Nv={scheme:"urn",parse:Iv,serialize:Tv,skipNormalize:!0},Mv={scheme:"urn:uuid",parse:Pv,serialize:Ov,skipNormalize:!0},Zi={http:mp,https:Rv,ws:Qi,wss:Cv,urn:Nv,"urn:uuid":Mv};Object.setPrototypeOf(Zi,null);function Cc(r){return r&&(Zi[r]||Zi[r.toLowerCase()])||void 0}yp.exports={wsIsSecure:Rc,SCHEMES:Zi,isValidSchemeName:Av,getSchemeHandler:Cc}});var Sp=$((QO,eo)=>{"use strict";var{normalizeIPv6:Lv,removeDotSegments:Ts,recomposeAuthority:qv,normalizePercentEncoding:Dv,normalizePathEncoding:jv,escapePreservingEscapes:Fv,reescapeHostDelimiters:Vv,isIPv4:Uv,nonSimpleDomain:Bv}=Oc(),{SCHEMES:Hv,getSchemeHandler:wp}=gp();function zv(r,e){return typeof r=="string"?r=Xv(r,e):typeof r=="object"&&(r=xn(Qr(r,e),e)),r}function Kv(r,e,t){let n=t?Object.assign({scheme:"null"},t):{scheme:"null"},s=_p(xn(r,n),xn(e,n),n,!0);return n.skipEscape=!0,Qr(s,n)}function _p(r,e,t,n){let s={};return n||(r=xn(Qr(r,t),t),e=xn(Qr(e,t),t)),t=t||{},!t.tolerant&&e.scheme?(s.scheme=e.scheme,s.userinfo=e.userinfo,s.host=e.host,s.port=e.port,s.path=Ts(e.path||""),s.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(s.userinfo=e.userinfo,s.host=e.host,s.port=e.port,s.path=Ts(e.path||""),s.query=e.query):(e.path?(e.path[0]==="/"?s.path=Ts(e.path):((r.userinfo!==void 0||r.host!==void 0||r.port!==void 0)&&!r.path?s.path="/"+e.path:r.path?s.path=r.path.slice(0,r.path.lastIndexOf("/")+1)+e.path:s.path=e.path,s.path=Ts(s.path)),s.query=e.query):(s.path=r.path,e.query!==void 0?s.query=e.query:s.query=r.query),s.userinfo=r.userinfo,s.host=r.host,s.port=r.port),s.scheme=r.scheme),s.fragment=e.fragment,s}function Gv(r,e,t){let n=bp(r,t),s=bp(e,t);return n!==void 0&&s!==void 0&&n.toLowerCase()===s.toLowerCase()}function Qr(r,e){let t={host:r.host,scheme:r.scheme,userinfo:r.userinfo,port:r.port,path:r.path,query:r.query,nid:r.nid,nss:r.nss,uuid:r.uuid,fragment:r.fragment,reference:r.reference,resourceName:r.resourceName,secure:r.secure,error:""},n=Object.assign({},e),s=[],i=wp(n.scheme||t.scheme);i&&i.serialize&&i.serialize(t,n),t.path!==void 0&&(n.skipEscape?t.path=Dv(t.path):(t.path=Fv(t.path),t.scheme!==void 0&&(t.path=t.path.split("%3A").join(":")))),n.reference!=="suffix"&&t.scheme&&s.push(t.scheme,":");let o=qv(t);if(o!==void 0&&(n.reference!=="suffix"&&s.push("//"),s.push(o),t.path&&t.path[0]!=="/"&&s.push("/")),t.path!==void 0){let a=t.path;!n.absolutePath&&(!i||!i.absolutePath)&&(a=Ts(a)),o===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),s.push(a)}return t.query!==void 0&&s.push("?",t.query),t.fragment!==void 0&&s.push("#",t.fragment),s.join("")}var Wv=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,Jv=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/;function Yv(r,e){if(e[2]!==void 0&&r.path&&r.path[0]!=="/")return'URI path must start with "/" when authority is present.';if(typeof r.port=="number"&&(r.port<0||r.port>65535))return"URI port is malformed."}function vp(r,e){let t=Object.assign({},e),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},s=!1,i=!1;t.reference==="suffix"&&(t.scheme?r=t.scheme+":"+r:r="//"+r);let o=r.match(Jv);o!==null&&o[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",s=!0);let a=r.match(Wv);if(a){n.scheme=a[1],n.userinfo=a[3],n.host=a[4],n.port=parseInt(a[5],10),n.path=a[6]||"",n.query=a[7],n.fragment=a[8],isNaN(n.port)&&(n.port=a[5]);let c=Yv(n,a);if(c!==void 0&&(n.error=n.error||c,s=!0),n.host)if(Uv(n.host)===!1){let d=Lv(n.host);n.host=d.host.toLowerCase(),i=d.isIPV6}else i=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",t.reference&&t.reference!=="suffix"&&t.reference!==n.reference&&(n.error=n.error||"URI is not a "+t.reference+" reference.");let l=wp(t.scheme||n.scheme);if(!t.unicodeSupport&&(!l||!l.unicodeSupport)&&n.host&&(t.domainHost||l&&l.domainHost)&&i===!1&&Bv(n.host))try{n.host=new URL("http://"+n.host).hostname}catch(u){n.error=n.error||"Host's domain name can not be converted to ASCII: "+u}if((!l||l&&!l.skipNormalize)&&(r.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=Vv(unescape(n.host),i))),n.path&&(n.path=jv(n.path)),n.fragment))try{n.fragment=encodeURI(decodeURIComponent(n.fragment))}catch(u){n.error=n.error||"URI malformed"}l&&l.parse&&l.parse(n,t)}else n.error=n.error||"URI can not be parsed.";return{parsed:n,malformedAuthorityOrPort:s}}function xn(r,e){return vp(r,e).parsed}function Xv(r,e){return $p(r,e).normalized}function $p(r,e){let{parsed:t,malformedAuthorityOrPort:n}=vp(r,e);return{normalized:n?r:Qr(t,e),malformedAuthorityOrPort:n}}function bp(r,e){if(typeof r=="string"){let{normalized:t,malformedAuthorityOrPort:n}=$p(r,e);return n?void 0:t}if(typeof r=="object")return Qr(r,e)}var Nc={SCHEMES:Hv,normalize:zv,resolve:Kv,resolveComponent:_p,equal:Gv,serialize:Qr,parse:xn};eo.exports=Nc;eo.exports.default=Nc;eo.exports.fastUri=Nc});var Ap=$(Mc=>{"use strict";Object.defineProperty(Mc,"__esModule",{value:!0});var Ep=Sp();Ep.code='require("ajv/dist/runtime/uri").default';Mc.default=Ep});var Dc=$(Ne=>{"use strict";Object.defineProperty(Ne,"__esModule",{value:!0});Ne.CodeGen=Ne.Name=Ne.nil=Ne.stringify=Ne.str=Ne._=Ne.KeywordCxt=void 0;var Qv=En();Object.defineProperty(Ne,"KeywordCxt",{enumerable:!0,get:function(){return Qv.KeywordCxt}});var In=B();Object.defineProperty(Ne,"_",{enumerable:!0,get:function(){return In._}});Object.defineProperty(Ne,"str",{enumerable:!0,get:function(){return In.str}});Object.defineProperty(Ne,"stringify",{enumerable:!0,get:function(){return In.stringify}});Object.defineProperty(Ne,"nil",{enumerable:!0,get:function(){return In.nil}});Object.defineProperty(Ne,"Name",{enumerable:!0,get:function(){return In.Name}});Object.defineProperty(Ne,"CodeGen",{enumerable:!0,get:function(){return In.CodeGen}});var Zv=xs(),Pp=An(),e$=lc(),Ps=Is(),t$=B(),Os=Es(),to=Ss(),qc=Y(),kp=op(),r$=Ap(),Op=(r,e)=>new RegExp(r,e);Op.code="new RegExp";var n$=["removeAdditional","useDefaults","coerceTypes"],s$=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),i$={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."},o$={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},xp=200;function a$(r){var e,t,n,s,i,o,a,c,l,u,d,f,p,m,h,y,b,g,w,S,_,x,I,E,T;let v=r.strict,F=(e=r.code)===null||e===void 0?void 0:e.optimize,V=F===!0||F===void 0?1:F||0,G=(n=(t=r.code)===null||t===void 0?void 0:t.regExp)!==null&&n!==void 0?n:Op,A=(s=r.uriResolver)!==null&&s!==void 0?s:r$.default;return{strictSchema:(o=(i=r.strictSchema)!==null&&i!==void 0?i:v)!==null&&o!==void 0?o:!0,strictNumbers:(c=(a=r.strictNumbers)!==null&&a!==void 0?a:v)!==null&&c!==void 0?c:!0,strictTypes:(u=(l=r.strictTypes)!==null&&l!==void 0?l:v)!==null&&u!==void 0?u:"log",strictTuples:(f=(d=r.strictTuples)!==null&&d!==void 0?d:v)!==null&&f!==void 0?f:"log",strictRequired:(m=(p=r.strictRequired)!==null&&p!==void 0?p:v)!==null&&m!==void 0?m:!1,code:r.code?{...r.code,optimize:V,regExp:G}:{optimize:V,regExp:G},loopRequired:(h=r.loopRequired)!==null&&h!==void 0?h:xp,loopEnum:(y=r.loopEnum)!==null&&y!==void 0?y:xp,meta:(b=r.meta)!==null&&b!==void 0?b:!0,messages:(g=r.messages)!==null&&g!==void 0?g:!0,inlineRefs:(w=r.inlineRefs)!==null&&w!==void 0?w:!0,schemaId:(S=r.schemaId)!==null&&S!==void 0?S:"$id",addUsedSchema:(_=r.addUsedSchema)!==null&&_!==void 0?_:!0,validateSchema:(x=r.validateSchema)!==null&&x!==void 0?x:!0,validateFormats:(I=r.validateFormats)!==null&&I!==void 0?I:!0,unicodeRegExp:(E=r.unicodeRegExp)!==null&&E!==void 0?E:!0,int32range:(T=r.int32range)!==null&&T!==void 0?T:!0,uriResolver:A}}var Rs=class{constructor(e={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...a$(e)};let{es5:t,lines:n}=this.opts.code;this.scope=new t$.ValueScope({scope:{},prefixes:s$,es5:t,lines:n}),this.logger=p$(e.logger);let s=e.validateFormats;e.validateFormats=!1,this.RULES=(0,e$.getRules)(),Ip.call(this,i$,e,"NOT SUPPORTED"),Ip.call(this,o$,e,"DEPRECATED","warn"),this._metaOpts=u$.call(this),e.formats&&l$.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&d$.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),c$.call(this),e.validateFormats=s}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:t,schemaId:n}=this.opts,s=kp;n==="id"&&(s={...kp},s.id=s.$id,delete s.$id),t&&e&&this.addMetaSchema(s,s[n],!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 n;if(typeof e=="string"){if(n=this.getSchema(e),!n)throw new Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let s=n(t);return"$async"in n||(this.errors=n.errors),s}compile(e,t){let n=this._addSchema(e,t);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,t){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return s.call(this,e,t);async function s(u,d){await i.call(this,u.$schema);let f=this._addSchema(u,d);return f.validate||o.call(this,f)}async function i(u){u&&!this.getSchema(u)&&await s.call(this,{$ref:u},!0)}async function o(u){try{return this._compileSchemaEnv(u)}catch(d){if(!(d instanceof Pp.default))throw d;return a.call(this,d),await c.call(this,d.missingSchema),o.call(this,u)}}function a({missingSchema:u,missingRef:d}){if(this.refs[u])throw new Error(`AnySchema ${u} is loaded but ${d} cannot be resolved`)}async function c(u){let d=await l.call(this,u);this.refs[u]||await i.call(this,d.$schema),this.refs[u]||this.addSchema(d,u,t)}async function l(u){let d=this._loading[u];if(d)return d;try{return await(this._loading[u]=n(u))}finally{delete this._loading[u]}}}addSchema(e,t,n,s=this.opts.validateSchema){if(Array.isArray(e)){for(let o of e)this.addSchema(o,void 0,n,s);return this}let i;if(typeof e=="object"){let{schemaId:o}=this.opts;if(i=e[o],i!==void 0&&typeof i!="string")throw new Error(`schema ${o} must be string`)}return t=(0,Os.normalizeId)(t||i),this._checkUnique(t),this.schemas[t]=this._addSchema(e,n,t,s,!0),this}addMetaSchema(e,t,n=this.opts.validateSchema){return this.addSchema(e,t,!0,n),this}validateSchema(e,t){if(typeof e=="boolean")return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!="string")throw new Error("$schema must be a string");if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let s=this.validate(n,e);if(!s&&t){let i="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(i);else throw new Error(i)}return s}getSchema(e){let t;for(;typeof(t=Tp.call(this,e))=="string";)e=t;if(t===void 0){let{schemaId:n}=this.opts,s=new Ps.SchemaEnv({schema:{},schemaId:n});if(t=Ps.resolveSchema.call(this,s,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=Tp.call(this,e);return typeof t=="object"&&this._cache.delete(t.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let t=e;this._cache.delete(t);let n=e[this.opts.schemaId];return n&&(n=(0,Os.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let t of e)this.addKeyword(t);return this}addKeyword(e,t){let n;if(typeof e=="string")n=e,typeof t=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),t.keyword=n);else if(typeof e=="object"&&t===void 0){if(t=e,n=t.keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(m$.call(this,n,t),!t)return(0,qc.eachItem)(n,i=>Lc.call(this,i)),this;g$.call(this,t);let s={...t,type:(0,to.getJSONTypes)(t.type),schemaType:(0,to.getJSONTypes)(t.schemaType)};return(0,qc.eachItem)(n,s.type.length===0?i=>Lc.call(this,i,s):i=>s.type.forEach(o=>Lc.call(this,i,s,o))),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 n of t.rules){let s=n.rules.findIndex(i=>i.keyword===e);s>=0&&n.rules.splice(s,1)}return this}addFormat(e,t){return typeof t=="string"&&(t=new RegExp(t)),this.formats[e]=t,this}errorsText(e=this.errors,{separator:t=", ",dataVar:n="data"}={}){return!e||e.length===0?"No errors":e.map(s=>`${n}${s.instancePath} ${s.message}`).reduce((s,i)=>s+t+i)}$dataMetaSchema(e,t){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let s of t){let i=s.split("/").slice(1),o=e;for(let a of i)o=o[a];for(let a in n){let c=n[a];if(typeof c!="object")continue;let{$data:l}=c.definition,u=o[a];l&&u&&(o[a]=Rp(u))}}return e}_removeAllSchemas(e,t){for(let n in e){let s=e[n];(!t||t.test(n))&&(typeof s=="string"?delete e[n]:s&&!s.meta&&(this._cache.delete(s.schema),delete e[n]))}}_addSchema(e,t,n,s=this.opts.validateSchema,i=this.opts.addUsedSchema){let o,{schemaId:a}=this.opts;if(typeof e=="object")o=e[a];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof e!="boolean")throw new Error("schema must be object or boolean")}let c=this._cache.get(e);if(c!==void 0)return c;n=(0,Os.normalizeId)(o||n);let l=Os.getSchemaRefs.call(this,e,n);return c=new Ps.SchemaEnv({schema:e,schemaId:a,meta:t,baseId:n,localRefs:l}),this._cache.set(c.schema,c),i&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=c),s&&this.validateSchema(e,!0),c}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):Ps.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let t=this.opts;this.opts=this._metaOpts;try{Ps.compileSchema.call(this,e)}finally{this.opts=t}}};Rs.ValidationError=Zv.default;Rs.MissingRefError=Pp.default;Ne.default=Rs;function Ip(r,e,t,n="error"){for(let s in r){let i=s;i in e&&this.logger[n](`${t}: option ${s}. ${r[i]}`)}}function Tp(r){return r=(0,Os.normalizeId)(r),this.schemas[r]||this.refs[r]}function c$(){let r=this.opts.schemas;if(r)if(Array.isArray(r))this.addSchema(r);else for(let e in r)this.addSchema(r[e],e)}function l$(){for(let r in this.opts.formats){let e=this.opts.formats[r];e&&this.addFormat(r,e)}}function d$(r){if(Array.isArray(r)){this.addVocabulary(r);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let e in r){let t=r[e];t.keyword||(t.keyword=e),this.addKeyword(t)}}function u$(){let r={...this.opts};for(let e of n$)delete r[e];return r}var f$={log(){},warn(){},error(){}};function p$(r){if(r===!1)return f$;if(r===void 0)return console;if(r.log&&r.warn&&r.error)return r;throw new Error("logger must implement log, warn and error methods")}var h$=/^[a-z_$][a-z0-9_$:-]*$/i;function m$(r,e){let{RULES:t}=this;if((0,qc.eachItem)(r,n=>{if(t.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!h$.test(n))throw new Error(`Keyword ${n} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function Lc(r,e,t){var n;let s=e==null?void 0:e.post;if(t&&s)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:i}=this,o=s?i.post:i.rules.find(({type:c})=>c===t);if(o||(o={type:t,rules:[]},i.rules.push(o)),i.keywords[r]=!0,!e)return;let a={keyword:r,definition:{...e,type:(0,to.getJSONTypes)(e.type),schemaType:(0,to.getJSONTypes)(e.schemaType)}};e.before?y$.call(this,o,a,e.before):o.rules.push(a),i.all[r]=a,(n=e.implements)===null||n===void 0||n.forEach(c=>this.addKeyword(c))}function y$(r,e,t){let n=r.rules.findIndex(s=>s.keyword===t);n>=0?r.rules.splice(n,0,e):(r.rules.push(e),this.logger.warn(`rule ${t} is not defined`))}function g$(r){let{metaSchema:e}=r;e!==void 0&&(r.$data&&this.opts.$data&&(e=Rp(e)),r.validateSchema=this.compile(e,!0))}var b$={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Rp(r){return{anyOf:[r,b$]}}});var Cp=$(jc=>{"use strict";Object.defineProperty(jc,"__esModule",{value:!0});var w$={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};jc.default=w$});var so=$(Zr=>{"use strict";Object.defineProperty(Zr,"__esModule",{value:!0});Zr.callRef=Zr.getValidate=void 0;var _$=An(),Np=pt(),Ze=B(),Tn=ft(),Mp=Is(),ro=Y(),v$={keyword:"$ref",schemaType:"string",code(r){let{gen:e,schema:t,it:n}=r,{baseId:s,schemaEnv:i,validateName:o,opts:a,self:c}=n,{root:l}=i;if((t==="#"||t==="#/")&&s===l.baseId)return d();let u=Mp.resolveRef.call(c,l,s,t);if(u===void 0)throw new _$.default(n.opts.uriResolver,s,t);if(u instanceof Mp.SchemaEnv)return f(u);return p(u);function d(){if(i===l)return no(r,o,i,i.$async);let m=e.scopeValue("root",{ref:l});return no(r,(0,Ze._)`${m}.validate`,l,l.$async)}function f(m){let h=Lp(r,m);no(r,h,m,m.$async)}function p(m){let h=e.scopeValue("schema",a.code.source===!0?{ref:m,code:(0,Ze.stringify)(m)}:{ref:m}),y=e.name("valid"),b=r.subschema({schema:m,dataTypes:[],schemaPath:Ze.nil,topSchemaRef:h,errSchemaPath:t},y);r.mergeEvaluated(b),r.ok(y)}}};function Lp(r,e){let{gen:t}=r;return e.validate?t.scopeValue("validate",{ref:e.validate}):(0,Ze._)`${t.scopeValue("wrapper",{ref:e})}.validate`}Zr.getValidate=Lp;function no(r,e,t,n){let{gen:s,it:i}=r,{allErrors:o,schemaEnv:a,opts:c}=i,l=c.passContext?Tn.default.this:Ze.nil;n?u():d();function u(){if(!a.$async)throw new Error("async schema referenced by sync schema");let m=s.let("valid");s.try(()=>{s.code((0,Ze._)`await ${(0,Np.callValidateCode)(r,e,l)}`),p(e),o||s.assign(m,!0)},h=>{s.if((0,Ze._)`!(${h} instanceof ${i.ValidationError})`,()=>s.throw(h)),f(h),o||s.assign(m,!1)}),r.ok(m)}function d(){r.result((0,Np.callValidateCode)(r,e,l),()=>p(e),()=>f(e))}function f(m){let h=(0,Ze._)`${m}.errors`;s.assign(Tn.default.vErrors,(0,Ze._)`${Tn.default.vErrors} === null ? ${h} : ${Tn.default.vErrors}.concat(${h})`),s.assign(Tn.default.errors,(0,Ze._)`${Tn.default.vErrors}.length`)}function p(m){var h;if(!i.opts.unevaluated)return;let y=(h=t==null?void 0:t.validate)===null||h===void 0?void 0:h.evaluated;if(i.props!==!0)if(y&&!y.dynamicProps)y.props!==void 0&&(i.props=ro.mergeEvaluated.props(s,y.props,i.props));else{let b=s.var("props",(0,Ze._)`${m}.evaluated.props`);i.props=ro.mergeEvaluated.props(s,b,i.props,Ze.Name)}if(i.items!==!0)if(y&&!y.dynamicItems)y.items!==void 0&&(i.items=ro.mergeEvaluated.items(s,y.items,i.items));else{let b=s.var("items",(0,Ze._)`${m}.evaluated.items`);i.items=ro.mergeEvaluated.items(s,b,i.items,Ze.Name)}}}Zr.callRef=no;Zr.default=v$});var Vc=$(Fc=>{"use strict";Object.defineProperty(Fc,"__esModule",{value:!0});var $$=Cp(),S$=so(),E$=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",$$.default,S$.default];Fc.default=E$});var qp=$(Uc=>{"use strict";Object.defineProperty(Uc,"__esModule",{value:!0});var io=B(),xr=io.operators,oo={maximum:{okStr:"<=",ok:xr.LTE,fail:xr.GT},minimum:{okStr:">=",ok:xr.GTE,fail:xr.LT},exclusiveMaximum:{okStr:"<",ok:xr.LT,fail:xr.GTE},exclusiveMinimum:{okStr:">",ok:xr.GT,fail:xr.LTE}},A$={message:({keyword:r,schemaCode:e})=>(0,io.str)`must be ${oo[r].okStr} ${e}`,params:({keyword:r,schemaCode:e})=>(0,io._)`{comparison: ${oo[r].okStr}, limit: ${e}}`},k$={keyword:Object.keys(oo),type:"number",schemaType:"number",$data:!0,error:A$,code(r){let{keyword:e,data:t,schemaCode:n}=r;r.fail$data((0,io._)`${t} ${oo[e].fail} ${n} || isNaN(${t})`)}};Uc.default=k$});var Dp=$(Bc=>{"use strict";Object.defineProperty(Bc,"__esModule",{value:!0});var Cs=B(),x$={message:({schemaCode:r})=>(0,Cs.str)`must be multiple of ${r}`,params:({schemaCode:r})=>(0,Cs._)`{multipleOf: ${r}}`},I$={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:x$,code(r){let{gen:e,data:t,schemaCode:n,it:s}=r,i=s.opts.multipleOfPrecision,o=e.let("res"),a=i?(0,Cs._)`Math.abs(Math.round(${o}) - ${o}) > 1e-${i}`:(0,Cs._)`${o} !== parseInt(${o})`;r.fail$data((0,Cs._)`(${n} === 0 || (${o} = ${t}/${n}, ${a}))`)}};Bc.default=I$});var Fp=$(Hc=>{"use strict";Object.defineProperty(Hc,"__esModule",{value:!0});function jp(r){let e=r.length,t=0,n=0,s;for(;n=55296&&s<=56319&&n{"use strict";Object.defineProperty(zc,"__esModule",{value:!0});var en=B(),T$=Y(),P$=Fp(),O$={message({keyword:r,schemaCode:e}){let t=r==="maxLength"?"more":"fewer";return(0,en.str)`must NOT have ${t} than ${e} characters`},params:({schemaCode:r})=>(0,en._)`{limit: ${r}}`},R$={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:O$,code(r){let{keyword:e,data:t,schemaCode:n,it:s}=r,i=e==="maxLength"?en.operators.GT:en.operators.LT,o=s.opts.unicode===!1?(0,en._)`${t}.length`:(0,en._)`${(0,T$.useFunc)(r.gen,P$.default)}(${t})`;r.fail$data((0,en._)`${o} ${i} ${n}`)}};zc.default=R$});var Up=$(Kc=>{"use strict";Object.defineProperty(Kc,"__esModule",{value:!0});var C$=pt(),N$=Y(),Pn=B(),M$={message:({schemaCode:r})=>(0,Pn.str)`must match pattern "${r}"`,params:({schemaCode:r})=>(0,Pn._)`{pattern: ${r}}`},L$={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:M$,code(r){let{gen:e,data:t,$data:n,schema:s,schemaCode:i,it:o}=r,a=o.opts.unicodeRegExp?"u":"";if(n){let{regExp:c}=o.opts.code,l=c.code==="new RegExp"?(0,Pn._)`new RegExp`:(0,N$.useFunc)(e,c),u=e.let("valid");e.try(()=>e.assign(u,(0,Pn._)`${l}(${i}, ${a}).test(${t})`),()=>e.assign(u,!1)),r.fail$data((0,Pn._)`!${u}`)}else{let c=(0,C$.usePattern)(r,s);r.fail$data((0,Pn._)`!${c}.test(${t})`)}}};Kc.default=L$});var Bp=$(Gc=>{"use strict";Object.defineProperty(Gc,"__esModule",{value:!0});var Ns=B(),q$={message({keyword:r,schemaCode:e}){let t=r==="maxProperties"?"more":"fewer";return(0,Ns.str)`must NOT have ${t} than ${e} properties`},params:({schemaCode:r})=>(0,Ns._)`{limit: ${r}}`},D$={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:q$,code(r){let{keyword:e,data:t,schemaCode:n}=r,s=e==="maxProperties"?Ns.operators.GT:Ns.operators.LT;r.fail$data((0,Ns._)`Object.keys(${t}).length ${s} ${n}`)}};Gc.default=D$});var Hp=$(Wc=>{"use strict";Object.defineProperty(Wc,"__esModule",{value:!0});var Ms=pt(),Ls=B(),j$=Y(),F$={message:({params:{missingProperty:r}})=>(0,Ls.str)`must have required property '${r}'`,params:({params:{missingProperty:r}})=>(0,Ls._)`{missingProperty: ${r}}`},V$={keyword:"required",type:"object",schemaType:"array",$data:!0,error:F$,code(r){let{gen:e,schema:t,schemaCode:n,data:s,$data:i,it:o}=r,{opts:a}=o;if(!i&&t.length===0)return;let c=t.length>=a.loopRequired;if(o.allErrors?l():u(),a.strictRequired){let p=r.parentSchema.properties,{definedProperties:m}=r.it;for(let h of t)if((p==null?void 0:p[h])===void 0&&!m.has(h)){let y=o.schemaEnv.baseId+o.errSchemaPath,b=`required property "${h}" is not defined at "${y}" (strictRequired)`;(0,j$.checkStrictMode)(o,b,o.opts.strictRequired)}}function l(){if(c||i)r.block$data(Ls.nil,d);else for(let p of t)(0,Ms.checkReportMissingProp)(r,p)}function u(){let p=e.let("missing");if(c||i){let m=e.let("valid",!0);r.block$data(m,()=>f(p,m)),r.ok(m)}else e.if((0,Ms.checkMissingProp)(r,t,p)),(0,Ms.reportMissingProp)(r,p),e.else()}function d(){e.forOf("prop",n,p=>{r.setParams({missingProperty:p}),e.if((0,Ms.noPropertyInData)(e,s,p,a.ownProperties),()=>r.error())})}function f(p,m){r.setParams({missingProperty:p}),e.forOf(p,n,()=>{e.assign(m,(0,Ms.propertyInData)(e,s,p,a.ownProperties)),e.if((0,Ls.not)(m),()=>{r.error(),e.break()})},Ls.nil)}}};Wc.default=V$});var zp=$(Jc=>{"use strict";Object.defineProperty(Jc,"__esModule",{value:!0});var qs=B(),U$={message({keyword:r,schemaCode:e}){let t=r==="maxItems"?"more":"fewer";return(0,qs.str)`must NOT have ${t} than ${e} items`},params:({schemaCode:r})=>(0,qs._)`{limit: ${r}}`},B$={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:U$,code(r){let{keyword:e,data:t,schemaCode:n}=r,s=e==="maxItems"?qs.operators.GT:qs.operators.LT;r.fail$data((0,qs._)`${t}.length ${s} ${n}`)}};Jc.default=B$});var ao=$(Yc=>{"use strict";Object.defineProperty(Yc,"__esModule",{value:!0});var Kp=gc();Kp.code='require("ajv/dist/runtime/equal").default';Yc.default=Kp});var Gp=$(Qc=>{"use strict";Object.defineProperty(Qc,"__esModule",{value:!0});var Xc=Ss(),Me=B(),H$=Y(),z$=ao(),K$={message:({params:{i:r,j:e}})=>(0,Me.str)`must NOT have duplicate items (items ## ${e} and ${r} are identical)`,params:({params:{i:r,j:e}})=>(0,Me._)`{i: ${r}, j: ${e}}`},G$={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:K$,code(r){let{gen:e,data:t,$data:n,schema:s,parentSchema:i,schemaCode:o,it:a}=r;if(!n&&!s)return;let c=e.let("valid"),l=i.items?(0,Xc.getSchemaTypes)(i.items):[];r.block$data(c,u,(0,Me._)`${o} === false`),r.ok(c);function u(){let m=e.let("i",(0,Me._)`${t}.length`),h=e.let("j");r.setParams({i:m,j:h}),e.assign(c,!0),e.if((0,Me._)`${m} > 1`,()=>(d()?f:p)(m,h))}function d(){return l.length>0&&!l.some(m=>m==="object"||m==="array")}function f(m,h){let y=e.name("item"),b=(0,Xc.checkDataTypes)(l,y,a.opts.strictNumbers,Xc.DataType.Wrong),g=e.const("indices",(0,Me._)`{}`);e.for((0,Me._)`;${m}--;`,()=>{e.let(y,(0,Me._)`${t}[${m}]`),e.if(b,(0,Me._)`continue`),l.length>1&&e.if((0,Me._)`typeof ${y} == "string"`,(0,Me._)`${y} += "_"`),e.if((0,Me._)`typeof ${g}[${y}] == "number"`,()=>{e.assign(h,(0,Me._)`${g}[${y}]`),r.error(),e.assign(c,!1).break()}).code((0,Me._)`${g}[${y}] = ${m}`)})}function p(m,h){let y=(0,H$.useFunc)(e,z$.default),b=e.name("outer");e.label(b).for((0,Me._)`;${m}--;`,()=>e.for((0,Me._)`${h} = ${m}; ${h}--;`,()=>e.if((0,Me._)`${y}(${t}[${m}], ${t}[${h}])`,()=>{r.error(),e.assign(c,!1).break(b)})))}}};Qc.default=G$});var Wp=$(el=>{"use strict";Object.defineProperty(el,"__esModule",{value:!0});var Zc=B(),W$=Y(),J$=ao(),Y$={message:"must be equal to constant",params:({schemaCode:r})=>(0,Zc._)`{allowedValue: ${r}}`},X$={keyword:"const",$data:!0,error:Y$,code(r){let{gen:e,data:t,$data:n,schemaCode:s,schema:i}=r;n||i&&typeof i=="object"?r.fail$data((0,Zc._)`!${(0,W$.useFunc)(e,J$.default)}(${t}, ${s})`):r.fail((0,Zc._)`${i} !== ${t}`)}};el.default=X$});var Jp=$(tl=>{"use strict";Object.defineProperty(tl,"__esModule",{value:!0});var Ds=B(),Q$=Y(),Z$=ao(),eS={message:"must be equal to one of the allowed values",params:({schemaCode:r})=>(0,Ds._)`{allowedValues: ${r}}`},tS={keyword:"enum",schemaType:"array",$data:!0,error:eS,code(r){let{gen:e,data:t,$data:n,schema:s,schemaCode:i,it:o}=r;if(!n&&s.length===0)throw new Error("enum must have non-empty array");let a=s.length>=o.opts.loopEnum,c,l=()=>c!=null?c:c=(0,Q$.useFunc)(e,Z$.default),u;if(a||n)u=e.let("valid"),r.block$data(u,d);else{if(!Array.isArray(s))throw new Error("ajv implementation error");let p=e.const("vSchema",i);u=(0,Ds.or)(...s.map((m,h)=>f(p,h)))}r.pass(u);function d(){e.assign(u,!1),e.forOf("v",i,p=>e.if((0,Ds._)`${l()}(${t}, ${p})`,()=>e.assign(u,!0).break()))}function f(p,m){let h=s[m];return typeof h=="object"&&h!==null?(0,Ds._)`${l()}(${t}, ${p}[${m}])`:(0,Ds._)`${t} === ${h}`}}};tl.default=tS});var nl=$(rl=>{"use strict";Object.defineProperty(rl,"__esModule",{value:!0});var rS=qp(),nS=Dp(),sS=Vp(),iS=Up(),oS=Bp(),aS=Hp(),cS=zp(),lS=Gp(),dS=Wp(),uS=Jp(),fS=[rS.default,nS.default,sS.default,iS.default,oS.default,aS.default,cS.default,lS.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},dS.default,uS.default];rl.default=fS});var il=$(js=>{"use strict";Object.defineProperty(js,"__esModule",{value:!0});js.validateAdditionalItems=void 0;var tn=B(),sl=Y(),pS={message:({params:{len:r}})=>(0,tn.str)`must NOT have more than ${r} items`,params:({params:{len:r}})=>(0,tn._)`{limit: ${r}}`},hS={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:pS,code(r){let{parentSchema:e,it:t}=r,{items:n}=e;if(!Array.isArray(n)){(0,sl.checkStrictMode)(t,'"additionalItems" is ignored when "items" is not an array of schemas');return}Yp(r,n)}};function Yp(r,e){let{gen:t,schema:n,data:s,keyword:i,it:o}=r;o.items=!0;let a=t.const("len",(0,tn._)`${s}.length`);if(n===!1)r.setParams({len:e.length}),r.pass((0,tn._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,sl.alwaysValidSchema)(o,n)){let l=t.var("valid",(0,tn._)`${a} <= ${e.length}`);t.if((0,tn.not)(l),()=>c(l)),r.ok(l)}function c(l){t.forRange("i",e.length,a,u=>{r.subschema({keyword:i,dataProp:u,dataPropType:sl.Type.Num},l),o.allErrors||t.if((0,tn.not)(l),()=>t.break())})}}js.validateAdditionalItems=Yp;js.default=hS});var ol=$(Fs=>{"use strict";Object.defineProperty(Fs,"__esModule",{value:!0});Fs.validateTuple=void 0;var Xp=B(),co=Y(),mS=pt(),yS={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(r){let{schema:e,it:t}=r;if(Array.isArray(e))return Qp(r,"additionalItems",e);t.items=!0,!(0,co.alwaysValidSchema)(t,e)&&r.ok((0,mS.validateArray)(r))}};function Qp(r,e,t=r.schema){let{gen:n,parentSchema:s,data:i,keyword:o,it:a}=r;u(s),a.opts.unevaluated&&t.length&&a.items!==!0&&(a.items=co.mergeEvaluated.items(n,t.length,a.items));let c=n.name("valid"),l=n.const("len",(0,Xp._)`${i}.length`);t.forEach((d,f)=>{(0,co.alwaysValidSchema)(a,d)||(n.if((0,Xp._)`${l} > ${f}`,()=>r.subschema({keyword:o,schemaProp:f,dataProp:f},c)),r.ok(c))});function u(d){let{opts:f,errSchemaPath:p}=a,m=t.length,h=m===d.minItems&&(m===d.maxItems||d[e]===!1);if(f.strictTuples&&!h){let y=`"${o}" is ${m}-tuple, but minItems or maxItems/${e} are not specified or different at path "${p}"`;(0,co.checkStrictMode)(a,y,f.strictTuples)}}}Fs.validateTuple=Qp;Fs.default=yS});var Zp=$(al=>{"use strict";Object.defineProperty(al,"__esModule",{value:!0});var gS=ol(),bS={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:r=>(0,gS.validateTuple)(r,"items")};al.default=bS});var th=$(cl=>{"use strict";Object.defineProperty(cl,"__esModule",{value:!0});var eh=B(),wS=Y(),_S=pt(),vS=il(),$S={message:({params:{len:r}})=>(0,eh.str)`must NOT have more than ${r} items`,params:({params:{len:r}})=>(0,eh._)`{limit: ${r}}`},SS={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:$S,code(r){let{schema:e,parentSchema:t,it:n}=r,{prefixItems:s}=t;n.items=!0,!(0,wS.alwaysValidSchema)(n,e)&&(s?(0,vS.validateAdditionalItems)(r,s):r.ok((0,_S.validateArray)(r)))}};cl.default=SS});var rh=$(ll=>{"use strict";Object.defineProperty(ll,"__esModule",{value:!0});var mt=B(),lo=Y(),ES={message:({params:{min:r,max:e}})=>e===void 0?(0,mt.str)`must contain at least ${r} valid item(s)`:(0,mt.str)`must contain at least ${r} and no more than ${e} valid item(s)`,params:({params:{min:r,max:e}})=>e===void 0?(0,mt._)`{minContains: ${r}}`:(0,mt._)`{minContains: ${r}, maxContains: ${e}}`},AS={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:ES,code(r){let{gen:e,schema:t,parentSchema:n,data:s,it:i}=r,o,a,{minContains:c,maxContains:l}=n;i.opts.next?(o=c===void 0?1:c,a=l):o=1;let u=e.const("len",(0,mt._)`${s}.length`);if(r.setParams({min:o,max:a}),a===void 0&&o===0){(0,lo.checkStrictMode)(i,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&o>a){(0,lo.checkStrictMode)(i,'"minContains" > "maxContains" is always invalid'),r.fail();return}if((0,lo.alwaysValidSchema)(i,t)){let h=(0,mt._)`${u} >= ${o}`;a!==void 0&&(h=(0,mt._)`${h} && ${u} <= ${a}`),r.pass(h);return}i.items=!0;let d=e.name("valid");a===void 0&&o===1?p(d,()=>e.if(d,()=>e.break())):o===0?(e.let(d,!0),a!==void 0&&e.if((0,mt._)`${s}.length > 0`,f)):(e.let(d,!1),f()),r.result(d,()=>r.reset());function f(){let h=e.name("_valid"),y=e.let("count",0);p(h,()=>e.if(h,()=>m(y)))}function p(h,y){e.forRange("i",0,u,b=>{r.subschema({keyword:"contains",dataProp:b,dataPropType:lo.Type.Num,compositeRule:!0},h),y()})}function m(h){e.code((0,mt._)`${h}++`),a===void 0?e.if((0,mt._)`${h} >= ${o}`,()=>e.assign(d,!0).break()):(e.if((0,mt._)`${h} > ${a}`,()=>e.assign(d,!1).break()),o===1?e.assign(d,!0):e.if((0,mt._)`${h} >= ${o}`,()=>e.assign(d,!0)))}}};ll.default=AS});var uo=$(Bt=>{"use strict";Object.defineProperty(Bt,"__esModule",{value:!0});Bt.validateSchemaDeps=Bt.validatePropertyDeps=Bt.error=void 0;var dl=B(),kS=Y(),Vs=pt();Bt.error={message:({params:{property:r,depsCount:e,deps:t}})=>{let n=e===1?"property":"properties";return(0,dl.str)`must have ${n} ${t} when property ${r} is present`},params:({params:{property:r,depsCount:e,deps:t,missingProperty:n}})=>(0,dl._)`{property: ${r}, + missingProperty: ${n}, depsCount: ${e}, - deps: ${t}}`};var tE={keyword:"dependencies",type:"object",schemaType:"object",error:Ht.error,code(r){let[e,t]=rE(r);Sh(r,e),Eh(r,t)}};function rE({schema:r}){let e={},t={};for(let i in r){if(i==="__proto__")continue;let n=Array.isArray(r[i])?e:t;n[i]=r[i]}return[e,t]}function Sh(r,e=r.schema){let{gen:t,data:i,it:n}=r;if(Object.keys(e).length===0)return;let s=t.let("missing");for(let o in e){let a=e[o];if(a.length===0)continue;let c=(0,Hn.propertyInData)(t,i,o,n.opts.ownProperties);r.setParams({property:o,depsCount:a.length,deps:a.join(", ")}),n.allErrors?t.if(c,()=>{for(let l of a)(0,Hn.checkReportMissingProp)(r,l)}):(t.if((0,Al._)`${c} && (${(0,Hn.checkMissingProp)(r,a,s)})`),(0,Hn.reportMissingProp)(r,s),t.else())}}Ht.validatePropertyDeps=Sh;function Eh(r,e=r.schema){let{gen:t,data:i,keyword:n,it:s}=r,o=t.name("valid");for(let a in e)(0,eE.alwaysValidSchema)(s,e[a])||(t.if((0,Hn.propertyInData)(t,i,a,s.opts.ownProperties),()=>{let c=r.subschema({keyword:n,schemaProp:a},o);r.mergeValidEvaluated(c,o)},()=>t.var(o,!0)),r.ok(o))}Ht.validateSchemaDeps=Eh;Ht.default=tE});var kh=$(kl=>{"use strict";Object.defineProperty(kl,"__esModule",{value:!0});var Ah=z(),iE=Y(),nE={message:"property name must be valid",params:({params:r})=>(0,Ah._)`{propertyName: ${r.propertyName}}`},sE={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:nE,code(r){let{gen:e,schema:t,data:i,it:n}=r;if((0,iE.alwaysValidSchema)(n,t))return;let s=e.name("valid");e.forIn("key",i,o=>{r.setParams({propertyName:o}),r.subschema({keyword:"propertyNames",data:o,dataTypes:["string"],propertyName:o,compositeRule:!0},s),e.if((0,Ah.not)(s),()=>{r.error(!0),n.allErrors||e.break()})}),r.ok(s)}};kl.default=sE});var xl=$(Pl=>{"use strict";Object.defineProperty(Pl,"__esModule",{value:!0});var $o=mt(),kt=z(),oE=ht(),So=Y(),aE={message:"must NOT have additional properties",params:({params:r})=>(0,kt._)`{additionalProperty: ${r.additionalProperty}}`},cE={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:aE,code(r){let{gen:e,schema:t,parentSchema:i,data:n,errsCount:s,it:o}=r;if(!s)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=o;if(o.props=!0,c.removeAdditional!=="all"&&(0,So.alwaysValidSchema)(o,t))return;let l=(0,$o.allSchemaProperties)(i.properties),u=(0,$o.allSchemaProperties)(i.patternProperties);d(),r.ok((0,kt._)`${s} === ${oE.default.errors}`);function d(){e.forIn("key",n,y=>{!l.length&&!u.length?m(y):e.if(f(y),()=>m(y))})}function f(y){let b;if(l.length>8){let g=(0,So.schemaRefOrVal)(o,i.properties,"properties");b=(0,$o.isOwnProperty)(e,g,y)}else l.length?b=(0,kt.or)(...l.map(g=>(0,kt._)`${y} === ${g}`)):b=kt.nil;return u.length&&(b=(0,kt.or)(b,...u.map(g=>(0,kt._)`${(0,$o.usePattern)(r,g)}.test(${y})`))),(0,kt.not)(b)}function p(y){e.code((0,kt._)`delete ${n}[${y}]`)}function m(y){if(c.removeAdditional==="all"||c.removeAdditional&&t===!1){p(y);return}if(t===!1){r.setParams({additionalProperty:y}),r.error(),a||e.break();return}if(typeof t=="object"&&!(0,So.alwaysValidSchema)(o,t)){let b=e.name("valid");c.removeAdditional==="failing"?(h(y,b,!1),e.if((0,kt.not)(b),()=>{r.reset(),p(y)})):(h(y,b),a||e.if((0,kt.not)(b),()=>e.break()))}}function h(y,b,g){let _={keyword:"additionalProperties",dataProp:y,dataPropType:So.Type.Str};g===!1&&Object.assign(_,{compositeRule:!0,createErrors:!1,allErrors:!1}),r.subschema(_,b)}}};Pl.default=cE});var Ih=$(Rl=>{"use strict";Object.defineProperty(Rl,"__esModule",{value:!0});var lE=xi(),Ph=mt(),Il=Y(),xh=xl(),dE={keyword:"properties",type:"object",schemaType:"object",code(r){let{gen:e,schema:t,parentSchema:i,data:n,it:s}=r;s.opts.removeAdditional==="all"&&i.additionalProperties===void 0&&xh.default.code(new lE.KeywordCxt(s,xh.default,"additionalProperties"));let o=(0,Ph.allSchemaProperties)(t);for(let d of o)s.definedProperties.add(d);s.opts.unevaluated&&o.length&&s.props!==!0&&(s.props=Il.mergeEvaluated.props(e,(0,Il.toHash)(o),s.props));let a=o.filter(d=>!(0,Il.alwaysValidSchema)(s,t[d]));if(a.length===0)return;let c=e.name("valid");for(let d of a)l(d)?u(d):(e.if((0,Ph.propertyInData)(e,n,d,s.opts.ownProperties)),u(d),s.allErrors||e.else().var(c,!0),e.endIf()),r.it.definedProperties.add(d),r.ok(c);function l(d){return s.opts.useDefaults&&!s.compositeRule&&t[d].default!==void 0}function u(d){r.subschema({keyword:"properties",schemaProp:d,dataProp:d},c)}}};Rl.default=dE});var Ch=$(Tl=>{"use strict";Object.defineProperty(Tl,"__esModule",{value:!0});var Rh=mt(),Eo=z(),Th=Y(),Oh=Y(),uE={keyword:"patternProperties",type:"object",schemaType:"object",code(r){let{gen:e,schema:t,data:i,parentSchema:n,it:s}=r,{opts:o}=s,a=(0,Rh.allSchemaProperties)(t),c=a.filter(h=>(0,Th.alwaysValidSchema)(s,t[h]));if(a.length===0||c.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let l=o.strictSchema&&!o.allowMatchingProperties&&n.properties,u=e.name("valid");s.props!==!0&&!(s.props instanceof Eo.Name)&&(s.props=(0,Oh.evaluatedPropsToName)(e,s.props));let{props:d}=s;f();function f(){for(let h of a)l&&p(h),s.allErrors?m(h):(e.var(u,!0),m(h),e.if(u))}function p(h){for(let y in l)new RegExp(h).test(y)&&(0,Th.checkStrictMode)(s,`property ${y} matches pattern ${h} (use allowMatchingProperties)`)}function m(h){e.forIn("key",i,y=>{e.if((0,Eo._)`${(0,Rh.usePattern)(r,h)}.test(${y})`,()=>{let b=c.includes(h);b||r.subschema({keyword:"patternProperties",schemaProp:h,dataProp:y,dataPropType:Oh.Type.Str},u),s.opts.unevaluated&&d!==!0?e.assign((0,Eo._)`${d}[${y}]`,!0):!b&&!s.allErrors&&e.if((0,Eo.not)(u),()=>e.break())})})}}};Tl.default=uE});var Nh=$(Ol=>{"use strict";Object.defineProperty(Ol,"__esModule",{value:!0});var fE=Y(),pE={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(r){let{gen:e,schema:t,it:i}=r;if((0,fE.alwaysValidSchema)(i,t)){r.fail();return}let n=e.name("valid");r.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},n),r.failResult(n,()=>r.reset(),()=>r.error())},error:{message:"must NOT be valid"}};Ol.default=pE});var Mh=$(Cl=>{"use strict";Object.defineProperty(Cl,"__esModule",{value:!0});var hE=mt(),mE={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:hE.validateUnion,error:{message:"must match a schema in anyOf"}};Cl.default=mE});var qh=$(Nl=>{"use strict";Object.defineProperty(Nl,"__esModule",{value:!0});var Ao=z(),yE=Y(),gE={message:"must match exactly one schema in oneOf",params:({params:r})=>(0,Ao._)`{passingSchemas: ${r.passing}}`},bE={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:gE,code(r){let{gen:e,schema:t,parentSchema:i,it:n}=r;if(!Array.isArray(t))throw new Error("ajv implementation error");if(n.opts.discriminator&&i.discriminator)return;let s=t,o=e.let("valid",!1),a=e.let("passing",null),c=e.name("_valid");r.setParams({passing:a}),e.block(l),r.result(o,()=>r.reset(),()=>r.error(!0));function l(){s.forEach((u,d)=>{let f;(0,yE.alwaysValidSchema)(n,u)?e.var(c,!0):f=r.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,Ao._)`${c} && ${o}`).assign(o,!1).assign(a,(0,Ao._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(o,!0),e.assign(a,d),f&&r.mergeEvaluated(f,Ao.Name)})})}}};Nl.default=bE});var Lh=$(Ml=>{"use strict";Object.defineProperty(Ml,"__esModule",{value:!0});var _E=Y(),vE={keyword:"allOf",schemaType:"array",code(r){let{gen:e,schema:t,it:i}=r;if(!Array.isArray(t))throw new Error("ajv implementation error");let n=e.name("valid");t.forEach((s,o)=>{if((0,_E.alwaysValidSchema)(i,s))return;let a=r.subschema({keyword:"allOf",schemaProp:o},n);r.ok(n),r.mergeEvaluated(a)})}};Ml.default=vE});var Fh=$(ql=>{"use strict";Object.defineProperty(ql,"__esModule",{value:!0});var ko=z(),Dh=Y(),wE={message:({params:r})=>(0,ko.str)`must match "${r.ifClause}" schema`,params:({params:r})=>(0,ko._)`{failingKeyword: ${r.ifClause}}`},$E={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:wE,code(r){let{gen:e,parentSchema:t,it:i}=r;t.then===void 0&&t.else===void 0&&(0,Dh.checkStrictMode)(i,'"if" without "then" and "else" is ignored');let n=jh(i,"then"),s=jh(i,"else");if(!n&&!s)return;let o=e.let("valid",!0),a=e.name("_valid");if(c(),r.reset(),n&&s){let u=e.let("ifClause");r.setParams({ifClause:u}),e.if(a,l("then",u),l("else",u))}else n?e.if(a,l("then")):e.if((0,ko.not)(a),l("else"));r.pass(o,()=>r.error(!0));function c(){let u=r.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);r.mergeEvaluated(u)}function l(u,d){return()=>{let f=r.subschema({keyword:u},a);e.assign(o,a),r.mergeValidEvaluated(f,o),d?e.assign(d,(0,ko._)`${u}`):r.setParams({ifClause:u})}}}};function jh(r,e){let t=r.schema[e];return t!==void 0&&!(0,Dh.alwaysValidSchema)(r,t)}ql.default=$E});var Vh=$(Ll=>{"use strict";Object.defineProperty(Ll,"__esModule",{value:!0});var SE=Y(),EE={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:r,parentSchema:e,it:t}){e.if===void 0&&(0,SE.checkStrictMode)(t,`"${r}" without "if" is ignored`)}};Ll.default=EE});var Dl=$(jl=>{"use strict";Object.defineProperty(jl,"__esModule",{value:!0});var AE=vl(),kE=_h(),PE=wl(),xE=wh(),IE=$h(),RE=wo(),TE=kh(),OE=xl(),CE=Ih(),NE=Ch(),ME=Nh(),qE=Mh(),LE=qh(),jE=Lh(),DE=Fh(),FE=Vh();function VE(r=!1){let e=[ME.default,qE.default,LE.default,jE.default,DE.default,FE.default,TE.default,OE.default,RE.default,CE.default,NE.default];return r?e.push(kE.default,xE.default):e.push(AE.default,PE.default),e.push(IE.default),e}jl.default=VE});var Vl=$(Kn=>{"use strict";Object.defineProperty(Kn,"__esModule",{value:!0});Kn.dynamicAnchor=void 0;var Fl=z(),UE=ht(),Uh=On(),zE=mo(),BE={keyword:"$dynamicAnchor",schemaType:"string",code:r=>zh(r,r.schema)};function zh(r,e){let{gen:t,it:i}=r;i.schemaEnv.root.dynamicAnchors[e]=!0;let n=(0,Fl._)`${UE.default.dynamicAnchors}${(0,Fl.getProperty)(e)}`,s=i.errSchemaPath==="#"?i.validateName:HE(r);t.if((0,Fl._)`!${n}`,()=>t.assign(n,s))}Kn.dynamicAnchor=zh;function HE(r){let{schemaEnv:e,schema:t,self:i}=r.it,{root:n,baseId:s,localRefs:o,meta:a}=e.root,{schemaId:c}=i.opts,l=new Uh.SchemaEnv({schema:t,schemaId:c,root:n,baseId:s,localRefs:o,meta:a});return Uh.compileSchema.call(i,l),(0,zE.getValidate)(r,l)}Kn.default=BE});var Ul=$(Gn=>{"use strict";Object.defineProperty(Gn,"__esModule",{value:!0});Gn.dynamicRef=void 0;var Bh=z(),KE=ht(),Hh=mo(),GE={keyword:"$dynamicRef",schemaType:"string",code:r=>Kh(r,r.schema)};function Kh(r,e){let{gen:t,keyword:i,it:n}=r;if(e[0]!=="#")throw new Error(`"${i}" only supports hash fragment reference`);let s=e.slice(1);if(n.allErrors)o();else{let c=t.let("valid",!1);o(c),r.ok(c)}function o(c){if(n.schemaEnv.root.dynamicAnchors[s]){let l=t.let("_v",(0,Bh._)`${KE.default.dynamicAnchors}${(0,Bh.getProperty)(s)}`);t.if(l,a(l,c),a(n.validateName,c))}else a(n.validateName,c)()}function a(c,l){return l?()=>t.block(()=>{(0,Hh.callRef)(r,c),t.let(l,!0)}):()=>(0,Hh.callRef)(r,c)}}Gn.dynamicRef=Kh;Gn.default=GE});var Gh=$(zl=>{"use strict";Object.defineProperty(zl,"__esModule",{value:!0});var WE=Vl(),JE=Y(),YE={keyword:"$recursiveAnchor",schemaType:"boolean",code(r){r.schema?(0,WE.dynamicAnchor)(r,""):(0,JE.checkStrictMode)(r.it,"$recursiveAnchor: false is ignored")}};zl.default=YE});var Wh=$(Bl=>{"use strict";Object.defineProperty(Bl,"__esModule",{value:!0});var XE=Ul(),ZE={keyword:"$recursiveRef",schemaType:"string",code:r=>(0,XE.dynamicRef)(r,r.schema)};Bl.default=ZE});var Jh=$(Hl=>{"use strict";Object.defineProperty(Hl,"__esModule",{value:!0});var QE=Vl(),e1=Ul(),t1=Gh(),r1=Wh(),i1=[QE.default,e1.default,t1.default,r1.default];Hl.default=i1});var Xh=$(Kl=>{"use strict";Object.defineProperty(Kl,"__esModule",{value:!0});var Yh=wo(),n1={keyword:"dependentRequired",type:"object",schemaType:"object",error:Yh.error,code:r=>(0,Yh.validatePropertyDeps)(r)};Kl.default=n1});var Zh=$(Gl=>{"use strict";Object.defineProperty(Gl,"__esModule",{value:!0});var s1=wo(),o1={keyword:"dependentSchemas",type:"object",schemaType:"object",code:r=>(0,s1.validateSchemaDeps)(r)};Gl.default=o1});var Qh=$(Wl=>{"use strict";Object.defineProperty(Wl,"__esModule",{value:!0});var a1=Y(),c1={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword:r,parentSchema:e,it:t}){e.contains===void 0&&(0,a1.checkStrictMode)(t,`"${r}" without "contains" is ignored`)}};Wl.default=c1});var em=$(Jl=>{"use strict";Object.defineProperty(Jl,"__esModule",{value:!0});var l1=Xh(),d1=Zh(),u1=Qh(),f1=[l1.default,d1.default,u1.default];Jl.default=f1});var rm=$(Yl=>{"use strict";Object.defineProperty(Yl,"__esModule",{value:!0});var Rr=z(),tm=Y(),p1=ht(),h1={message:"must NOT have unevaluated properties",params:({params:r})=>(0,Rr._)`{unevaluatedProperty: ${r.unevaluatedProperty}}`},m1={keyword:"unevaluatedProperties",type:"object",schemaType:["boolean","object"],trackErrors:!0,error:h1,code(r){let{gen:e,schema:t,data:i,errsCount:n,it:s}=r;if(!n)throw new Error("ajv implementation error");let{allErrors:o,props:a}=s;a instanceof Rr.Name?e.if((0,Rr._)`${a} !== true`,()=>e.forIn("key",i,d=>e.if(l(a,d),()=>c(d)))):a!==!0&&e.forIn("key",i,d=>a===void 0?c(d):e.if(u(a,d),()=>c(d))),s.props=!0,r.ok((0,Rr._)`${n} === ${p1.default.errors}`);function c(d){if(t===!1){r.setParams({unevaluatedProperty:d}),r.error(),o||e.break();return}if(!(0,tm.alwaysValidSchema)(s,t)){let f=e.name("valid");r.subschema({keyword:"unevaluatedProperties",dataProp:d,dataPropType:tm.Type.Str},f),o||e.if((0,Rr.not)(f),()=>e.break())}}function l(d,f){return(0,Rr._)`!${d} || !${d}[${f}]`}function u(d,f){let p=[];for(let m in d)d[m]===!0&&p.push((0,Rr._)`${f} !== ${m}`);return(0,Rr.and)(...p)}}};Yl.default=m1});var nm=$(Xl=>{"use strict";Object.defineProperty(Xl,"__esModule",{value:!0});var si=z(),im=Y(),y1={message:({params:{len:r}})=>(0,si.str)`must NOT have more than ${r} items`,params:({params:{len:r}})=>(0,si._)`{limit: ${r}}`},g1={keyword:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error:y1,code(r){let{gen:e,schema:t,data:i,it:n}=r,s=n.items||0;if(s===!0)return;let o=e.const("len",(0,si._)`${i}.length`);if(t===!1)r.setParams({len:s}),r.fail((0,si._)`${o} > ${s}`);else if(typeof t=="object"&&!(0,im.alwaysValidSchema)(n,t)){let c=e.var("valid",(0,si._)`${o} <= ${s}`);e.if((0,si.not)(c),()=>a(c,s)),r.ok(c)}n.items=!0;function a(c,l){e.forRange("i",l,o,u=>{r.subschema({keyword:"unevaluatedItems",dataProp:u,dataPropType:im.Type.Num},c),n.allErrors||e.if((0,si.not)(c),()=>e.break())})}}};Xl.default=g1});var sm=$(Zl=>{"use strict";Object.defineProperty(Zl,"__esModule",{value:!0});var b1=rm(),_1=nm(),v1=[b1.default,_1.default];Zl.default=v1});var om=$(Ql=>{"use strict";Object.defineProperty(Ql,"__esModule",{value:!0});var Ee=z(),w1={message:({schemaCode:r})=>(0,Ee.str)`must match format "${r}"`,params:({schemaCode:r})=>(0,Ee._)`{format: ${r}}`},$1={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:w1,code(r,e){let{gen:t,data:i,$data:n,schema:s,schemaCode:o,it:a}=r,{opts:c,errSchemaPath:l,schemaEnv:u,self:d}=a;if(!c.validateFormats)return;n?f():p();function f(){let m=t.scopeValue("formats",{ref:d.formats,code:c.code.formats}),h=t.const("fDef",(0,Ee._)`${m}[${o}]`),y=t.let("fType"),b=t.let("format");t.if((0,Ee._)`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>t.assign(y,(0,Ee._)`${h}.type || "string"`).assign(b,(0,Ee._)`${h}.validate`),()=>t.assign(y,(0,Ee._)`"string"`).assign(b,h)),r.fail$data((0,Ee.or)(g(),_()));function g(){return c.strictSchema===!1?Ee.nil:(0,Ee._)`${o} && !${b}`}function _(){let S=u.$async?(0,Ee._)`(${h}.async ? await ${b}(${i}) : ${b}(${i}))`:(0,Ee._)`${b}(${i})`,v=(0,Ee._)`(typeof ${b} == "function" ? ${S} : ${b}.test(${i}))`;return(0,Ee._)`${b} && ${b} !== true && ${y} === ${e} && !${v}`}}function p(){let m=d.formats[s];if(!m){g();return}if(m===!0)return;let[h,y,b]=_(m);h===e&&r.pass(S());function g(){if(c.strictSchema===!1){d.logger.warn(v());return}throw new Error(v());function v(){return`unknown format "${s}" ignored in schema at path "${l}"`}}function _(v){let P=v instanceof RegExp?(0,Ee.regexpCode)(v):c.code.formats?(0,Ee._)`${c.code.formats}${(0,Ee.getProperty)(s)}`:void 0,x=t.scopeValue("formats",{key:s,ref:v,code:P});return typeof v=="object"&&!(v instanceof RegExp)?[v.type||"string",v.validate,(0,Ee._)`${x}.validate`]:["string",v,x]}function S(){if(typeof m=="object"&&!(m instanceof RegExp)&&m.async){if(!u.$async)throw new Error("async format in sync schema");return(0,Ee._)`await ${b}(${i})`}return typeof y=="function"?(0,Ee._)`${b}(${i})`:(0,Ee._)`${b}.test(${i})`}}}};Ql.default=$1});var td=$(ed=>{"use strict";Object.defineProperty(ed,"__esModule",{value:!0});var S1=om(),E1=[S1.default];ed.default=E1});var rd=$(Mi=>{"use strict";Object.defineProperty(Mi,"__esModule",{value:!0});Mi.contentVocabulary=Mi.metadataVocabulary=void 0;Mi.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Mi.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var cm=$(id=>{"use strict";Object.defineProperty(id,"__esModule",{value:!0});var A1=rl(),k1=bl(),P1=Dl(),x1=Jh(),I1=em(),R1=sm(),T1=td(),am=rd(),O1=[x1.default,A1.default,k1.default,(0,P1.default)(!0),T1.default,am.metadataVocabulary,am.contentVocabulary,I1.default,R1.default];id.default=O1});var dm=$(Po=>{"use strict";Object.defineProperty(Po,"__esModule",{value:!0});Po.DiscrError=void 0;var lm;(function(r){r.Tag="tag",r.Mapping="mapping"})(lm||(Po.DiscrError=lm={}))});var od=$(sd=>{"use strict";Object.defineProperty(sd,"__esModule",{value:!0});var qi=z(),nd=dm(),um=On(),C1=Ii(),N1=Y(),M1={message:({params:{discrError:r,tagName:e}})=>r===nd.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:r,tag:e,tagName:t}})=>(0,qi._)`{error: ${r}, tag: ${t}, tagValue: ${e}}`},q1={keyword:"discriminator",type:"object",schemaType:"object",error:M1,code(r){let{gen:e,data:t,schema:i,parentSchema:n,it:s}=r,{oneOf:o}=n;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=i.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(i.mapping)throw new Error("discriminator: mapping is not supported");if(!o)throw new Error("discriminator: requires oneOf keyword");let c=e.let("valid",!1),l=e.const("tag",(0,qi._)`${t}${(0,qi.getProperty)(a)}`);e.if((0,qi._)`typeof ${l} == "string"`,()=>u(),()=>r.error(!1,{discrError:nd.DiscrError.Tag,tag:l,tagName:a})),r.ok(c);function u(){let p=f();e.if(!1);for(let m in p)e.elseIf((0,qi._)`${l} === ${m}`),e.assign(c,d(p[m]));e.else(),r.error(!1,{discrError:nd.DiscrError.Mapping,tag:l,tagName:a}),e.endIf()}function d(p){let m=e.name("valid"),h=r.subschema({keyword:"oneOf",schemaProp:p},m);return r.mergeEvaluated(h,qi.Name),m}function f(){var p;let m={},h=b(n),y=!0;for(let S=0;S{L1.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/schema",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0,"https://json-schema.org/draft/2020-12/vocab/applicator":!0,"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0,"https://json-schema.org/draft/2020-12/vocab/validation":!0,"https://json-schema.org/draft/2020-12/vocab/meta-data":!0,"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0,"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:"meta",title:"Core and Validation specifications meta-schema",allOf:[{$ref:"meta/core"},{$ref:"meta/applicator"},{$ref:"meta/unevaluated"},{$ref:"meta/validation"},{$ref:"meta/meta-data"},{$ref:"meta/format-annotation"},{$ref:"meta/content"}],type:["object","boolean"],$comment:"This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.",properties:{definitions:{$comment:'"definitions" has been replaced by "$defs".',type:"object",additionalProperties:{$dynamicRef:"#meta"},deprecated:!0,default:{}},dependencies:{$comment:'"dependencies" has been split and replaced by "dependentSchemas" and "dependentRequired" in order to serve their differing semantics.',type:"object",additionalProperties:{anyOf:[{$dynamicRef:"#meta"},{$ref:"meta/validation#/$defs/stringArray"}]},deprecated:!0,default:{}},$recursiveAnchor:{$comment:'"$recursiveAnchor" has been replaced by "$dynamicAnchor".',$ref:"meta/core#/$defs/anchorString",deprecated:!0},$recursiveRef:{$comment:'"$recursiveRef" has been replaced by "$dynamicRef".',$ref:"meta/core#/$defs/uriReferenceString",deprecated:!0}}}});var pm=$((CC,j1)=>{j1.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/applicator",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/applicator":!0},$dynamicAnchor:"meta",title:"Applicator vocabulary meta-schema",type:["object","boolean"],properties:{prefixItems:{$ref:"#/$defs/schemaArray"},items:{$dynamicRef:"#meta"},contains:{$dynamicRef:"#meta"},additionalProperties:{$dynamicRef:"#meta"},properties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},patternProperties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},propertyNames:{format:"regex"},default:{}},dependentSchemas:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},propertyNames:{$dynamicRef:"#meta"},if:{$dynamicRef:"#meta"},then:{$dynamicRef:"#meta"},else:{$dynamicRef:"#meta"},allOf:{$ref:"#/$defs/schemaArray"},anyOf:{$ref:"#/$defs/schemaArray"},oneOf:{$ref:"#/$defs/schemaArray"},not:{$dynamicRef:"#meta"}},$defs:{schemaArray:{type:"array",minItems:1,items:{$dynamicRef:"#meta"}}}}});var hm=$((NC,D1)=>{D1.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/unevaluated",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0},$dynamicAnchor:"meta",title:"Unevaluated applicator vocabulary meta-schema",type:["object","boolean"],properties:{unevaluatedItems:{$dynamicRef:"#meta"},unevaluatedProperties:{$dynamicRef:"#meta"}}}});var mm=$((MC,F1)=>{F1.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/content",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:"meta",title:"Content vocabulary meta-schema",type:["object","boolean"],properties:{contentEncoding:{type:"string"},contentMediaType:{type:"string"},contentSchema:{$dynamicRef:"#meta"}}}});var ym=$((qC,V1)=>{V1.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/core",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0},$dynamicAnchor:"meta",title:"Core vocabulary meta-schema",type:["object","boolean"],properties:{$id:{$ref:"#/$defs/uriReferenceString",$comment:"Non-empty fragments not allowed.",pattern:"^[^#]*#?$"},$schema:{$ref:"#/$defs/uriString"},$ref:{$ref:"#/$defs/uriReferenceString"},$anchor:{$ref:"#/$defs/anchorString"},$dynamicRef:{$ref:"#/$defs/uriReferenceString"},$dynamicAnchor:{$ref:"#/$defs/anchorString"},$vocabulary:{type:"object",propertyNames:{$ref:"#/$defs/uriString"},additionalProperties:{type:"boolean"}},$comment:{type:"string"},$defs:{type:"object",additionalProperties:{$dynamicRef:"#meta"}}},$defs:{anchorString:{type:"string",pattern:"^[A-Za-z_][-A-Za-z0-9._]*$"},uriString:{type:"string",format:"uri"},uriReferenceString:{type:"string",format:"uri-reference"}}}});var gm=$((LC,U1)=>{U1.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/format-annotation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0},$dynamicAnchor:"meta",title:"Format vocabulary meta-schema for annotation results",type:["object","boolean"],properties:{format:{type:"string"}}}});var bm=$((jC,z1)=>{z1.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/meta-data",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/meta-data":!0},$dynamicAnchor:"meta",title:"Meta-data vocabulary meta-schema",type:["object","boolean"],properties:{title:{type:"string"},description:{type:"string"},default:!0,deprecated:{type:"boolean",default:!1},readOnly:{type:"boolean",default:!1},writeOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0}}}});var _m=$((DC,B1)=>{B1.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/validation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/validation":!0},$dynamicAnchor:"meta",title:"Validation vocabulary meta-schema",type:["object","boolean"],properties:{type:{anyOf:[{$ref:"#/$defs/simpleTypes"},{type:"array",items:{$ref:"#/$defs/simpleTypes"},minItems:1,uniqueItems:!0}]},const:!0,enum:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/$defs/nonNegativeInteger"},minLength:{$ref:"#/$defs/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},maxItems:{$ref:"#/$defs/nonNegativeInteger"},minItems:{$ref:"#/$defs/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},maxContains:{$ref:"#/$defs/nonNegativeInteger"},minContains:{$ref:"#/$defs/nonNegativeInteger",default:1},maxProperties:{$ref:"#/$defs/nonNegativeInteger"},minProperties:{$ref:"#/$defs/nonNegativeIntegerDefault0"},required:{$ref:"#/$defs/stringArray"},dependentRequired:{type:"object",additionalProperties:{$ref:"#/$defs/stringArray"}}},$defs:{nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{$ref:"#/$defs/nonNegativeInteger",default:0},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}}}});var vm=$(ad=>{"use strict";Object.defineProperty(ad,"__esModule",{value:!0});var H1=fm(),K1=pm(),G1=hm(),W1=mm(),J1=ym(),Y1=gm(),X1=bm(),Z1=_m(),Q1=["/properties"];function eA(r){return[H1,K1,G1,W1,J1,e(this,Y1),X1,e(this,Z1)].forEach(t=>this.addMetaSchema(t,void 0,!1)),this;function e(t,i){return r?t.$dataMetaSchema(i,Q1):i}}ad.default=eA});var Wn=$((me,ld)=>{"use strict";Object.defineProperty(me,"__esModule",{value:!0});me.MissingRefError=me.ValidationError=me.CodeGen=me.Name=me.nil=me.stringify=me.str=me._=me.KeywordCxt=me.Ajv2020=void 0;var tA=Qc(),rA=cm(),iA=od(),nA=vm(),cd="https://json-schema.org/draft/2020-12/schema",Li=class extends tA.default{constructor(e={}){super({...e,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){super._addVocabularies(),rA.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(iA.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data:e,meta:t}=this.opts;t&&(nA.default.call(this,e),this.refs["http://json-schema.org/schema"]=cd)}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(cd)?cd:void 0)}};me.Ajv2020=Li;ld.exports=me=Li;ld.exports.Ajv2020=Li;Object.defineProperty(me,"__esModule",{value:!0});me.default=Li;var sA=xi();Object.defineProperty(me,"KeywordCxt",{enumerable:!0,get:function(){return sA.KeywordCxt}});var ji=z();Object.defineProperty(me,"_",{enumerable:!0,get:function(){return ji._}});Object.defineProperty(me,"str",{enumerable:!0,get:function(){return ji.str}});Object.defineProperty(me,"stringify",{enumerable:!0,get:function(){return ji.stringify}});Object.defineProperty(me,"nil",{enumerable:!0,get:function(){return ji.nil}});Object.defineProperty(me,"Name",{enumerable:!0,get:function(){return ji.Name}});Object.defineProperty(me,"CodeGen",{enumerable:!0,get:function(){return ji.CodeGen}});var oA=Tn();Object.defineProperty(me,"ValidationError",{enumerable:!0,get:function(){return oA.default}});var aA=Ii();Object.defineProperty(me,"MissingRefError",{enumerable:!0,get:function(){return aA.default}})});var xm=$(Gt=>{"use strict";Object.defineProperty(Gt,"__esModule",{value:!0});Gt.formatNames=Gt.fastFormats=Gt.fullFormats=void 0;function Kt(r,e){return{validate:r,compare:e}}Gt.fullFormats={date:Kt(Em,pd),time:Kt(ud(!0),hd),"date-time":Kt(wm(!0),km),"iso-time":Kt(ud(),Am),"iso-date-time":Kt(wm(),Pm),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:pA,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:vA,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:hA,int32:{type:"number",validate:gA},int64:{type:"number",validate:bA},float:{type:"number",validate:Sm},double:{type:"number",validate:Sm},password:!0,binary:!0};Gt.fastFormats={...Gt.fullFormats,date:Kt(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,pd),time:Kt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,hd),"date-time":Kt(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,km),"iso-time":Kt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,Am),"iso-date-time":Kt(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,Pm),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};Gt.formatNames=Object.keys(Gt.fullFormats);function cA(r){return r%4===0&&(r%100!==0||r%400===0)}var lA=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,dA=[0,31,28,31,30,31,30,31,31,30,31,30,31];function Em(r){let e=lA.exec(r);if(!e)return!1;let t=+e[1],i=+e[2],n=+e[3];return i>=1&&i<=12&&n>=1&&n<=(i===2&&cA(t)?29:dA[i])}function pd(r,e){if(r&&e)return r>e?1:r23||u>59||r&&!a)return!1;if(n<=23&&s<=59&&o<60)return!0;let d=s-u*c,f=n-l*c-(d<0?1:0);return(f===23||f===-1)&&(d===59||d===-1)&&o<61}}function hd(r,e){if(!(r&&e))return;let t=new Date("2020-01-01T"+r).valueOf(),i=new Date("2020-01-01T"+e).valueOf();if(t&&i)return t-i}function Am(r,e){if(!(r&&e))return;let t=dd.exec(r),i=dd.exec(e);if(t&&i)return r=t[1]+t[2]+t[3],e=i[1]+i[2]+i[3],r>e?1:r=mA}function bA(r){return Number.isInteger(r)}function Sm(){return!0}var _A=/[^\\]\\Z/;function vA(r){if(_A.test(r))return!1;try{return new RegExp(r),!0}catch(e){return!1}}});var Rm=$(md=>{"use strict";Object.defineProperty(md,"__esModule",{value:!0});var wA=rl(),$A=bl(),SA=Dl(),EA=td(),Im=rd(),AA=[wA.default,$A.default,(0,SA.default)(),EA.default,Im.metadataVocabulary,Im.contentVocabulary];md.default=AA});var Tm=$((zC,kA)=>{kA.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 Cm=$((ye,yd)=>{"use strict";Object.defineProperty(ye,"__esModule",{value:!0});ye.MissingRefError=ye.ValidationError=ye.CodeGen=ye.Name=ye.nil=ye.stringify=ye.str=ye._=ye.KeywordCxt=ye.Ajv=void 0;var PA=Qc(),xA=Rm(),IA=od(),Om=Tm(),RA=["/properties"],xo="http://json-schema.org/draft-07/schema",Di=class extends PA.default{_addVocabularies(){super._addVocabularies(),xA.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(IA.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(Om,RA):Om;this.addMetaSchema(e,xo,!1),this.refs["http://json-schema.org/schema"]=xo}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(xo)?xo:void 0)}};ye.Ajv=Di;yd.exports=ye=Di;yd.exports.Ajv=Di;Object.defineProperty(ye,"__esModule",{value:!0});ye.default=Di;var TA=xi();Object.defineProperty(ye,"KeywordCxt",{enumerable:!0,get:function(){return TA.KeywordCxt}});var Fi=z();Object.defineProperty(ye,"_",{enumerable:!0,get:function(){return Fi._}});Object.defineProperty(ye,"str",{enumerable:!0,get:function(){return Fi.str}});Object.defineProperty(ye,"stringify",{enumerable:!0,get:function(){return Fi.stringify}});Object.defineProperty(ye,"nil",{enumerable:!0,get:function(){return Fi.nil}});Object.defineProperty(ye,"Name",{enumerable:!0,get:function(){return Fi.Name}});Object.defineProperty(ye,"CodeGen",{enumerable:!0,get:function(){return Fi.CodeGen}});var OA=Tn();Object.defineProperty(ye,"ValidationError",{enumerable:!0,get:function(){return OA.default}});var CA=Ii();Object.defineProperty(ye,"MissingRefError",{enumerable:!0,get:function(){return CA.default}})});var Nm=$(Vi=>{"use strict";Object.defineProperty(Vi,"__esModule",{value:!0});Vi.formatLimitDefinition=void 0;var NA=Cm(),Pt=z(),Tr=Pt.operators,Io={formatMaximum:{okStr:"<=",ok:Tr.LTE,fail:Tr.GT},formatMinimum:{okStr:">=",ok:Tr.GTE,fail:Tr.LT},formatExclusiveMaximum:{okStr:"<",ok:Tr.LT,fail:Tr.GTE},formatExclusiveMinimum:{okStr:">",ok:Tr.GT,fail:Tr.LTE}},MA={message:({keyword:r,schemaCode:e})=>(0,Pt.str)`should be ${Io[r].okStr} ${e}`,params:({keyword:r,schemaCode:e})=>(0,Pt._)`{comparison: ${Io[r].okStr}, limit: ${e}}`};Vi.formatLimitDefinition={keyword:Object.keys(Io),type:"string",schemaType:"string",$data:!0,error:MA,code(r){let{gen:e,data:t,schemaCode:i,keyword:n,it:s}=r,{opts:o,self:a}=s;if(!o.validateFormats)return;let c=new NA.KeywordCxt(s,a.RULES.all.format.definition,"format");c.$data?l():u();function l(){let f=e.scopeValue("formats",{ref:a.formats,code:o.code.formats}),p=e.const("fmt",(0,Pt._)`${f}[${c.schemaCode}]`);r.fail$data((0,Pt.or)((0,Pt._)`typeof ${p} != "object"`,(0,Pt._)`${p} instanceof RegExp`,(0,Pt._)`typeof ${p}.compare != "function"`,d(p)))}function u(){let f=c.schema,p=a.formats[f];if(!p||p===!0)return;if(typeof p!="object"||p instanceof RegExp||typeof p.compare!="function")throw new Error(`"${n}": format "${f}" does not define "compare" function`);let m=e.scopeValue("formats",{key:f,ref:p,code:o.code.formats?(0,Pt._)`${o.code.formats}${(0,Pt.getProperty)(f)}`:void 0});r.fail$data(d(m))}function d(f){return(0,Pt._)`${f}.compare(${t}, ${i}) ${Io[n].fail} 0`}},dependencies:["format"]};var qA=r=>(r.addKeyword(Vi.formatLimitDefinition),r);Vi.default=qA});var Yn=$((Jn,Lm)=>{"use strict";Object.defineProperty(Jn,"__esModule",{value:!0});var Ui=xm(),LA=Nm(),gd=z(),Mm=new gd.Name("fullFormats"),jA=new gd.Name("fastFormats"),bd=(r,e={keywords:!0})=>{if(Array.isArray(e))return qm(r,e,Ui.fullFormats,Mm),r;let[t,i]=e.mode==="fast"?[Ui.fastFormats,jA]:[Ui.fullFormats,Mm],n=e.formats||Ui.formatNames;return qm(r,n,t,i),e.keywords&&(0,LA.default)(r),r};bd.get=(r,e="full")=>{let i=(e==="fast"?Ui.fastFormats:Ui.fullFormats)[r];if(!i)throw new Error(`Unknown format "${r}"`);return i};function qm(r,e,t,i){var n,s;(n=(s=r.opts.code).formats)!==null&&n!==void 0||(s.formats=(0,gd._)`require("ajv-formats/dist/formats").${i}`);for(let o of e)r.addFormat(o,t[o])}Lm.exports=Jn=bd;Object.defineProperty(Jn,"__esModule",{value:!0});Jn.default=bd});var zi=$((HC,jm)=>{"use strict";var DA="2.0.0",FA=Number.MAX_SAFE_INTEGER||9007199254740991,VA=16,UA=250,zA=["major","premajor","minor","preminor","patch","prepatch","prerelease"];jm.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:VA,MAX_SAFE_BUILD_LENGTH:UA,MAX_SAFE_INTEGER:FA,RELEASE_TYPES:zA,SEMVER_SPEC_VERSION:DA,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var Xn=$((KC,Dm)=>{"use strict";var BA=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...r)=>console.error("SEMVER",...r):()=>{};Dm.exports=BA});var Bi=$((Wt,Fm)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:_d,MAX_SAFE_BUILD_LENGTH:HA,MAX_LENGTH:KA}=zi(),GA=Xn();Wt=Fm.exports={};var WA=Wt.re=[],JA=Wt.safeRe=[],q=Wt.src=[],YA=Wt.safeSrc=[],L=Wt.t={},XA=0,vd="[a-zA-Z0-9-]",ZA=[["\\s",1],["\\d",KA],[vd,HA]],QA=r=>{for(let[e,t]of ZA)r=r.split(`${e}*`).join(`${e}{0,${t}}`).split(`${e}+`).join(`${e}{1,${t}}`);return r},B=(r,e,t)=>{let i=QA(e),n=XA++;GA(r,n,e),L[r]=n,q[n]=e,YA[n]=i,WA[n]=new RegExp(e,t?"g":void 0),JA[n]=new RegExp(i,t?"g":void 0)};B("NUMERICIDENTIFIER","0|[1-9]\\d*");B("NUMERICIDENTIFIERLOOSE","\\d+");B("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${vd}*`);B("MAINVERSION",`(${q[L.NUMERICIDENTIFIER]})\\.(${q[L.NUMERICIDENTIFIER]})\\.(${q[L.NUMERICIDENTIFIER]})`);B("MAINVERSIONLOOSE",`(${q[L.NUMERICIDENTIFIERLOOSE]})\\.(${q[L.NUMERICIDENTIFIERLOOSE]})\\.(${q[L.NUMERICIDENTIFIERLOOSE]})`);B("PRERELEASEIDENTIFIER",`(?:${q[L.NONNUMERICIDENTIFIER]}|${q[L.NUMERICIDENTIFIER]})`);B("PRERELEASEIDENTIFIERLOOSE",`(?:${q[L.NONNUMERICIDENTIFIER]}|${q[L.NUMERICIDENTIFIERLOOSE]})`);B("PRERELEASE",`(?:-(${q[L.PRERELEASEIDENTIFIER]}(?:\\.${q[L.PRERELEASEIDENTIFIER]})*))`);B("PRERELEASELOOSE",`(?:-?(${q[L.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${q[L.PRERELEASEIDENTIFIERLOOSE]})*))`);B("BUILDIDENTIFIER",`${vd}+`);B("BUILD",`(?:\\+(${q[L.BUILDIDENTIFIER]}(?:\\.${q[L.BUILDIDENTIFIER]})*))`);B("FULLPLAIN",`v?${q[L.MAINVERSION]}${q[L.PRERELEASE]}?${q[L.BUILD]}?`);B("FULL",`^${q[L.FULLPLAIN]}$`);B("LOOSEPLAIN",`[v=\\s]*${q[L.MAINVERSIONLOOSE]}${q[L.PRERELEASELOOSE]}?${q[L.BUILD]}?`);B("LOOSE",`^${q[L.LOOSEPLAIN]}$`);B("GTLT","((?:<|>)?=?)");B("XRANGEIDENTIFIERLOOSE",`${q[L.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);B("XRANGEIDENTIFIER",`${q[L.NUMERICIDENTIFIER]}|x|X|\\*`);B("XRANGEPLAIN",`[v=\\s]*(${q[L.XRANGEIDENTIFIER]})(?:\\.(${q[L.XRANGEIDENTIFIER]})(?:\\.(${q[L.XRANGEIDENTIFIER]})(?:${q[L.PRERELEASE]})?${q[L.BUILD]}?)?)?`);B("XRANGEPLAINLOOSE",`[v=\\s]*(${q[L.XRANGEIDENTIFIERLOOSE]})(?:\\.(${q[L.XRANGEIDENTIFIERLOOSE]})(?:\\.(${q[L.XRANGEIDENTIFIERLOOSE]})(?:${q[L.PRERELEASELOOSE]})?${q[L.BUILD]}?)?)?`);B("XRANGE",`^${q[L.GTLT]}\\s*${q[L.XRANGEPLAIN]}$`);B("XRANGELOOSE",`^${q[L.GTLT]}\\s*${q[L.XRANGEPLAINLOOSE]}$`);B("COERCEPLAIN",`(^|[^\\d])(\\d{1,${_d}})(?:\\.(\\d{1,${_d}}))?(?:\\.(\\d{1,${_d}}))?`);B("COERCE",`${q[L.COERCEPLAIN]}(?:$|[^\\d])`);B("COERCEFULL",q[L.COERCEPLAIN]+`(?:${q[L.PRERELEASE]})?(?:${q[L.BUILD]})?(?:$|[^\\d])`);B("COERCERTL",q[L.COERCE],!0);B("COERCERTLFULL",q[L.COERCEFULL],!0);B("LONETILDE","(?:~>?)");B("TILDETRIM",`(\\s*)${q[L.LONETILDE]}\\s+`,!0);Wt.tildeTrimReplace="$1~";B("TILDE",`^${q[L.LONETILDE]}${q[L.XRANGEPLAIN]}$`);B("TILDELOOSE",`^${q[L.LONETILDE]}${q[L.XRANGEPLAINLOOSE]}$`);B("LONECARET","(?:\\^)");B("CARETTRIM",`(\\s*)${q[L.LONECARET]}\\s+`,!0);Wt.caretTrimReplace="$1^";B("CARET",`^${q[L.LONECARET]}${q[L.XRANGEPLAIN]}$`);B("CARETLOOSE",`^${q[L.LONECARET]}${q[L.XRANGEPLAINLOOSE]}$`);B("COMPARATORLOOSE",`^${q[L.GTLT]}\\s*(${q[L.LOOSEPLAIN]})$|^$`);B("COMPARATOR",`^${q[L.GTLT]}\\s*(${q[L.FULLPLAIN]})$|^$`);B("COMPARATORTRIM",`(\\s*)${q[L.GTLT]}\\s*(${q[L.LOOSEPLAIN]}|${q[L.XRANGEPLAIN]})`,!0);Wt.comparatorTrimReplace="$1$2$3";B("HYPHENRANGE",`^\\s*(${q[L.XRANGEPLAIN]})\\s+-\\s+(${q[L.XRANGEPLAIN]})\\s*$`);B("HYPHENRANGELOOSE",`^\\s*(${q[L.XRANGEPLAINLOOSE]})\\s+-\\s+(${q[L.XRANGEPLAINLOOSE]})\\s*$`);B("STAR","(<|>)?=?\\s*\\*");B("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");B("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")});var Ro=$((GC,Vm)=>{"use strict";var ek=Object.freeze({loose:!0}),tk=Object.freeze({}),rk=r=>r?typeof r!="object"?ek:r:tk;Vm.exports=rk});var wd=$((WC,Bm)=>{"use strict";var Um=/^[0-9]+$/,zm=(r,e)=>{if(typeof r=="number"&&typeof e=="number")return r===e?0:rzm(e,r);Bm.exports={compareIdentifiers:zm,rcompareIdentifiers:ik}});var Le=$((JC,Km)=>{"use strict";var To=Xn(),{MAX_LENGTH:Hm,MAX_SAFE_INTEGER:Oo}=zi(),{safeRe:Co,t:No}=Bi(),nk=Ro(),{compareIdentifiers:$d}=wd(),sk=(r,e)=>{let t=e.split(".");if(t.length>r.length)return!1;for(let i=0;iHm)throw new TypeError(`version is longer than ${Hm} characters`);To("SemVer",e,t),this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease;let i=e.trim().match(t.loose?Co[No.LOOSE]:Co[No.FULL]);if(!i)throw new TypeError(`Invalid Version: ${e}`);if(this.raw=e,this.major=+i[1],this.minor=+i[2],this.patch=+i[3],this.major>Oo||this.major<0)throw new TypeError("Invalid major version");if(this.minor>Oo||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>Oo||this.patch<0)throw new TypeError("Invalid patch version");i[4]?this.prerelease=i[4].split(".").map(n=>{if(/^[0-9]+$/.test(n)){let s=+n;if(s>=0&&se.major?1:this.minore.minor?1:this.patche.patch?1:0}comparePre(e){if(e instanceof r||(e=new r(e,this.options)),this.prerelease.length&&!e.prerelease.length)return-1;if(!this.prerelease.length&&e.prerelease.length)return 1;if(!this.prerelease.length&&!e.prerelease.length)return 0;let t=0;do{let i=this.prerelease[t],n=e.prerelease[t];if(To("prerelease compare",t,i,n),i===void 0&&n===void 0)return 0;if(n===void 0)return 1;if(i===void 0)return-1;if(i===n)continue;return $d(i,n)}while(++t)}compareBuild(e){e instanceof r||(e=new r(e,this.options));let t=0;do{let i=this.build[t],n=e.build[t];if(To("build compare",t,i,n),i===void 0&&n===void 0)return 0;if(n===void 0)return 1;if(i===void 0)return-1;if(i===n)continue;return $d(i,n)}while(++t)}inc(e,t,i){if(e.startsWith("pre")){if(!t&&i===!1)throw new Error("invalid increment argument: identifier is empty");if(t){let n=`-${t}`.match(this.options.loose?Co[No.PRERELEASELOOSE]:Co[No.PRERELEASE]);if(!n||n[1]!==t)throw new Error(`invalid identifier: ${t}`)}}switch(e){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",t,i);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",t,i);break;case"prepatch":this.prerelease.length=0,this.inc("patch",t,i),this.inc("pre",t,i);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",t,i),this.inc("pre",t,i);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{let n=Number(i)?1:0;if(this.prerelease.length===0)this.prerelease=[n];else{let s=this.prerelease.length;for(;--s>=0;)typeof this.prerelease[s]=="number"&&(this.prerelease[s]++,s=-2);if(s===-1){if(t===this.prerelease.join(".")&&i===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(n)}}if(t){let s=[t,n];if(i===!1&&(s=[t]),sk(this.prerelease,t)){let o=this.prerelease[t.split(".").length];isNaN(o)&&(this.prerelease=s)}else this.prerelease=s}break}default:throw new Error(`invalid increment argument: ${e}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};Km.exports=Sd});var Or=$((YC,Wm)=>{"use strict";var Gm=Le(),ok=(r,e,t=!1)=>{if(r instanceof Gm)return r;try{return new Gm(r,e)}catch(i){if(!t)return null;throw i}};Wm.exports=ok});var Ym=$((XC,Jm)=>{"use strict";var ak=Or(),ck=(r,e)=>{let t=ak(r,e);return t?t.version:null};Jm.exports=ck});var Zm=$((ZC,Xm)=>{"use strict";var lk=Or(),dk=(r,e)=>{let t=lk(r.trim().replace(/^[=v]+/,""),e);return t?t.version:null};Xm.exports=dk});var ty=$((QC,ey)=>{"use strict";var Qm=Le(),uk=(r,e,t,i,n)=>{typeof t=="string"&&(n=i,i=t,t=void 0);try{return new Qm(r instanceof Qm?r.version:r,t).inc(e,i,n).version}catch(s){return null}};ey.exports=uk});var ny=$((eN,iy)=>{"use strict";var ry=Or(),fk=(r,e)=>{let t=ry(r,null,!0),i=ry(e,null,!0),n=t.compare(i);if(n===0)return null;let s=n>0,o=s?t:i,a=s?i:t,c=!!o.prerelease.length;if(!!a.prerelease.length&&!c){if(!a.patch&&!a.minor)return"major";if(a.compareMain(o)===0)return a.minor&&!a.patch?"minor":"patch"}let u=c?"pre":"";return t.major!==i.major?u+"major":t.minor!==i.minor?u+"minor":t.patch!==i.patch?u+"patch":"prerelease"};iy.exports=fk});var oy=$((tN,sy)=>{"use strict";var pk=Le(),hk=(r,e)=>new pk(r,e).major;sy.exports=hk});var cy=$((rN,ay)=>{"use strict";var mk=Le(),yk=(r,e)=>new mk(r,e).minor;ay.exports=yk});var dy=$((iN,ly)=>{"use strict";var gk=Le(),bk=(r,e)=>new gk(r,e).patch;ly.exports=bk});var fy=$((nN,uy)=>{"use strict";var _k=Or(),vk=(r,e)=>{let t=_k(r,e);return t&&t.prerelease.length?t.prerelease:null};uy.exports=vk});var bt=$((sN,hy)=>{"use strict";var py=Le(),wk=(r,e,t)=>new py(r,t).compare(new py(e,t));hy.exports=wk});var yy=$((oN,my)=>{"use strict";var $k=bt(),Sk=(r,e,t)=>$k(e,r,t);my.exports=Sk});var by=$((aN,gy)=>{"use strict";var Ek=bt(),Ak=(r,e)=>Ek(r,e,!0);gy.exports=Ak});var Mo=$((cN,vy)=>{"use strict";var _y=Le(),kk=(r,e,t)=>{let i=new _y(r,t),n=new _y(e,t);return i.compare(n)||i.compareBuild(n)};vy.exports=kk});var $y=$((lN,wy)=>{"use strict";var Pk=Mo(),xk=(r,e)=>r.sort((t,i)=>Pk(t,i,e));wy.exports=xk});var Ey=$((dN,Sy)=>{"use strict";var Ik=Mo(),Rk=(r,e)=>r.sort((t,i)=>Ik(i,t,e));Sy.exports=Rk});var Zn=$((uN,Ay)=>{"use strict";var Tk=bt(),Ok=(r,e,t)=>Tk(r,e,t)>0;Ay.exports=Ok});var qo=$((fN,ky)=>{"use strict";var Ck=bt(),Nk=(r,e,t)=>Ck(r,e,t)<0;ky.exports=Nk});var Ed=$((pN,Py)=>{"use strict";var Mk=bt(),qk=(r,e,t)=>Mk(r,e,t)===0;Py.exports=qk});var Ad=$((hN,xy)=>{"use strict";var Lk=bt(),jk=(r,e,t)=>Lk(r,e,t)!==0;xy.exports=jk});var Lo=$((mN,Iy)=>{"use strict";var Dk=bt(),Fk=(r,e,t)=>Dk(r,e,t)>=0;Iy.exports=Fk});var jo=$((yN,Ry)=>{"use strict";var Vk=bt(),Uk=(r,e,t)=>Vk(r,e,t)<=0;Ry.exports=Uk});var kd=$((gN,Ty)=>{"use strict";var zk=Ed(),Bk=Ad(),Hk=Zn(),Kk=Lo(),Gk=qo(),Wk=jo(),Jk=(r,e,t,i)=>{switch(e){case"===":return typeof r=="object"&&(r=r.version),typeof t=="object"&&(t=t.version),r===t;case"!==":return typeof r=="object"&&(r=r.version),typeof t=="object"&&(t=t.version),r!==t;case"":case"=":case"==":return zk(r,t,i);case"!=":return Bk(r,t,i);case">":return Hk(r,t,i);case">=":return Kk(r,t,i);case"<":return Gk(r,t,i);case"<=":return Wk(r,t,i);default:throw new TypeError(`Invalid operator: ${e}`)}};Ty.exports=Jk});var Cy=$((bN,Oy)=>{"use strict";var Yk=Le(),Xk=Or(),{safeRe:Do,t:Fo}=Bi(),Zk=(r,e)=>{if(r instanceof Yk)return r;if(typeof r=="number"&&(r=String(r)),typeof r!="string")return null;e=e||{};let t=null;if(!e.rtl)t=r.match(e.includePrerelease?Do[Fo.COERCEFULL]:Do[Fo.COERCE]);else{let c=e.includePrerelease?Do[Fo.COERCERTLFULL]:Do[Fo.COERCERTL],l;for(;(l=c.exec(r))&&(!t||t.index+t[0].length!==r.length);)(!t||l.index+l[0].length!==t.index+t[0].length)&&(t=l),c.lastIndex=l.index+l[1].length+l[2].length;c.lastIndex=-1}if(t===null)return null;let i=t[2],n=t[3]||"0",s=t[4]||"0",o=e.includePrerelease&&t[5]?`-${t[5]}`:"",a=e.includePrerelease&&t[6]?`+${t[6]}`:"";return Xk(`${i}.${n}.${s}${o}${a}`,e)};Oy.exports=Zk});var My=$((_N,Ny)=>{"use strict";var Qk=Or(),eP=zi(),tP=Le(),rP=(r,e,t)=>{if(!eP.RELEASE_TYPES.includes(e))return null;let i=iP(r,t);return i&&nP(i,e)},iP=(r,e)=>{let t=r instanceof tP?r.version:r;return Qk(t,e)},nP=(r,e)=>{if(sP(e))return r.version;switch(r.prerelease=[],e){case"major":r.minor=0,r.patch=0;break;case"minor":r.patch=0;break}return r.format()},sP=r=>r.startsWith("pre");Ny.exports=rP});var Ly=$((vN,qy)=>{"use strict";var Pd=class{constructor(){this.max=1e3,this.map=new Map}get(e){let t=this.map.get(e);if(t!==void 0)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}};qy.exports=Pd});var _t=$((wN,Vy)=>{"use strict";var oP=/\s+/g,xd=class r{constructor(e,t){if(t=cP(t),e instanceof r)return e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease?e:new r(e.raw,t);if(e instanceof Id)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(oP," "),this.set=this.raw.split("||").map(i=>this.parseRange(i.trim())).filter(i=>i.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let i=this.set[0];if(this.set=this.set.filter(n=>!Dy(n[0])),this.set.length===0)this.set=[i];else if(this.set.length>1){for(let n of this.set)if(n.length===1&&gP(n[0])){this.set=[n];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let e=0;e0&&(this.formatted+="||");let t=this.set[e];for(let i=0;i0&&(this.formatted+=" "),this.formatted+=t[i].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(e){e=e.replace(yP,"");let i=((this.options.includePrerelease&&hP)|(this.options.loose&&mP))+":"+e,n=jy.get(i);if(n)return n;let s=this.options.loose,o=s?We[je.HYPHENRANGELOOSE]:We[je.HYPHENRANGE];e=e.replace(o,xP(this.options.includePrerelease)),ge("hyphen replace",e),e=e.replace(We[je.COMPARATORTRIM],uP),ge("comparator trim",e),e=e.replace(We[je.TILDETRIM],fP),ge("tilde trim",e),e=e.replace(We[je.CARETTRIM],pP),ge("caret trim",e);let a=e.split(" ").map(d=>bP(d,this.options)).join(" ").split(/\s+/).map(d=>PP(d,this.options));s&&(a=a.filter(d=>(ge("loose invalid filter",d,this.options),!!d.match(We[je.COMPARATORLOOSE])))),ge("range list",a);let c=new Map,l=a.map(d=>new Id(d,this.options));for(let d of l){if(Dy(d))return[d];c.set(d.value,d)}c.size>1&&c.has("")&&c.delete("");let u=[...c.values()];return jy.set(i,u),u}intersects(e,t){if(!(e instanceof r))throw new TypeError("a Range is required");return this.set.some(i=>Fy(i,t)&&e.set.some(n=>Fy(n,t)&&i.every(s=>n.every(o=>s.intersects(o,t)))))}test(e){if(!e)return!1;if(typeof e=="string")try{e=new lP(e,this.options)}catch(t){return!1}for(let t=0;tr.value==="<0.0.0-0",gP=r=>r.value==="",Fy=(r,e)=>{let t=!0,i=r.slice(),n=i.pop();for(;t&&i.length;)t=i.every(s=>n.intersects(s,e)),n=i.pop();return t},bP=(r,e)=>(r=r.replace(We[je.BUILD],""),ge("comp",r,e),r=$P(r,e),ge("caret",r),r=vP(r,e),ge("tildes",r),r=EP(r,e),ge("xrange",r),r=kP(r,e),ge("stars",r),r),Ie=r=>!r||r.toLowerCase()==="x"||r==="*",_P=(r,e,t)=>Ie(r)&&!Ie(e)||Ie(e)&&t&&!Ie(t),vP=(r,e)=>r.trim().split(/\s+/).map(t=>wP(t,e)).join(" "),wP=(r,e)=>{let t=e.loose?We[je.TILDELOOSE]:We[je.TILDE],i=e.includePrerelease?"-0":"";return r.replace(t,(n,s,o,a,c)=>{ge("tilde",r,n,s,o,a,c);let l;return Ie(s)?l="":Ie(o)?l=`>=${s}.0.0${i} <${+s+1}.0.0-0`:Ie(a)?l=`>=${s}.${o}.0${i} <${s}.${+o+1}.0-0`:c?(ge("replaceTilde pr",c),l=`>=${s}.${o}.${a}-${c} <${s}.${+o+1}.0-0`):l=`>=${s}.${o}.${a} <${s}.${+o+1}.0-0`,ge("tilde return",l),l})},$P=(r,e)=>r.trim().split(/\s+/).map(t=>SP(t,e)).join(" "),SP=(r,e)=>{ge("caret",r,e);let t=e.loose?We[je.CARETLOOSE]:We[je.CARET],i=e.includePrerelease?"-0":"";return r.replace(t,(n,s,o,a,c)=>{ge("caret",r,n,s,o,a,c);let l;return Ie(s)?l="":Ie(o)?l=`>=${s}.0.0${i} <${+s+1}.0.0-0`:Ie(a)?s==="0"?l=`>=${s}.${o}.0${i} <${s}.${+o+1}.0-0`:l=`>=${s}.${o}.0${i} <${+s+1}.0.0-0`:c?(ge("replaceCaret pr",c),s==="0"?o==="0"?l=`>=${s}.${o}.${a}-${c} <${s}.${o}.${+a+1}-0`:l=`>=${s}.${o}.${a}-${c} <${s}.${+o+1}.0-0`:l=`>=${s}.${o}.${a}-${c} <${+s+1}.0.0-0`):(ge("no pr"),s==="0"?o==="0"?l=`>=${s}.${o}.${a} <${s}.${o}.${+a+1}-0`:l=`>=${s}.${o}.${a} <${s}.${+o+1}.0-0`:l=`>=${s}.${o}.${a} <${+s+1}.0.0-0`),ge("caret return",l),l})},EP=(r,e)=>(ge("replaceXRanges",r,e),r.split(/\s+/).map(t=>AP(t,e)).join(" ")),AP=(r,e)=>{r=r.trim();let t=e.loose?We[je.XRANGELOOSE]:We[je.XRANGE];return r.replace(t,(i,n,s,o,a,c)=>{if(ge("xRange",r,i,n,s,o,a,c),_P(s,o,a))return r;let l=Ie(s),u=l||Ie(o),d=u||Ie(a),f=d;return n==="="&&f&&(n=""),c=e.includePrerelease?"-0":"",l?n===">"||n==="<"?i="<0.0.0-0":i="*":n&&f?(u&&(o=0),a=0,n===">"?(n=">=",u?(s=+s+1,o=0,a=0):(o=+o+1,a=0)):n==="<="&&(n="<",u?s=+s+1:o=+o+1),n==="<"&&(c="-0"),i=`${n+s}.${o}.${a}${c}`):u?i=`>=${s}.0.0${c} <${+s+1}.0.0-0`:d&&(i=`>=${s}.${o}.0${c} <${s}.${+o+1}.0-0`),ge("xRange return",i),i})},kP=(r,e)=>(ge("replaceStars",r,e),r.trim().replace(We[je.STAR],"")),PP=(r,e)=>(ge("replaceGTE0",r,e),r.trim().replace(We[e.includePrerelease?je.GTE0PRE:je.GTE0],"")),xP=r=>(e,t,i,n,s,o,a,c,l,u,d,f)=>(Ie(i)?t="":Ie(n)?t=`>=${i}.0.0${r?"-0":""}`:Ie(s)?t=`>=${i}.${n}.0${r?"-0":""}`:o?t=`>=${t}`:t=`>=${t}${r?"-0":""}`,Ie(l)?c="":Ie(u)?c=`<${+l+1}.0.0-0`:Ie(d)?c=`<${l}.${+u+1}.0-0`:f?c=`<=${l}.${u}.${d}-${f}`:r?c=`<${l}.${u}.${+d+1}-0`:c=`<=${c}`,`${t} ${c}`.trim()),IP=(r,e,t)=>{for(let i=0;i0){let n=r[i].semver;if(n.major===e.major&&n.minor===e.minor&&n.patch===e.patch)return!0}return!1}return!0}});var Qn=$(($N,Gy)=>{"use strict";var es=Symbol("SemVer ANY"),Od=class r{static get ANY(){return es}constructor(e,t){if(t=Uy(t),e instanceof r){if(e.loose===!!t.loose)return e;e=e.value}e=e.trim().split(/\s+/).join(" "),Td("comparator",e,t),this.options=t,this.loose=!!t.loose,this.parse(e),this.semver===es?this.value="":this.value=this.operator+this.semver.version,Td("comp",this)}parse(e){let t=this.options.loose?zy[By.COMPARATORLOOSE]:zy[By.COMPARATOR],i=e.match(t);if(!i)throw new TypeError(`Invalid comparator: ${e}`);this.operator=i[1]!==void 0?i[1]:"",this.operator==="="&&(this.operator=""),i[2]?this.semver=new Hy(i[2],this.options.loose):this.semver=es}toString(){return this.value}test(e){if(Td("Comparator.test",e,this.options.loose),this.semver===es||e===es)return!0;if(typeof e=="string")try{e=new Hy(e,this.options)}catch(t){return!1}return Rd(e,this.operator,this.semver,this.options)}intersects(e,t){if(!(e instanceof r))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new Ky(e.value,t).test(this.value):e.operator===""?e.value===""?!0:new Ky(this.value,t).test(e.semver):(t=Uy(t),t.includePrerelease&&(this.value==="<0.0.0-0"||e.value==="<0.0.0-0")||!t.includePrerelease&&(this.value.startsWith("<0.0.0")||e.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&e.operator.startsWith(">")||this.operator.startsWith("<")&&e.operator.startsWith("<")||this.semver.version===e.semver.version&&this.operator.includes("=")&&e.operator.includes("=")||Rd(this.semver,"<",e.semver,t)&&this.operator.startsWith(">")&&e.operator.startsWith("<")||Rd(this.semver,">",e.semver,t)&&this.operator.startsWith("<")&&e.operator.startsWith(">")))}};Gy.exports=Od;var Uy=Ro(),{safeRe:zy,t:By}=Bi(),Rd=kd(),Td=Xn(),Hy=Le(),Ky=_t()});var ts=$((SN,Wy)=>{"use strict";var RP=_t(),TP=(r,e,t)=>{try{e=new RP(e,t)}catch(i){return!1}return e.test(r)};Wy.exports=TP});var Yy=$((EN,Jy)=>{"use strict";var OP=_t(),CP=(r,e)=>new OP(r,e).set.map(t=>t.map(i=>i.value).join(" ").trim().split(" "));Jy.exports=CP});var Zy=$((AN,Xy)=>{"use strict";var NP=Le(),MP=_t(),qP=(r,e,t)=>{let i=null,n=null,s=null;try{s=new MP(e,t)}catch(o){return null}return r.forEach(o=>{s.test(o)&&(!i||n.compare(o)===-1)&&(i=o,n=new NP(i,t))}),i};Xy.exports=qP});var eg=$((kN,Qy)=>{"use strict";var LP=Le(),jP=_t(),DP=(r,e,t)=>{let i=null,n=null,s=null;try{s=new jP(e,t)}catch(o){return null}return r.forEach(o=>{s.test(o)&&(!i||n.compare(o)===1)&&(i=o,n=new LP(i,t))}),i};Qy.exports=DP});var ig=$((PN,rg)=>{"use strict";var Cd=Le(),FP=_t(),tg=Zn(),VP=(r,e)=>{r=new FP(r,e);let t=new Cd("0.0.0");if(r.test(t)||(t=new Cd("0.0.0-0"),r.test(t)))return t;t=null;for(let i=0;i{let a=new Cd(o.semver.version);switch(o.operator){case">":a.prerelease.length===0?a.patch++:a.prerelease.push(0),a.raw=a.format();case"":case">=":(!s||tg(a,s))&&(s=a);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${o.operator}`)}}),s&&(!t||tg(t,s))&&(t=s)}return t&&r.test(t)?t:null};rg.exports=VP});var sg=$((xN,ng)=>{"use strict";var UP=_t(),zP=(r,e)=>{try{return new UP(r,e).range||"*"}catch(t){return null}};ng.exports=zP});var Vo=$((IN,lg)=>{"use strict";var BP=Le(),cg=Qn(),{ANY:HP}=cg,KP=_t(),GP=ts(),og=Zn(),ag=qo(),WP=jo(),JP=Lo(),YP=(r,e,t,i)=>{r=new BP(r,i),e=new KP(e,i);let n,s,o,a,c;switch(t){case">":n=og,s=WP,o=ag,a=">",c=">=";break;case"<":n=ag,s=JP,o=og,a="<",c="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(GP(r,e,i))return!1;for(let l=0;l{p.semver===HP&&(p=new cg(">=0.0.0")),d=d||p,f=f||p,n(p.semver,d.semver,i)?d=p:o(p.semver,f.semver,i)&&(f=p)}),d.operator===a||d.operator===c||(!f.operator||f.operator===a)&&s(r,f.semver))return!1;if(f.operator===c&&o(r,f.semver))return!1}return!0};lg.exports=YP});var ug=$((RN,dg)=>{"use strict";var XP=Vo(),ZP=(r,e,t)=>XP(r,e,">",t);dg.exports=ZP});var pg=$((TN,fg)=>{"use strict";var QP=Vo(),ex=(r,e,t)=>QP(r,e,"<",t);fg.exports=ex});var yg=$((ON,mg)=>{"use strict";var hg=_t(),tx=(r,e,t)=>(r=new hg(r,t),e=new hg(e,t),r.intersects(e,t));mg.exports=tx});var bg=$((CN,gg)=>{"use strict";var rx=ts(),ix=bt();gg.exports=(r,e,t)=>{let i=[],n=null,s=null,o=r.sort((u,d)=>ix(u,d,t));for(let u of o)rx(u,e,t)?(s=u,n||(n=u)):(s&&i.push([n,s]),s=null,n=null);n&&i.push([n,null]);let a=[];for(let[u,d]of i)u===d?a.push(u):!d&&u===o[0]?a.push("*"):d?u===o[0]?a.push(`<=${d}`):a.push(`${u} - ${d}`):a.push(`>=${u}`);let c=a.join(" || "),l=typeof e.raw=="string"?e.raw:String(e);return c.length{"use strict";var _g=_t(),qd=Qn(),{ANY:Nd}=qd,Md=ts(),Ld=bt(),nx=(r,e,t={})=>{if(r===e)return!0;r=new _g(r,t),e=new _g(e,t);let i=!1;e:for(let n of r.set){for(let s of e.set){let o=ox(n,s,t);if(i=i||o!==null,o)continue e}if(i)return!1}return!0},sx=[new qd(">=0.0.0-0")],vg=[new qd(">=0.0.0")],ox=(r,e,t)=>{if(r===e)return!0;if(r.length===1&&r[0].semver===Nd){if(e.length===1&&e[0].semver===Nd)return!0;t.includePrerelease?r=sx:r=vg}if(e.length===1&&e[0].semver===Nd){if(t.includePrerelease)return!0;e=vg}let i=new Set,n,s;for(let p of r)p.operator===">"||p.operator===">="?n=wg(n,p,t):p.operator==="<"||p.operator==="<="?s=$g(s,p,t):i.add(p.semver);if(i.size>1)return null;let o;if(n&&s){if(o=Ld(n.semver,s.semver,t),o>0)return null;if(o===0&&(n.operator!==">="||s.operator!=="<="))return null}for(let p of i){if(n&&!Md(p,String(n),t)||s&&!Md(p,String(s),t))return null;for(let m of e)if(!Md(p,String(m),t))return!1;return!0}let a,c,l,u,d=s&&!t.includePrerelease&&s.semver.prerelease.length?s.semver:!1,f=n&&!t.includePrerelease&&n.semver.prerelease.length?n.semver:!1;d&&d.prerelease.length===1&&s.operator==="<"&&d.prerelease[0]===0&&(d=!1);for(let p of e){if(u=u||p.operator===">"||p.operator===">=",l=l||p.operator==="<"||p.operator==="<=",n){if(f&&p.semver.prerelease&&p.semver.prerelease.length&&p.semver.major===f.major&&p.semver.minor===f.minor&&p.semver.patch===f.patch&&(f=!1),p.operator===">"||p.operator===">="){if(a=wg(n,p,t),a===p&&a!==n)return!1}else if(n.operator===">="&&!p.test(n.semver))return!1}if(s){if(d&&p.semver.prerelease&&p.semver.prerelease.length&&p.semver.major===d.major&&p.semver.minor===d.minor&&p.semver.patch===d.patch&&(d=!1),p.operator==="<"||p.operator==="<="){if(c=$g(s,p,t),c===p&&c!==s)return!1}else if(s.operator==="<="&&!p.test(s.semver))return!1}if(!p.operator&&(s||n)&&o!==0)return!1}return!(n&&l&&!s&&o!==0||s&&u&&!n&&o!==0||f||d)},wg=(r,e,t)=>{if(!r)return e;let i=Ld(r.semver,e.semver,t);return i>0?r:i<0||e.operator===">"&&r.operator===">="?e:r},$g=(r,e,t)=>{if(!r)return e;let i=Ld(r.semver,e.semver,t);return i<0?r:i>0||e.operator==="<"&&r.operator==="<="?e:r};Sg.exports=nx});var Dd=$((MN,Pg)=>{"use strict";var jd=Bi(),Ag=zi(),ax=Le(),kg=wd(),cx=Or(),lx=Ym(),dx=Zm(),ux=ty(),fx=ny(),px=oy(),hx=cy(),mx=dy(),yx=fy(),gx=bt(),bx=yy(),_x=by(),vx=Mo(),wx=$y(),$x=Ey(),Sx=Zn(),Ex=qo(),Ax=Ed(),kx=Ad(),Px=Lo(),xx=jo(),Ix=kd(),Rx=Cy(),Tx=My(),Ox=Qn(),Cx=_t(),Nx=ts(),Mx=Yy(),qx=Zy(),Lx=eg(),jx=ig(),Dx=sg(),Fx=Vo(),Vx=ug(),Ux=pg(),zx=yg(),Bx=bg(),Hx=Eg();Pg.exports={parse:cx,valid:lx,clean:dx,inc:ux,diff:fx,major:px,minor:hx,patch:mx,prerelease:yx,compare:gx,rcompare:bx,compareLoose:_x,compareBuild:vx,sort:wx,rsort:$x,gt:Sx,lt:Ex,eq:Ax,neq:kx,gte:Px,lte:xx,cmp:Ix,coerce:Rx,truncate:Tx,Comparator:Ox,Range:Cx,satisfies:Nx,toComparators:Mx,maxSatisfying:qx,minSatisfying:Lx,minVersion:jx,validRange:Dx,outside:Fx,gtr:Vx,ltr:Ux,intersects:zx,simplifyRange:Bx,subset:Hx,SemVer:ax,re:jd.re,src:jd.src,tokens:jd.t,SEMVER_SPEC_VERSION:Ag.SEMVER_SPEC_VERSION,RELEASE_TYPES:Ag.RELEASE_TYPES,compareIdentifiers:kg.compareIdentifiers,rcompareIdentifiers:kg.rcompareIdentifiers}});var as=$((wM,Jg)=>{"use strict";var Hg="[^\\\\/]",lI="(?=.)",Kg="[^/]",Zd="(?:\\/|$)",Gg="(?:^|\\/)",Qd=`\\.{1,2}${Zd}`,dI="(?!\\.)",uI=`(?!${Gg}${Qd})`,fI=`(?!\\.{0,1}${Zd})`,pI=`(?!${Qd})`,hI="[^.\\/]",mI=`${Kg}*?`,yI="/",Wg={DOT_LITERAL:"\\.",PLUS_LITERAL:"\\+",QMARK_LITERAL:"\\?",SLASH_LITERAL:"\\/",ONE_CHAR:lI,QMARK:Kg,END_ANCHOR:Zd,DOTS_SLASH:Qd,NO_DOT:dI,NO_DOTS:uI,NO_DOT_SLASH:fI,NO_DOTS_SLASH:pI,QMARK_NO_DOT:hI,STAR:mI,START_ANCHOR:Gg,SEP:yI},gI={...Wg,SLASH_LITERAL:"[\\\\/]",QMARK:Hg,STAR:`${Hg}*?`,DOTS_SLASH:"\\.{1,2}(?:[\\\\/]|$)",NO_DOT:"(?!\\.)",NO_DOTS:"(?!(?:^|[\\\\/])\\.{1,2}(?:[\\\\/]|$))",NO_DOT_SLASH:"(?!\\.{0,1}(?:[\\\\/]|$))",NO_DOTS_SLASH:"(?!\\.{1,2}(?:[\\\\/]|$))",QMARK_NO_DOT:"[^.\\\\/]",START_ANCHOR:"(?:^|[\\\\/])",END_ANCHOR:"(?:[\\\\/]|$)",SEP:"\\"},bI={__proto__:null,alnum:"a-zA-Z0-9",alpha:"a-zA-Z",ascii:"\\x00-\\x7F",blank:" \\t",cntrl:"\\x00-\\x1F\\x7F",digit:"0-9",graph:"\\x21-\\x7E",lower:"a-z",print:"\\x20-\\x7E ",punct:"\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",space:" \\t\\r\\n\\v\\f",upper:"A-Z",word:"A-Za-z0-9_",xdigit:"A-Fa-f0-9"};Jg.exports={DEFAULT_MAX_EXTGLOB_RECURSION:0,MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:bI,REGEX_BACKSLASH:/\\(?![*+?^${}(|)[\]])/g,REGEX_NON_SPECIAL_CHARS:/^[^@![\].,$*+?^{}()|\\/]+/,REGEX_SPECIAL_CHARS:/[-*+?.^${}(|)[\]]/,REGEX_SPECIAL_CHARS_BACKREF:/(\\?)((\W)(\3*))/g,REGEX_SPECIAL_CHARS_GLOBAL:/([-*+?.^${}(|)[\]])/g,REGEX_REMOVE_BACKSLASH:/(?:\[.*?[^\\]\]|\\(?=.))/g,REPLACEMENTS:{__proto__:null,"***":"*","**/**":"**","**/**/**":"**"},CHAR_0:48,CHAR_9:57,CHAR_UPPERCASE_A:65,CHAR_LOWERCASE_A:97,CHAR_UPPERCASE_Z:90,CHAR_LOWERCASE_Z:122,CHAR_LEFT_PARENTHESES:40,CHAR_RIGHT_PARENTHESES:41,CHAR_ASTERISK:42,CHAR_AMPERSAND:38,CHAR_AT:64,CHAR_BACKWARD_SLASH:92,CHAR_CARRIAGE_RETURN:13,CHAR_CIRCUMFLEX_ACCENT:94,CHAR_COLON:58,CHAR_COMMA:44,CHAR_DOT:46,CHAR_DOUBLE_QUOTE:34,CHAR_EQUAL:61,CHAR_EXCLAMATION_MARK:33,CHAR_FORM_FEED:12,CHAR_FORWARD_SLASH:47,CHAR_GRAVE_ACCENT:96,CHAR_HASH:35,CHAR_HYPHEN_MINUS:45,CHAR_LEFT_ANGLE_BRACKET:60,CHAR_LEFT_CURLY_BRACE:123,CHAR_LEFT_SQUARE_BRACKET:91,CHAR_LINE_FEED:10,CHAR_NO_BREAK_SPACE:160,CHAR_PERCENT:37,CHAR_PLUS:43,CHAR_QUESTION_MARK:63,CHAR_RIGHT_ANGLE_BRACKET:62,CHAR_RIGHT_CURLY_BRACE:125,CHAR_RIGHT_SQUARE_BRACKET:93,CHAR_SEMICOLON:59,CHAR_SINGLE_QUOTE:39,CHAR_SPACE:32,CHAR_TAB:9,CHAR_UNDERSCORE:95,CHAR_VERTICAL_LINE:124,CHAR_ZERO_WIDTH_NOBREAK_SPACE:65279,extglobChars(r){return{"!":{type:"negate",open:"(?:(?!(?:",close:`))${r.STAR})`},"?":{type:"qmark",open:"(?:",close:")?"},"+":{type:"plus",open:"(?:",close:")+"},"*":{type:"star",open:"(?:",close:")*"},"@":{type:"at",open:"(?:",close:")"}}},globChars(r){return r===!0?gI:Wg}}});var cs=$(rt=>{"use strict";var{REGEX_BACKSLASH:_I,REGEX_REMOVE_BACKSLASH:vI,REGEX_SPECIAL_CHARS:wI,REGEX_SPECIAL_CHARS_GLOBAL:$I}=as();rt.isObject=r=>r!==null&&typeof r=="object"&&!Array.isArray(r);rt.hasRegexChars=r=>wI.test(r);rt.isRegexChar=r=>r.length===1&&rt.hasRegexChars(r);rt.escapeRegex=r=>r.replace($I,"\\$1");rt.toPosixSlashes=r=>r.replace(_I,"/");rt.isWindows=()=>{if(typeof navigator!="undefined"&&navigator.platform){let r=navigator.platform.toLowerCase();return r==="win32"||r==="windows"}return typeof process!="undefined"&&process.platform?process.platform==="win32":!1};rt.removeBackslashes=r=>r.replace(vI,e=>e==="\\"?"":e);rt.escapeLast=(r,e,t)=>{let i=r.lastIndexOf(e,t);return i===-1?r:r[i-1]==="\\"?rt.escapeLast(r,e,i-1):`${r.slice(0,i)}\\${r.slice(i)}`};rt.removePrefix=(r,e={})=>{let t=r;return t.startsWith("./")&&(t=t.slice(2),e.prefix="./"),t};rt.wrapOutput=(r,e={},t={})=>{let i=t.contains?"":"^",n=t.contains?"":"$",s=`${i}(?:${r})${n}`;return e.negated===!0&&(s=`(?:^(?!${s}).*$)`),s};rt.basename=(r,{windows:e}={})=>{let t=r.split(e?/[\\/]/:"/"),i=t[t.length-1];return i===""?t[t.length-2]:i}});var ib=$((SM,rb)=>{"use strict";var Yg=cs(),{CHAR_ASTERISK:eu,CHAR_AT:SI,CHAR_BACKWARD_SLASH:ls,CHAR_COMMA:EI,CHAR_DOT:tu,CHAR_EXCLAMATION_MARK:ru,CHAR_FORWARD_SLASH:tb,CHAR_LEFT_CURLY_BRACE:iu,CHAR_LEFT_PARENTHESES:nu,CHAR_LEFT_SQUARE_BRACKET:AI,CHAR_PLUS:kI,CHAR_QUESTION_MARK:Xg,CHAR_RIGHT_CURLY_BRACE:PI,CHAR_RIGHT_PARENTHESES:Zg,CHAR_RIGHT_SQUARE_BRACKET:xI}=as(),Qg=r=>r===tb||r===ls,eb=r=>{r.isPrefix!==!0&&(r.depth=r.isGlobstar?1/0:1)},II=(r,e)=>{let t=e||{},i=r.length-1,n=t.parts===!0||t.scanToEnd===!0,s=[],o=[],a=[],c=r,l=-1,u=0,d=0,f=!1,p=!1,m=!1,h=!1,y=!1,b=!1,g=!1,_=!1,S=!1,v=!1,P=0,x,E,R={value:"",depth:0,isGlob:!1},w=()=>l>=i,F=()=>c.charCodeAt(l+1),V=()=>(x=E,c.charCodeAt(++l));for(;l0&&(A=c.slice(0,u),c=c.slice(u),d-=u),G&&m===!0&&d>0?(G=c.slice(0,d),k=c.slice(d)):m===!0?(G="",k=c):G=c,G&&G!==""&&G!=="/"&&G!==c&&Qg(G.charCodeAt(G.length-1))&&(G=G.slice(0,-1)),t.unescape===!0&&(k&&(k=Yg.removeBackslashes(k)),G&&g===!0&&(G=Yg.removeBackslashes(G)));let Ce={prefix:A,input:r,start:u,base:G,glob:k,isBrace:f,isBracket:p,isGlob:m,isExtglob:h,isGlobstar:y,negated:_,negatedExtglob:S};if(t.tokens===!0&&(Ce.maxDepth=0,Qg(E)||o.push(R),Ce.tokens=o),t.parts===!0||t.tokens===!0){let oe;for(let ae=0;ae{"use strict";var ds=as(),ot=cs(),{MAX_LENGTH:Xo,POSIX_REGEX_SOURCE:RI,REGEX_NON_SPECIAL_CHARS:TI,REGEX_SPECIAL_CHARS_BACKREF:OI,REPLACEMENTS:nb}=ds,CI=(r,e)=>{if(typeof e.expandRange=="function")return e.expandRange(...r,e);r.sort();let t=`[${r.join("-")}]`;try{new RegExp(t)}catch(i){return r.map(n=>ot.escapeRegex(n)).join("..")}return t},Gi=(r,e)=>`Missing ${r}: "${e}" - use "\\\\${e}" to match literal characters`,sb=r=>{let e=[],t=0,i=0,n=0,s="",o=!1;for(let a of r){if(o===!0){s+=a,o=!1;continue}if(a==="\\"){s+=a,o=!0;continue}if(a==='"'){n=n===1?0:1,s+=a;continue}if(n===0){if(a==="[")t++;else if(a==="]"&&t>0)t--;else if(t===0){if(a==="(")i++;else if(a===")"&&i>0)i--;else if(a==="|"&&i===0){e.push(s),s="";continue}}}s+=a}return e.push(s),e},NI=r=>{let e=!1;for(let t of r){if(e===!0){e=!1;continue}if(t==="\\"){e=!0;continue}if(/[?*+@!()[\]{}]/.test(t))return!1}return!0},ou=r=>{let e=r.trim(),t=!0;for(;t===!0;)t=!1,/^@\([^\\()[\]{}|]+\)$/.test(e)&&(e=e.slice(2,-1),t=!0);if(NI(e))return e.replace(/\\(.)/g,"$1")},MI=r=>{let e=r.map(ou).filter(Boolean);for(let t=0;t{if(r[0]!=="+"&&r[0]!=="*"||r[1]!=="(")return;let t=0,i=0,n=0,s=!1;for(let o=1;o0){t--;continue}if(!(t>0)){if(a==="("){i++;continue}if(a===")"&&(i--,i===0))return e===!0&&o!==r.length-1?void 0:{type:r[0],body:r.slice(2,o),end:o}}}}},qI=r=>`${r.length===1?ot.escapeRegex(r[0]):`[${r.map(t=>ot.escapeRegex(t)).join("")}]`}*`,LI=r=>{let e=0,t=[];for(;eo.trim());if(n.length!==1)return;let s=ou(n[0]);if(!s||s.length!==1)return;t.push(s),e+=i.end+1}if(!(t.length<1))return t},jI=r=>{let e=0,t=r.trim(),i=su(t);for(;i;)e++,t=i.body.trim(),i=su(t);return e},DI=(r,e)=>{if(e.maxExtglobRecursion===!1)return{risky:!1};let t=typeof e.maxExtglobRecursion=="number"?e.maxExtglobRecursion:ds.DEFAULT_MAX_EXTGLOB_RECURSION,i=sb(r).map(a=>a.trim());if(i.length>1&&(i.some(a=>a==="")||i.some(a=>/^[*?]+$/.test(a))||MI(i)))return{risky:!0};let n=[],s=!1,o=!0;for(let a of i){let c=LI(a);if(c){s=!0,n.push(...c);continue}let l=ou(a);if(l&&l.length===1){n.push(l);continue}if(o=!1,jI(a)>t)return{risky:!0}}return s?o?{risky:!0,safeOutput:qI([...new Set(n)])}:{risky:!0}:{risky:!1}},au=(r,e)=>{if(typeof r!="string")throw new TypeError("Expected a string");r=nb[r]||r;let t={...e},i=typeof t.maxLength=="number"?Math.min(Xo,t.maxLength):Xo,n=r.length;if(n>i)throw new SyntaxError(`Input length: ${n}, exceeds maximum allowed length: ${i}`);let s={type:"bos",value:"",output:t.prepend||""},o=[s],a=t.capture?"":"?:",c=ds.globChars(t.windows),l=ds.extglobChars(c),{DOT_LITERAL:u,PLUS_LITERAL:d,SLASH_LITERAL:f,ONE_CHAR:p,DOTS_SLASH:m,NO_DOT:h,NO_DOT_SLASH:y,NO_DOTS_SLASH:b,QMARK:g,QMARK_NO_DOT:_,STAR:S,START_ANCHOR:v}=c,P=C=>`(${a}(?:(?!${v}${C.dot?m:u}).)*?)`,x=t.dot?"":h,E=t.dot?g:_,R=t.bash===!0?P(t):S;t.capture&&(R=`(${R})`),typeof t.noext=="boolean"&&(t.noextglob=t.noext);let w={input:r,index:-1,start:0,dot:t.dot===!0,consumed:"",output:"",prefix:"",backtrack:!1,negated:!1,brackets:0,braces:0,parens:0,quotes:0,globstar:!1,tokens:o};r=ot.removePrefix(r,w),n=r.length;let F=[],V=[],G=[],A=s,k,Ce=()=>w.index===n-1,oe=w.peek=(C=1)=>r[w.index+C],ae=w.advance=()=>r[++w.index]||"",ir=()=>r.slice(w.index+1),ut=(C="",ve=0)=>{w.consumed+=C,w.index+=ve},wr=C=>{w.output+=C.output!=null?C.output:C.value,ut(C.value)},h_=()=>{let C=1;for(;oe()==="!"&&(oe(2)!=="("||oe(3)==="?");)ae(),w.start++,C++;return C%2===0?!1:(w.negated=!0,w.start++,!0)},Gs=C=>{w[C]++,G.push(C)},$r=C=>{w[C]--,G.pop()},X=C=>{if(A.type==="globstar"){let ve=w.braces>0&&(C.type==="comma"||C.type==="brace"),O=C.extglob===!0||F.length&&(C.type==="pipe"||C.type==="paren");C.type!=="slash"&&C.type!=="paren"&&!ve&&!O&&(w.output=w.output.slice(0,-A.output.length),A.type="star",A.value="*",A.output=R,w.output+=A.output)}if(F.length&&C.type!=="paren"&&(F[F.length-1].inner+=C.value),(C.value||C.output)&&wr(C),A&&A.type==="text"&&C.type==="text"){A.output=(A.output||A.value)+C.value,A.value+=C.value;return}C.prev=A,o.push(C),A=C},Ws=(C,ve)=>{let O={...l[ve],conditions:1,inner:""};O.prev=A,O.parens=w.parens,O.output=w.output,O.startIndex=w.index,O.tokensIndex=o.length;let Z=(t.capture?"(":"")+O.open;Gs("parens"),X({type:C,value:ve,output:w.output?"":p}),X({type:"paren",extglob:!0,value:ae(),output:Z}),F.push(O)},m_=C=>{let ve=r.slice(C.startIndex,w.index+1),O=r.slice(C.startIndex+2,w.index),Z=DI(O,t);if((C.type==="plus"||C.type==="star")&&Z.risky){let ue=Z.safeOutput?(C.output?"":p)+(t.capture?`(${Z.safeOutput})`:Z.safeOutput):void 0,Vt=o[C.tokensIndex];Vt.type="text",Vt.value=ve,Vt.output=ue||ot.escapeRegex(ve);for(let Ut=C.tokensIndex+1;Ut1&&C.inner.includes("/")&&(ue=P(t)),(ue!==R||Ce()||/^\)+$/.test(ir()))&&(pe=C.close=`)$))${ue}`),C.inner.includes("*")&&(xe=ir())&&/^\.[^\\/.]+$/.test(xe)){let Vt=au(xe,{...e,fastpaths:!1}).output;pe=C.close=`)${Vt})${ue})`}C.prev.type==="bos"&&(w.negatedExtglob=!0)}X({type:"paren",extglob:!0,value:k,output:pe}),$r("parens")};if(t.fastpaths!==!1&&!/(^[*!]|[/()[\]{}"])/.test(r)){let C=!1,ve=r.replace(OI,(O,Z,pe,xe,ue,Vt)=>xe==="\\"?(C=!0,O):xe==="?"?Z?Z+xe+(ue?g.repeat(ue.length):""):Vt===0?E+(ue?g.repeat(ue.length):""):g.repeat(pe.length):xe==="."?u.repeat(pe.length):xe==="*"?Z?Z+xe+(ue?R:""):R:Z?O:`\\${O}`);return C===!0&&(t.unescape===!0?ve=ve.replace(/\\/g,""):ve=ve.replace(/\\+/g,O=>O.length%2===0?"\\\\":O?"\\":"")),ve===r&&t.contains===!0?(w.output=r,w):(w.output=ot.wrapOutput(ve,w,e),w)}for(;!Ce();){if(k=ae(),k==="\0")continue;if(k==="\\"){let O=oe();if(O==="/"&&t.bash!==!0||O==="."||O===";")continue;if(!O){k+="\\",X({type:"text",value:k});continue}let Z=/^\\+/.exec(ir()),pe=0;if(Z&&Z[0].length>2&&(pe=Z[0].length,w.index+=pe,pe%2!==0&&(k+="\\")),t.unescape===!0?k=ae():k+=ae(),w.brackets===0){X({type:"text",value:k});continue}}if(w.brackets>0&&(k!=="]"||A.value==="["||A.value==="[^")){if(t.posix!==!1&&k===":"){let O=A.value.slice(1);if(O.includes("[")&&(A.posix=!0,O.includes(":"))){let Z=A.value.lastIndexOf("["),pe=A.value.slice(0,Z),xe=A.value.slice(Z+2),ue=RI[xe];if(ue){A.value=pe+ue,w.backtrack=!0,ae(),!s.output&&o.indexOf(A)===1&&(s.output=p);continue}}}(k==="["&&oe()!==":"||k==="-"&&oe()==="]")&&(k=`\\${k}`),k==="]"&&(A.value==="["||A.value==="[^")&&(k=`\\${k}`),t.posix===!0&&k==="!"&&A.value==="["&&(k="^"),A.value+=k,wr({value:k});continue}if(w.quotes===1&&k!=='"'){k=ot.escapeRegex(k),A.value+=k,wr({value:k});continue}if(k==='"'){w.quotes=w.quotes===1?0:1,t.keepQuotes===!0&&X({type:"text",value:k});continue}if(k==="("){Gs("parens"),X({type:"paren",value:k});continue}if(k===")"){if(w.parens===0&&t.strictBrackets===!0)throw new SyntaxError(Gi("opening","("));let O=F[F.length-1];if(O&&w.parens===O.parens+1){m_(F.pop());continue}X({type:"paren",value:k,output:w.parens?")":"\\)"}),$r("parens");continue}if(k==="["){if(t.nobracket===!0||!ir().includes("]")){if(t.nobracket!==!0&&t.strictBrackets===!0)throw new SyntaxError(Gi("closing","]"));k=`\\${k}`}else Gs("brackets");X({type:"bracket",value:k});continue}if(k==="]"){if(t.nobracket===!0||A&&A.type==="bracket"&&A.value.length===1){X({type:"text",value:k,output:`\\${k}`});continue}if(w.brackets===0){if(t.strictBrackets===!0)throw new SyntaxError(Gi("opening","["));X({type:"text",value:k,output:`\\${k}`});continue}$r("brackets");let O=A.value.slice(1);if(A.posix!==!0&&O[0]==="^"&&!O.includes("/")&&(k=`/${k}`),A.value+=k,wr({value:k}),t.literalBrackets===!1||ot.hasRegexChars(O))continue;let Z=ot.escapeRegex(A.value);if(w.output=w.output.slice(0,-A.value.length),t.literalBrackets===!0){w.output+=Z,A.value=Z;continue}A.value=`(${a}${Z}|${A.value})`,w.output+=A.value;continue}if(k==="{"&&t.nobrace!==!0){Gs("braces");let O={type:"brace",value:k,output:"(",outputIndex:w.output.length,tokensIndex:w.tokens.length};V.push(O),X(O);continue}if(k==="}"){let O=V[V.length-1];if(t.nobrace===!0||!O){X({type:"text",value:k,output:k});continue}let Z=")";if(O.dots===!0){let pe=o.slice(),xe=[];for(let ue=pe.length-1;ue>=0&&(o.pop(),pe[ue].type!=="brace");ue--)pe[ue].type!=="dots"&&xe.unshift(pe[ue].value);Z=CI(xe,t),w.backtrack=!0}if(O.comma!==!0&&O.dots!==!0){let pe=w.output.slice(0,O.outputIndex),xe=w.tokens.slice(O.tokensIndex);O.value=O.output="\\{",k=Z="\\}",w.output=pe;for(let ue of xe)w.output+=ue.output||ue.value}X({type:"brace",value:k,output:Z}),$r("braces"),V.pop();continue}if(k==="|"){F.length>0&&F[F.length-1].conditions++,X({type:"text",value:k});continue}if(k===","){let O=k,Z=V[V.length-1];Z&&G[G.length-1]==="braces"&&(Z.comma=!0,O="|"),X({type:"comma",value:k,output:O});continue}if(k==="/"){if(A.type==="dot"&&w.index===w.start+1){w.start=w.index+1,w.consumed="",w.output="",o.pop(),A=s;continue}X({type:"slash",value:k,output:f});continue}if(k==="."){if(w.braces>0&&A.type==="dot"){A.value==="."&&(A.output=u);let O=V[V.length-1];A.type="dots",A.output+=k,A.value+=k,O.dots=!0;continue}if(w.braces+w.parens===0&&A.type!=="bos"&&A.type!=="slash"){X({type:"text",value:k,output:u});continue}X({type:"dot",value:k,output:u});continue}if(k==="?"){if(!(A&&A.value==="(")&&t.noextglob!==!0&&oe()==="("&&oe(2)!=="?"){Ws("qmark",k);continue}if(A&&A.type==="paren"){let Z=oe(),pe=k;(A.value==="("&&!/[!=<:]/.test(Z)||Z==="<"&&!/<([!=]|\w+>)/.test(ir()))&&(pe=`\\${k}`),X({type:"text",value:k,output:pe});continue}if(t.dot!==!0&&(A.type==="slash"||A.type==="bos")){X({type:"qmark",value:k,output:_});continue}X({type:"qmark",value:k,output:g});continue}if(k==="!"){if(t.noextglob!==!0&&oe()==="("&&(oe(2)!=="?"||!/[!=<:]/.test(oe(3)))){Ws("negate",k);continue}if(t.nonegate!==!0&&w.index===0){h_();continue}}if(k==="+"){if(t.noextglob!==!0&&oe()==="("&&oe(2)!=="?"){Ws("plus",k);continue}if(A&&A.value==="("||t.regex===!1){X({type:"plus",value:k,output:d});continue}if(A&&(A.type==="bracket"||A.type==="paren"||A.type==="brace")||w.parens>0){X({type:"plus",value:k});continue}X({type:"plus",value:d});continue}if(k==="@"){if(t.noextglob!==!0&&oe()==="("&&oe(2)!=="?"){X({type:"at",extglob:!0,value:k,output:""});continue}X({type:"text",value:k});continue}if(k!=="*"){(k==="$"||k==="^")&&(k=`\\${k}`);let O=TI.exec(ir());O&&(k+=O[0],w.index+=O[0].length),X({type:"text",value:k});continue}if(A&&(A.type==="globstar"||A.star===!0)){A.type="star",A.star=!0,A.value+=k,A.output=R,w.backtrack=!0,w.globstar=!0,ut(k);continue}let C=ir();if(t.noextglob!==!0&&/^\([^?]/.test(C)){Ws("star",k);continue}if(A.type==="star"){if(t.noglobstar===!0){ut(k);continue}let O=A.prev,Z=O.prev,pe=O.type==="slash"||O.type==="bos",xe=Z&&(Z.type==="star"||Z.type==="globstar");if(t.bash===!0&&(!pe||C[0]&&C[0]!=="/")){X({type:"star",value:k,output:""});continue}let ue=w.braces>0&&(O.type==="comma"||O.type==="brace"),Vt=F.length&&(O.type==="pipe"||O.type==="paren");if(!pe&&O.type!=="paren"&&!ue&&!Vt){X({type:"star",value:k,output:""});continue}for(;C.slice(0,3)==="/**";){let Ut=r[w.index+4];if(Ut&&Ut!=="/")break;C=C.slice(3),ut("/**",3)}if(O.type==="bos"&&Ce()){A.type="globstar",A.value+=k,A.output=P(t),w.output=A.output,w.globstar=!0,ut(k);continue}if(O.type==="slash"&&O.prev.type!=="bos"&&!xe&&Ce()){w.output=w.output.slice(0,-(O.output+A.output).length),O.output=`(?:${O.output}`,A.type="globstar",A.output=P(t)+(t.strictSlashes?")":"|$)"),A.value+=k,w.globstar=!0,w.output+=O.output+A.output,ut(k);continue}if(O.type==="slash"&&O.prev.type!=="bos"&&C[0]==="/"){let Ut=C[1]!==void 0?"|$":"";w.output=w.output.slice(0,-(O.output+A.output).length),O.output=`(?:${O.output}`,A.type="globstar",A.output=`${P(t)}${f}|${f}${Ut})`,A.value+=k,w.output+=O.output+A.output,w.globstar=!0,ut(k+ae()),X({type:"slash",value:"/",output:""});continue}if(O.type==="bos"&&C[0]==="/"){A.type="globstar",A.value+=k,A.output=`(?:^|${f}|${P(t)}${f})`,w.output=A.output,w.globstar=!0,ut(k+ae()),X({type:"slash",value:"/",output:""});continue}w.output=w.output.slice(0,-A.output.length),A.type="globstar",A.output=P(t),A.value+=k,w.output+=A.output,w.globstar=!0,ut(k);continue}let ve={type:"star",value:k,output:R};if(t.bash===!0){ve.output=".*?",(A.type==="bos"||A.type==="slash")&&(ve.output=x+ve.output),X(ve);continue}if(A&&(A.type==="bracket"||A.type==="paren")&&t.regex===!0){ve.output=k,X(ve);continue}(w.index===w.start||A.type==="slash"||A.type==="dot")&&(A.type==="dot"?(w.output+=y,A.output+=y):t.dot===!0?(w.output+=b,A.output+=b):(w.output+=x,A.output+=x),oe()!=="*"&&(w.output+=p,A.output+=p)),X(ve)}for(;w.brackets>0;){if(t.strictBrackets===!0)throw new SyntaxError(Gi("closing","]"));w.output=ot.escapeLast(w.output,"["),$r("brackets")}for(;w.parens>0;){if(t.strictBrackets===!0)throw new SyntaxError(Gi("closing",")"));w.output=ot.escapeLast(w.output,"("),$r("parens")}for(;w.braces>0;){if(t.strictBrackets===!0)throw new SyntaxError(Gi("closing","}"));w.output=ot.escapeLast(w.output,"{"),$r("braces")}if(t.strictSlashes!==!0&&(A.type==="star"||A.type==="bracket")&&X({type:"maybe_slash",value:"",output:`${f}?`}),w.backtrack===!0){w.output="";for(let C of w.tokens)w.output+=C.output!=null?C.output:C.value,C.suffix&&(w.output+=C.suffix)}return w};au.fastpaths=(r,e)=>{let t={...e},i=typeof t.maxLength=="number"?Math.min(Xo,t.maxLength):Xo,n=r.length;if(n>i)throw new SyntaxError(`Input length: ${n}, exceeds maximum allowed length: ${i}`);r=nb[r]||r;let{DOT_LITERAL:s,SLASH_LITERAL:o,ONE_CHAR:a,DOTS_SLASH:c,NO_DOT:l,NO_DOTS:u,NO_DOTS_SLASH:d,STAR:f,START_ANCHOR:p}=ds.globChars(t.windows),m=t.dot?u:l,h=t.dot?d:l,y=t.capture?"":"?:",b={negated:!1,prefix:""},g=t.bash===!0?".*?":f;t.capture&&(g=`(${g})`);let _=x=>x.noglobstar===!0?g:`(${y}(?:(?!${p}${x.dot?c:s}).)*?)`,S=x=>{switch(x){case"*":return`${m}${a}${g}`;case".*":return`${s}${a}${g}`;case"*.*":return`${m}${g}${s}${a}${g}`;case"*/*":return`${m}${g}${o}${a}${h}${g}`;case"**":return m+_(t);case"**/*":return`(?:${m}${_(t)}${o})?${h}${a}${g}`;case"**/*.*":return`(?:${m}${_(t)}${o})?${h}${g}${s}${a}${g}`;case"**/.*":return`(?:${m}${_(t)}${o})?${s}${a}${g}`;default:{let E=/^(.*?)\.(\w+)$/.exec(x);if(!E)return;let R=S(E[1]);return R?R+s+E[2]:void 0}}},v=ot.removePrefix(r,b),P=S(v);return P&&t.strictSlashes!==!0&&(P+=`${o}?`),P};ob.exports=au});var db=$((AM,lb)=>{"use strict";var FI=ib(),cu=ab(),cb=cs(),VI=as(),UI=r=>r&&typeof r=="object"&&!Array.isArray(r),Ae=(r,e,t=!1)=>{if(Array.isArray(r)){let u=r.map(f=>Ae(f,e,t));return f=>{for(let p of u){let m=p(f);if(m)return m}return!1}}let i=UI(r)&&r.tokens&&r.input;if(r===""||typeof r!="string"&&!i)throw new TypeError("Expected pattern to be a non-empty string");let n=e||{},s=n.windows,o=i?Ae.compileRe(r,e):Ae.makeRe(r,e,!1,!0),a=o.state;delete o.state;let c=()=>!1;if(n.ignore){let u={...e,ignore:null,onMatch:null,onResult:null};c=Ae(n.ignore,u,t)}let l=(u,d=!1)=>{let{isMatch:f,match:p,output:m}=Ae.test(u,o,e,{glob:r,posix:s}),h={glob:r,state:a,regex:o,posix:s,input:u,output:m,match:p,isMatch:f};return typeof n.onResult=="function"&&n.onResult(h),f===!1?(h.isMatch=!1,d?h:!1):c(u)?(typeof n.onIgnore=="function"&&n.onIgnore(h),h.isMatch=!1,d?h:!1):(typeof n.onMatch=="function"&&n.onMatch(h),d?h:!0)};return t&&(l.state=a),l};Ae.test=(r,e,t,{glob:i,posix:n}={})=>{if(typeof r!="string")throw new TypeError("Expected input to be a string");if(r==="")return{isMatch:!1,output:""};let s=t||{},o=s.format||(n?cb.toPosixSlashes:null),a=r===i,c=a&&o?o(r):r;return a===!1&&(c=o?o(r):r,a=c===i),(a===!1||s.capture===!0)&&(s.matchBase===!0||s.basename===!0?a=Ae.matchBase(r,e,t,n):a=e.exec(c)),{isMatch:!!a,match:a,output:c}};Ae.matchBase=(r,e,t,i=t&&t.windows)=>(e instanceof RegExp?e:Ae.makeRe(e,t)).test(cb.basename(r,{windows:i}));Ae.isMatch=(r,e,t)=>Ae(e,t)(r);Ae.parse=(r,e)=>Array.isArray(r)?r.map(t=>Ae.parse(t,e)):cu(r,{...e,fastpaths:!1});Ae.scan=(r,e)=>FI(r,e);Ae.compileRe=(r,e,t=!1,i=!1)=>{if(t===!0)return r.output;let n=e||{},s=n.contains?"":"^",o=n.contains?"":"$",a=`${s}(?:${r.output})${o}`;r&&r.negated===!0&&(a=`^(?!${a}).*$`);let c=Ae.toRegex(a,e);return i===!0&&(c.state=r),c};Ae.makeRe=(r,e={},t=!1,i=!1)=>{if(!r||typeof r!="string")throw new TypeError("Expected a non-empty string");let n={negated:!1,fastpaths:!0};return e.fastpaths!==!1&&(r[0]==="."||r[0]==="*")&&(n.output=cu.fastpaths(r,e)),n.output||(n=cu(r,e)),Ae.compileRe(n,e,t,i)};Ae.toRegex=(r,e)=>{try{let t=e||{};return new RegExp(r,t.flags||(t.nocase?"i":""))}catch(t){if(e&&e.debug===!0)throw t;return/$^/}};Ae.constants=VI;lb.exports=Ae});var lu=$((kM,pb)=>{"use strict";var ub=db(),zI=cs();function fb(r,e,t=!1){return e&&(e.windows===null||e.windows===void 0)&&(e={...e,windows:zI.isWindows()}),ub(r,e,t)}Object.assign(fb,ub);pb.exports=fb});var oO={};$_(oO,{default:()=>rc});module.exports=S_(oO);var M=require("obsidian");var Og=ft(Wn(),1),Cg=ft(Yn(),1),Ho=ft(Dd(),1);var xg={config:{$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://mdbase.dev/schemas/v0.3/config.schema.json",title:"mdbase v0.3 collection configuration",type:"object",required:["spec_version"],properties:{spec_version:{const:"0.3.0"},settings:{$ref:"#/$defs/settings"},runtime:{$ref:"#/$defs/runtime"}},patternProperties:{"^x-[A-Za-z][A-Za-z0-9._:-]{0,127}$":!0},additionalProperties:!0,$defs:{settings:{type:"object",properties:{types_folder:{type:"string",minLength:1},record_extensions:{type:"array",minItems:1,uniqueItems:!0,items:{type:"string",pattern:"^[A-Za-z0-9]+$"}},validation:{enum:["off","warn","error"]},explicit_type_keys:{type:"array",minItems:1,uniqueItems:!0,items:{type:"string",minLength:1}},id_field:{type:"string",minLength:1},include_subfolders:{type:"boolean"},exclude:{type:"array",items:{type:"string",minLength:1}}},additionalProperties:!0},runtime:{type:"object",required:["profile_version"],properties:{profile_version:{const:"0.1.0"},enabled:{type:"boolean"},contract_mode:{enum:["runtime","materialized","strict"]},policy:{type:"string",minLength:1},materialize:{type:"object",additionalProperties:!0}},additionalProperties:!0}}},conformanceClaim:{$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://mdbase.dev/schemas/v0.3/conformance-claim.schema.json",title:"mdbase v0.3 conformance claim",type:"object",required:["kind","status","implementation","spec_version","profiles","json_schema","limits","evidence"],properties:{kind:{const:"mdbase.conformance"},status:{const:"verified"},implementation:{type:"object",required:["id","name","version"],properties:{id:{$ref:"#/$defs/identifier"},name:{type:"string",minLength:1},version:{type:"string",minLength:1},language:{type:"string",minLength:1},target:{type:"string",minLength:1},url:{type:"string",format:"uri"}},patternProperties:{"^x-[A-Za-z0-9._:-]+$":!0},additionalProperties:!1},spec_version:{type:"string",pattern:"^0\\.3\\.0(?:-[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?$"},runtime_profile_version:{const:"0.1.0"},profiles:{type:"array",minItems:1,uniqueItems:!0,items:{$ref:"#/$defs/profile"}},optional_features:{type:"array",uniqueItems:!0,items:{$ref:"#/$defs/identifier"}},json_schema:{type:"object",required:["dialect","keywords","formats","remote_refs"],properties:{dialect:{const:"https://json-schema.org/draft/2020-12/schema"},keywords:{type:"array",uniqueItems:!0,items:{type:"string",minLength:1}},formats:{type:"array",uniqueItems:!0,items:{type:"string",minLength:1}},remote_refs:{const:!1}},additionalProperties:!1},compatibility:{type:"object",properties:{v0_2_read:{type:"boolean"},v0_2_migrate:{type:"boolean"}},additionalProperties:!1},limits:{type:"object",additionalProperties:{$ref:"#/$defs/limitValue"}},evidence:{type:"array",minItems:1,items:{type:"object",required:["kind","command","result","verified_at"],properties:{kind:{enum:["conformance_suite","test_suite","package_smoke","manual_smoke"]},command:{type:"string",minLength:1},result:{const:"pass"},verified_at:{type:"string",format:"date-time"},artifact:{type:"string",minLength:1},environment:{type:"string",minLength:1}},additionalProperties:!1}}},patternProperties:{"^x-[A-Za-z0-9._:-]+$":!0},additionalProperties:!1,allOf:[{if:{properties:{profiles:{contains:{const:"collection_semantics"}}}},then:{properties:{profiles:{contains:{const:"core_read"}}}}},{if:{properties:{profiles:{contains:{const:"cel_query"}}}},then:{properties:{profiles:{contains:{const:"core_read"}}}}},{if:{properties:{profiles:{contains:{const:"links"}}}},then:{properties:{profiles:{allOf:[{contains:{const:"collection_semantics"}},{contains:{const:"cel_query"}}]}}}},{if:{properties:{profiles:{contains:{const:"core_write"}}}},then:{properties:{profiles:{contains:{const:"collection_semantics"}}}}},{if:{properties:{profiles:{contains:{const:"lifecycle"}}}},then:{properties:{profiles:{allOf:[{contains:{const:"core_write"}},{contains:{const:"cel_query"}}]}}}},{if:{properties:{profiles:{contains:{const:"runtime_contracts/0.1"}}}},then:{required:["runtime_profile_version"],properties:{profiles:{contains:{const:"core_read"}}}}},{if:{properties:{profiles:{contains:{const:"workflow/0.1"}}}},then:{required:["runtime_profile_version"],properties:{profiles:{allOf:[{contains:{const:"runtime_contracts/0.1"}},{contains:{const:"cel_query"}}]}}}},{if:{properties:{profiles:{contains:{const:"watch"}}}},then:{properties:{profiles:{contains:{const:"core_read"}}}}}],$defs:{identifier:{type:"string",pattern:"^[A-Za-z][A-Za-z0-9._:/-]*$"},profile:{enum:["core_read","collection_semantics","cel_query","links","core_write","lifecycle","runtime_contracts/0.1","workflow/0.1","watch"]},limitValue:{oneOf:[{type:"string"},{type:"number"},{type:"boolean"},{type:"array",items:{oneOf:[{type:"string"},{type:"number"},{type:"boolean"}]}}]}}},coreDiagnostic:{$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://mdbase.dev/schemas/v0.3/diagnostic.schema.json",title:"mdbase v0.3 diagnostic",type:"object",required:["severity","code","message"],properties:{severity:{enum:["info","warning","error"]},code:{type:"string",pattern:"^[a-z][a-z0-9_]*$"},message:{type:"string",minLength:1},path:{type:"string",pattern:"^(?!/)(?!.*(?:^|/)\\.\\.(?:/|$))[^\\\\]*$"},field:{type:"string"},type:{type:"string"},schema_location:{type:"string",format:"uri-reference"},details:{}},patternProperties:{"^x-[A-Za-z][A-Za-z0-9._:-]{0,127}$":!0},additionalProperties:!1},operationResult:{$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://mdbase.dev/schemas/v0.3/operation-result.schema.json",title:"mdbase v0.3 operation result",type:"object",required:["valid","result","diagnostics"],properties:{valid:{type:"boolean"},result:{},diagnostics:{type:"array",items:{$ref:"diagnostic.schema.json"}}},additionalProperties:!1},queryResult:{$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://mdbase.dev/schemas/v0.3/query-result.schema.json",title:"mdbase v0.3 query result",type:"object",required:["results","meta","diagnostics"],properties:{results:{type:"array",items:{type:"object",required:["file"],properties:{file:{type:"object",required:["path"],properties:{path:{type:"string",minLength:1}},additionalProperties:!0},frontmatter:{type:"object"},body:{type:"string"}},additionalProperties:!0}},meta:{type:"object",required:["total_count","has_more"],properties:{total_count:{type:"integer",minimum:0},has_more:{type:"boolean"}},additionalProperties:!0},diagnostics:{type:"array",items:{$ref:"diagnostic.schema.json"}}},additionalProperties:!1},typeFile:{$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://mdbase.dev/schemas/v0.3/type-file.schema.json",title:"mdbase v0.3 type file frontmatter",type:"object",required:["kind","name","schema"],properties:{kind:{const:"mdbase.type"},name:{$ref:"#/$defs/typeName"},version:{type:"integer",minimum:1},description:{type:"string"},match:{$ref:"#/$defs/match"},schema:{$ref:"#/$defs/schemaWrapper"},collection:{$ref:"#/$defs/collection"},lifecycle:{$ref:"#/$defs/lifecycle"},runtime:{$ref:"#/$defs/runtime"},migrations:{$ref:"#/$defs/migrations"}},patternProperties:{"^x-[A-Za-z][A-Za-z0-9._:-]{0,127}$":{$ref:"#/$defs/domainExtension"}},unevaluatedProperties:!1,$defs:{typeName:{type:"string",pattern:"^[A-Za-z][A-Za-z0-9_-]{0,127}$"},identifier:{type:"string",pattern:"^[A-Za-z][A-Za-z0-9._:-]*$"},fieldName:{type:"string",pattern:"^[A-Za-z_][A-Za-z0-9_:-]*$"},fieldPath:{type:"string",pattern:"^[A-Za-z_][A-Za-z0-9_:-]*(\\[\\])?(\\.[A-Za-z_][A-Za-z0-9_:-]*(\\[\\])?)*$"},jsonPointer:{type:"string",pattern:"^(/([^/~]|~0|~1)*)*$"},jsonSchema:{type:"object",additionalProperties:!0},schemaWrapper:{type:"object",required:["dialect"],properties:{dialect:{const:"json-schema-2020-12"},value:{$ref:"#/$defs/jsonSchema"},ref:{type:"string",minLength:1}},oneOf:[{required:["value"],not:{required:["ref"]}},{required:["ref"],not:{required:["value"]}}],additionalProperties:!1},match:{type:"object",minProperties:1,properties:{path_glob:{oneOf:[{type:"string",minLength:1},{type:"array",minItems:1,items:{type:"string",minLength:1}}]},fields_present:{type:"array",minItems:1,items:{$ref:"#/$defs/fieldPath"},uniqueItems:!0},where:{$ref:"#/$defs/matchWhere"},expr:{$ref:"#/$defs/expression"}},additionalProperties:!1},matchWhere:{type:"object",minProperties:1,additionalProperties:{$ref:"#/$defs/matchPredicate"}},matchPredicate:{oneOf:[{$ref:"#/$defs/scalar"},{type:"array"},{type:"object",properties:{eq:{},neq:{},contains:{},containsAll:{type:"array"},containsAny:{type:"array"},exists:{type:"boolean"},startsWith:{type:"string"},endsWith:{type:"string"},matches:{type:"string"},gt:{$ref:"#/$defs/scalar"},gte:{$ref:"#/$defs/scalar"},lt:{$ref:"#/$defs/scalar"},lte:{$ref:"#/$defs/scalar"}},minProperties:1,additionalProperties:!1}]},collection:{type:"object",properties:{display:{$ref:"#/$defs/display"},read_defaults:{type:"object",additionalProperties:!0},links:{$ref:"#/$defs/links"},unique:{$ref:"#/$defs/uniqueRules"},path:{$ref:"#/$defs/pathPolicy"},projections:{$ref:"#/$defs/projections"}},patternProperties:{"^x-[A-Za-z][A-Za-z0-9._:-]{0,127}$":{$ref:"#/$defs/domainExtension"}},additionalProperties:!1},display:{type:"object",properties:{name_field:{$ref:"#/$defs/fieldPath"},description_field:{$ref:"#/$defs/fieldPath"},icon:{type:"string"},color_field:{$ref:"#/$defs/fieldPath"}},additionalProperties:!1},links:{type:"object",minProperties:1,propertyNames:{$ref:"#/$defs/fieldPath"},additionalProperties:{$ref:"#/$defs/linkRule"}},linkRule:{type:"object",properties:{target_type:{anyOf:[{$ref:"#/$defs/typeName"},{const:"any"},{type:"array",minItems:1,items:{$ref:"#/$defs/typeName"},uniqueItems:!0}]},validate_exists:{type:"boolean"},format:{enum:["wikilink","markdown","path","any"]}},additionalProperties:!1},uniqueRules:{type:"array",minItems:1,items:{type:"object",required:["field"],properties:{field:{$ref:"#/$defs/fieldPath"},scope:{enum:["collection","type","path_glob"]},path_glob:{type:"string",minLength:1}},allOf:[{if:{properties:{scope:{const:"path_glob"}},required:["scope"]},then:{required:["path_glob"]}}],additionalProperties:!1}},pathPolicy:{type:"object",properties:{pattern:{type:"string",minLength:1},runtime:{$ref:"#/$defs/identifier"},template:{type:"string",minLength:1},folder:{type:"string"},generated_by:{$ref:"#/$defs/identifier"}},additionalProperties:!1},projections:{type:"object",propertyNames:{$ref:"#/$defs/fieldName"},additionalProperties:{type:"object",required:["expr"],properties:{expr:{type:"string",minLength:1},description:{type:"string"}},additionalProperties:!1}},lifecycle:{type:"object",properties:{on_create:{$ref:"#/$defs/lifecycleEvent"},on_update:{$ref:"#/$defs/lifecycleEvent"},on_delete:{$ref:"#/$defs/lifecycleEvent"},on_rename:{$ref:"#/$defs/lifecycleEvent"}},additionalProperties:!1},lifecycleEvent:{oneOf:[{$ref:"#/$defs/lifecycleAction"},{type:"array",minItems:1,items:{$ref:"#/$defs/lifecycleAction"}}]},lifecycleAction:{type:"object",required:["set"],properties:{if:{type:"string",minLength:1},set:{type:"object",minProperties:1,propertyNames:{$ref:"#/$defs/fieldPath"},additionalProperties:{$ref:"#/$defs/lifecycleValue"}}},additionalProperties:!1},lifecycleValue:{oneOf:[{type:"object",required:["now"],properties:{now:{const:!0}},additionalProperties:!1},{type:"object",required:["today"],properties:{today:{const:!0}},additionalProperties:!1},{type:"object",required:["uuid"],properties:{uuid:{const:!0}},additionalProperties:!1},{type:"object",required:["ulid"],properties:{ulid:{const:!0}},additionalProperties:!1},{type:"object",required:["slugify"],properties:{slugify:{$ref:"#/$defs/fieldPath"}},additionalProperties:!1},{type:"object",required:["copy"],properties:{copy:{$ref:"#/$defs/fieldPath"}},additionalProperties:!1},{type:"object",required:["literal"],properties:{literal:!0},additionalProperties:!1}]},runtime:{type:"object",properties:{contracts:{type:"object",properties:{mode:{enum:["runtime","materialized","strict"]}},additionalProperties:!1}},patternProperties:{"^x-[A-Za-z][A-Za-z0-9._:-]{0,127}$":{$ref:"#/$defs/domainExtension"}},additionalProperties:!1},migrations:{type:"array",items:{type:"object",required:["from","to"],properties:{from:{type:"integer",minimum:0},to:{type:"integer",minimum:1},steps:{type:"array",items:{type:"object",minProperties:1,additionalProperties:!0}},action:{$ref:"#/$defs/identifier"},description:{type:"string"}},oneOf:[{required:["steps"]},{required:["action"]}],additionalProperties:!1}},expression:{type:"object",required:["$expr"],properties:{$expr:{type:"string",minLength:1}},additionalProperties:!1},domainExtension:{type:"object",additionalProperties:!0},scalar:{type:["string","number","integer","boolean","null"]}}},provider:{$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://mdbase.dev/schemas/runtime/v0.1/provider.schema.json",title:"mdbase runtime provider contract",type:"object",required:["type","id","version","provider_version","name"],properties:{type:{const:"provider"},id:{$ref:"#/$defs/identifier"},version:{type:"integer",minimum:1},provider_version:{$ref:"#/$defs/semver"},name:{type:"string",minLength:1},description:{type:"string"},contracts:{type:"object",properties:{events:{$ref:"#/$defs/identifierList"},actions:{$ref:"#/$defs/identifierList"},capabilities:{$ref:"#/$defs/identifierList"},workflows:{$ref:"#/$defs/identifierList"}},additionalProperties:!1}},patternProperties:{"^x-[A-Za-z0-9._:-]+$":!0},additionalProperties:!1,$defs:{identifier:{type:"string",pattern:"^[A-Za-z][A-Za-z0-9._:-]*$"},identifierList:{type:"array",uniqueItems:!0,items:{$ref:"#/$defs/identifier"}},semver:{type:"string",pattern:"^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)(?:-[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?(?:\\+[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?$"}}},action:{$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://mdbase.dev/schemas/runtime/v0.1/action.schema.json",title:"mdbase runtime action contract",type:"object",required:["type","id","version","provider","name","schemas"],properties:{type:{const:"action"},id:{$ref:"#/$defs/identifier"},version:{type:"integer",minimum:1},provider:{$ref:"#/$defs/identifier"},name:{type:"string",minLength:1},description:{type:"string"},requires:{$ref:"#/$defs/requires"},schemas:{type:"object",required:["dialect","input"],properties:{dialect:{const:"json-schema-2020-12"},input:{$ref:"#/$defs/jsonSchema"},output:{oneOf:[{type:"null"},{$ref:"#/$defs/jsonSchema"}]}},additionalProperties:!1},effects:{type:"array",uniqueItems:!0,items:{$ref:"#/$defs/identifier"}},emits:{type:"array",uniqueItems:!0,items:{$ref:"#/$defs/identifier"}},risk:{enum:["low","medium","high","destructive"]}},patternProperties:{"^x-[A-Za-z0-9._:-]+$":!0},additionalProperties:!1,$defs:{identifier:{type:"string",pattern:"^[A-Za-z][A-Za-z0-9._:-]*$"},jsonSchema:{type:"object",additionalProperties:!0},requires:{type:"object",properties:{capabilities:{type:"array",uniqueItems:!0,items:{$ref:"#/$defs/identifier"}},providers:{type:"array",uniqueItems:!0,items:{$ref:"#/$defs/providerRequirement"}}},additionalProperties:!1},providerRequirement:{oneOf:[{$ref:"#/$defs/identifier"},{type:"object",required:["id","version"],properties:{id:{$ref:"#/$defs/identifier"},version:{type:"string",minLength:1}},additionalProperties:!1}]}}},event:{$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://mdbase.dev/schemas/runtime/v0.1/event.schema.json",title:"mdbase runtime event contract",type:"object",required:["type","id","version","provider","name","schemas"],properties:{type:{const:"event"},id:{$ref:"#/$defs/identifier"},version:{type:"integer",minimum:1},provider:{$ref:"#/$defs/identifier"},name:{type:"string",minLength:1},description:{type:"string"},schemas:{type:"object",required:["dialect","payload"],properties:{dialect:{const:"json-schema-2020-12"},payload:{$ref:"#/$defs/jsonSchema"}},additionalProperties:!1}},patternProperties:{"^x-[A-Za-z0-9._:-]+$":!0},additionalProperties:!1,$defs:{identifier:{type:"string",pattern:"^[A-Za-z][A-Za-z0-9._:-]*$"},jsonSchema:{type:"object",additionalProperties:!0}}},capability:{$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://mdbase.dev/schemas/runtime/v0.1/capability.schema.json",title:"mdbase runtime capability contract",type:"object",required:["type","id","version","name"],properties:{type:{const:"capability"},id:{$ref:"#/$defs/identifier"},version:{type:"integer",minimum:1},provider:{$ref:"#/$defs/identifier"},name:{type:"string",minLength:1},description:{type:"string"},risk:{enum:["low","medium","high","destructive"]},effects:{type:"array",uniqueItems:!0,items:{$ref:"#/$defs/identifier"}}},patternProperties:{"^x-[A-Za-z0-9._:-]+$":!0},additionalProperties:!1,$defs:{identifier:{type:"string",pattern:"^[A-Za-z][A-Za-z0-9._:-]*$"}}},workflow:{$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://mdbase.dev/schemas/runtime/v0.1/workflow.schema.json",title:"mdbase runtime workflow record",type:"object",required:["type","id","version","name","enabled","triggers","steps"],properties:{type:{const:"workflow"},id:{$ref:"#/$defs/identifier"},version:{type:"integer",minimum:1},name:{type:"string",minLength:1},description:{type:"string"},enabled:{type:"boolean"},requires:{$ref:"#/$defs/requires"},vars:{type:"object",additionalProperties:{$ref:"#/$defs/expressionValue"}},triggers:{type:"array",minItems:1,items:{$ref:"#/$defs/trigger"}},if:{$ref:"#/$defs/expression"},steps:{type:"array",minItems:1,items:{$ref:"#/$defs/step"}},run:{$ref:"#/$defs/runPolicy"}},patternProperties:{"^x-[A-Za-z0-9._:-]+$":!0},additionalProperties:!1,$defs:{identifier:{type:"string",pattern:"^[A-Za-z][A-Za-z0-9._:-]*$"},expression:{type:"object",required:["$expr"],properties:{$expr:{type:"string",minLength:1}},additionalProperties:!1},expressionValue:{oneOf:[{type:"null"},{type:"boolean"},{type:"number"},{type:"string"},{$ref:"#/$defs/expression"},{type:"array",items:{$ref:"#/$defs/expressionValue"}},{type:"object",not:{required:["$expr"]},additionalProperties:{$ref:"#/$defs/expressionValue"}}]},requires:{type:"object",properties:{capabilities:{type:"array",uniqueItems:!0,items:{$ref:"#/$defs/identifier"}},providers:{type:"array",uniqueItems:!0,items:{$ref:"#/$defs/providerRequirement"}}},additionalProperties:!1},providerRequirement:{oneOf:[{$ref:"#/$defs/identifier"},{type:"object",required:["id","version"],properties:{id:{$ref:"#/$defs/identifier"},version:{type:"string",minLength:1}},additionalProperties:!1}]},trigger:{type:"object",required:["id","event"],properties:{id:{$ref:"#/$defs/identifier"},event:{$ref:"#/$defs/identifier"},if:{$ref:"#/$defs/expression"},debounce:{$ref:"#/$defs/duration"},minimum_interval:{$ref:"#/$defs/duration"}},patternProperties:{"^x-[A-Za-z0-9._:-]+$":!0},additionalProperties:!1},step:{type:"object",required:["id","action"],properties:{id:{$ref:"#/$defs/identifier"},action:{$ref:"#/$defs/identifier"},name:{type:"string"},if:{$ref:"#/$defs/expression"},input:{type:"object",additionalProperties:{$ref:"#/$defs/expressionValue"}},for_each:{type:"object",required:["items"],properties:{items:{$ref:"#/$defs/expressionValue"},as:{type:"string",pattern:"^[A-Za-z_][A-Za-z0-9_]*$"}},additionalProperties:!1},requires:{$ref:"#/$defs/requires"}},patternProperties:{"^x-[A-Za-z0-9._:-]+$":!0},additionalProperties:!1},runPolicy:{type:"object",properties:{execution:{type:"object",properties:{mode:{enum:["single_executor","broadcast","best_effort"]}},additionalProperties:!1},idempotency:{type:"object",required:["key"],properties:{key:{$ref:"#/$defs/expressionValue"}},additionalProperties:!1},concurrency:{type:"object",properties:{group:{$ref:"#/$defs/expressionValue"},policy:{enum:["skip","queue","replace","allow"]}},required:["policy"],additionalProperties:!1},limits:{type:"object",properties:{timeout:{$ref:"#/$defs/duration"},max_items:{type:"integer",minimum:1}},additionalProperties:!1},on_error:{enum:["stop","continue"]}},additionalProperties:!1},duration:{type:"string",pattern:"^[0-9]+(ms|s|m|h|d)$"}}},runtimePolicy:{$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://mdbase.dev/schemas/runtime/v0.1/runtime-policy.schema.json",title:"mdbase runtime policy record",type:"object",required:["type","id","version","name"],properties:{type:{const:"runtime_policy"},id:{$ref:"#/$defs/identifier"},version:{type:"integer",minimum:1},name:{type:"string",minLength:1},enabled:{type:"boolean"},limits:{type:"object",properties:{workflow_timeout:{$ref:"#/$defs/duration"},max_concurrent_runs:{type:"integer",minimum:1},max_steps_per_run:{type:"integer",minimum:1},max_items_per_step:{type:"integer",minimum:1}},additionalProperties:!1},capabilities:{type:"object",propertyNames:{$ref:"#/$defs/identifier"},additionalProperties:{$ref:"#/$defs/capabilityPolicy"}},executors:{type:"object",properties:{default:{$ref:"#/$defs/identifier"},workflows:{type:"object",propertyNames:{$ref:"#/$defs/identifier"},additionalProperties:{$ref:"#/$defs/identifier"}}},additionalProperties:!1}},patternProperties:{"^x-[A-Za-z0-9._:-]+$":!0},additionalProperties:!1,$defs:{identifier:{type:"string",pattern:"^[A-Za-z][A-Za-z0-9._:-]*$"},duration:{type:"string",pattern:"^[0-9]+(ms|s|m|h|d)$"},capabilityMode:{enum:["allow","deny"]},capabilityPolicy:{type:"object",properties:{mode:{$ref:"#/$defs/capabilityMode"},max_files_per_run:{type:"integer",minimum:1},max_calls_per_run:{type:"integer",minimum:1}},patternProperties:{"^x-[A-Za-z0-9._:-]+$":!0},additionalProperties:!1}}},run:{$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://mdbase.dev/schemas/runtime/v0.1/run.schema.json",title:"mdbase runtime run record",type:"object",required:["type","id","workflow","status","started_at"],properties:{type:{const:"runtime_run"},id:{$ref:"#/$defs/identifier"},workflow:{$ref:"#/$defs/identifier"},trigger_event:{$ref:"#/$defs/identifier"},executor:{$ref:"#/$defs/identifier"},idempotency_key:{type:"string"},status:{enum:["queued","running","succeeded","failed","cancelled"]},started_at:{type:"string",format:"date-time"},finished_at:{type:"string",format:"date-time"},steps:{type:"array",items:{type:"object",required:["id","action","status"],properties:{id:{$ref:"#/$defs/identifier"},action:{$ref:"#/$defs/identifier"},status:{enum:["pending","running","succeeded","failed","skipped","cancelled","timed_out"]},output:{},error:{type:"object",additionalProperties:!0}},patternProperties:{"^x-[A-Za-z0-9._:-]+$":!0},additionalProperties:!1}}},patternProperties:{"^x-[A-Za-z0-9._:-]+$":!0},additionalProperties:!1,$defs:{identifier:{type:"string",pattern:"^[A-Za-z][A-Za-z0-9._:-]*$"}}},checkpoint:{$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://mdbase.dev/schemas/runtime/v0.1/checkpoint.schema.json",title:"mdbase runtime checkpoint record",type:"object",required:["type","id","workflow","status","updated_at","state"],properties:{type:{const:"runtime_checkpoint"},id:{$ref:"#/$defs/identifier"},workflow:{$ref:"#/$defs/identifier"},run:{$ref:"#/$defs/identifier"},status:{enum:["open","waiting","ready","completed","failed","cancelled"]},updated_at:{type:"string",format:"date-time"},state:{type:"object",additionalProperties:!0},next_step:{$ref:"#/$defs/identifier"}},patternProperties:{"^x-[A-Za-z0-9._:-]+$":!0},additionalProperties:!1,$defs:{identifier:{type:"string",pattern:"^[A-Za-z][A-Za-z0-9._:-]*$"}}},diagnostic:{$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://mdbase.dev/schemas/runtime/v0.1/diagnostic.schema.json",title:"mdbase runtime diagnostic record",type:"object",required:["type","id","severity","code","message","created_at"],properties:{type:{const:"runtime_diagnostic"},id:{$ref:"#/$defs/identifier"},severity:{enum:["info","warning","error"]},code:{$ref:"#/$defs/identifier"},message:{type:"string",minLength:1},created_at:{type:"string",format:"date-time"},path:{type:"string"},field:{type:"string"},workflow:{$ref:"#/$defs/identifier"},action:{$ref:"#/$defs/identifier"},event:{$ref:"#/$defs/identifier"},details:{type:"object",additionalProperties:!0}},patternProperties:{"^x-[A-Za-z0-9._:-]+$":!0},additionalProperties:!1,$defs:{identifier:{type:"string",pattern:"^[A-Za-z][A-Za-z0-9._:-]*$"}}},eventEnvelope:{$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://mdbase.dev/schemas/runtime/v0.1/event-envelope.schema.json",title:"mdbase runtime event envelope",type:"object",required:["type","contract_version","id","occurred_at","source","payload"],properties:{type:{$ref:"#/$defs/identifier"},contract_version:{type:"integer",minimum:1},id:{$ref:"#/$defs/identifier"},occurred_at:{type:"string",format:"date-time"},source:{type:"object",required:["runtime"],properties:{runtime:{$ref:"#/$defs/identifier"},provider:{$ref:"#/$defs/identifier"},collection:{type:"string"}},patternProperties:{"^x-[A-Za-z0-9._:-]+$":!0},additionalProperties:!1},payload:{type:"object",additionalProperties:!0},trace:{type:"object",properties:{correlation_id:{$ref:"#/$defs/identifier"},causation_id:{$ref:"#/$defs/identifier"}},patternProperties:{"^x-[A-Za-z0-9._:-]+$":!0},additionalProperties:!1}},additionalProperties:!1,$defs:{identifier:{type:"string",pattern:"^[A-Za-z][A-Za-z0-9._:-]*$"}}}};var Ig=ft(Wn(),1),Rg=ft(Yn(),1),Cr=xg,Uo;function Fd(){return zo({action:Cr.action,event:Cr.event,capability:Cr.capability,workflow:Cr.workflow})}function Vd(){return zo(Cr.provider)}function Ud(){return zo(Cr.eventEnvelope)}function zd(r,e){var n;let t=Kx()[r],i=t(e);return{valid:i,errors:i?[]:((n=t.errors)!=null?n:[]).map(Gx)}}function Kx(){if(Uo)return Uo;let r=new Ig.Ajv2020({allErrors:!0,strict:!1,allowUnionTypes:!0,schemas:Object.values(Cr)});return(0,Rg.default)(r),Uo=Object.fromEntries(Object.entries(Cr).map(([t,i])=>{let n=i.$id,s=typeof n=="string"?r.getSchema(n):void 0;return[t,s!=null?s:r.compile(i)]})),Uo}function Gx(r){return{instancePath:r.instancePath,schemaPath:r.schemaPath,keyword:r.keyword,message:r.message,params:zo(r.params)}}function zo(r){return JSON.parse(JSON.stringify(r))}var Bd="0.1.0";var Nr={id:"mdbase.default-deny",selected:!0,capabilities:{}},ns=class{constructor(e={}){I(this,"options");I(this,"profileVersion",Bd);I(this,"ajv",Yx());I(this,"providerValidator",this.ajv.compile(Vd()));I(this,"contractValidators",Xx(this.ajv));I(this,"eventEnvelopeValidator",this.ajv.compile(Ud()));I(this,"providerRegistry",new Map);I(this,"actionOwners",new Map);I(this,"eventOwners",new Map);I(this,"actionValidators",new Map);I(this,"eventValidators",new Map);I(this,"eventHandlers",new Map);I(this,"recentEventIds",new Set);I(this,"policyResolver");I(this,"recentEventLimit");I(this,"registrationQueue",Promise.resolve());I(this,"disposed",!1);var i,n,s;if(this.options=e,e.policy&&e.policyResolver)throw new be("invalid_runtime_options","Specify policy or policyResolver, not both.");let t=oi((i=e.policy)!=null?i:Nr);this.policyResolver=(n=e.policyResolver)!=null?n:(()=>t),this.recentEventLimit=Math.max(1,(s=e.recentEventLimit)!=null?s:1e3)}registerProvider(e){let t=this.registrationQueue.then(()=>this.registerProviderAtomic(e));return this.registrationQueue=t.then(()=>{},()=>{}),t}providers(){return[...this.providerRegistry.values()].map(({descriptor:e,contracts:t})=>({descriptor:oi(e),contracts:oi(t)})).sort((e,t)=>e.descriptor.id.localeCompare(t.descriptor.id))}contracts(){return this.providers().flatMap(e=>[e.descriptor,...e.contracts])}policy(){return this.resolvePolicy()}preflight(e={}){var s,o,a,c;let t=[],i=this.resolvePolicy();for(let l of(s=e.providers)!=null?s:[]){let u=Wx(l),d=this.providerRegistry.get(u.id);if(!d){t.push(rs("provider_unavailable",`Required provider ${u.id} is not registered.`));continue}u.version&&!(0,Ho.satisfies)(d.descriptor.provider_version,u.version,{includePrerelease:!0})&&t.push(rs("provider_version_mismatch",`Provider ${u.id} ${d.descriptor.provider_version} does not satisfy ${u.version}.`))}let n=new Set;for(let l of this.contracts())if(l.type==="capability"&&n.add(l.id),l.type==="action")for(let u of(o=l.effects)!=null?o:[])n.add(u);for(let l of Object.keys(i.capabilities))n.add(l);for(let l of(a=e.capabilities)!=null?a:[])n.has(l)?i.capabilities[l]==="deny"&&t.push(rs("capability_denied",`Selected policy denies capability ${l}.`)):t.push(rs("capability_unavailable",`Required capability ${l} is unavailable.`));for(let l of(c=e.actions)!=null?c:[])this.actionOwners.has(l)||t.push(rs("action_unavailable",`Required action ${l} is unavailable.`));return{valid:t.length===0,diagnostics:t}}subscribe(e,t){var s;this.assertActive();let i=(s=this.eventHandlers.get(e))!=null?s:new Set;i.add(t),this.eventHandlers.set(e,i);let n=!0;return{dispose:()=>{n&&(n=!1,i.delete(t),i.size===0&&this.eventHandlers.delete(e))}}}async dispatch(e,t,i){var d,f,p,m,h,y,b;this.assertActive(),Jx(i);let n=this.actionOwners.get(e),s=n?this.providerRegistry.get(n):void 0;if(!s)throw new be("action_unavailable",`Action ${e} is unavailable.`);let o=s.contracts.find(g=>g.type==="action"&&g.id===e);if(!o)throw new be("contract_missing",`Action contract ${e} is missing.`);let a=this.preflight({providers:(d=o.requires)==null?void 0:d.providers,capabilities:(f=o.requires)==null?void 0:f.capabilities});if(!a.valid){let g=a.diagnostics[0];throw new be((p=g==null?void 0:g.code)!=null?p:"action_preflight_failed",(m=g==null?void 0:g.message)!=null?m:`Action ${e} failed preflight.`)}let c=this.resolvePolicy(),l=this.actionValidators.get(e);if(!(l!=null&&l.input(t)))throw new be("invalid_action_input",is(e,l==null?void 0:l.input));for(let g of new Set([...(y=(h=o.requires)==null?void 0:h.capabilities)!=null?y:[],...(b=o.effects)!=null?b:[]]))if(c.capabilities[g]!=="allow")throw new be("capability_denied",`Selected policy does not allow ${g}.`);let u=await s.provider.dispatch(e,t,i);if(l.output&&!l.output(u))throw new be("invalid_action_output",is(e,l.output));return u}async dispose(){if(!this.disposed){this.disposed=!0,await this.registrationQueue;for(let e of[...this.providerRegistry.keys()])await this.unregisterProvider(e);this.eventHandlers.clear(),this.recentEventIds.clear()}}async registerProviderAtomic(e){this.assertActive();let t=[],i;try{let n=await e.descriptor();i=n.id;let s=await e.contracts(),o=await e.readiness();if(!o.valid||o.status==="unavailable")throw new be("provider_not_ready",o.diagnostics.map(c=>c.message).join("; ")||`${n.id} is not ready.`);this.validateProvider(n,s);let a=this.compileContracts(s);for(let c of s)c.type==="event"&&t.push(e.subscribe(c.id,l=>this.deliverProviderEvent(n.id,l)));this.providerRegistry.set(n.id,{provider:e,descriptor:oi(n),contracts:oi(s),subscriptions:t});for(let[c,l]of a.actions)this.actionOwners.set(c,n.id),this.actionValidators.set(c,l);for(let[c,l]of a.events)this.eventOwners.set(c,n.id),this.eventValidators.set(c,l);return{providerId:n.id,unregister:async()=>this.unregisterProvider(n.id)}}catch(n){await Promise.allSettled(t.map(async s=>s.dispose()));try{await e.dispose()}catch(s){this.report({severity:"warning",code:"provider_cleanup_failed",message:"Provider cleanup failed after registration error.",providerId:i,cause:s})}throw n}}validateProvider(e,t){if(Tg(this.providerValidator,e,"invalid_provider","Provider descriptor"),!(0,Ho.valid)(e.provider_version))throw new be("invalid_provider_version",`${e.id} provider_version must be SemVer.`);if(this.providerRegistry.has(e.id))throw new be("provider_conflict",`Provider ${e.id} is already registered.`);let i=new Set;for(let n of t){if(!Zx(n.type))throw new be("invalid_contract",`Provider ${e.id} supplied unsupported ${n.type} contract ${n.id}.`);Tg(this.contractValidators[n.type],n,"invalid_contract",`${n.type} contract ${n.id||""}`);let s=`${n.type}:${n.id}`;if(i.has(s))throw new be("contract_conflict",`Provider ${e.id} repeats ${s}.`);if(i.add(s),(n.type==="action"||n.type==="event"||n.type==="capability")&&n.provider!==void 0&&n.provider!==e.id)throw new be("provider_contract_mismatch",`${n.id} names provider ${String(n.provider)}.`);if(n.type==="action"&&this.actionOwners.has(n.id))throw new be("contract_conflict",`Action ${n.id} is already registered.`);if(n.type==="event"&&this.eventOwners.has(n.id))throw new be("contract_conflict",`Event ${n.id} is already registered.`)}Bo(e,t,"actions","action"),Bo(e,t,"events","event"),Bo(e,t,"capabilities","capability"),Bo(e,t,"workflows","workflow")}compileContracts(e){let t=new Map,i=new Map;try{for(let n of e){if(n.type==="action"){let s=n;t.set(s.id,{input:this.ajv.compile(s.schemas.input),output:s.schemas.output?this.ajv.compile(s.schemas.output):void 0})}if(n.type==="event"){let s=n;i.set(s.id,this.ajv.compile(s.schemas.payload))}}}catch(n){throw new be("invalid_contract_schema",n instanceof Error?n.message:"A contract schema could not be compiled.")}return{actions:t,events:i}}deliverProviderEvent(e,t){var c;let i=t;if(!this.eventEnvelopeValidator(i)){this.rejectEvent("invalid_event_envelope",is(t.type||"event",this.eventEnvelopeValidator),e,t.type||"");return}let n=this.eventOwners.get(t.type),s=this.providerRegistry.get(e),o=s==null?void 0:s.contracts.find(l=>l.type==="event"&&l.id===t.type);if(!o||n!==e){this.rejectEvent("event_provider_mismatch",`Provider ${e} cannot emit ${t.type}.`,e,t.type);return}if(t.contract_version!==o.version||t.source.provider!==void 0&&t.source.provider!==e){this.rejectEvent("contract_version_mismatch",`Event ${t.type} does not match its registered contract.`,e,t.type);return}if(this.recentEventIds.has(t.id))return;let a=this.eventValidators.get(t.type);if(!(a!=null&&a(t.payload))){this.rejectEvent("invalid_event_payload",is(t.type,a),e,t.type);return}if(this.recentEventIds.add(t.id),this.recentEventIds.size>this.recentEventLimit){let l=this.recentEventIds.values().next().value;l&&this.recentEventIds.delete(l)}for(let l of(c=this.eventHandlers.get(t.type))!=null?c:[])Promise.resolve(l(oi(t))).catch(u=>{this.report({severity:"error",code:"event_handler_failed",message:`Event handler failed for ${t.type}.`,providerId:e,contractId:t.type,cause:u})})}async unregisterProvider(e){let t=this.providerRegistry.get(e);if(t){this.providerRegistry.delete(e);for(let i of t.contracts)i.type==="action"&&(this.actionOwners.delete(i.id),this.actionValidators.delete(i.id)),i.type==="event"&&(this.eventOwners.delete(i.id),this.eventValidators.delete(i.id));for(let i of t.subscriptions)await i.dispose();await t.provider.dispose()}}rejectEvent(e,t,i,n){this.report({severity:"warning",code:e,message:t,providerId:i,contractId:n})}report(e){var t,i;(i=(t=this.options).onDiagnostic)==null||i.call(t,e)}assertActive(){if(this.disposed)throw new be("runtime_disposed","Runtime provider host is disposed.")}resolvePolicy(){let e=this.policyResolver();if(!e||e.selected!==!0||typeof e.id!="string"||e.id.length===0||typeof e.capabilities!="object")throw new be("invalid_runtime_policy","The host policy resolver returned an invalid policy.");for(let t of Object.values(e.capabilities))if(t!=="allow"&&t!=="deny")throw new be("invalid_runtime_policy","Runtime policy capability modes must be allow or deny.");return oi(e)}},be=class extends Error{constructor(t,i){super(i);I(this,"code");this.code=t,this.name="RuntimeHostError"}};function Wx(r){return typeof r=="string"?{id:r}:r}function Bo(r,e,t,i){var o,a;let n=[...(a=(o=r.contracts)==null?void 0:o[t])!=null?a:[]].sort(),s=e.filter(c=>c.type===i).map(c=>c.id).sort();if(n.length!==s.length||n.some((c,l)=>c!==s[l]))throw new be("provider_contract_mismatch",`${r.id} advertised ${t} do not match its supplied contracts.`)}function Jx(r){var e;if(!((e=r.actor)!=null&&e.id)||!r.actor.kind||!r.origin||!r.run_id||!r.correlation_id||!r.executor)throw new be("invalid_dispatch_context","Dispatch context is missing required provenance fields.")}function is(r,e){var i;let t=(i=e==null?void 0:e.errors)==null?void 0:i.map(n=>{var s;return`${n.instancePath||"/"} ${(s=n.message)!=null?s:"is invalid"}`}).join("; ");return`${r} validation failed${t?`: ${t}`:"."}`}function rs(r,e){return{code:r,message:e,severity:"error"}}function oi(r){return JSON.parse(JSON.stringify(r))}function Yx(){let r=new Og.Ajv2020({allErrors:!0,strict:!1});return(0,Cg.default)(r),r}function Xx(r){let e=Fd();return{action:r.compile(e.action),event:r.compile(e.event),capability:r.compile(e.capability),workflow:r.compile(e.workflow)}}function Zx(r){return r==="action"||r==="event"||r==="capability"||r==="workflow"}function Tg(r,e,t,i){if(!r(e))throw new be(t,is(i,r))}var N=class extends Error{constructor(t,i,n){super(i);I(this,"code");I(this,"details");this.code=t,this.details=n,this.name="InteropError"}toPortableError(t){return{code:this.code,message:this.message,...this.details===void 0?{}:{details:this.details},...t===void 0?{}:{retryable:t}}}},ss=class extends Error{constructor(t,i){super(i.message);I(this,"status");I(this,"error");this.status=t,this.error=i,this.name="ActionHandlerError"}};var Ng=ft(Wn(),1),Mg=ft(Yn(),1);var Hd={contract:{$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://mdbase.dev/schemas/v0.3/data-contract.schema.json",title:"mdbase v0.3 contract frontmatter",type:"object",required:["kind","contract_type","id","version"],properties:{kind:{const:"mdbase.contract"},contract_type:{enum:["record","event","action"]},id:{$ref:"#/$defs/contractId"},version:{$ref:"#/$defs/semanticVersion"},name:{type:"string",minLength:1},description:{type:"string"},record_schema:{$ref:"#/$defs/schemaWrapper"},binding_schema:{$ref:"#/$defs/schemaWrapper"},data_schema:{$ref:"#/$defs/schemaWrapper"},source_schema:{$ref:"#/$defs/schemaWrapper"},input_schema:{$ref:"#/$defs/schemaWrapper"},output_schema:{$ref:"#/$defs/schemaWrapper"},error_schema:{$ref:"#/$defs/schemaWrapper"},provider_schema:{$ref:"#/$defs/schemaWrapper"},behavior:{$ref:"#/$defs/actionBehavior"}},patternProperties:{"^x-[A-Za-z][A-Za-z0-9._:-]{0,127}$":!0},oneOf:[{properties:{contract_type:{const:"record"},record_schema:!0,binding_schema:!0,data_schema:!1,source_schema:!1,input_schema:!1,output_schema:!1,error_schema:!1,provider_schema:!1,behavior:!1},required:["record_schema"]},{properties:{contract_type:{const:"event"},record_schema:!1,binding_schema:!1,data_schema:!0,source_schema:!0,input_schema:!1,output_schema:!1,error_schema:!1,provider_schema:!1,behavior:!1},required:["data_schema"]},{properties:{contract_type:{const:"action"},record_schema:!1,binding_schema:!1,data_schema:!1,source_schema:!1,input_schema:!0,output_schema:!0,error_schema:!0,provider_schema:!0,behavior:!0},required:["input_schema"]}],additionalProperties:!1,$defs:{contractId:{type:"string",minLength:3,maxLength:128,pattern:"^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)+$"},semanticVersion:{type:"string",pattern:"^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)(?:-[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?(?:\\+[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?$"},schemaWrapper:{type:"object",required:["dialect"],properties:{dialect:{const:"json-schema-2020-12"},value:{type:"object"},ref:{type:"string",minLength:1}},oneOf:[{required:["value"],properties:{value:!0,ref:!1}},{required:["ref"],properties:{ref:!0,value:!1}}],additionalProperties:!1},actionBehavior:{type:"object",properties:{idempotency:{enum:["none","optional","required"]},cancellation:{enum:["none","cooperative"]}},additionalProperties:!1}}},profile:{$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://mdbase.dev/schemas/interop/v0.1/profile.schema.json",title:"mdbase event and action interoperability profile 0.1",oneOf:[{$ref:"#/$defs/event"},{$ref:"#/$defs/actionRequest"},{$ref:"#/$defs/actionInvocation"},{$ref:"#/$defs/actionOutcome"},{$ref:"#/$defs/actionCancellation"},{$ref:"#/$defs/eventSourceDeclaration"},{$ref:"#/$defs/actionProviderDeclaration"},{$ref:"#/$defs/conformanceClaim"}],$defs:{contractId:{type:"string",minLength:3,maxLength:128,pattern:"^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)+$"},semanticVersion:{type:"string",pattern:"^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)(?:-[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?(?:\\+[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?$"},semanticVersionRequirement:{type:"string",minLength:1,maxLength:128},digest:{type:"string",pattern:"^sha256:[0-9a-f]{64}$"},portableId:{type:"string",minLength:1,maxLength:256,pattern:"^[A-Za-z0-9][A-Za-z0-9._:@/-]*$"},exactContract:{type:"object",required:["id","version","digest"],properties:{id:{$ref:"#/$defs/contractId"},version:{$ref:"#/$defs/semanticVersion"},digest:{$ref:"#/$defs/digest"}},additionalProperties:!1},contractRequirement:{type:"object",required:["id","version"],properties:{id:{$ref:"#/$defs/contractId"},version:{$ref:"#/$defs/semanticVersionRequirement"},digest:{$ref:"#/$defs/digest"}},additionalProperties:!1},implementationIdentity:{type:"object",required:["application","implementation","version"],properties:{application:{$ref:"#/$defs/portableId"},implementation:{$ref:"#/$defs/portableId"},version:{$ref:"#/$defs/semanticVersion"},instance_id:{$ref:"#/$defs/portableId"}},additionalProperties:!1},transportCapabilities:{type:"object",required:["delivery","ordering","cancellation","deadlines"],properties:{delivery:{type:"array",minItems:1,uniqueItems:!0,items:{enum:["ephemeral","at_least_once","durable_cursor","offline_queue"]}},ordering:{type:"array",uniqueItems:!0,items:{enum:["none","source","subject"]}},cancellation:{type:"boolean"},deadlines:{type:"boolean"},provider_discovery:{type:"boolean"},max_payload_bytes:{type:"integer",minimum:1},outcome_retention_seconds:{type:"integer",minimum:0},request_deduplication:{type:"boolean"},cross_process_identity:{type:"boolean"}},additionalProperties:!1},extensionValue:{oneOf:[{type:"null"},{type:"boolean"},{type:"integer"},{type:"number"},{type:"string"}]},event:{title:"mdbase CloudEvents event envelope",type:"object",required:["specversion","id","source","type","time","datacontenttype","dataschema","data","mdbaseprofile","mdbasecontractversion","mdbasecontractdigest","mdbaseapplication","mdbaseimplementation","mdbaseimplementationversion"],properties:{specversion:{const:"1.0"},id:{$ref:"#/$defs/portableId"},source:{type:"string",format:"uri-reference",minLength:1},type:{$ref:"#/$defs/contractId"},time:{type:"string",format:"date-time"},subject:{type:"string",format:"uri-reference",minLength:1},datacontenttype:{const:"application/json"},dataschema:{type:"string",format:"uri",minLength:1},data:!0,mdbaseprofile:{const:"0.1"},mdbasecontractversion:{$ref:"#/$defs/semanticVersion"},mdbasecontractdigest:{$ref:"#/$defs/digest"},mdbaseapplication:{$ref:"#/$defs/portableId"},mdbaseimplementation:{$ref:"#/$defs/portableId"},mdbaseimplementationversion:{$ref:"#/$defs/semanticVersion"},mdbaseinstanceid:{$ref:"#/$defs/portableId"},correlationid:{$ref:"#/$defs/portableId"},causationid:{$ref:"#/$defs/portableId"}},propertyNames:{pattern:"^[a-z0-9]+$"},additionalProperties:{$ref:"#/$defs/extensionValue"}},actionRequest:{title:"mdbase action request",type:"object",required:["kind","profile_version","request_id","contract","caller","created_at","input"],properties:{kind:{const:"mdbase.action.request"},profile_version:{const:"0.1"},request_id:{$ref:"#/$defs/portableId"},contract:{$ref:"#/$defs/contractRequirement"},caller:{$ref:"#/$defs/implementationIdentity"},created_at:{type:"string",format:"date-time"},correlation_id:{$ref:"#/$defs/portableId"},causation_id:{$ref:"#/$defs/portableId"},subject:{type:"string",format:"uri-reference",minLength:1},idempotency_key:{type:"string",minLength:1,maxLength:512},deadline:{type:"string",format:"date-time"},requested_provider:{type:"object",properties:{application:{$ref:"#/$defs/portableId"},implementation:{$ref:"#/$defs/portableId"},instance_id:{$ref:"#/$defs/portableId"}},minProperties:1,additionalProperties:!1},authorization_context:{type:"string",format:"uri-reference",minLength:1},input:!0},additionalProperties:!1},actionInvocation:{title:"mdbase admitted action invocation",type:"object",required:["kind","profile_version","invocation_id","attempt_id","request_id","contract","caller","provider","provider_declaration_digest","handler_id","admitted_at","input"],properties:{kind:{const:"mdbase.action.invocation"},profile_version:{const:"0.1"},invocation_id:{$ref:"#/$defs/portableId"},attempt_id:{$ref:"#/$defs/portableId"},request_id:{$ref:"#/$defs/portableId"},contract:{$ref:"#/$defs/exactContract"},caller:{$ref:"#/$defs/implementationIdentity"},provider:{$ref:"#/$defs/implementationIdentity"},provider_declaration_digest:{$ref:"#/$defs/digest"},handler_id:{$ref:"#/$defs/portableId"},admitted_at:{type:"string",format:"date-time"},correlation_id:{$ref:"#/$defs/portableId"},causation_id:{$ref:"#/$defs/portableId"},subject:{type:"string",format:"uri-reference",minLength:1},idempotency_key:{type:"string",minLength:1,maxLength:512},deadline:{type:"string",format:"date-time"},authorization_context:{type:"string",format:"uri-reference",minLength:1},input:!0},additionalProperties:!1},portableError:{type:"object",required:["code","message"],properties:{code:{enum:["unknown_contract","unsupported_contract_version","contract_digest_conflict","invalid_event_data","invalid_action_input","invalid_action_output","no_provider","ambiguous_provider","requested_provider_unavailable","unauthorized","capability_denied","request_rejected","deadline_exceeded","cancellation_unsupported","cancelled","handler_failure","outcome_indeterminate","transport_unavailable","unsupported_transport_capability"]},message:{type:"string",minLength:1},details:!0,retryable:{type:"boolean"}},additionalProperties:!1},actionOutcome:{title:"mdbase action outcome",type:"object",required:["kind","profile_version","outcome_id","request_id","invocation_id","attempt_id","contract","provider","provider_declaration_digest","status","completed_at"],properties:{kind:{const:"mdbase.action.outcome"},profile_version:{const:"0.1"},outcome_id:{$ref:"#/$defs/portableId"},request_id:{$ref:"#/$defs/portableId"},invocation_id:{$ref:"#/$defs/portableId"},attempt_id:{$ref:"#/$defs/portableId"},contract:{$ref:"#/$defs/exactContract"},provider:{$ref:"#/$defs/implementationIdentity"},provider_declaration_digest:{$ref:"#/$defs/digest"},status:{enum:["succeeded","rejected","failed","cancelled","outcome_indeterminate"]},completed_at:{type:"string",format:"date-time"},output:!0,error:{$ref:"#/$defs/portableError"}},allOf:[{if:{properties:{status:{const:"succeeded"}},required:["status"]},then:{required:["output"],not:{required:["error"]}},else:{required:["error"],not:{required:["output"]}}}],additionalProperties:!1},actionCancellation:{title:"mdbase action cancellation request",type:"object",required:["kind","profile_version","cancellation_id","request_id","caller","requested_at"],properties:{kind:{const:"mdbase.action.cancel"},profile_version:{const:"0.1"},cancellation_id:{$ref:"#/$defs/portableId"},request_id:{$ref:"#/$defs/portableId"},caller:{$ref:"#/$defs/implementationIdentity"},requested_at:{type:"string",format:"date-time"},reason:{type:"string",maxLength:1024}},additionalProperties:!1},eventSourceDeclaration:{title:"mdbase event-source declaration",type:"object",required:["kind","profile_version","declaration_id","declaration_digest","source","contracts"],properties:{kind:{const:"mdbase.event-source"},profile_version:{const:"0.1"},declaration_id:{$ref:"#/$defs/portableId"},declaration_digest:{$ref:"#/$defs/digest"},source:{$ref:"#/$defs/implementationIdentity"},contracts:{type:"array",minItems:1,items:{type:"object",required:["requirement","resolved"],properties:{requirement:{$ref:"#/$defs/contractRequirement"},resolved:{$ref:"#/$defs/exactContract"},binding:!0,ordering:{type:"array",uniqueItems:!0,items:{enum:["none","source","subject"]}}},additionalProperties:!1}}},additionalProperties:!1},actionProviderDeclaration:{title:"mdbase action-provider declaration",type:"object",required:["kind","profile_version","declaration_id","declaration_digest","provider","handlers"],properties:{kind:{const:"mdbase.action-provider"},profile_version:{const:"0.1"},declaration_id:{$ref:"#/$defs/portableId"},declaration_digest:{$ref:"#/$defs/digest"},provider:{$ref:"#/$defs/implementationIdentity"},handlers:{type:"array",minItems:1,items:{type:"object",required:["handler_id","requirement","resolved"],properties:{handler_id:{$ref:"#/$defs/portableId"},requirement:{$ref:"#/$defs/contractRequirement"},resolved:{$ref:"#/$defs/exactContract"},binding:!0,idempotency:{type:"object",required:["mode"],properties:{mode:{enum:["none","request"]},retention_seconds:{type:"integer",minimum:1}},additionalProperties:!1},cancellation:{enum:["none","cooperative"]},max_concurrency:{type:"integer",minimum:1}},additionalProperties:!1}}},additionalProperties:!1},conformanceClaim:{title:"mdbase interoperability conformance claim",type:"object",required:["kind","profile_version","implementation","roles","transport"],properties:{kind:{const:"mdbase.interop.conformance"},profile_version:{const:"0.1"},implementation:{$ref:"#/$defs/implementationIdentity"},roles:{type:"array",minItems:1,uniqueItems:!0,items:{enum:["event_source","event_consumer","action_caller","action_provider","bridge"]}},transport:{$ref:"#/$defs/transportCapabilities"},evidence:{type:"array",items:{type:"object",required:["scenario","result"],properties:{scenario:{type:"string",minLength:1},result:{const:"pass"},uri:{type:"string",format:"uri-reference"}},additionalProperties:!1}}},additionalProperties:!1}}},event:{$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://mdbase.dev/schemas/interop/v0.1/event.schema.json",title:"mdbase CloudEvents event envelope",$ref:"profile.schema.json#/$defs/event"},actionRequest:{$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://mdbase.dev/schemas/interop/v0.1/action-request.schema.json",title:"mdbase action request",$ref:"profile.schema.json#/$defs/actionRequest"},actionInvocation:{$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://mdbase.dev/schemas/interop/v0.1/action-invocation.schema.json",title:"mdbase admitted action invocation",$ref:"profile.schema.json#/$defs/actionInvocation"},actionOutcome:{$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://mdbase.dev/schemas/interop/v0.1/action-outcome.schema.json",title:"mdbase action outcome",$ref:"profile.schema.json#/$defs/actionOutcome"},actionCancellation:{$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://mdbase.dev/schemas/interop/v0.1/action-cancellation.schema.json",title:"mdbase action cancellation request",$ref:"profile.schema.json#/$defs/actionCancellation"},eventSourceDeclaration:{$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://mdbase.dev/schemas/interop/v0.1/event-source-declaration.schema.json",title:"mdbase event-source declaration",$ref:"profile.schema.json#/$defs/eventSourceDeclaration"},actionProviderDeclaration:{$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://mdbase.dev/schemas/interop/v0.1/action-provider-declaration.schema.json",title:"mdbase action-provider declaration",$ref:"profile.schema.json#/$defs/actionProviderDeclaration"},conformanceClaim:{$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://mdbase.dev/schemas/interop/v0.1/conformance-claim.schema.json",title:"mdbase interoperability conformance claim",$ref:"profile.schema.json#/$defs/conformanceClaim"}};var Qx=Mg.default;function qg(){return Object.fromEntries(Object.entries(Hd).map(([r,e])=>[r,structuredClone(e)]))}function Kd(){let r=new Ng.Ajv2020({allErrors:!0,strict:!1,validateFormats:!0});Qx(r);let e=qg();r.addSchema(e.profile);for(let[t,i]of Object.entries(e))t!=="profile"&&r.addSchema(i);return r}function ar(r,e){let t=String(Hd[e].$id),i=r.getSchema(t);if(!i)throw new Error(`Canonical interoperability schema is unavailable: ${e}`);return i}function Mr(r){return(r!=null?r:[]).map(e=>{var t;return`${e.instancePath||"/"} ${(t=e.message)!=null?t:e.keyword}`}).join("; ")}function Jt(r,e){if(!("value"in r))throw new N("contract_digest_conflict",`${e} must be resolved to an inline JSON Schema before runtime registration.`);return structuredClone(r.value)}function Lg(r){let e={kind:r.kind,contract_type:r.contract_type,id:r.id,version:r.version};switch(r.contract_type){case"record":e.record_schema=Jt(r.record_schema,"record_schema"),r.binding_schema&&(e.binding_schema=Jt(r.binding_schema,"binding_schema"));break;case"event":e.data_schema=Jt(r.data_schema,"data_schema"),r.source_schema&&(e.source_schema=Jt(r.source_schema,"source_schema"));break;case"action":e.input_schema=Jt(r.input_schema,"input_schema"),r.output_schema&&(e.output_schema=Jt(r.output_schema,"output_schema")),r.error_schema&&(e.error_schema=Jt(r.error_schema,"error_schema")),r.provider_schema&&(e.provider_schema=Jt(r.provider_schema,"provider_schema")),r.behavior&&(e.behavior=structuredClone(r.behavior));break}return e}async function Ko(r){return Ki(Lg(r))}async function Ki(r){return`sha256:${await eI(Gd(r))}`}function jg(r,e){return{data:Hi(r,e.data_schema,`${e.id} data_schema`),...e.source_schema?{source:Hi(r,e.source_schema,`${e.id} source_schema`)}:{}}}function Dg(r,e){return{input:Hi(r,e.input_schema,`${e.id} input_schema`),...e.output_schema?{output:Hi(r,e.output_schema,`${e.id} output_schema`)}:{},...e.error_schema?{error:Hi(r,e.error_schema,`${e.id} error_schema`)}:{},...e.provider_schema?{provider:Hi(r,e.provider_schema,`${e.id} provider_schema`)}:{}}}function Go(r,e,t,i){if(!(!r||r(e)))throw new N(t,`${i} failed JSON Schema validation: ${Mr(r.errors)}`)}function Hi(r,e,t){try{return r.compile(Jt(e,t))}catch(i){throw new N("contract_digest_conflict",`${t} could not be compiled: ${i instanceof Error?i.message:String(i)}`)}}function Gd(r){return r===null||typeof r!="object"?JSON.stringify(r):Array.isArray(r)?`[${r.map(Gd).join(",")}]`:`{${Object.entries(r).filter(([,t])=>t!==void 0).sort(([t],[i])=>ti?1:0).map(([t,i])=>`${JSON.stringify(t)}:${Gd(i)}`).join(",")}}`}async function eI(r){let e=new TextEncoder().encode(r),t=await globalThis.crypto.subtle.digest("SHA-256",e);return[...new Uint8Array(t)].map(i=>i.toString(16).padStart(2,"0")).join("")}var lr=ft(Dd(),1);var Wd={delivery:["ephemeral"],ordering:["none"],cancellation:!0,deadlines:!0,provider_discovery:!0,request_deduplication:!0,cross_process_identity:!1},tI=new Set(["specversion","id","source","type","time","subject","datacontenttype","dataschema","data","mdbaseprofile","mdbasecontractversion","mdbasecontractdigest","mdbaseapplication","mdbaseimplementation","mdbaseimplementationversion","mdbaseinstanceid","correlationid","causationid"]),os=class{constructor(e={}){I(this,"options");I(this,"profileVersion","0.1");I(this,"transport");I(this,"ajv",Kd());I(this,"contractValidator",ar(this.ajv,"contract"));I(this,"eventValidator",ar(this.ajv,"event"));I(this,"actionRequestValidator",ar(this.ajv,"actionRequest"));I(this,"actionInvocationValidator",ar(this.ajv,"actionInvocation"));I(this,"actionOutcomeValidator",ar(this.ajv,"actionOutcome"));I(this,"eventSourceDeclarationValidator",ar(this.ajv,"eventSourceDeclaration"));I(this,"actionProviderDeclarationValidator",ar(this.ajv,"actionProviderDeclaration"));I(this,"contracts",new Map);I(this,"clients",new Map);I(this,"eventSources",new Map);I(this,"actionProviders",new Map);I(this,"subscriptions",new Map);I(this,"activeActions",new Map);I(this,"completedActions",new Map);I(this,"admissionLocks",new Map);I(this,"recentEvents",new Map);I(this,"authorize");I(this,"now");I(this,"idFactory");I(this,"recentEventLimit");I(this,"completedRequestLimit");I(this,"nextSequence",0);I(this,"disposed",!1);var t,i,n,s,o,a,c,l,u,d;this.options=e,this.authorize=(t=e.authorize)!=null?t:(()=>!1),this.now=(i=e.now)!=null?i:(()=>new Date),this.idFactory=(n=e.idFactory)!=null?n:(f=>{var m;this.nextSequence+=1;let p=typeof((m=globalThis.crypto)==null?void 0:m.randomUUID)=="function"?globalThis.crypto.randomUUID():`${this.now().getTime().toString(36)}-${this.nextSequence.toString(36)}`;return`${f}_${p}`}),this.recentEventLimit=Math.max(1,(s=e.recentEventLimit)!=null?s:1e3),this.completedRequestLimit=Math.max(1,(o=e.completedRequestLimit)!=null?o:1e3),this.transport={...Wd,...structuredClone((a=e.transport)!=null?a:{}),delivery:[...(l=(c=e.transport)==null?void 0:c.delivery)!=null?l:Wd.delivery],ordering:[...(d=(u=e.transport)==null?void 0:u.ordering)!=null?d:Wd.ordering]}}connect(e){this.assertActive(),rI(e);let t=this.idFactory("client"),i={identity:structuredClone(e),disposed:!1,sources:new Set,providers:new Set,subscriptions:new Set};return this.clients.set(t,i),{identity:structuredClone(e),registerEventSource:n=>this.registerEventSource(t,n),publishEvent:n=>this.publishEvent(t,n),subscribeEvents:(n,s)=>this.subscribeEvents(t,n,s),registerActionProvider:n=>this.registerActionProvider(t,n),invokeAction:n=>this.invokeAction(t,n),cancelAction:(n,s)=>this.cancelAction(t,n,s),dispose:()=>this.disposeClient(t)}}describe(){return this.assertActive(),{profile_version:"0.1",transport:structuredClone(this.transport),contracts:[...this.contracts.values()].map(({artifact:e,reference:t})=>({artifact:structuredClone(e),reference:structuredClone(t)})).sort((e,t)=>e.reference.id.localeCompare(t.reference.id)||e.reference.version.localeCompare(t.reference.version)),event_sources:[...this.eventSources.values()].map(({declaration:e})=>structuredClone(e)).sort((e,t)=>e.declaration_id.localeCompare(t.declaration_id)),action_providers:[...this.actionProviders.values()].map(({declaration:e})=>structuredClone(e)).sort((e,t)=>e.declaration_id.localeCompare(t.declaration_id))}}async dispose(){if(!this.disposed){this.disposed=!0;for(let e of[...this.clients.keys()])await this.disposeClient(e,!0);this.contracts.clear(),this.recentEvents.clear(),this.completedActions.clear()}}async registerEventSource(e,t){var l;let i=this.requireClient(e);if(t.contracts.length===0)throw new N("request_rejected","An event-source declaration must include a contract.");let n=`${e}:${t.declaration_id}`;if(this.eventSources.has(n))throw new N("request_rejected",`Event-source declaration ${t.declaration_id} is already registered.`);let s=new Map;for(let u of t.contracts){let d=await this.prepareEventContract(u.contract),f=Fg(u.requirement,d.reference);if(Vg(f,d.reference),await this.assertAuthorized({operation:"register_event_source",principal:i.identity,contract:d.reference}),d.sourceValidator&&!d.sourceValidator((l=u.binding)!=null?l:{}))throw new N("request_rejected",`${d.reference.id} source binding is invalid: ${Mr(d.sourceValidator.errors)}`);let p=Wo(d.reference);if(s.has(p))throw new N("contract_digest_conflict",`Event contract ${p} is repeated by one declaration.`);s.set(p,{contract:d,requirement:f,...u.binding===void 0?{}:{binding:structuredClone(u.binding)},...u.ordering===void 0?{}:{ordering:[...u.ordering]}})}let o={kind:"mdbase.event-source",profile_version:"0.1",declaration_id:t.declaration_id,source:structuredClone(i.identity),contracts:[...s.values()].map(({contract:u,requirement:d,binding:f,ordering:p})=>({requirement:structuredClone(d),resolved:structuredClone(u.reference),...f===void 0?{}:{binding:f},...p===void 0?{}:{ordering:p}}))},a={...o,declaration_digest:await Ki(o)};qr(this.eventSourceDeclarationValidator,a,"request_rejected","Event-source declaration"),this.commitContracts([...s.values()].map(({contract:u})=>u)),this.eventSources.set(n,{id:n,clientId:e,declaration:structuredClone(a),contracts:new Map([...s.entries()].map(([u,d])=>[u,{contract:d.contract,...d.binding===void 0?{}:{binding:d.binding}}]))}),i.sources.add(n);let c=!0;return{declaration:structuredClone(a),dispose:()=>{c&&(c=!1,this.removeEventSource(n))}}}async publishEvent(e,t){var m,h,y,b;let i=this.requireClient(e),n=Wo(t.contract),s=[...i.sources].map(g=>this.eventSources.get(g)).find(g=>g==null?void 0:g.contracts.has(n));if(!s)throw new N("unknown_contract",`This client has not registered event contract ${t.contract.id} ${t.contract.version}.`);let o=(m=s.contracts.get(n))==null?void 0:m.contract;if(!o)throw new N("unknown_contract",`Event contract ${n} is unavailable.`);if(t.contract.digest&&t.contract.digest!==o.reference.digest)throw new N("contract_digest_conflict",`Event contract ${n} has a different digest.`);await this.assertAuthorized({operation:"publish_event",principal:i.identity,contract:o.reference,...t.subject===void 0?{}:{subject:t.subject}}),Jd(t.data,"invalid_event_data",`Event ${o.reference.id} data`),Go(o.dataValidator,t.data,"invalid_event_data",`Event ${o.reference.id} data`);let a=(h=t.extensions)!=null?h:{};for(let g of Object.keys(a))if(tI.has(g))throw new N("request_rejected",`Event extension ${g} is reserved.`);let c={...structuredClone(a),specversion:"1.0",id:(y=t.id)!=null?y:this.idFactory("evt"),source:iI(i.identity),type:o.reference.id,time:(b=t.time)!=null?b:this.now().toISOString(),...t.subject===void 0?{}:{subject:t.subject},datacontenttype:"application/json",dataschema:Bg(o.reference),data:structuredClone(t.data),mdbaseprofile:"0.1",mdbasecontractversion:o.reference.version,mdbasecontractdigest:o.reference.digest,mdbaseapplication:i.identity.application,mdbaseimplementation:i.identity.implementation,mdbaseimplementationversion:i.identity.version,...i.identity.instance_id===void 0?{}:{mdbaseinstanceid:i.identity.instance_id},...t.correlation_id===void 0?{}:{correlationid:t.correlation_id},...t.causation_id===void 0?{}:{causationid:t.causation_id}};qr(this.eventValidator,c,"invalid_event_data","Event envelope"),Yd(this.transport,c),nI(c,o.reference);let l=`${c.source}\0${c.id}`,u=this.recentEvents.get(l);if(u){if(JSON.stringify(u)!==JSON.stringify(c))throw new N("contract_digest_conflict",`Event ${c.source} ${c.id} was reused with different content.`);return{event:structuredClone(u),deliveries:0,duplicate:!0}}this.recentEvents.set(l,structuredClone(c)),zg(this.recentEvents,this.recentEventLimit);let d=[...this.subscriptions.values()].filter(({subscription:g})=>Jo(g.contract,o.reference)),f=await Promise.allSettled(d.map(async g=>await this.isAuthorized({operation:"subscribe_event",principal:g.principal,contract:o.reference,...c.subject===void 0?{}:{subject:c.subject}})?(await g.handler(structuredClone(c)),!0):!1)),p=0;for(let g of f)g.status==="fulfilled"&&g.value?p+=1:g.status==="rejected"&&this.report({severity:"error",code:"event_consumer_failed",message:`An event consumer failed while handling ${c.type}.`,contract:o.reference,cause:g.reason});return{event:structuredClone(c),deliveries:p,duplicate:!1}}async subscribeEvents(e,t,i){let n=this.requireClient(e);Xd(t.contract),aI(this.transport,t.require_transport),await this.assertAuthorized({operation:"subscribe_event",principal:n.identity,contract:t.contract});let s=this.idFactory("subscription");this.subscriptions.set(s,{id:s,clientId:e,principal:structuredClone(n.identity),subscription:structuredClone(t),handler:i}),n.subscriptions.add(s);let o=!0;return{dispose:()=>{o&&(o=!1,this.removeSubscription(s))}}}async registerActionProvider(e,t){var d,f,p,m,h,y,b;let i=this.requireClient(e);if(t.handlers.length===0)throw new N("request_rejected","An action-provider declaration must include a handler.");let n=`${e}:${t.declaration_id}`;if(this.actionProviders.has(n))throw new N("request_rejected",`Action-provider declaration ${t.declaration_id} is already registered.`);let s=[],o=new Set;for(let g of t.handlers){if(o.has(g.handler_id))throw new N("request_rejected",`Handler ${g.handler_id} is repeated.`);o.add(g.handler_id);let _=await this.prepareActionContract(g.contract),S=Fg(g.requirement,_.reference);if(Vg(S,_.reference),await this.assertAuthorized({operation:"register_action_provider",principal:i.identity,contract:_.reference,provider:i.identity}),_.providerValidator&&!_.providerValidator((d=g.binding)!=null?d:{}))throw new N("request_rejected",`${_.reference.id} provider binding is invalid: ${Mr(_.providerValidator.errors)}`);let v=(p=(f=g.contract.behavior)==null?void 0:f.idempotency)!=null?p:"none";if(((m=g.idempotency)==null?void 0:m.mode)==="request"&&v==="none")throw new N("request_rejected",`${_.reference.id} does not permit request deduplication.`);if(v==="required"&&((h=g.idempotency)==null?void 0:h.mode)!=="request")throw new N("request_rejected",`${_.reference.id} requires a provider with request deduplication.`);let P=(b=(y=g.contract.behavior)==null?void 0:y.cancellation)!=null?b:"none";if(g.cancellation==="cooperative"&&P!=="cooperative")throw new N("request_rejected",`${_.reference.id} does not declare cooperative cancellation.`);s.push({contract:_,declaration:{handler_id:g.handler_id,requirement:S,resolved:structuredClone(_.reference),...g.binding===void 0?{}:{binding:structuredClone(g.binding)},...g.idempotency===void 0?{}:{idempotency:structuredClone(g.idempotency)},...g.cancellation===void 0?{}:{cancellation:g.cancellation},...g.max_concurrency===void 0?{}:{max_concurrency:g.max_concurrency}},handler:g.handler})}let a={kind:"mdbase.action-provider",profile_version:"0.1",declaration_id:t.declaration_id,provider:structuredClone(i.identity),handlers:s.map(({declaration:g})=>structuredClone(g))},c={...a,declaration_digest:await Ki(a)};qr(this.actionProviderDeclarationValidator,c,"request_rejected","Action-provider declaration"),this.commitContracts(s.map(({contract:g})=>g));let l=s.map(({contract:g,declaration:_,handler:S})=>({registrationId:n,clientId:e,declaration:structuredClone(c),handlerDeclaration:structuredClone(_),contract:g,handler:S,active:0}));this.actionProviders.set(n,{id:n,clientId:e,declaration:structuredClone(c),handlers:l}),i.providers.add(n);let u=!0;return{declaration:structuredClone(c),dispose:()=>{u&&(u=!1,this.removeActionProvider(n))}}}async invokeAction(e,t){var a,c,l,u,d,f,p,m,h,y,b,g;let i=this.requireClient(e);Xd(t.contract);let n=(a=t.request_id)!=null?a:this.idFactory("req");this.cleanCompletedActions(),Jd(t.input,"invalid_action_input",`Action ${t.contract.id} input`);let s={kind:"mdbase.action.request",profile_version:"0.1",request_id:n,contract:structuredClone(t.contract),caller:structuredClone(i.identity),created_at:(c=t.created_at)!=null?c:this.now().toISOString(),...t.correlation_id===void 0?{}:{correlation_id:t.correlation_id},...t.causation_id===void 0?{}:{causation_id:t.causation_id},...t.subject===void 0?{}:{subject:t.subject},...t.idempotency_key===void 0?{}:{idempotency_key:t.idempotency_key},...t.deadline===void 0?{}:{deadline:t.deadline},...t.requested_provider===void 0?{}:{requested_provider:structuredClone(t.requested_provider)},input:structuredClone(t.input)};qr(this.actionRequestValidator,s,"request_rejected","Action request"),Yd(this.transport,s);let o=await this.acquireAdmission(n);try{let _=await Ki(sI(s)),S=this.activeActions.get(n);if(S){if(Ug(e,n,_,S),((l=S.handler.handlerDeclaration.idempotency)==null?void 0:l.mode)!=="request")throw new N("request_rejected",`Action request ${n} is already active without deduplication.`);return structuredClone(await S.promise)}let v=this.completedActions.get(n);if(v){if(Ug(e,n,_,v),!v.reusable)throw new N("request_rejected",`Action request ${n} was already completed without deduplication.`);return structuredClone(v.outcome)}if(s.deadline&&new Date(s.deadline).getTime()<=this.now().getTime())throw new N("deadline_exceeded",`Action request ${n} passed its deadline before admission.`);if(s.deadline&&!this.transport.deadlines)throw new N("unsupported_transport_capability","The active transport cannot enforce action deadlines.");let P=this.resolveActionCandidates(s.contract,s.requested_provider);P.length===0&&this.throwResolutionFailure(s.contract,s.requested_provider);let x=[];for(let ae of P)await this.isAuthorized({operation:"invoke_action",principal:i.identity,contract:ae.contract.reference,provider:ae.declaration.provider,...s.subject===void 0?{}:{subject:s.subject}})&&x.push(ae);if(x.length===0)throw new N("unauthorized",`No authorized provider can execute ${s.contract.id}.`);if(x.length>1)throw new N("ambiguous_provider",`Action ${s.contract.id} has ${x.length} eligible providers; select one explicitly.`);let E=x[0];if(E.handlerDeclaration.max_concurrency!==void 0&&E.active>=E.handlerDeclaration.max_concurrency)throw new N("request_rejected",`Provider ${E.declaration.provider.implementation} is at capacity.`);if(((d=(u=E.contract.artifact.behavior)==null?void 0:u.idempotency)!=null?d:"none")==="required"&&!s.idempotency_key)throw new N("request_rejected",`${E.contract.reference.id} requires an idempotency key.`);Go(E.contract.inputValidator,s.input,"invalid_action_input",`Action ${E.contract.reference.id} input`);let w={operation:"invoke_action",principal:i.identity,contract:E.contract.reference,provider:E.declaration.provider,...s.subject===void 0?{}:{subject:s.subject}},F=await((p=(f=this.options).authorizationContext)==null?void 0:p.call(f,w)),V={kind:"mdbase.action.invocation",profile_version:"0.1",invocation_id:this.idFactory("inv"),attempt_id:this.idFactory("attempt"),request_id:n,contract:structuredClone(E.contract.reference),caller:structuredClone(i.identity),provider:structuredClone(E.declaration.provider),provider_declaration_digest:E.declaration.declaration_digest,handler_id:E.handlerDeclaration.handler_id,admitted_at:this.now().toISOString(),...s.correlation_id===void 0?{}:{correlation_id:s.correlation_id},...s.causation_id===void 0?{}:{causation_id:s.causation_id},...s.subject===void 0?{}:{subject:s.subject},...s.idempotency_key===void 0?{}:{idempotency_key:s.idempotency_key},...s.deadline===void 0?{}:{deadline:s.deadline},...F===void 0?{}:{authorization_context:F},input:structuredClone(s.input)};qr(this.actionInvocationValidator,V,"request_rejected","Action invocation"),await((h=(m=this.options).onInvocation)==null?void 0:h.call(m,structuredClone(V)));let G=new AbortController,A;if(V.deadline){let ae=Math.max(0,new Date(V.deadline).getTime()-this.now().getTime());A=setTimeout(()=>G.abort(new N("deadline_exceeded",`Action request ${n} exceeded its deadline.`)),ae)}E.active+=1;let k=this.executeAction(E,V,G).finally(()=>{A!==void 0&&clearTimeout(A),E.active=Math.max(0,E.active-1),this.activeActions.delete(n)});this.activeActions.set(n,{clientId:e,requestId:n,requestDigest:_,handler:E,invocation:V,controller:G,promise:k}),o();let Ce=await k,oe=(b=(y=E.handlerDeclaration.idempotency)==null?void 0:y.retention_seconds)!=null?b:300;return this.completedActions.set(n,{clientId:e,requestDigest:_,outcome:structuredClone(Ce),reusable:((g=E.handlerDeclaration.idempotency)==null?void 0:g.mode)==="request",expiresAt:this.now().getTime()+oe*1e3}),zg(this.completedActions,this.completedRequestLimit),structuredClone(Ce)}finally{o()}}async executeAction(e,t,i){var n;try{let s=await e.handler(structuredClone(t.input),{invocation:structuredClone(t),signal:i.signal});if(i.signal.aborted){let a=i.signal.reason;return a instanceof N&&a.code==="deadline_exceeded"?this.failureOutcome(t,"failed",a.toPortableError()):this.failureOutcome(t,"cancelled",{code:"cancelled",message:`Action request ${t.request_id} was cancelled.`})}Jd(s,"invalid_action_output",`Action ${e.contract.reference.id} output`),Go(e.contract.outputValidator,s,"invalid_action_output",`Action ${e.contract.reference.id} output`);let o={kind:"mdbase.action.outcome",profile_version:"0.1",outcome_id:this.idFactory("outcome"),request_id:t.request_id,invocation_id:t.invocation_id,attempt_id:t.attempt_id,contract:structuredClone(t.contract),provider:structuredClone(t.provider),provider_declaration_digest:t.provider_declaration_digest,status:"succeeded",completed_at:this.now().toISOString(),output:structuredClone(s)};return qr(this.actionOutcomeValidator,o,"invalid_action_output","Action outcome"),Yd(this.transport,o),o}catch(s){if(s instanceof ss)return e.contract.errorValidator&&!e.contract.errorValidator((n=s.error.details)!=null?n:{})?this.failureOutcome(t,"failed",{code:"handler_failure",message:`Provider returned invalid declared error details: ${Mr(e.contract.errorValidator.errors)}`}):this.failureOutcome(t,s.status,s.error);if(s instanceof N)return this.failureOutcome(t,s.code==="cancelled"?"cancelled":s.code==="outcome_indeterminate"?"outcome_indeterminate":"failed",s.toPortableError());if(i.signal.aborted||cI(s)){let o=i.signal.reason;return o instanceof N&&o.code==="deadline_exceeded"?this.failureOutcome(t,"failed",o.toPortableError()):this.failureOutcome(t,"cancelled",{code:"cancelled",message:`Action request ${t.request_id} was cancelled.`})}return this.report({severity:"error",code:"action_handler_failed",message:`Provider ${t.provider.implementation} failed ${t.contract.id}.`,principal:t.provider,contract:t.contract,cause:s}),this.failureOutcome(t,"failed",{code:"handler_failure",message:"The selected provider failed while executing the action."})}}failureOutcome(e,t,i){let n={kind:"mdbase.action.outcome",profile_version:"0.1",outcome_id:this.idFactory("outcome"),request_id:e.request_id,invocation_id:e.invocation_id,attempt_id:e.attempt_id,contract:structuredClone(e.contract),provider:structuredClone(e.provider),provider_declaration_digest:e.provider_declaration_digest,status:t,completed_at:this.now().toISOString(),error:structuredClone(i)};return qr(this.actionOutcomeValidator,n,"invalid_action_output","Action outcome"),n}async cancelAction(e,t,i){let n=this.requireClient(e),s=this.admissionLocks.get(t);s&&await s;let o=this.activeActions.get(t);if(!o){let a=this.completedActions.get(t);if(a&&a.clientId!==e)throw new N("unauthorized",`Action request ${t} belongs to another caller.`);return a?structuredClone(a.outcome):null}if(o.clientId!==e)throw new N("unauthorized",`Action request ${t} belongs to another caller.`);if(await this.assertAuthorized({operation:"cancel_action",principal:n.identity,contract:o.invocation.contract,provider:o.invocation.provider,...o.invocation.subject===void 0?{}:{subject:o.invocation.subject}}),!this.transport.cancellation)throw new N("unsupported_transport_capability","The active transport cannot deliver cancellation.");if(o.handler.handlerDeclaration.cancellation!=="cooperative")throw new N("cancellation_unsupported",`Provider ${o.invocation.provider.implementation} does not support cancellation.`);return o.controller.abort(new N("cancelled",(i==null?void 0:i.trim())||`Action request ${t} was cancelled.`)),structuredClone(await o.promise)}resolveActionCandidates(e,t){let i=[...this.actionProviders.values()].flatMap(({handlers:s})=>s).filter(({contract:s,declaration:o})=>Jo(e,s.reference)&&oI(t,o.provider)),n=(0,lr.maxSatisfying)([...new Set(i.map(({contract:s})=>s.reference.version))],e.version,{includePrerelease:!0});return n?i.filter(({contract:s})=>s.reference.version===n).sort((s,o)=>{var a,c;return s.declaration.provider.application.localeCompare(o.declaration.provider.application)||s.declaration.provider.implementation.localeCompare(o.declaration.provider.implementation)||((a=s.declaration.provider.instance_id)!=null?a:"").localeCompare((c=o.declaration.provider.instance_id)!=null?c:"")||s.handlerDeclaration.handler_id.localeCompare(o.handlerDeclaration.handler_id)}):[]}throwResolutionFailure(e,t){let i=[...this.contracts.values()].filter(n=>n.artifact.contract_type==="action"&&n.reference.id===e.id);throw i.length===0?new N("unknown_contract",`Action contract ${e.id} is unknown.`):i.some(({reference:n})=>Jo(e,n))?t?new N("requested_provider_unavailable",`The requested provider is unavailable for ${e.id}.`):new N("no_provider",`No provider is registered for ${e.id}.`):new N("unsupported_contract_version",`No ${e.id} artifact satisfies ${e.version}.`)}async prepareEventContract(e){if(this.assertContractArtifact(e),e.contract_type!=="event")throw new N("unknown_contract",`${e.id} is not an event contract.`);let t={id:e.id,version:e.version,digest:await Ko(e)};this.assertNoContractConflict(t);let i=jg(this.ajv,e);return{artifact:structuredClone(e),reference:t,dataValidator:i.data,...i.source===void 0?{}:{sourceValidator:i.source}}}async prepareActionContract(e){if(this.assertContractArtifact(e),e.contract_type!=="action")throw new N("unknown_contract",`${e.id} is not an action contract.`);let t={id:e.id,version:e.version,digest:await Ko(e)};this.assertNoContractConflict(t);let i=Dg(this.ajv,e);return{artifact:structuredClone(e),reference:t,inputValidator:i.input,...i.output===void 0?{}:{outputValidator:i.output},...i.error===void 0?{}:{errorValidator:i.error},...i.provider===void 0?{}:{providerValidator:i.provider}}}assertContractArtifact(e){if(qr(this.contractValidator,e,"contract_digest_conflict",`Contract ${e.id||""}`),!(0,lr.valid)(e.version))throw new N("unsupported_contract_version",`${e.id} version must be exact SemVer.`)}assertNoContractConflict(e){let t=this.contracts.get(Wo(e));if(t&&t.reference.digest!==e.digest)throw new N("contract_digest_conflict",`Contract ${e.id} ${e.version} conflicts with the registered artifact.`)}commitContracts(e){var i;let t=new Map;for(let n of e){let s=Wo(n.reference),o=(i=t.get(s))!=null?i:this.contracts.get(s);if(o&&o.reference.digest!==n.reference.digest)throw new N("contract_digest_conflict",`Contract ${n.reference.id} ${n.reference.version} conflicts within the registration.`);t.set(s,n)}for(let[n,s]of t)this.contracts.has(n)||this.contracts.set(n,s)}async disposeClient(e,t=!1){let i=this.clients.get(e);if(!(!i||i.disposed)){i.disposed=!0;for(let n of[...i.subscriptions])this.removeSubscription(n);for(let n of[...i.sources])this.removeEventSource(n);for(let n of[...i.providers])this.removeActionProvider(n);for(let n of[...this.activeActions.values()])n.clientId===e&&n.handler.handlerDeclaration.cancellation==="cooperative"&&n.controller.abort(new N("cancelled","The caller unloaded.")),n.handler.clientId===e&&n.handler.handlerDeclaration.cancellation==="cooperative"&&n.controller.abort(new N("cancelled","The provider unloaded."));this.clients.delete(e),t||this.assertActive()}}removeEventSource(e){var i;let t=this.eventSources.get(e);t&&(this.eventSources.delete(e),(i=this.clients.get(t.clientId))==null||i.sources.delete(e))}removeActionProvider(e){var i;let t=this.actionProviders.get(e);if(t){this.actionProviders.delete(e),(i=this.clients.get(t.clientId))==null||i.providers.delete(e);for(let n of this.activeActions.values())n.handler.registrationId===e&&n.handler.handlerDeclaration.cancellation==="cooperative"&&n.controller.abort(new N("cancelled","The provider unloaded."))}}removeSubscription(e){var i;let t=this.subscriptions.get(e);t&&(this.subscriptions.delete(e),(i=this.clients.get(t.clientId))==null||i.subscriptions.delete(e))}requireClient(e){this.assertActive();let t=this.clients.get(e);if(!t||t.disposed)throw new N("transport_unavailable","Interop client is disposed.");return t}assertActive(){if(this.disposed)throw new N("transport_unavailable","Interop bridge is disposed.")}async assertAuthorized(e){if(!await this.isAuthorized(e))throw new N("unauthorized",`${e.operation} is not authorized.`)}async isAuthorized(e){try{return await this.authorize(structuredClone(e))}catch(t){return this.report({severity:"error",code:"authorization_failed",message:`Authorization failed for ${e.operation}.`,principal:e.principal,cause:t}),!1}}cleanCompletedActions(){let e=this.now().getTime();for(let[t,i]of this.completedActions)i.expiresAt<=e&&this.completedActions.delete(t)}async acquireAdmission(e){var a;let t=(a=this.admissionLocks.get(e))!=null?a:Promise.resolve(),i,n=new Promise(c=>{i=c}),s=t.then(()=>n);this.admissionLocks.set(e,s),await t;let o=!1;return()=>{o||(o=!0,i(),this.admissionLocks.get(e)===s&&this.admissionLocks.delete(e))}}report(e){var t,i;(i=(t=this.options).onDiagnostic)==null||i.call(t,structuredClone(e))}};function qr(r,e,t,i){if(!r(e))throw new N(t,`${i} is invalid: ${Mr(r.errors)}`)}function rI(r){for(let[e,t]of Object.entries(r))if(t!==void 0&&(typeof t!="string"||t.length===0||!/^[A-Za-z0-9][A-Za-z0-9._:@/-]*$/u.test(t)))throw new N("request_rejected",`Implementation identity ${e} is invalid.`);if(!(0,lr.valid)(r.version))throw new N("request_rejected","Implementation identity version must be exact SemVer.")}function Xd(r){if(!/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)+$/u.test(r.id))throw new N("unknown_contract",`Contract ID ${r.id} is invalid.`);if(!(0,lr.validRange)(r.version,{includePrerelease:!0}))throw new N("unsupported_contract_version",`Contract requirement ${r.version} is not a SemVer range.`);if(r.digest&&!/^sha256:[0-9a-f]{64}$/u.test(r.digest))throw new N("contract_digest_conflict","Contract digest is invalid.")}function Fg(r,e){let t=r!=null?r:{id:e.id,version:e.version,digest:e.digest};return Xd(t),structuredClone(t)}function Vg(r,e){if(!Jo(r,e))throw new N("unsupported_contract_version",`${e.id} ${e.version} does not satisfy its implementation requirement.`)}function Jo(r,e){return r.id===e.id&&(0,lr.satisfies)(e.version,r.version,{includePrerelease:!0})&&(!r.digest||r.digest===e.digest)}function Wo(r){return`${r.id}@${r.version}`}function Bg(r){return`urn:mdbase:contract:${r.id}:${r.version}:${r.digest}`}function iI(r){return`urn:mdbase:app:${[r.application,r.implementation,...r.instance_id?[r.instance_id]:[]].map(encodeURIComponent).join(":")}`}function nI(r,e){if(r.type!==e.id||r.mdbasecontractversion!==e.version||r.mdbasecontractdigest!==e.digest||r.dataschema!==Bg(e))throw new N("contract_digest_conflict","Event contract evidence is inconsistent.")}function sI(r){let{created_at:e,...t}=r;return t}function Ug(r,e,t,i){if(i.clientId!==r)throw new N("unauthorized",`Action request ${e} belongs to another caller.`);if(i.requestDigest!==t)throw new N("request_rejected",`Action request ${e} was reused with different content.`)}function Jd(r,e,t){let i=new Set,n=(s,o)=>{if(!(s===null||typeof s=="boolean"||typeof s=="string")){if(typeof s=="number"){if(Number.isFinite(s))return;throw new N(e,`${t}${o} must be a finite JSON number.`)}if(typeof s!="object")throw new N(e,`${t}${o} is not a JSON value.`);if(i.has(s))throw new N(e,`${t}${o} contains a cycle.`);if(i.add(s),Array.isArray(s))s.forEach((a,c)=>n(a,`${o}/${c}`));else{let a=Object.getPrototypeOf(s);if(a!==Object.prototype&&a!==null)throw new N(e,`${t}${o} must be a plain JSON object.`);for(let[c,l]of Object.entries(s))n(l,`${o}/${c}`)}i.delete(s)}};n(r,"")}function Yd(r,e){if(r.max_payload_bytes===void 0)return;let t=JSON.stringify(e),i=new TextEncoder().encode(t).byteLength;if(i>r.max_payload_bytes)throw new N("unsupported_transport_capability",`The portable envelope is ${i} bytes; the active transport allows ${r.max_payload_bytes}.`)}function oI(r,e){return r?(r.application===void 0||r.application===e.application)&&(r.implementation===void 0||r.implementation===e.implementation)&&(r.instance_id===void 0||r.instance_id===e.instance_id):!0}function aI(r,e){var t,i;if(e){if((t=e.delivery)!=null&&t.some(n=>!r.delivery.includes(n)))throw new N("unsupported_transport_capability","The active transport lacks a required delivery capability.");if((i=e.ordering)!=null&&i.some(n=>!r.ordering.includes(n)))throw new N("unsupported_transport_capability","The active transport lacks a required ordering capability.");for(let n of["cancellation","deadlines","provider_discovery","request_deduplication","cross_process_identity"])if(e[n]===!0&&r[n]!==!0)throw new N("unsupported_transport_capability",`The active transport lacks ${n}.`);if(e.max_payload_bytes!==void 0&&(r.max_payload_bytes===void 0||r.max_payload_bytese;){let t=r.keys().next().value;if(t===void 0)return;r.delete(t)}}function cI(r){return r instanceof Error&&r.name==="AbortError"}var Yo=class{constructor(e,t){this.app=e;this.profileVersion="0.1";this.bridge=new os({authorize:()=>t(),transport:{delivery:["ephemeral"],ordering:["none"],cancellation:!0,deadlines:!0,provider_discovery:!0,request_deduplication:!0,cross_process_identity:!1},onDiagnostic:i=>{var s;(i.severity==="error"?console.error:console.warn)(`[mdbase/interop] ${i.code}: ${i.message}`,(s=i.cause)!=null?s:"")}}),this.transport=this.bridge.describe().transport}connect(e){var s,o;let t=(s=e.manifest)==null?void 0:s.id,i=(o=e.manifest)==null?void 0:o.version;if(!t||!i)throw new Error("Only a loaded Obsidian plugin with manifest identity can connect to mdbase interop.");let n=this.app.plugins;if(!n||n.getPlugin(t)!==e)throw new Error(`Obsidian plugin ${t} is not the active loaded instance.`);return this.bridge.connect({application:t,implementation:`${t}.obsidian`,version:i})}describe(){return this.bridge.describe()}dispose(){return this.bridge.dispose()}};var fe=require("obsidian"),mb=ft(Wn(),1),yb=ft(Yn(),1),pu=ft(lu(),1),ea=class extends Error{constructor(t,i){super(i);this.code=t;this.name="MdbasePathError"}},xt={spec_version:"0.3.0",name:"My mdbase collection",description:"Typed markdown collection",settings:{types_folder:"_types",explicit_type_keys:["type","types"],default_strict:!1,include_subfolders:!0,exclude:["_types",".obsidian",".git","node_modules",".trash",".mdbase"]}},us=null;function BI(){return us||(us=new mb.Ajv2020({allErrors:!0,strict:!1,allowUnionTypes:!0}),(0,yb.default)(us),us)}function Q(r){return!!r&&typeof r=="object"&&!Array.isArray(r)}function Je(r){return JSON.parse(JSON.stringify(r))}function HI(r){if(r===!0)return!0;if(r===!1)return!1;if(r==="warn")return"warn"}function du(r){return Array.isArray(r)?`[${r.map(e=>du(e)).join(",")}]`:Q(r)?`{${Object.keys(r).sort().map(t=>`${JSON.stringify(t)}:${du(r[t])}`).join(",")}}`:JSON.stringify(r)}function KI(r){let e=r.indexOf("."),t=r.indexOf("[");return e===-1&&t===-1?r:e===-1?r.slice(0,t):t===-1?r.slice(0,e):r.slice(0,Math.min(e,t))}function GI(r){let e=new Map,t=new Set,i=n=>{var l,u,d,f;let s=e.get(n);if(s)return s;let o=r.get(n);if(!o)return null;if(t.has(n)){let p={...o,fields:Je(o.fields)};return e.set(n,p),p}t.add(n);let a=o.extends?i(o.extends):null;t.delete(n);let c={...o,fields:a?{...Je(a.fields),...Je(o.fields)}:Je(o.fields),display_name_key:(l=o.display_name_key)!=null?l:a==null?void 0:a.display_name_key,path_pattern:(u=o.path_pattern)!=null?u:a==null?void 0:a.path_pattern,filename_pattern:(d=o.filename_pattern)!=null?d:a==null?void 0:a.filename_pattern,strict:o.strict!==void 0?o.strict:a==null?void 0:a.strict,match:(f=o.match)!=null?f:a==null?void 0:a.match};return e.set(n,c),c};for(let n of r.keys())i(n);return e}function gb(r){let e=(0,fe.normalizePath)(r),t=e.lastIndexOf("/");return t>=0?e.slice(0,t):""}function bb(r){let e=r.trim();e.startsWith("[[")&&e.endsWith("]]")&&(e=e.slice(2,-2));let t=e.indexOf("|");t>=0&&(e=e.slice(0,t));let i=e.indexOf("#");return i>=0&&(e=e.slice(0,i)),e.trim()}function _b(r){return/^[a-z][a-z0-9+.-]*:\/\//i.test(r)}function vb(r,e,t){var c;let i=bb(t);if(!i||_b(i))return null;let n=new Set,s=(0,fe.normalizePath)(i);n.add(s),s.endsWith(".md")||n.add(`${s}.md`);let o=gb(e);if(o){let l=(0,fe.normalizePath)(`${o}/${i}`);n.add(l),l.endsWith(".md")||n.add(`${l}.md`)}for(let l of n){let u=r.getAbstractFileByPath(l);if(u instanceof fe.TFile)return u}let a=i.replace(/\.md$/i,"");return(c=r.getMarkdownFiles().find(l=>l.basename===a))!=null?c:null}function WI(r,e,t){return _b(bb(t))||vb(r,e,t)!==null}function Ue(r){let e=r.match(/^---[ \t]*\r?\n([\s\S]*?)^---[ \t]*(?:\r?\n|$)/m);if(!e)return{hasFrontmatter:!1,frontmatter:{},body:r};try{let t=e[1],i=(0,fe.parseYaml)(t);return i==null&&t.trim()!==""?{hasFrontmatter:!0,frontmatter:{},body:r.slice(e[0].length),error:"Frontmatter must be a YAML object"}:i!=null&&!Q(i)?{hasFrontmatter:!0,frontmatter:{},body:r.slice(e[0].length),error:"Frontmatter must be a YAML object"}:{hasFrontmatter:!0,frontmatter:i!=null?i:{},body:r.slice(e[0].length)}}catch(t){return{hasFrontmatter:!0,frontmatter:{},body:r.slice(e[0].length),error:t instanceof Error?t.message:String(t)}}}function at(r,e=""){if(Object.keys(r).length===0)return e;let t=(0,fe.stringifyYaml)(r).trimEnd(),i=e.replace(/^\n+/,"");return`--- + deps: ${t}}`};var xS={keyword:"dependencies",type:"object",schemaType:"object",error:Bt.error,code(r){let[e,t]=IS(r);nh(r,e),sh(r,t)}};function IS({schema:r}){let e={},t={};for(let n in r){if(n==="__proto__")continue;let s=Array.isArray(r[n])?e:t;s[n]=r[n]}return[e,t]}function nh(r,e=r.schema){let{gen:t,data:n,it:s}=r;if(Object.keys(e).length===0)return;let i=t.let("missing");for(let o in e){let a=e[o];if(a.length===0)continue;let c=(0,Vs.propertyInData)(t,n,o,s.opts.ownProperties);r.setParams({property:o,depsCount:a.length,deps:a.join(", ")}),s.allErrors?t.if(c,()=>{for(let l of a)(0,Vs.checkReportMissingProp)(r,l)}):(t.if((0,dl._)`${c} && (${(0,Vs.checkMissingProp)(r,a,i)})`),(0,Vs.reportMissingProp)(r,i),t.else())}}Bt.validatePropertyDeps=nh;function sh(r,e=r.schema){let{gen:t,data:n,keyword:s,it:i}=r,o=t.name("valid");for(let a in e)(0,kS.alwaysValidSchema)(i,e[a])||(t.if((0,Vs.propertyInData)(t,n,a,i.opts.ownProperties),()=>{let c=r.subschema({keyword:s,schemaProp:a},o);r.mergeValidEvaluated(c,o)},()=>t.var(o,!0)),r.ok(o))}Bt.validateSchemaDeps=sh;Bt.default=xS});var oh=$(ul=>{"use strict";Object.defineProperty(ul,"__esModule",{value:!0});var ih=B(),TS=Y(),PS={message:"property name must be valid",params:({params:r})=>(0,ih._)`{propertyName: ${r.propertyName}}`},OS={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:PS,code(r){let{gen:e,schema:t,data:n,it:s}=r;if((0,TS.alwaysValidSchema)(s,t))return;let i=e.name("valid");e.forIn("key",n,o=>{r.setParams({propertyName:o}),r.subschema({keyword:"propertyNames",data:o,dataTypes:["string"],propertyName:o,compositeRule:!0},i),e.if((0,ih.not)(i),()=>{r.error(!0),s.allErrors||e.break()})}),r.ok(i)}};ul.default=OS});var pl=$(fl=>{"use strict";Object.defineProperty(fl,"__esModule",{value:!0});var fo=pt(),Et=B(),RS=ft(),po=Y(),CS={message:"must NOT have additional properties",params:({params:r})=>(0,Et._)`{additionalProperty: ${r.additionalProperty}}`},NS={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:CS,code(r){let{gen:e,schema:t,parentSchema:n,data:s,errsCount:i,it:o}=r;if(!i)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=o;if(o.props=!0,c.removeAdditional!=="all"&&(0,po.alwaysValidSchema)(o,t))return;let l=(0,fo.allSchemaProperties)(n.properties),u=(0,fo.allSchemaProperties)(n.patternProperties);d(),r.ok((0,Et._)`${i} === ${RS.default.errors}`);function d(){e.forIn("key",s,y=>{!l.length&&!u.length?m(y):e.if(f(y),()=>m(y))})}function f(y){let b;if(l.length>8){let g=(0,po.schemaRefOrVal)(o,n.properties,"properties");b=(0,fo.isOwnProperty)(e,g,y)}else l.length?b=(0,Et.or)(...l.map(g=>(0,Et._)`${y} === ${g}`)):b=Et.nil;return u.length&&(b=(0,Et.or)(b,...u.map(g=>(0,Et._)`${(0,fo.usePattern)(r,g)}.test(${y})`))),(0,Et.not)(b)}function p(y){e.code((0,Et._)`delete ${s}[${y}]`)}function m(y){if(c.removeAdditional==="all"||c.removeAdditional&&t===!1){p(y);return}if(t===!1){r.setParams({additionalProperty:y}),r.error(),a||e.break();return}if(typeof t=="object"&&!(0,po.alwaysValidSchema)(o,t)){let b=e.name("valid");c.removeAdditional==="failing"?(h(y,b,!1),e.if((0,Et.not)(b),()=>{r.reset(),p(y)})):(h(y,b),a||e.if((0,Et.not)(b),()=>e.break()))}}function h(y,b,g){let w={keyword:"additionalProperties",dataProp:y,dataPropType:po.Type.Str};g===!1&&Object.assign(w,{compositeRule:!0,createErrors:!1,allErrors:!1}),r.subschema(w,b)}}};fl.default=NS});var lh=$(ml=>{"use strict";Object.defineProperty(ml,"__esModule",{value:!0});var MS=En(),ah=pt(),hl=Y(),ch=pl(),LS={keyword:"properties",type:"object",schemaType:"object",code(r){let{gen:e,schema:t,parentSchema:n,data:s,it:i}=r;i.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&ch.default.code(new MS.KeywordCxt(i,ch.default,"additionalProperties"));let o=(0,ah.allSchemaProperties)(t);for(let d of o)i.definedProperties.add(d);i.opts.unevaluated&&o.length&&i.props!==!0&&(i.props=hl.mergeEvaluated.props(e,(0,hl.toHash)(o),i.props));let a=o.filter(d=>!(0,hl.alwaysValidSchema)(i,t[d]));if(a.length===0)return;let c=e.name("valid");for(let d of a)l(d)?u(d):(e.if((0,ah.propertyInData)(e,s,d,i.opts.ownProperties)),u(d),i.allErrors||e.else().var(c,!0),e.endIf()),r.it.definedProperties.add(d),r.ok(c);function l(d){return i.opts.useDefaults&&!i.compositeRule&&t[d].default!==void 0}function u(d){r.subschema({keyword:"properties",schemaProp:d,dataProp:d},c)}}};ml.default=LS});var ph=$(yl=>{"use strict";Object.defineProperty(yl,"__esModule",{value:!0});var dh=pt(),ho=B(),uh=Y(),fh=Y(),qS={keyword:"patternProperties",type:"object",schemaType:"object",code(r){let{gen:e,schema:t,data:n,parentSchema:s,it:i}=r,{opts:o}=i,a=(0,dh.allSchemaProperties)(t),c=a.filter(h=>(0,uh.alwaysValidSchema)(i,t[h]));if(a.length===0||c.length===a.length&&(!i.opts.unevaluated||i.props===!0))return;let l=o.strictSchema&&!o.allowMatchingProperties&&s.properties,u=e.name("valid");i.props!==!0&&!(i.props instanceof ho.Name)&&(i.props=(0,fh.evaluatedPropsToName)(e,i.props));let{props:d}=i;f();function f(){for(let h of a)l&&p(h),i.allErrors?m(h):(e.var(u,!0),m(h),e.if(u))}function p(h){for(let y in l)new RegExp(h).test(y)&&(0,uh.checkStrictMode)(i,`property ${y} matches pattern ${h} (use allowMatchingProperties)`)}function m(h){e.forIn("key",n,y=>{e.if((0,ho._)`${(0,dh.usePattern)(r,h)}.test(${y})`,()=>{let b=c.includes(h);b||r.subschema({keyword:"patternProperties",schemaProp:h,dataProp:y,dataPropType:fh.Type.Str},u),i.opts.unevaluated&&d!==!0?e.assign((0,ho._)`${d}[${y}]`,!0):!b&&!i.allErrors&&e.if((0,ho.not)(u),()=>e.break())})})}}};yl.default=qS});var hh=$(gl=>{"use strict";Object.defineProperty(gl,"__esModule",{value:!0});var DS=Y(),jS={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(r){let{gen:e,schema:t,it:n}=r;if((0,DS.alwaysValidSchema)(n,t)){r.fail();return}let s=e.name("valid");r.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},s),r.failResult(s,()=>r.reset(),()=>r.error())},error:{message:"must NOT be valid"}};gl.default=jS});var mh=$(bl=>{"use strict";Object.defineProperty(bl,"__esModule",{value:!0});var FS=pt(),VS={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:FS.validateUnion,error:{message:"must match a schema in anyOf"}};bl.default=VS});var yh=$(wl=>{"use strict";Object.defineProperty(wl,"__esModule",{value:!0});var mo=B(),US=Y(),BS={message:"must match exactly one schema in oneOf",params:({params:r})=>(0,mo._)`{passingSchemas: ${r.passing}}`},HS={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:BS,code(r){let{gen:e,schema:t,parentSchema:n,it:s}=r;if(!Array.isArray(t))throw new Error("ajv implementation error");if(s.opts.discriminator&&n.discriminator)return;let i=t,o=e.let("valid",!1),a=e.let("passing",null),c=e.name("_valid");r.setParams({passing:a}),e.block(l),r.result(o,()=>r.reset(),()=>r.error(!0));function l(){i.forEach((u,d)=>{let f;(0,US.alwaysValidSchema)(s,u)?e.var(c,!0):f=r.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,mo._)`${c} && ${o}`).assign(o,!1).assign(a,(0,mo._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(o,!0),e.assign(a,d),f&&r.mergeEvaluated(f,mo.Name)})})}}};wl.default=HS});var gh=$(_l=>{"use strict";Object.defineProperty(_l,"__esModule",{value:!0});var zS=Y(),KS={keyword:"allOf",schemaType:"array",code(r){let{gen:e,schema:t,it:n}=r;if(!Array.isArray(t))throw new Error("ajv implementation error");let s=e.name("valid");t.forEach((i,o)=>{if((0,zS.alwaysValidSchema)(n,i))return;let a=r.subschema({keyword:"allOf",schemaProp:o},s);r.ok(s),r.mergeEvaluated(a)})}};_l.default=KS});var _h=$(vl=>{"use strict";Object.defineProperty(vl,"__esModule",{value:!0});var yo=B(),wh=Y(),GS={message:({params:r})=>(0,yo.str)`must match "${r.ifClause}" schema`,params:({params:r})=>(0,yo._)`{failingKeyword: ${r.ifClause}}`},WS={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:GS,code(r){let{gen:e,parentSchema:t,it:n}=r;t.then===void 0&&t.else===void 0&&(0,wh.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let s=bh(n,"then"),i=bh(n,"else");if(!s&&!i)return;let o=e.let("valid",!0),a=e.name("_valid");if(c(),r.reset(),s&&i){let u=e.let("ifClause");r.setParams({ifClause:u}),e.if(a,l("then",u),l("else",u))}else s?e.if(a,l("then")):e.if((0,yo.not)(a),l("else"));r.pass(o,()=>r.error(!0));function c(){let u=r.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);r.mergeEvaluated(u)}function l(u,d){return()=>{let f=r.subschema({keyword:u},a);e.assign(o,a),r.mergeValidEvaluated(f,o),d?e.assign(d,(0,yo._)`${u}`):r.setParams({ifClause:u})}}}};function bh(r,e){let t=r.schema[e];return t!==void 0&&!(0,wh.alwaysValidSchema)(r,t)}vl.default=WS});var vh=$($l=>{"use strict";Object.defineProperty($l,"__esModule",{value:!0});var JS=Y(),YS={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:r,parentSchema:e,it:t}){e.if===void 0&&(0,JS.checkStrictMode)(t,`"${r}" without "if" is ignored`)}};$l.default=YS});var El=$(Sl=>{"use strict";Object.defineProperty(Sl,"__esModule",{value:!0});var XS=il(),QS=Zp(),ZS=ol(),eE=th(),tE=rh(),rE=uo(),nE=oh(),sE=pl(),iE=lh(),oE=ph(),aE=hh(),cE=mh(),lE=yh(),dE=gh(),uE=_h(),fE=vh();function pE(r=!1){let e=[aE.default,cE.default,lE.default,dE.default,uE.default,fE.default,nE.default,sE.default,rE.default,iE.default,oE.default];return r?e.push(QS.default,eE.default):e.push(XS.default,ZS.default),e.push(tE.default),e}Sl.default=pE});var kl=$(Us=>{"use strict";Object.defineProperty(Us,"__esModule",{value:!0});Us.dynamicAnchor=void 0;var Al=B(),hE=ft(),$h=Is(),mE=so(),yE={keyword:"$dynamicAnchor",schemaType:"string",code:r=>Sh(r,r.schema)};function Sh(r,e){let{gen:t,it:n}=r;n.schemaEnv.root.dynamicAnchors[e]=!0;let s=(0,Al._)`${hE.default.dynamicAnchors}${(0,Al.getProperty)(e)}`,i=n.errSchemaPath==="#"?n.validateName:gE(r);t.if((0,Al._)`!${s}`,()=>t.assign(s,i))}Us.dynamicAnchor=Sh;function gE(r){let{schemaEnv:e,schema:t,self:n}=r.it,{root:s,baseId:i,localRefs:o,meta:a}=e.root,{schemaId:c}=n.opts,l=new $h.SchemaEnv({schema:t,schemaId:c,root:s,baseId:i,localRefs:o,meta:a});return $h.compileSchema.call(n,l),(0,mE.getValidate)(r,l)}Us.default=yE});var xl=$(Bs=>{"use strict";Object.defineProperty(Bs,"__esModule",{value:!0});Bs.dynamicRef=void 0;var Eh=B(),bE=ft(),Ah=so(),wE={keyword:"$dynamicRef",schemaType:"string",code:r=>kh(r,r.schema)};function kh(r,e){let{gen:t,keyword:n,it:s}=r;if(e[0]!=="#")throw new Error(`"${n}" only supports hash fragment reference`);let i=e.slice(1);if(s.allErrors)o();else{let c=t.let("valid",!1);o(c),r.ok(c)}function o(c){if(s.schemaEnv.root.dynamicAnchors[i]){let l=t.let("_v",(0,Eh._)`${bE.default.dynamicAnchors}${(0,Eh.getProperty)(i)}`);t.if(l,a(l,c),a(s.validateName,c))}else a(s.validateName,c)()}function a(c,l){return l?()=>t.block(()=>{(0,Ah.callRef)(r,c),t.let(l,!0)}):()=>(0,Ah.callRef)(r,c)}}Bs.dynamicRef=kh;Bs.default=wE});var xh=$(Il=>{"use strict";Object.defineProperty(Il,"__esModule",{value:!0});var _E=kl(),vE=Y(),$E={keyword:"$recursiveAnchor",schemaType:"boolean",code(r){r.schema?(0,_E.dynamicAnchor)(r,""):(0,vE.checkStrictMode)(r.it,"$recursiveAnchor: false is ignored")}};Il.default=$E});var Ih=$(Tl=>{"use strict";Object.defineProperty(Tl,"__esModule",{value:!0});var SE=xl(),EE={keyword:"$recursiveRef",schemaType:"string",code:r=>(0,SE.dynamicRef)(r,r.schema)};Tl.default=EE});var Th=$(Pl=>{"use strict";Object.defineProperty(Pl,"__esModule",{value:!0});var AE=kl(),kE=xl(),xE=xh(),IE=Ih(),TE=[AE.default,kE.default,xE.default,IE.default];Pl.default=TE});var Oh=$(Ol=>{"use strict";Object.defineProperty(Ol,"__esModule",{value:!0});var Ph=uo(),PE={keyword:"dependentRequired",type:"object",schemaType:"object",error:Ph.error,code:r=>(0,Ph.validatePropertyDeps)(r)};Ol.default=PE});var Rh=$(Rl=>{"use strict";Object.defineProperty(Rl,"__esModule",{value:!0});var OE=uo(),RE={keyword:"dependentSchemas",type:"object",schemaType:"object",code:r=>(0,OE.validateSchemaDeps)(r)};Rl.default=RE});var Ch=$(Cl=>{"use strict";Object.defineProperty(Cl,"__esModule",{value:!0});var CE=Y(),NE={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword:r,parentSchema:e,it:t}){e.contains===void 0&&(0,CE.checkStrictMode)(t,`"${r}" without "contains" is ignored`)}};Cl.default=NE});var Nh=$(Nl=>{"use strict";Object.defineProperty(Nl,"__esModule",{value:!0});var ME=Oh(),LE=Rh(),qE=Ch(),DE=[ME.default,LE.default,qE.default];Nl.default=DE});var Lh=$(Ml=>{"use strict";Object.defineProperty(Ml,"__esModule",{value:!0});var Ir=B(),Mh=Y(),jE=ft(),FE={message:"must NOT have unevaluated properties",params:({params:r})=>(0,Ir._)`{unevaluatedProperty: ${r.unevaluatedProperty}}`},VE={keyword:"unevaluatedProperties",type:"object",schemaType:["boolean","object"],trackErrors:!0,error:FE,code(r){let{gen:e,schema:t,data:n,errsCount:s,it:i}=r;if(!s)throw new Error("ajv implementation error");let{allErrors:o,props:a}=i;a instanceof Ir.Name?e.if((0,Ir._)`${a} !== true`,()=>e.forIn("key",n,d=>e.if(l(a,d),()=>c(d)))):a!==!0&&e.forIn("key",n,d=>a===void 0?c(d):e.if(u(a,d),()=>c(d))),i.props=!0,r.ok((0,Ir._)`${s} === ${jE.default.errors}`);function c(d){if(t===!1){r.setParams({unevaluatedProperty:d}),r.error(),o||e.break();return}if(!(0,Mh.alwaysValidSchema)(i,t)){let f=e.name("valid");r.subschema({keyword:"unevaluatedProperties",dataProp:d,dataPropType:Mh.Type.Str},f),o||e.if((0,Ir.not)(f),()=>e.break())}}function l(d,f){return(0,Ir._)`!${d} || !${d}[${f}]`}function u(d,f){let p=[];for(let m in d)d[m]===!0&&p.push((0,Ir._)`${f} !== ${m}`);return(0,Ir.and)(...p)}}};Ml.default=VE});var Dh=$(Ll=>{"use strict";Object.defineProperty(Ll,"__esModule",{value:!0});var rn=B(),qh=Y(),UE={message:({params:{len:r}})=>(0,rn.str)`must NOT have more than ${r} items`,params:({params:{len:r}})=>(0,rn._)`{limit: ${r}}`},BE={keyword:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error:UE,code(r){let{gen:e,schema:t,data:n,it:s}=r,i=s.items||0;if(i===!0)return;let o=e.const("len",(0,rn._)`${n}.length`);if(t===!1)r.setParams({len:i}),r.fail((0,rn._)`${o} > ${i}`);else if(typeof t=="object"&&!(0,qh.alwaysValidSchema)(s,t)){let c=e.var("valid",(0,rn._)`${o} <= ${i}`);e.if((0,rn.not)(c),()=>a(c,i)),r.ok(c)}s.items=!0;function a(c,l){e.forRange("i",l,o,u=>{r.subschema({keyword:"unevaluatedItems",dataProp:u,dataPropType:qh.Type.Num},c),s.allErrors||e.if((0,rn.not)(c),()=>e.break())})}}};Ll.default=BE});var jh=$(ql=>{"use strict";Object.defineProperty(ql,"__esModule",{value:!0});var HE=Lh(),zE=Dh(),KE=[HE.default,zE.default];ql.default=KE});var Fh=$(Dl=>{"use strict";Object.defineProperty(Dl,"__esModule",{value:!0});var Se=B(),GE={message:({schemaCode:r})=>(0,Se.str)`must match format "${r}"`,params:({schemaCode:r})=>(0,Se._)`{format: ${r}}`},WE={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:GE,code(r,e){let{gen:t,data:n,$data:s,schema:i,schemaCode:o,it:a}=r,{opts:c,errSchemaPath:l,schemaEnv:u,self:d}=a;if(!c.validateFormats)return;s?f():p();function f(){let m=t.scopeValue("formats",{ref:d.formats,code:c.code.formats}),h=t.const("fDef",(0,Se._)`${m}[${o}]`),y=t.let("fType"),b=t.let("format");t.if((0,Se._)`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>t.assign(y,(0,Se._)`${h}.type || "string"`).assign(b,(0,Se._)`${h}.validate`),()=>t.assign(y,(0,Se._)`"string"`).assign(b,h)),r.fail$data((0,Se.or)(g(),w()));function g(){return c.strictSchema===!1?Se.nil:(0,Se._)`${o} && !${b}`}function w(){let S=u.$async?(0,Se._)`(${h}.async ? await ${b}(${n}) : ${b}(${n}))`:(0,Se._)`${b}(${n})`,_=(0,Se._)`(typeof ${b} == "function" ? ${S} : ${b}.test(${n}))`;return(0,Se._)`${b} && ${b} !== true && ${y} === ${e} && !${_}`}}function p(){let m=d.formats[i];if(!m){g();return}if(m===!0)return;let[h,y,b]=w(m);h===e&&r.pass(S());function g(){if(c.strictSchema===!1){d.logger.warn(_());return}throw new Error(_());function _(){return`unknown format "${i}" ignored in schema at path "${l}"`}}function w(_){let x=_ instanceof RegExp?(0,Se.regexpCode)(_):c.code.formats?(0,Se._)`${c.code.formats}${(0,Se.getProperty)(i)}`:void 0,I=t.scopeValue("formats",{key:i,ref:_,code:x});return typeof _=="object"&&!(_ instanceof RegExp)?[_.type||"string",_.validate,(0,Se._)`${I}.validate`]:["string",_,I]}function S(){if(typeof m=="object"&&!(m instanceof RegExp)&&m.async){if(!u.$async)throw new Error("async format in sync schema");return(0,Se._)`await ${b}(${n})`}return typeof y=="function"?(0,Se._)`${b}(${n})`:(0,Se._)`${b}.test(${n})`}}}};Dl.default=WE});var Fl=$(jl=>{"use strict";Object.defineProperty(jl,"__esModule",{value:!0});var JE=Fh(),YE=[JE.default];jl.default=YE});var Vl=$(On=>{"use strict";Object.defineProperty(On,"__esModule",{value:!0});On.contentVocabulary=On.metadataVocabulary=void 0;On.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];On.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var Uh=$(Ul=>{"use strict";Object.defineProperty(Ul,"__esModule",{value:!0});var XE=Vc(),QE=nl(),ZE=El(),e1=Th(),t1=Nh(),r1=jh(),n1=Fl(),Vh=Vl(),s1=[e1.default,XE.default,QE.default,(0,ZE.default)(!0),n1.default,Vh.metadataVocabulary,Vh.contentVocabulary,t1.default,r1.default];Ul.default=s1});var Hh=$(go=>{"use strict";Object.defineProperty(go,"__esModule",{value:!0});go.DiscrError=void 0;var Bh;(function(r){r.Tag="tag",r.Mapping="mapping"})(Bh||(go.DiscrError=Bh={}))});var zl=$(Hl=>{"use strict";Object.defineProperty(Hl,"__esModule",{value:!0});var Rn=B(),Bl=Hh(),zh=Is(),i1=An(),o1=Y(),a1={message:({params:{discrError:r,tagName:e}})=>r===Bl.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:r,tag:e,tagName:t}})=>(0,Rn._)`{error: ${r}, tag: ${t}, tagValue: ${e}}`},c1={keyword:"discriminator",type:"object",schemaType:"object",error:a1,code(r){let{gen:e,data:t,schema:n,parentSchema:s,it:i}=r,{oneOf:o}=s;if(!i.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=n.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!o)throw new Error("discriminator: requires oneOf keyword");let c=e.let("valid",!1),l=e.const("tag",(0,Rn._)`${t}${(0,Rn.getProperty)(a)}`);e.if((0,Rn._)`typeof ${l} == "string"`,()=>u(),()=>r.error(!1,{discrError:Bl.DiscrError.Tag,tag:l,tagName:a})),r.ok(c);function u(){let p=f();e.if(!1);for(let m in p)e.elseIf((0,Rn._)`${l} === ${m}`),e.assign(c,d(p[m]));e.else(),r.error(!1,{discrError:Bl.DiscrError.Mapping,tag:l,tagName:a}),e.endIf()}function d(p){let m=e.name("valid"),h=r.subschema({keyword:"oneOf",schemaProp:p},m);return r.mergeEvaluated(h,Rn.Name),m}function f(){var p;let m={},h=b(s),y=!0;for(let S=0;S{l1.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/schema",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0,"https://json-schema.org/draft/2020-12/vocab/applicator":!0,"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0,"https://json-schema.org/draft/2020-12/vocab/validation":!0,"https://json-schema.org/draft/2020-12/vocab/meta-data":!0,"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0,"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:"meta",title:"Core and Validation specifications meta-schema",allOf:[{$ref:"meta/core"},{$ref:"meta/applicator"},{$ref:"meta/unevaluated"},{$ref:"meta/validation"},{$ref:"meta/meta-data"},{$ref:"meta/format-annotation"},{$ref:"meta/content"}],type:["object","boolean"],$comment:"This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.",properties:{definitions:{$comment:'"definitions" has been replaced by "$defs".',type:"object",additionalProperties:{$dynamicRef:"#meta"},deprecated:!0,default:{}},dependencies:{$comment:'"dependencies" has been split and replaced by "dependentSchemas" and "dependentRequired" in order to serve their differing semantics.',type:"object",additionalProperties:{anyOf:[{$dynamicRef:"#meta"},{$ref:"meta/validation#/$defs/stringArray"}]},deprecated:!0,default:{}},$recursiveAnchor:{$comment:'"$recursiveAnchor" has been replaced by "$dynamicAnchor".',$ref:"meta/core#/$defs/anchorString",deprecated:!0},$recursiveRef:{$comment:'"$recursiveRef" has been replaced by "$dynamicRef".',$ref:"meta/core#/$defs/uriReferenceString",deprecated:!0}}}});var Gh=$((ZR,d1)=>{d1.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/applicator",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/applicator":!0},$dynamicAnchor:"meta",title:"Applicator vocabulary meta-schema",type:["object","boolean"],properties:{prefixItems:{$ref:"#/$defs/schemaArray"},items:{$dynamicRef:"#meta"},contains:{$dynamicRef:"#meta"},additionalProperties:{$dynamicRef:"#meta"},properties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},patternProperties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},propertyNames:{format:"regex"},default:{}},dependentSchemas:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},propertyNames:{$dynamicRef:"#meta"},if:{$dynamicRef:"#meta"},then:{$dynamicRef:"#meta"},else:{$dynamicRef:"#meta"},allOf:{$ref:"#/$defs/schemaArray"},anyOf:{$ref:"#/$defs/schemaArray"},oneOf:{$ref:"#/$defs/schemaArray"},not:{$dynamicRef:"#meta"}},$defs:{schemaArray:{type:"array",minItems:1,items:{$dynamicRef:"#meta"}}}}});var Wh=$((eC,u1)=>{u1.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/unevaluated",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0},$dynamicAnchor:"meta",title:"Unevaluated applicator vocabulary meta-schema",type:["object","boolean"],properties:{unevaluatedItems:{$dynamicRef:"#meta"},unevaluatedProperties:{$dynamicRef:"#meta"}}}});var Jh=$((tC,f1)=>{f1.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/content",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:"meta",title:"Content vocabulary meta-schema",type:["object","boolean"],properties:{contentEncoding:{type:"string"},contentMediaType:{type:"string"},contentSchema:{$dynamicRef:"#meta"}}}});var Yh=$((rC,p1)=>{p1.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/core",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0},$dynamicAnchor:"meta",title:"Core vocabulary meta-schema",type:["object","boolean"],properties:{$id:{$ref:"#/$defs/uriReferenceString",$comment:"Non-empty fragments not allowed.",pattern:"^[^#]*#?$"},$schema:{$ref:"#/$defs/uriString"},$ref:{$ref:"#/$defs/uriReferenceString"},$anchor:{$ref:"#/$defs/anchorString"},$dynamicRef:{$ref:"#/$defs/uriReferenceString"},$dynamicAnchor:{$ref:"#/$defs/anchorString"},$vocabulary:{type:"object",propertyNames:{$ref:"#/$defs/uriString"},additionalProperties:{type:"boolean"}},$comment:{type:"string"},$defs:{type:"object",additionalProperties:{$dynamicRef:"#meta"}}},$defs:{anchorString:{type:"string",pattern:"^[A-Za-z_][-A-Za-z0-9._]*$"},uriString:{type:"string",format:"uri"},uriReferenceString:{type:"string",format:"uri-reference"}}}});var Xh=$((nC,h1)=>{h1.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/format-annotation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0},$dynamicAnchor:"meta",title:"Format vocabulary meta-schema for annotation results",type:["object","boolean"],properties:{format:{type:"string"}}}});var Qh=$((sC,m1)=>{m1.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/meta-data",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/meta-data":!0},$dynamicAnchor:"meta",title:"Meta-data vocabulary meta-schema",type:["object","boolean"],properties:{title:{type:"string"},description:{type:"string"},default:!0,deprecated:{type:"boolean",default:!1},readOnly:{type:"boolean",default:!1},writeOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0}}}});var Zh=$((iC,y1)=>{y1.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/validation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/validation":!0},$dynamicAnchor:"meta",title:"Validation vocabulary meta-schema",type:["object","boolean"],properties:{type:{anyOf:[{$ref:"#/$defs/simpleTypes"},{type:"array",items:{$ref:"#/$defs/simpleTypes"},minItems:1,uniqueItems:!0}]},const:!0,enum:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/$defs/nonNegativeInteger"},minLength:{$ref:"#/$defs/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},maxItems:{$ref:"#/$defs/nonNegativeInteger"},minItems:{$ref:"#/$defs/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},maxContains:{$ref:"#/$defs/nonNegativeInteger"},minContains:{$ref:"#/$defs/nonNegativeInteger",default:1},maxProperties:{$ref:"#/$defs/nonNegativeInteger"},minProperties:{$ref:"#/$defs/nonNegativeIntegerDefault0"},required:{$ref:"#/$defs/stringArray"},dependentRequired:{type:"object",additionalProperties:{$ref:"#/$defs/stringArray"}}},$defs:{nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{$ref:"#/$defs/nonNegativeInteger",default:0},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}}}});var em=$(Kl=>{"use strict";Object.defineProperty(Kl,"__esModule",{value:!0});var g1=Kh(),b1=Gh(),w1=Wh(),_1=Jh(),v1=Yh(),$1=Xh(),S1=Qh(),E1=Zh(),A1=["/properties"];function k1(r){return[g1,b1,w1,_1,v1,e(this,$1),S1,e(this,E1)].forEach(t=>this.addMetaSchema(t,void 0,!1)),this;function e(t,n){return r?t.$dataMetaSchema(n,A1):n}}Kl.default=k1});var Jl=$((me,Wl)=>{"use strict";Object.defineProperty(me,"__esModule",{value:!0});me.MissingRefError=me.ValidationError=me.CodeGen=me.Name=me.nil=me.stringify=me.str=me._=me.KeywordCxt=me.Ajv2020=void 0;var x1=Dc(),I1=Uh(),T1=zl(),P1=em(),Gl="https://json-schema.org/draft/2020-12/schema",Cn=class extends x1.default{constructor(e={}){super({...e,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){super._addVocabularies(),I1.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(T1.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data:e,meta:t}=this.opts;t&&(P1.default.call(this,e),this.refs["http://json-schema.org/schema"]=Gl)}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Gl)?Gl:void 0)}};me.Ajv2020=Cn;Wl.exports=me=Cn;Wl.exports.Ajv2020=Cn;Object.defineProperty(me,"__esModule",{value:!0});me.default=Cn;var O1=En();Object.defineProperty(me,"KeywordCxt",{enumerable:!0,get:function(){return O1.KeywordCxt}});var Nn=B();Object.defineProperty(me,"_",{enumerable:!0,get:function(){return Nn._}});Object.defineProperty(me,"str",{enumerable:!0,get:function(){return Nn.str}});Object.defineProperty(me,"stringify",{enumerable:!0,get:function(){return Nn.stringify}});Object.defineProperty(me,"nil",{enumerable:!0,get:function(){return Nn.nil}});Object.defineProperty(me,"Name",{enumerable:!0,get:function(){return Nn.Name}});Object.defineProperty(me,"CodeGen",{enumerable:!0,get:function(){return Nn.CodeGen}});var R1=xs();Object.defineProperty(me,"ValidationError",{enumerable:!0,get:function(){return R1.default}});var C1=An();Object.defineProperty(me,"MissingRefError",{enumerable:!0,get:function(){return C1.default}})});var cm=$(zt=>{"use strict";Object.defineProperty(zt,"__esModule",{value:!0});zt.formatNames=zt.fastFormats=zt.fullFormats=void 0;function Ht(r,e){return{validate:r,compare:e}}zt.fullFormats={date:Ht(sm,Zl),time:Ht(Xl(!0),ed),"date-time":Ht(tm(!0),om),"iso-time":Ht(Xl(),im),"iso-date-time":Ht(tm(),am),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:j1,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:K1,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:F1,int32:{type:"number",validate:B1},int64:{type:"number",validate:H1},float:{type:"number",validate:nm},double:{type:"number",validate:nm},password:!0,binary:!0};zt.fastFormats={...zt.fullFormats,date:Ht(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Zl),time:Ht(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,ed),"date-time":Ht(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,om),"iso-time":Ht(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,im),"iso-date-time":Ht(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,am),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};zt.formatNames=Object.keys(zt.fullFormats);function N1(r){return r%4===0&&(r%100!==0||r%400===0)}var M1=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,L1=[0,31,28,31,30,31,30,31,31,30,31,30,31];function sm(r){let e=M1.exec(r);if(!e)return!1;let t=+e[1],n=+e[2],s=+e[3];return n>=1&&n<=12&&s>=1&&s<=(n===2&&N1(t)?29:L1[n])}function Zl(r,e){if(r&&e)return r>e?1:r23||u>59||r&&!a)return!1;if(s<=23&&i<=59&&o<60)return!0;let d=i-u*c,f=s-l*c-(d<0?1:0);return(f===23||f===-1)&&(d===59||d===-1)&&o<61}}function ed(r,e){if(!(r&&e))return;let t=new Date("2020-01-01T"+r).valueOf(),n=new Date("2020-01-01T"+e).valueOf();if(t&&n)return t-n}function im(r,e){if(!(r&&e))return;let t=Yl.exec(r),n=Yl.exec(e);if(t&&n)return r=t[1]+t[2]+t[3],e=n[1]+n[2]+n[3],r>e?1:r=V1}function H1(r){return Number.isInteger(r)}function nm(){return!0}var z1=/[^\\]\\Z/;function K1(r){if(z1.test(r))return!1;try{return new RegExp(r),!0}catch(e){return!1}}});var dm=$(td=>{"use strict";Object.defineProperty(td,"__esModule",{value:!0});var G1=Vc(),W1=nl(),J1=El(),Y1=Fl(),lm=Vl(),X1=[G1.default,W1.default,(0,J1.default)(),Y1.default,lm.metadataVocabulary,lm.contentVocabulary];td.default=X1});var um=$((lC,Q1)=>{Q1.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 pm=$((ye,rd)=>{"use strict";Object.defineProperty(ye,"__esModule",{value:!0});ye.MissingRefError=ye.ValidationError=ye.CodeGen=ye.Name=ye.nil=ye.stringify=ye.str=ye._=ye.KeywordCxt=ye.Ajv=void 0;var Z1=Dc(),eA=dm(),tA=zl(),fm=um(),rA=["/properties"],bo="http://json-schema.org/draft-07/schema",Mn=class extends Z1.default{_addVocabularies(){super._addVocabularies(),eA.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(tA.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(fm,rA):fm;this.addMetaSchema(e,bo,!1),this.refs["http://json-schema.org/schema"]=bo}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(bo)?bo:void 0)}};ye.Ajv=Mn;rd.exports=ye=Mn;rd.exports.Ajv=Mn;Object.defineProperty(ye,"__esModule",{value:!0});ye.default=Mn;var nA=En();Object.defineProperty(ye,"KeywordCxt",{enumerable:!0,get:function(){return nA.KeywordCxt}});var Ln=B();Object.defineProperty(ye,"_",{enumerable:!0,get:function(){return Ln._}});Object.defineProperty(ye,"str",{enumerable:!0,get:function(){return Ln.str}});Object.defineProperty(ye,"stringify",{enumerable:!0,get:function(){return Ln.stringify}});Object.defineProperty(ye,"nil",{enumerable:!0,get:function(){return Ln.nil}});Object.defineProperty(ye,"Name",{enumerable:!0,get:function(){return Ln.Name}});Object.defineProperty(ye,"CodeGen",{enumerable:!0,get:function(){return Ln.CodeGen}});var sA=xs();Object.defineProperty(ye,"ValidationError",{enumerable:!0,get:function(){return sA.default}});var iA=An();Object.defineProperty(ye,"MissingRefError",{enumerable:!0,get:function(){return iA.default}})});var hm=$(qn=>{"use strict";Object.defineProperty(qn,"__esModule",{value:!0});qn.formatLimitDefinition=void 0;var oA=pm(),At=B(),Tr=At.operators,wo={formatMaximum:{okStr:"<=",ok:Tr.LTE,fail:Tr.GT},formatMinimum:{okStr:">=",ok:Tr.GTE,fail:Tr.LT},formatExclusiveMaximum:{okStr:"<",ok:Tr.LT,fail:Tr.GTE},formatExclusiveMinimum:{okStr:">",ok:Tr.GT,fail:Tr.LTE}},aA={message:({keyword:r,schemaCode:e})=>(0,At.str)`should be ${wo[r].okStr} ${e}`,params:({keyword:r,schemaCode:e})=>(0,At._)`{comparison: ${wo[r].okStr}, limit: ${e}}`};qn.formatLimitDefinition={keyword:Object.keys(wo),type:"string",schemaType:"string",$data:!0,error:aA,code(r){let{gen:e,data:t,schemaCode:n,keyword:s,it:i}=r,{opts:o,self:a}=i;if(!o.validateFormats)return;let c=new oA.KeywordCxt(i,a.RULES.all.format.definition,"format");c.$data?l():u();function l(){let f=e.scopeValue("formats",{ref:a.formats,code:o.code.formats}),p=e.const("fmt",(0,At._)`${f}[${c.schemaCode}]`);r.fail$data((0,At.or)((0,At._)`typeof ${p} != "object"`,(0,At._)`${p} instanceof RegExp`,(0,At._)`typeof ${p}.compare != "function"`,d(p)))}function u(){let f=c.schema,p=a.formats[f];if(!p||p===!0)return;if(typeof p!="object"||p instanceof RegExp||typeof p.compare!="function")throw new Error(`"${s}": format "${f}" does not define "compare" function`);let m=e.scopeValue("formats",{key:f,ref:p,code:o.code.formats?(0,At._)`${o.code.formats}${(0,At.getProperty)(f)}`:void 0});r.fail$data(d(m))}function d(f){return(0,At._)`${f}.compare(${t}, ${n}) ${wo[s].fail} 0`}},dependencies:["format"]};var cA=r=>(r.addKeyword(qn.formatLimitDefinition),r);qn.default=cA});var id=$((Hs,gm)=>{"use strict";Object.defineProperty(Hs,"__esModule",{value:!0});var Dn=cm(),lA=hm(),nd=B(),mm=new nd.Name("fullFormats"),dA=new nd.Name("fastFormats"),sd=(r,e={keywords:!0})=>{if(Array.isArray(e))return ym(r,e,Dn.fullFormats,mm),r;let[t,n]=e.mode==="fast"?[Dn.fastFormats,dA]:[Dn.fullFormats,mm],s=e.formats||Dn.formatNames;return ym(r,s,t,n),e.keywords&&(0,lA.default)(r),r};sd.get=(r,e="full")=>{let n=(e==="fast"?Dn.fastFormats:Dn.fullFormats)[r];if(!n)throw new Error(`Unknown format "${r}"`);return n};function ym(r,e,t,n){var s,i;(s=(i=r.opts.code).formats)!==null&&s!==void 0||(i.formats=(0,nd._)`require("ajv-formats/dist/formats").${n}`);for(let o of e)r.addFormat(o,t[o])}gm.exports=Hs=sd;Object.defineProperty(Hs,"__esModule",{value:!0});Hs.default=sd});var Vn=$((gC,Em)=>{"use strict";var pA="2.0.0",hA=Number.MAX_SAFE_INTEGER||9007199254740991,mA=16,yA=250,gA=["major","premajor","minor","preminor","patch","prepatch","prerelease"];Em.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:mA,MAX_SAFE_BUILD_LENGTH:yA,MAX_SAFE_INTEGER:hA,RELEASE_TYPES:gA,SEMVER_SPEC_VERSION:pA,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var zs=$((bC,Am)=>{"use strict";var bA=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...r)=>console.error("SEMVER",...r):()=>{};Am.exports=bA});var Un=$((Gt,km)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:ld,MAX_SAFE_BUILD_LENGTH:wA,MAX_LENGTH:_A}=Vn(),vA=zs();Gt=km.exports={};var $A=Gt.re=[],SA=Gt.safeRe=[],L=Gt.src=[],EA=Gt.safeSrc=[],q=Gt.t={},AA=0,dd="[a-zA-Z0-9-]",kA=[["\\s",1],["\\d",_A],[dd,wA]],xA=r=>{for(let[e,t]of kA)r=r.split(`${e}*`).join(`${e}{0,${t}}`).split(`${e}+`).join(`${e}{1,${t}}`);return r},H=(r,e,t)=>{let n=xA(e),s=AA++;vA(r,s,e),q[r]=s,L[s]=e,EA[s]=n,$A[s]=new RegExp(e,t?"g":void 0),SA[s]=new RegExp(n,t?"g":void 0)};H("NUMERICIDENTIFIER","0|[1-9]\\d*");H("NUMERICIDENTIFIERLOOSE","\\d+");H("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${dd}*`);H("MAINVERSION",`(${L[q.NUMERICIDENTIFIER]})\\.(${L[q.NUMERICIDENTIFIER]})\\.(${L[q.NUMERICIDENTIFIER]})`);H("MAINVERSIONLOOSE",`(${L[q.NUMERICIDENTIFIERLOOSE]})\\.(${L[q.NUMERICIDENTIFIERLOOSE]})\\.(${L[q.NUMERICIDENTIFIERLOOSE]})`);H("PRERELEASEIDENTIFIER",`(?:${L[q.NONNUMERICIDENTIFIER]}|${L[q.NUMERICIDENTIFIER]})`);H("PRERELEASEIDENTIFIERLOOSE",`(?:${L[q.NONNUMERICIDENTIFIER]}|${L[q.NUMERICIDENTIFIERLOOSE]})`);H("PRERELEASE",`(?:-(${L[q.PRERELEASEIDENTIFIER]}(?:\\.${L[q.PRERELEASEIDENTIFIER]})*))`);H("PRERELEASELOOSE",`(?:-?(${L[q.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${L[q.PRERELEASEIDENTIFIERLOOSE]})*))`);H("BUILDIDENTIFIER",`${dd}+`);H("BUILD",`(?:\\+(${L[q.BUILDIDENTIFIER]}(?:\\.${L[q.BUILDIDENTIFIER]})*))`);H("FULLPLAIN",`v?${L[q.MAINVERSION]}${L[q.PRERELEASE]}?${L[q.BUILD]}?`);H("FULL",`^${L[q.FULLPLAIN]}$`);H("LOOSEPLAIN",`[v=\\s]*${L[q.MAINVERSIONLOOSE]}${L[q.PRERELEASELOOSE]}?${L[q.BUILD]}?`);H("LOOSE",`^${L[q.LOOSEPLAIN]}$`);H("GTLT","((?:<|>)?=?)");H("XRANGEIDENTIFIERLOOSE",`${L[q.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);H("XRANGEIDENTIFIER",`${L[q.NUMERICIDENTIFIER]}|x|X|\\*`);H("XRANGEPLAIN",`[v=\\s]*(${L[q.XRANGEIDENTIFIER]})(?:\\.(${L[q.XRANGEIDENTIFIER]})(?:\\.(${L[q.XRANGEIDENTIFIER]})(?:${L[q.PRERELEASE]})?${L[q.BUILD]}?)?)?`);H("XRANGEPLAINLOOSE",`[v=\\s]*(${L[q.XRANGEIDENTIFIERLOOSE]})(?:\\.(${L[q.XRANGEIDENTIFIERLOOSE]})(?:\\.(${L[q.XRANGEIDENTIFIERLOOSE]})(?:${L[q.PRERELEASELOOSE]})?${L[q.BUILD]}?)?)?`);H("XRANGE",`^${L[q.GTLT]}\\s*${L[q.XRANGEPLAIN]}$`);H("XRANGELOOSE",`^${L[q.GTLT]}\\s*${L[q.XRANGEPLAINLOOSE]}$`);H("COERCEPLAIN",`(^|[^\\d])(\\d{1,${ld}})(?:\\.(\\d{1,${ld}}))?(?:\\.(\\d{1,${ld}}))?`);H("COERCE",`${L[q.COERCEPLAIN]}(?:$|[^\\d])`);H("COERCEFULL",L[q.COERCEPLAIN]+`(?:${L[q.PRERELEASE]})?(?:${L[q.BUILD]})?(?:$|[^\\d])`);H("COERCERTL",L[q.COERCE],!0);H("COERCERTLFULL",L[q.COERCEFULL],!0);H("LONETILDE","(?:~>?)");H("TILDETRIM",`(\\s*)${L[q.LONETILDE]}\\s+`,!0);Gt.tildeTrimReplace="$1~";H("TILDE",`^${L[q.LONETILDE]}${L[q.XRANGEPLAIN]}$`);H("TILDELOOSE",`^${L[q.LONETILDE]}${L[q.XRANGEPLAINLOOSE]}$`);H("LONECARET","(?:\\^)");H("CARETTRIM",`(\\s*)${L[q.LONECARET]}\\s+`,!0);Gt.caretTrimReplace="$1^";H("CARET",`^${L[q.LONECARET]}${L[q.XRANGEPLAIN]}$`);H("CARETLOOSE",`^${L[q.LONECARET]}${L[q.XRANGEPLAINLOOSE]}$`);H("COMPARATORLOOSE",`^${L[q.GTLT]}\\s*(${L[q.LOOSEPLAIN]})$|^$`);H("COMPARATOR",`^${L[q.GTLT]}\\s*(${L[q.FULLPLAIN]})$|^$`);H("COMPARATORTRIM",`(\\s*)${L[q.GTLT]}\\s*(${L[q.LOOSEPLAIN]}|${L[q.XRANGEPLAIN]})`,!0);Gt.comparatorTrimReplace="$1$2$3";H("HYPHENRANGE",`^\\s*(${L[q.XRANGEPLAIN]})\\s+-\\s+(${L[q.XRANGEPLAIN]})\\s*$`);H("HYPHENRANGELOOSE",`^\\s*(${L[q.XRANGEPLAINLOOSE]})\\s+-\\s+(${L[q.XRANGEPLAINLOOSE]})\\s*$`);H("STAR","(<|>)?=?\\s*\\*");H("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");H("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")});var $o=$((wC,xm)=>{"use strict";var IA=Object.freeze({loose:!0}),TA=Object.freeze({}),PA=r=>r?typeof r!="object"?IA:r:TA;xm.exports=PA});var ud=$((_C,Pm)=>{"use strict";var Im=/^[0-9]+$/,Tm=(r,e)=>{if(typeof r=="number"&&typeof e=="number")return r===e?0:rTm(e,r);Pm.exports={compareIdentifiers:Tm,rcompareIdentifiers:OA}});var Le=$((vC,Rm)=>{"use strict";var So=zs(),{MAX_LENGTH:Om,MAX_SAFE_INTEGER:Eo}=Vn(),{safeRe:Ao,t:ko}=Un(),RA=$o(),{compareIdentifiers:fd}=ud(),CA=(r,e)=>{let t=e.split(".");if(t.length>r.length)return!1;for(let n=0;nOm)throw new TypeError(`version is longer than ${Om} characters`);So("SemVer",e,t),this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease;let n=e.trim().match(t.loose?Ao[ko.LOOSE]:Ao[ko.FULL]);if(!n)throw new TypeError(`Invalid Version: ${e}`);if(this.raw=e,this.major=+n[1],this.minor=+n[2],this.patch=+n[3],this.major>Eo||this.major<0)throw new TypeError("Invalid major version");if(this.minor>Eo||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>Eo||this.patch<0)throw new TypeError("Invalid patch version");n[4]?this.prerelease=n[4].split(".").map(s=>{if(/^[0-9]+$/.test(s)){let i=+s;if(i>=0&&ie.major?1:this.minore.minor?1:this.patche.patch?1:0}comparePre(e){if(e instanceof r||(e=new r(e,this.options)),this.prerelease.length&&!e.prerelease.length)return-1;if(!this.prerelease.length&&e.prerelease.length)return 1;if(!this.prerelease.length&&!e.prerelease.length)return 0;let t=0;do{let n=this.prerelease[t],s=e.prerelease[t];if(So("prerelease compare",t,n,s),n===void 0&&s===void 0)return 0;if(s===void 0)return 1;if(n===void 0)return-1;if(n===s)continue;return fd(n,s)}while(++t)}compareBuild(e){e instanceof r||(e=new r(e,this.options));let t=0;do{let n=this.build[t],s=e.build[t];if(So("build compare",t,n,s),n===void 0&&s===void 0)return 0;if(s===void 0)return 1;if(n===void 0)return-1;if(n===s)continue;return fd(n,s)}while(++t)}inc(e,t,n){if(e.startsWith("pre")){if(!t&&n===!1)throw new Error("invalid increment argument: identifier is empty");if(t){let s=`-${t}`.match(this.options.loose?Ao[ko.PRERELEASELOOSE]:Ao[ko.PRERELEASE]);if(!s||s[1]!==t)throw new Error(`invalid identifier: ${t}`)}}switch(e){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",t,n);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",t,n);break;case"prepatch":this.prerelease.length=0,this.inc("patch",t,n),this.inc("pre",t,n);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",t,n),this.inc("pre",t,n);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{let s=Number(n)?1:0;if(this.prerelease.length===0)this.prerelease=[s];else{let i=this.prerelease.length;for(;--i>=0;)typeof this.prerelease[i]=="number"&&(this.prerelease[i]++,i=-2);if(i===-1){if(t===this.prerelease.join(".")&&n===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(s)}}if(t){let i=[t,s];if(n===!1&&(i=[t]),CA(this.prerelease,t)){let o=this.prerelease[t.split(".").length];isNaN(o)&&(this.prerelease=i)}else this.prerelease=i}break}default:throw new Error(`invalid increment argument: ${e}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};Rm.exports=pd});var Or=$(($C,Nm)=>{"use strict";var Cm=Le(),NA=(r,e,t=!1)=>{if(r instanceof Cm)return r;try{return new Cm(r,e)}catch(n){if(!t)return null;throw n}};Nm.exports=NA});var Lm=$((SC,Mm)=>{"use strict";var MA=Or(),LA=(r,e)=>{let t=MA(r,e);return t?t.version:null};Mm.exports=LA});var Dm=$((EC,qm)=>{"use strict";var qA=Or(),DA=(r,e)=>{let t=qA(r.trim().replace(/^[=v]+/,""),e);return t?t.version:null};qm.exports=DA});var Vm=$((AC,Fm)=>{"use strict";var jm=Le(),jA=(r,e,t,n,s)=>{typeof t=="string"&&(s=n,n=t,t=void 0);try{return new jm(r instanceof jm?r.version:r,t).inc(e,n,s).version}catch(i){return null}};Fm.exports=jA});var Hm=$((kC,Bm)=>{"use strict";var Um=Or(),FA=(r,e)=>{let t=Um(r,null,!0),n=Um(e,null,!0),s=t.compare(n);if(s===0)return null;let i=s>0,o=i?t:n,a=i?n:t,c=!!o.prerelease.length;if(!!a.prerelease.length&&!c){if(!a.patch&&!a.minor)return"major";if(a.compareMain(o)===0)return a.minor&&!a.patch?"minor":"patch"}let u=c?"pre":"";return t.major!==n.major?u+"major":t.minor!==n.minor?u+"minor":t.patch!==n.patch?u+"patch":"prerelease"};Bm.exports=FA});var Km=$((xC,zm)=>{"use strict";var VA=Le(),UA=(r,e)=>new VA(r,e).major;zm.exports=UA});var Wm=$((IC,Gm)=>{"use strict";var BA=Le(),HA=(r,e)=>new BA(r,e).minor;Gm.exports=HA});var Ym=$((TC,Jm)=>{"use strict";var zA=Le(),KA=(r,e)=>new zA(r,e).patch;Jm.exports=KA});var Qm=$((PC,Xm)=>{"use strict";var GA=Or(),WA=(r,e)=>{let t=GA(r,e);return t&&t.prerelease.length?t.prerelease:null};Xm.exports=WA});var yt=$((OC,ey)=>{"use strict";var Zm=Le(),JA=(r,e,t)=>new Zm(r,t).compare(new Zm(e,t));ey.exports=JA});var ry=$((RC,ty)=>{"use strict";var YA=yt(),XA=(r,e,t)=>YA(e,r,t);ty.exports=XA});var sy=$((CC,ny)=>{"use strict";var QA=yt(),ZA=(r,e)=>QA(r,e,!0);ny.exports=ZA});var xo=$((NC,oy)=>{"use strict";var iy=Le(),ek=(r,e,t)=>{let n=new iy(r,t),s=new iy(e,t);return n.compare(s)||n.compareBuild(s)};oy.exports=ek});var cy=$((MC,ay)=>{"use strict";var tk=xo(),rk=(r,e)=>r.sort((t,n)=>tk(t,n,e));ay.exports=rk});var dy=$((LC,ly)=>{"use strict";var nk=xo(),sk=(r,e)=>r.sort((t,n)=>nk(n,t,e));ly.exports=sk});var Ks=$((qC,uy)=>{"use strict";var ik=yt(),ok=(r,e,t)=>ik(r,e,t)>0;uy.exports=ok});var Io=$((DC,fy)=>{"use strict";var ak=yt(),ck=(r,e,t)=>ak(r,e,t)<0;fy.exports=ck});var hd=$((jC,py)=>{"use strict";var lk=yt(),dk=(r,e,t)=>lk(r,e,t)===0;py.exports=dk});var md=$((FC,hy)=>{"use strict";var uk=yt(),fk=(r,e,t)=>uk(r,e,t)!==0;hy.exports=fk});var To=$((VC,my)=>{"use strict";var pk=yt(),hk=(r,e,t)=>pk(r,e,t)>=0;my.exports=hk});var Po=$((UC,yy)=>{"use strict";var mk=yt(),yk=(r,e,t)=>mk(r,e,t)<=0;yy.exports=yk});var yd=$((BC,gy)=>{"use strict";var gk=hd(),bk=md(),wk=Ks(),_k=To(),vk=Io(),$k=Po(),Sk=(r,e,t,n)=>{switch(e){case"===":return typeof r=="object"&&(r=r.version),typeof t=="object"&&(t=t.version),r===t;case"!==":return typeof r=="object"&&(r=r.version),typeof t=="object"&&(t=t.version),r!==t;case"":case"=":case"==":return gk(r,t,n);case"!=":return bk(r,t,n);case">":return wk(r,t,n);case">=":return _k(r,t,n);case"<":return vk(r,t,n);case"<=":return $k(r,t,n);default:throw new TypeError(`Invalid operator: ${e}`)}};gy.exports=Sk});var wy=$((HC,by)=>{"use strict";var Ek=Le(),Ak=Or(),{safeRe:Oo,t:Ro}=Un(),kk=(r,e)=>{if(r instanceof Ek)return r;if(typeof r=="number"&&(r=String(r)),typeof r!="string")return null;e=e||{};let t=null;if(!e.rtl)t=r.match(e.includePrerelease?Oo[Ro.COERCEFULL]:Oo[Ro.COERCE]);else{let c=e.includePrerelease?Oo[Ro.COERCERTLFULL]:Oo[Ro.COERCERTL],l;for(;(l=c.exec(r))&&(!t||t.index+t[0].length!==r.length);)(!t||l.index+l[0].length!==t.index+t[0].length)&&(t=l),c.lastIndex=l.index+l[1].length+l[2].length;c.lastIndex=-1}if(t===null)return null;let n=t[2],s=t[3]||"0",i=t[4]||"0",o=e.includePrerelease&&t[5]?`-${t[5]}`:"",a=e.includePrerelease&&t[6]?`+${t[6]}`:"";return Ak(`${n}.${s}.${i}${o}${a}`,e)};by.exports=kk});var vy=$((zC,_y)=>{"use strict";var xk=Or(),Ik=Vn(),Tk=Le(),Pk=(r,e,t)=>{if(!Ik.RELEASE_TYPES.includes(e))return null;let n=Ok(r,t);return n&&Rk(n,e)},Ok=(r,e)=>{let t=r instanceof Tk?r.version:r;return xk(t,e)},Rk=(r,e)=>{if(Ck(e))return r.version;switch(r.prerelease=[],e){case"major":r.minor=0,r.patch=0;break;case"minor":r.patch=0;break}return r.format()},Ck=r=>r.startsWith("pre");_y.exports=Pk});var Sy=$((KC,$y)=>{"use strict";var gd=class{constructor(){this.max=1e3,this.map=new Map}get(e){let t=this.map.get(e);if(t!==void 0)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 s=this.map.keys().next().value;this.delete(s)}this.map.set(e,t)}return this}};$y.exports=gd});var gt=$((GC,xy)=>{"use strict";var Nk=/\s+/g,bd=class r{constructor(e,t){if(t=Lk(t),e instanceof r)return e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease?e:new r(e.raw,t);if(e instanceof wd)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(Nk," "),this.set=this.raw.split("||").map(n=>this.parseRange(n.trim())).filter(n=>n.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let n=this.set[0];if(this.set=this.set.filter(s=>!Ay(s[0])),this.set.length===0)this.set=[n];else if(this.set.length>1){for(let s of this.set)if(s.length===1&&zk(s[0])){this.set=[s];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let e=0;e0&&(this.formatted+="||");let t=this.set[e];for(let n=0;n0&&(this.formatted+=" "),this.formatted+=t[n].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(e){e=e.replace(Hk,"");let n=((this.options.includePrerelease&&Uk)|(this.options.loose&&Bk))+":"+e,s=Ey.get(n);if(s)return s;let i=this.options.loose,o=i?Ke[qe.HYPHENRANGELOOSE]:Ke[qe.HYPHENRANGE];e=e.replace(o,rx(this.options.includePrerelease)),ge("hyphen replace",e),e=e.replace(Ke[qe.COMPARATORTRIM],jk),ge("comparator trim",e),e=e.replace(Ke[qe.TILDETRIM],Fk),ge("tilde trim",e),e=e.replace(Ke[qe.CARETTRIM],Vk),ge("caret trim",e);let a=e.split(" ").map(d=>Kk(d,this.options)).join(" ").split(/\s+/).map(d=>tx(d,this.options));i&&(a=a.filter(d=>(ge("loose invalid filter",d,this.options),!!d.match(Ke[qe.COMPARATORLOOSE])))),ge("range list",a);let c=new Map,l=a.map(d=>new wd(d,this.options));for(let d of l){if(Ay(d))return[d];c.set(d.value,d)}c.size>1&&c.has("")&&c.delete("");let u=[...c.values()];return Ey.set(n,u),u}intersects(e,t){if(!(e instanceof r))throw new TypeError("a Range is required");return this.set.some(n=>ky(n,t)&&e.set.some(s=>ky(s,t)&&n.every(i=>s.every(o=>i.intersects(o,t)))))}test(e){if(!e)return!1;if(typeof e=="string")try{e=new qk(e,this.options)}catch(t){return!1}for(let t=0;tr.value==="<0.0.0-0",zk=r=>r.value==="",ky=(r,e)=>{let t=!0,n=r.slice(),s=n.pop();for(;t&&n.length;)t=n.every(i=>s.intersects(i,e)),s=n.pop();return t},Kk=(r,e)=>(r=r.replace(Ke[qe.BUILD],""),ge("comp",r,e),r=Yk(r,e),ge("caret",r),r=Wk(r,e),ge("tildes",r),r=Qk(r,e),ge("xrange",r),r=ex(r,e),ge("stars",r),r),Ie=r=>!r||r.toLowerCase()==="x"||r==="*",Gk=(r,e,t)=>Ie(r)&&!Ie(e)||Ie(e)&&t&&!Ie(t),Wk=(r,e)=>r.trim().split(/\s+/).map(t=>Jk(t,e)).join(" "),Jk=(r,e)=>{let t=e.loose?Ke[qe.TILDELOOSE]:Ke[qe.TILDE],n=e.includePrerelease?"-0":"";return r.replace(t,(s,i,o,a,c)=>{ge("tilde",r,s,i,o,a,c);let l;return Ie(i)?l="":Ie(o)?l=`>=${i}.0.0${n} <${+i+1}.0.0-0`:Ie(a)?l=`>=${i}.${o}.0${n} <${i}.${+o+1}.0-0`:c?(ge("replaceTilde pr",c),l=`>=${i}.${o}.${a}-${c} <${i}.${+o+1}.0-0`):l=`>=${i}.${o}.${a} <${i}.${+o+1}.0-0`,ge("tilde return",l),l})},Yk=(r,e)=>r.trim().split(/\s+/).map(t=>Xk(t,e)).join(" "),Xk=(r,e)=>{ge("caret",r,e);let t=e.loose?Ke[qe.CARETLOOSE]:Ke[qe.CARET],n=e.includePrerelease?"-0":"";return r.replace(t,(s,i,o,a,c)=>{ge("caret",r,s,i,o,a,c);let l;return Ie(i)?l="":Ie(o)?l=`>=${i}.0.0${n} <${+i+1}.0.0-0`:Ie(a)?i==="0"?l=`>=${i}.${o}.0${n} <${i}.${+o+1}.0-0`:l=`>=${i}.${o}.0${n} <${+i+1}.0.0-0`:c?(ge("replaceCaret pr",c),i==="0"?o==="0"?l=`>=${i}.${o}.${a}-${c} <${i}.${o}.${+a+1}-0`:l=`>=${i}.${o}.${a}-${c} <${i}.${+o+1}.0-0`:l=`>=${i}.${o}.${a}-${c} <${+i+1}.0.0-0`):(ge("no pr"),i==="0"?o==="0"?l=`>=${i}.${o}.${a} <${i}.${o}.${+a+1}-0`:l=`>=${i}.${o}.${a} <${i}.${+o+1}.0-0`:l=`>=${i}.${o}.${a} <${+i+1}.0.0-0`),ge("caret return",l),l})},Qk=(r,e)=>(ge("replaceXRanges",r,e),r.split(/\s+/).map(t=>Zk(t,e)).join(" ")),Zk=(r,e)=>{r=r.trim();let t=e.loose?Ke[qe.XRANGELOOSE]:Ke[qe.XRANGE];return r.replace(t,(n,s,i,o,a,c)=>{if(ge("xRange",r,n,s,i,o,a,c),Gk(i,o,a))return r;let l=Ie(i),u=l||Ie(o),d=u||Ie(a),f=d;return s==="="&&f&&(s=""),c=e.includePrerelease?"-0":"",l?s===">"||s==="<"?n="<0.0.0-0":n="*":s&&f?(u&&(o=0),a=0,s===">"?(s=">=",u?(i=+i+1,o=0,a=0):(o=+o+1,a=0)):s==="<="&&(s="<",u?i=+i+1:o=+o+1),s==="<"&&(c="-0"),n=`${s+i}.${o}.${a}${c}`):u?n=`>=${i}.0.0${c} <${+i+1}.0.0-0`:d&&(n=`>=${i}.${o}.0${c} <${i}.${+o+1}.0-0`),ge("xRange return",n),n})},ex=(r,e)=>(ge("replaceStars",r,e),r.trim().replace(Ke[qe.STAR],"")),tx=(r,e)=>(ge("replaceGTE0",r,e),r.trim().replace(Ke[e.includePrerelease?qe.GTE0PRE:qe.GTE0],"")),rx=r=>(e,t,n,s,i,o,a,c,l,u,d,f)=>(Ie(n)?t="":Ie(s)?t=`>=${n}.0.0${r?"-0":""}`:Ie(i)?t=`>=${n}.${s}.0${r?"-0":""}`:o?t=`>=${t}`:t=`>=${t}${r?"-0":""}`,Ie(l)?c="":Ie(u)?c=`<${+l+1}.0.0-0`:Ie(d)?c=`<${l}.${+u+1}.0-0`:f?c=`<=${l}.${u}.${d}-${f}`:r?c=`<${l}.${u}.${+d+1}-0`:c=`<=${c}`,`${t} ${c}`.trim()),nx=(r,e,t)=>{for(let n=0;n0){let s=r[n].semver;if(s.major===e.major&&s.minor===e.minor&&s.patch===e.patch)return!0}return!1}return!0}});var Gs=$((WC,Cy)=>{"use strict";var Ws=Symbol("SemVer ANY"),$d=class r{static get ANY(){return Ws}constructor(e,t){if(t=Iy(t),e instanceof r){if(e.loose===!!t.loose)return e;e=e.value}e=e.trim().split(/\s+/).join(" "),vd("comparator",e,t),this.options=t,this.loose=!!t.loose,this.parse(e),this.semver===Ws?this.value="":this.value=this.operator+this.semver.version,vd("comp",this)}parse(e){let t=this.options.loose?Ty[Py.COMPARATORLOOSE]:Ty[Py.COMPARATOR],n=e.match(t);if(!n)throw new TypeError(`Invalid comparator: ${e}`);this.operator=n[1]!==void 0?n[1]:"",this.operator==="="&&(this.operator=""),n[2]?this.semver=new Oy(n[2],this.options.loose):this.semver=Ws}toString(){return this.value}test(e){if(vd("Comparator.test",e,this.options.loose),this.semver===Ws||e===Ws)return!0;if(typeof e=="string")try{e=new Oy(e,this.options)}catch(t){return!1}return _d(e,this.operator,this.semver,this.options)}intersects(e,t){if(!(e instanceof r))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new Ry(e.value,t).test(this.value):e.operator===""?e.value===""?!0:new Ry(this.value,t).test(e.semver):(t=Iy(t),t.includePrerelease&&(this.value==="<0.0.0-0"||e.value==="<0.0.0-0")||!t.includePrerelease&&(this.value.startsWith("<0.0.0")||e.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&e.operator.startsWith(">")||this.operator.startsWith("<")&&e.operator.startsWith("<")||this.semver.version===e.semver.version&&this.operator.includes("=")&&e.operator.includes("=")||_d(this.semver,"<",e.semver,t)&&this.operator.startsWith(">")&&e.operator.startsWith("<")||_d(this.semver,">",e.semver,t)&&this.operator.startsWith("<")&&e.operator.startsWith(">")))}};Cy.exports=$d;var Iy=$o(),{safeRe:Ty,t:Py}=Un(),_d=yd(),vd=zs(),Oy=Le(),Ry=gt()});var Js=$((JC,Ny)=>{"use strict";var sx=gt(),ix=(r,e,t)=>{try{e=new sx(e,t)}catch(n){return!1}return e.test(r)};Ny.exports=ix});var Ly=$((YC,My)=>{"use strict";var ox=gt(),ax=(r,e)=>new ox(r,e).set.map(t=>t.map(n=>n.value).join(" ").trim().split(" "));My.exports=ax});var Dy=$((XC,qy)=>{"use strict";var cx=Le(),lx=gt(),dx=(r,e,t)=>{let n=null,s=null,i=null;try{i=new lx(e,t)}catch(o){return null}return r.forEach(o=>{i.test(o)&&(!n||s.compare(o)===-1)&&(n=o,s=new cx(n,t))}),n};qy.exports=dx});var Fy=$((QC,jy)=>{"use strict";var ux=Le(),fx=gt(),px=(r,e,t)=>{let n=null,s=null,i=null;try{i=new fx(e,t)}catch(o){return null}return r.forEach(o=>{i.test(o)&&(!n||s.compare(o)===1)&&(n=o,s=new ux(n,t))}),n};jy.exports=px});var By=$((ZC,Uy)=>{"use strict";var Sd=Le(),hx=gt(),Vy=Ks(),mx=(r,e)=>{r=new hx(r,e);let t=new Sd("0.0.0");if(r.test(t)||(t=new Sd("0.0.0-0"),r.test(t)))return t;t=null;for(let n=0;n{let a=new Sd(o.semver.version);switch(o.operator){case">":a.prerelease.length===0?a.patch++:a.prerelease.push(0),a.raw=a.format();case"":case">=":(!i||Vy(a,i))&&(i=a);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${o.operator}`)}}),i&&(!t||Vy(t,i))&&(t=i)}return t&&r.test(t)?t:null};Uy.exports=mx});var zy=$((eN,Hy)=>{"use strict";var yx=gt(),gx=(r,e)=>{try{return new yx(r,e).range||"*"}catch(t){return null}};Hy.exports=gx});var Co=$((tN,Jy)=>{"use strict";var bx=Le(),Wy=Gs(),{ANY:wx}=Wy,_x=gt(),vx=Js(),Ky=Ks(),Gy=Io(),$x=Po(),Sx=To(),Ex=(r,e,t,n)=>{r=new bx(r,n),e=new _x(e,n);let s,i,o,a,c;switch(t){case">":s=Ky,i=$x,o=Gy,a=">",c=">=";break;case"<":s=Gy,i=Sx,o=Ky,a="<",c="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(vx(r,e,n))return!1;for(let l=0;l{p.semver===wx&&(p=new Wy(">=0.0.0")),d=d||p,f=f||p,s(p.semver,d.semver,n)?d=p:o(p.semver,f.semver,n)&&(f=p)}),d.operator===a||d.operator===c||(!f.operator||f.operator===a)&&i(r,f.semver))return!1;if(f.operator===c&&o(r,f.semver))return!1}return!0};Jy.exports=Ex});var Xy=$((rN,Yy)=>{"use strict";var Ax=Co(),kx=(r,e,t)=>Ax(r,e,">",t);Yy.exports=kx});var Zy=$((nN,Qy)=>{"use strict";var xx=Co(),Ix=(r,e,t)=>xx(r,e,"<",t);Qy.exports=Ix});var rg=$((sN,tg)=>{"use strict";var eg=gt(),Tx=(r,e,t)=>(r=new eg(r,t),e=new eg(e,t),r.intersects(e,t));tg.exports=Tx});var sg=$((iN,ng)=>{"use strict";var Px=Js(),Ox=yt();ng.exports=(r,e,t)=>{let n=[],s=null,i=null,o=r.sort((u,d)=>Ox(u,d,t));for(let u of o)Px(u,e,t)?(i=u,s||(s=u)):(i&&n.push([s,i]),i=null,s=null);s&&n.push([s,null]);let a=[];for(let[u,d]of n)u===d?a.push(u):!d&&u===o[0]?a.push("*"):d?u===o[0]?a.push(`<=${d}`):a.push(`${u} - ${d}`):a.push(`>=${u}`);let c=a.join(" || "),l=typeof e.raw=="string"?e.raw:String(e);return c.length{"use strict";var ig=gt(),kd=Gs(),{ANY:Ed}=kd,Ad=Js(),xd=yt(),Rx=(r,e,t={})=>{if(r===e)return!0;r=new ig(r,t),e=new ig(e,t);let n=!1;e:for(let s of r.set){for(let i of e.set){let o=Nx(s,i,t);if(n=n||o!==null,o)continue e}if(n)return!1}return!0},Cx=[new kd(">=0.0.0-0")],og=[new kd(">=0.0.0")],Nx=(r,e,t)=>{if(r===e)return!0;if(r.length===1&&r[0].semver===Ed){if(e.length===1&&e[0].semver===Ed)return!0;t.includePrerelease?r=Cx:r=og}if(e.length===1&&e[0].semver===Ed){if(t.includePrerelease)return!0;e=og}let n=new Set,s,i;for(let p of r)p.operator===">"||p.operator===">="?s=ag(s,p,t):p.operator==="<"||p.operator==="<="?i=cg(i,p,t):n.add(p.semver);if(n.size>1)return null;let o;if(s&&i){if(o=xd(s.semver,i.semver,t),o>0)return null;if(o===0&&(s.operator!==">="||i.operator!=="<="))return null}for(let p of n){if(s&&!Ad(p,String(s),t)||i&&!Ad(p,String(i),t))return null;for(let m of e)if(!Ad(p,String(m),t))return!1;return!0}let a,c,l,u,d=i&&!t.includePrerelease&&i.semver.prerelease.length?i.semver:!1,f=s&&!t.includePrerelease&&s.semver.prerelease.length?s.semver:!1;d&&d.prerelease.length===1&&i.operator==="<"&&d.prerelease[0]===0&&(d=!1);for(let p of e){if(u=u||p.operator===">"||p.operator===">=",l=l||p.operator==="<"||p.operator==="<=",s){if(f&&p.semver.prerelease&&p.semver.prerelease.length&&p.semver.major===f.major&&p.semver.minor===f.minor&&p.semver.patch===f.patch&&(f=!1),p.operator===">"||p.operator===">="){if(a=ag(s,p,t),a===p&&a!==s)return!1}else if(s.operator===">="&&!p.test(s.semver))return!1}if(i){if(d&&p.semver.prerelease&&p.semver.prerelease.length&&p.semver.major===d.major&&p.semver.minor===d.minor&&p.semver.patch===d.patch&&(d=!1),p.operator==="<"||p.operator==="<="){if(c=cg(i,p,t),c===p&&c!==i)return!1}else if(i.operator==="<="&&!p.test(i.semver))return!1}if(!p.operator&&(i||s)&&o!==0)return!1}return!(s&&l&&!i&&o!==0||i&&u&&!s&&o!==0||f||d)},ag=(r,e,t)=>{if(!r)return e;let n=xd(r.semver,e.semver,t);return n>0?r:n<0||e.operator===">"&&r.operator===">="?e:r},cg=(r,e,t)=>{if(!r)return e;let n=xd(r.semver,e.semver,t);return n<0?r:n>0||e.operator==="<"&&r.operator==="<="?e:r};lg.exports=Rx});var hg=$((aN,pg)=>{"use strict";var Id=Un(),ug=Vn(),Mx=Le(),fg=ud(),Lx=Or(),qx=Lm(),Dx=Dm(),jx=Vm(),Fx=Hm(),Vx=Km(),Ux=Wm(),Bx=Ym(),Hx=Qm(),zx=yt(),Kx=ry(),Gx=sy(),Wx=xo(),Jx=cy(),Yx=dy(),Xx=Ks(),Qx=Io(),Zx=hd(),eI=md(),tI=To(),rI=Po(),nI=yd(),sI=wy(),iI=vy(),oI=Gs(),aI=gt(),cI=Js(),lI=Ly(),dI=Dy(),uI=Fy(),fI=By(),pI=zy(),hI=Co(),mI=Xy(),yI=Zy(),gI=rg(),bI=sg(),wI=dg();pg.exports={parse:Lx,valid:qx,clean:Dx,inc:jx,diff:Fx,major:Vx,minor:Ux,patch:Bx,prerelease:Hx,compare:zx,rcompare:Kx,compareLoose:Gx,compareBuild:Wx,sort:Jx,rsort:Yx,gt:Xx,lt:Qx,eq:Zx,neq:eI,gte:tI,lte:rI,cmp:nI,coerce:sI,truncate:iI,Comparator:oI,Range:aI,satisfies:cI,toComparators:lI,maxSatisfying:dI,minSatisfying:uI,minVersion:fI,validRange:pI,outside:hI,gtr:mI,ltr:yI,intersects:gI,simplifyRange:bI,subset:wI,SemVer:Mx,re:Id.re,src:Id.src,tokens:Id.t,SEMVER_SPEC_VERSION:ug.SEMVER_SPEC_VERSION,RELEASE_TYPES:ug.RELEASE_TYPES,compareIdentifiers:fg.compareIdentifiers,rcompareIdentifiers:fg.rcompareIdentifiers}});var Xs=$((AN,Eg)=>{"use strict";var _g="[^\\\\/]",II="(?=.)",vg="[^/]",Cd="(?:\\/|$)",$g="(?:^|\\/)",Nd=`\\.{1,2}${Cd}`,TI="(?!\\.)",PI=`(?!${$g}${Nd})`,OI=`(?!\\.{0,1}${Cd})`,RI=`(?!${Nd})`,CI="[^.\\/]",NI=`${vg}*?`,MI="/",Sg={DOT_LITERAL:"\\.",PLUS_LITERAL:"\\+",QMARK_LITERAL:"\\?",SLASH_LITERAL:"\\/",ONE_CHAR:II,QMARK:vg,END_ANCHOR:Cd,DOTS_SLASH:Nd,NO_DOT:TI,NO_DOTS:PI,NO_DOT_SLASH:OI,NO_DOTS_SLASH:RI,QMARK_NO_DOT:CI,STAR:NI,START_ANCHOR:$g,SEP:MI},LI={...Sg,SLASH_LITERAL:"[\\\\/]",QMARK:_g,STAR:`${_g}*?`,DOTS_SLASH:"\\.{1,2}(?:[\\\\/]|$)",NO_DOT:"(?!\\.)",NO_DOTS:"(?!(?:^|[\\\\/])\\.{1,2}(?:[\\\\/]|$))",NO_DOT_SLASH:"(?!\\.{0,1}(?:[\\\\/]|$))",NO_DOTS_SLASH:"(?!\\.{1,2}(?:[\\\\/]|$))",QMARK_NO_DOT:"[^.\\\\/]",START_ANCHOR:"(?:^|[\\\\/])",END_ANCHOR:"(?:[\\\\/]|$)",SEP:"\\"},qI={__proto__:null,alnum:"a-zA-Z0-9",alpha:"a-zA-Z",ascii:"\\x00-\\x7F",blank:" \\t",cntrl:"\\x00-\\x1F\\x7F",digit:"0-9",graph:"\\x21-\\x7E",lower:"a-z",print:"\\x20-\\x7E ",punct:"\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",space:" \\t\\r\\n\\v\\f",upper:"A-Z",word:"A-Za-z0-9_",xdigit:"A-Fa-f0-9"};Eg.exports={DEFAULT_MAX_EXTGLOB_RECURSION:0,MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:qI,REGEX_BACKSLASH:/\\(?![*+?^${}(|)[\]])/g,REGEX_NON_SPECIAL_CHARS:/^[^@![\].,$*+?^{}()|\\/]+/,REGEX_SPECIAL_CHARS:/[-*+?.^${}(|)[\]]/,REGEX_SPECIAL_CHARS_BACKREF:/(\\?)((\W)(\3*))/g,REGEX_SPECIAL_CHARS_GLOBAL:/([-*+?.^${}(|)[\]])/g,REGEX_REMOVE_BACKSLASH:/(?:\[.*?[^\\]\]|\\(?=.))/g,REPLACEMENTS:{__proto__:null,"***":"*","**/**":"**","**/**/**":"**"},CHAR_0:48,CHAR_9:57,CHAR_UPPERCASE_A:65,CHAR_LOWERCASE_A:97,CHAR_UPPERCASE_Z:90,CHAR_LOWERCASE_Z:122,CHAR_LEFT_PARENTHESES:40,CHAR_RIGHT_PARENTHESES:41,CHAR_ASTERISK:42,CHAR_AMPERSAND:38,CHAR_AT:64,CHAR_BACKWARD_SLASH:92,CHAR_CARRIAGE_RETURN:13,CHAR_CIRCUMFLEX_ACCENT:94,CHAR_COLON:58,CHAR_COMMA:44,CHAR_DOT:46,CHAR_DOUBLE_QUOTE:34,CHAR_EQUAL:61,CHAR_EXCLAMATION_MARK:33,CHAR_FORM_FEED:12,CHAR_FORWARD_SLASH:47,CHAR_GRAVE_ACCENT:96,CHAR_HASH:35,CHAR_HYPHEN_MINUS:45,CHAR_LEFT_ANGLE_BRACKET:60,CHAR_LEFT_CURLY_BRACE:123,CHAR_LEFT_SQUARE_BRACKET:91,CHAR_LINE_FEED:10,CHAR_NO_BREAK_SPACE:160,CHAR_PERCENT:37,CHAR_PLUS:43,CHAR_QUESTION_MARK:63,CHAR_RIGHT_ANGLE_BRACKET:62,CHAR_RIGHT_CURLY_BRACE:125,CHAR_RIGHT_SQUARE_BRACKET:93,CHAR_SEMICOLON:59,CHAR_SINGLE_QUOTE:39,CHAR_SPACE:32,CHAR_TAB:9,CHAR_UNDERSCORE:95,CHAR_VERTICAL_LINE:124,CHAR_ZERO_WIDTH_NOBREAK_SPACE:65279,extglobChars(r){return{"!":{type:"negate",open:"(?:(?!(?:",close:`))${r.STAR})`},"?":{type:"qmark",open:"(?:",close:")?"},"+":{type:"plus",open:"(?:",close:")+"},"*":{type:"star",open:"(?:",close:")*"},"@":{type:"at",open:"(?:",close:")"}}},globChars(r){return r===!0?LI:Sg}}});var Qs=$(et=>{"use strict";var{REGEX_BACKSLASH:DI,REGEX_REMOVE_BACKSLASH:jI,REGEX_SPECIAL_CHARS:FI,REGEX_SPECIAL_CHARS_GLOBAL:VI}=Xs();et.isObject=r=>r!==null&&typeof r=="object"&&!Array.isArray(r);et.hasRegexChars=r=>FI.test(r);et.isRegexChar=r=>r.length===1&&et.hasRegexChars(r);et.escapeRegex=r=>r.replace(VI,"\\$1");et.toPosixSlashes=r=>r.replace(DI,"/");et.isWindows=()=>{if(typeof navigator!="undefined"&&navigator.platform){let r=navigator.platform.toLowerCase();return r==="win32"||r==="windows"}return typeof process!="undefined"&&process.platform?process.platform==="win32":!1};et.removeBackslashes=r=>r.replace(jI,e=>e==="\\"?"":e);et.escapeLast=(r,e,t)=>{let n=r.lastIndexOf(e,t);return n===-1?r:r[n-1]==="\\"?et.escapeLast(r,e,n-1):`${r.slice(0,n)}\\${r.slice(n)}`};et.removePrefix=(r,e={})=>{let t=r;return t.startsWith("./")&&(t=t.slice(2),e.prefix="./"),t};et.wrapOutput=(r,e={},t={})=>{let n=t.contains?"":"^",s=t.contains?"":"$",i=`${n}(?:${r})${s}`;return e.negated===!0&&(i=`(?:^(?!${i}).*$)`),i};et.basename=(r,{windows:e}={})=>{let t=r.split(e?/[\\/]/:"/"),n=t[t.length-1];return n===""?t[t.length-2]:n}});var Rg=$((xN,Og)=>{"use strict";var Ag=Qs(),{CHAR_ASTERISK:Md,CHAR_AT:UI,CHAR_BACKWARD_SLASH:Zs,CHAR_COMMA:BI,CHAR_DOT:Ld,CHAR_EXCLAMATION_MARK:qd,CHAR_FORWARD_SLASH:Pg,CHAR_LEFT_CURLY_BRACE:Dd,CHAR_LEFT_PARENTHESES:jd,CHAR_LEFT_SQUARE_BRACKET:HI,CHAR_PLUS:zI,CHAR_QUESTION_MARK:kg,CHAR_RIGHT_CURLY_BRACE:KI,CHAR_RIGHT_PARENTHESES:xg,CHAR_RIGHT_SQUARE_BRACKET:GI}=Xs(),Ig=r=>r===Pg||r===Zs,Tg=r=>{r.isPrefix!==!0&&(r.depth=r.isGlobstar?1/0:1)},WI=(r,e)=>{let t=e||{},n=r.length-1,s=t.parts===!0||t.scanToEnd===!0,i=[],o=[],a=[],c=r,l=-1,u=0,d=0,f=!1,p=!1,m=!1,h=!1,y=!1,b=!1,g=!1,w=!1,S=!1,_=!1,x=0,I,E,T={value:"",depth:0,isGlob:!1},v=()=>l>=n,F=()=>c.charCodeAt(l+1),V=()=>(I=E,c.charCodeAt(++l));for(;l0&&(A=c.slice(0,u),c=c.slice(u),d-=u),G&&m===!0&&d>0?(G=c.slice(0,d),k=c.slice(d)):m===!0?(G="",k=c):G=c,G&&G!==""&&G!=="/"&&G!==c&&Ig(G.charCodeAt(G.length-1))&&(G=G.slice(0,-1)),t.unescape===!0&&(k&&(k=Ag.removeBackslashes(k)),G&&g===!0&&(G=Ag.removeBackslashes(G)));let Re={prefix:A,input:r,start:u,base:G,glob:k,isBrace:f,isBracket:p,isGlob:m,isExtglob:h,isGlobstar:y,negated:w,negatedExtglob:S};if(t.tokens===!0&&(Re.maxDepth=0,Ig(E)||o.push(T),Re.tokens=o),t.parts===!0||t.tokens===!0){let oe;for(let ae=0;ae{"use strict";var ei=Xs(),it=Qs(),{MAX_LENGTH:qo,POSIX_REGEX_SOURCE:JI,REGEX_NON_SPECIAL_CHARS:YI,REGEX_SPECIAL_CHARS_BACKREF:XI,REPLACEMENTS:Cg}=ei,QI=(r,e)=>{if(typeof e.expandRange=="function")return e.expandRange(...r,e);r.sort();let t=`[${r.join("-")}]`;try{new RegExp(t)}catch(n){return r.map(s=>it.escapeRegex(s)).join("..")}return t},Bn=(r,e)=>`Missing ${r}: "${e}" - use "\\\\${e}" to match literal characters`,Ng=r=>{let e=[],t=0,n=0,s=0,i="",o=!1;for(let a of r){if(o===!0){i+=a,o=!1;continue}if(a==="\\"){i+=a,o=!0;continue}if(a==='"'){s=s===1?0:1,i+=a;continue}if(s===0){if(a==="[")t++;else if(a==="]"&&t>0)t--;else if(t===0){if(a==="(")n++;else if(a===")"&&n>0)n--;else if(a==="|"&&n===0){e.push(i),i="";continue}}}i+=a}return e.push(i),e},ZI=r=>{let e=!1;for(let t of r){if(e===!0){e=!1;continue}if(t==="\\"){e=!0;continue}if(/[?*+@!()[\]{}]/.test(t))return!1}return!0},Vd=r=>{let e=r.trim(),t=!0;for(;t===!0;)t=!1,/^@\([^\\()[\]{}|]+\)$/.test(e)&&(e=e.slice(2,-1),t=!0);if(ZI(e))return e.replace(/\\(.)/g,"$1")},eT=r=>{let e=r.map(Vd).filter(Boolean);for(let t=0;t{if(r[0]!=="+"&&r[0]!=="*"||r[1]!=="(")return;let t=0,n=0,s=0,i=!1;for(let o=1;o0){t--;continue}if(!(t>0)){if(a==="("){n++;continue}if(a===")"&&(n--,n===0))return e===!0&&o!==r.length-1?void 0:{type:r[0],body:r.slice(2,o),end:o}}}}},tT=r=>`${r.length===1?it.escapeRegex(r[0]):`[${r.map(t=>it.escapeRegex(t)).join("")}]`}*`,rT=r=>{let e=0,t=[];for(;eo.trim());if(s.length!==1)return;let i=Vd(s[0]);if(!i||i.length!==1)return;t.push(i),e+=n.end+1}if(!(t.length<1))return t},nT=r=>{let e=0,t=r.trim(),n=Fd(t);for(;n;)e++,t=n.body.trim(),n=Fd(t);return e},sT=(r,e)=>{if(e.maxExtglobRecursion===!1)return{risky:!1};let t=typeof e.maxExtglobRecursion=="number"?e.maxExtglobRecursion:ei.DEFAULT_MAX_EXTGLOB_RECURSION,n=Ng(r).map(a=>a.trim());if(n.length>1&&(n.some(a=>a==="")||n.some(a=>/^[*?]+$/.test(a))||eT(n)))return{risky:!0};let s=[],i=!1,o=!0;for(let a of n){let c=rT(a);if(c){i=!0,s.push(...c);continue}let l=Vd(a);if(l&&l.length===1){s.push(l);continue}if(o=!1,nT(a)>t)return{risky:!0}}return i?o?{risky:!0,safeOutput:tT([...new Set(s)])}:{risky:!0}:{risky:!1}},Ud=(r,e)=>{if(typeof r!="string")throw new TypeError("Expected a string");r=Cg[r]||r;let t={...e},n=typeof t.maxLength=="number"?Math.min(qo,t.maxLength):qo,s=r.length;if(s>n)throw new SyntaxError(`Input length: ${s}, exceeds maximum allowed length: ${n}`);let i={type:"bos",value:"",output:t.prepend||""},o=[i],a=t.capture?"":"?:",c=ei.globChars(t.windows),l=ei.extglobChars(c),{DOT_LITERAL:u,PLUS_LITERAL:d,SLASH_LITERAL:f,ONE_CHAR:p,DOTS_SLASH:m,NO_DOT:h,NO_DOT_SLASH:y,NO_DOTS_SLASH:b,QMARK:g,QMARK_NO_DOT:w,STAR:S,START_ANCHOR:_}=c,x=C=>`(${a}(?:(?!${_}${C.dot?m:u}).)*?)`,I=t.dot?"":h,E=t.dot?g:w,T=t.bash===!0?x(t):S;t.capture&&(T=`(${T})`),typeof t.noext=="boolean"&&(t.noextglob=t.noext);let v={input:r,index:-1,start:0,dot:t.dot===!0,consumed:"",output:"",prefix:"",backtrack:!1,negated:!1,brackets:0,braces:0,parens:0,quotes:0,globstar:!1,tokens:o};r=it.removePrefix(r,v),s=r.length;let F=[],V=[],G=[],A=i,k,Re=()=>v.index===s-1,oe=v.peek=(C=1)=>r[v.index+C],ae=v.advance=()=>r[++v.index]||"",tr=()=>r.slice(v.index+1),dt=(C="",we=0)=>{v.consumed+=C,v.index+=we},wr=C=>{v.output+=C.output!=null?C.output:C.value,dt(C.value)},F0=()=>{let C=1;for(;oe()==="!"&&(oe(2)!=="("||oe(3)==="?");)ae(),v.start++,C++;return C%2===0?!1:(v.negated=!0,v.start++,!0)},qi=C=>{v[C]++,G.push(C)},_r=C=>{v[C]--,G.pop()},X=C=>{if(A.type==="globstar"){let we=v.braces>0&&(C.type==="comma"||C.type==="brace"),R=C.extglob===!0||F.length&&(C.type==="pipe"||C.type==="paren");C.type!=="slash"&&C.type!=="paren"&&!we&&!R&&(v.output=v.output.slice(0,-A.output.length),A.type="star",A.value="*",A.output=T,v.output+=A.output)}if(F.length&&C.type!=="paren"&&(F[F.length-1].inner+=C.value),(C.value||C.output)&&wr(C),A&&A.type==="text"&&C.type==="text"){A.output=(A.output||A.value)+C.value,A.value+=C.value;return}C.prev=A,o.push(C),A=C},Di=(C,we)=>{let R={...l[we],conditions:1,inner:""};R.prev=A,R.parens=v.parens,R.output=v.output,R.startIndex=v.index,R.tokensIndex=o.length;let Q=(t.capture?"(":"")+R.open;qi("parens"),X({type:C,value:we,output:v.output?"":p}),X({type:"paren",extglob:!0,value:ae(),output:Q}),F.push(R)},V0=C=>{let we=r.slice(C.startIndex,v.index+1),R=r.slice(C.startIndex+2,v.index),Q=sT(R,t);if((C.type==="plus"||C.type==="star")&&Q.risky){let ue=Q.safeOutput?(C.output?"":p)+(t.capture?`(${Q.safeOutput})`:Q.safeOutput):void 0,jt=o[C.tokensIndex];jt.type="text",jt.value=we,jt.output=ue||it.escapeRegex(we);for(let Ft=C.tokensIndex+1;Ft1&&C.inner.includes("/")&&(ue=x(t)),(ue!==T||Re()||/^\)+$/.test(tr()))&&(pe=C.close=`)$))${ue}`),C.inner.includes("*")&&(xe=tr())&&/^\.[^\\/.]+$/.test(xe)){let jt=Ud(xe,{...e,fastpaths:!1}).output;pe=C.close=`)${jt})${ue})`}C.prev.type==="bos"&&(v.negatedExtglob=!0)}X({type:"paren",extglob:!0,value:k,output:pe}),_r("parens")};if(t.fastpaths!==!1&&!/(^[*!]|[/()[\]{}"])/.test(r)){let C=!1,we=r.replace(XI,(R,Q,pe,xe,ue,jt)=>xe==="\\"?(C=!0,R):xe==="?"?Q?Q+xe+(ue?g.repeat(ue.length):""):jt===0?E+(ue?g.repeat(ue.length):""):g.repeat(pe.length):xe==="."?u.repeat(pe.length):xe==="*"?Q?Q+xe+(ue?T:""):T:Q?R:`\\${R}`);return C===!0&&(t.unescape===!0?we=we.replace(/\\/g,""):we=we.replace(/\\+/g,R=>R.length%2===0?"\\\\":R?"\\":"")),we===r&&t.contains===!0?(v.output=r,v):(v.output=it.wrapOutput(we,v,e),v)}for(;!Re();){if(k=ae(),k==="\0")continue;if(k==="\\"){let R=oe();if(R==="/"&&t.bash!==!0||R==="."||R===";")continue;if(!R){k+="\\",X({type:"text",value:k});continue}let Q=/^\\+/.exec(tr()),pe=0;if(Q&&Q[0].length>2&&(pe=Q[0].length,v.index+=pe,pe%2!==0&&(k+="\\")),t.unescape===!0?k=ae():k+=ae(),v.brackets===0){X({type:"text",value:k});continue}}if(v.brackets>0&&(k!=="]"||A.value==="["||A.value==="[^")){if(t.posix!==!1&&k===":"){let R=A.value.slice(1);if(R.includes("[")&&(A.posix=!0,R.includes(":"))){let Q=A.value.lastIndexOf("["),pe=A.value.slice(0,Q),xe=A.value.slice(Q+2),ue=JI[xe];if(ue){A.value=pe+ue,v.backtrack=!0,ae(),!i.output&&o.indexOf(A)===1&&(i.output=p);continue}}}(k==="["&&oe()!==":"||k==="-"&&oe()==="]")&&(k=`\\${k}`),k==="]"&&(A.value==="["||A.value==="[^")&&(k=`\\${k}`),t.posix===!0&&k==="!"&&A.value==="["&&(k="^"),A.value+=k,wr({value:k});continue}if(v.quotes===1&&k!=='"'){k=it.escapeRegex(k),A.value+=k,wr({value:k});continue}if(k==='"'){v.quotes=v.quotes===1?0:1,t.keepQuotes===!0&&X({type:"text",value:k});continue}if(k==="("){qi("parens"),X({type:"paren",value:k});continue}if(k===")"){if(v.parens===0&&t.strictBrackets===!0)throw new SyntaxError(Bn("opening","("));let R=F[F.length-1];if(R&&v.parens===R.parens+1){V0(F.pop());continue}X({type:"paren",value:k,output:v.parens?")":"\\)"}),_r("parens");continue}if(k==="["){if(t.nobracket===!0||!tr().includes("]")){if(t.nobracket!==!0&&t.strictBrackets===!0)throw new SyntaxError(Bn("closing","]"));k=`\\${k}`}else qi("brackets");X({type:"bracket",value:k});continue}if(k==="]"){if(t.nobracket===!0||A&&A.type==="bracket"&&A.value.length===1){X({type:"text",value:k,output:`\\${k}`});continue}if(v.brackets===0){if(t.strictBrackets===!0)throw new SyntaxError(Bn("opening","["));X({type:"text",value:k,output:`\\${k}`});continue}_r("brackets");let R=A.value.slice(1);if(A.posix!==!0&&R[0]==="^"&&!R.includes("/")&&(k=`/${k}`),A.value+=k,wr({value:k}),t.literalBrackets===!1||it.hasRegexChars(R))continue;let Q=it.escapeRegex(A.value);if(v.output=v.output.slice(0,-A.value.length),t.literalBrackets===!0){v.output+=Q,A.value=Q;continue}A.value=`(${a}${Q}|${A.value})`,v.output+=A.value;continue}if(k==="{"&&t.nobrace!==!0){qi("braces");let R={type:"brace",value:k,output:"(",outputIndex:v.output.length,tokensIndex:v.tokens.length};V.push(R),X(R);continue}if(k==="}"){let R=V[V.length-1];if(t.nobrace===!0||!R){X({type:"text",value:k,output:k});continue}let Q=")";if(R.dots===!0){let pe=o.slice(),xe=[];for(let ue=pe.length-1;ue>=0&&(o.pop(),pe[ue].type!=="brace");ue--)pe[ue].type!=="dots"&&xe.unshift(pe[ue].value);Q=QI(xe,t),v.backtrack=!0}if(R.comma!==!0&&R.dots!==!0){let pe=v.output.slice(0,R.outputIndex),xe=v.tokens.slice(R.tokensIndex);R.value=R.output="\\{",k=Q="\\}",v.output=pe;for(let ue of xe)v.output+=ue.output||ue.value}X({type:"brace",value:k,output:Q}),_r("braces"),V.pop();continue}if(k==="|"){F.length>0&&F[F.length-1].conditions++,X({type:"text",value:k});continue}if(k===","){let R=k,Q=V[V.length-1];Q&&G[G.length-1]==="braces"&&(Q.comma=!0,R="|"),X({type:"comma",value:k,output:R});continue}if(k==="/"){if(A.type==="dot"&&v.index===v.start+1){v.start=v.index+1,v.consumed="",v.output="",o.pop(),A=i;continue}X({type:"slash",value:k,output:f});continue}if(k==="."){if(v.braces>0&&A.type==="dot"){A.value==="."&&(A.output=u);let R=V[V.length-1];A.type="dots",A.output+=k,A.value+=k,R.dots=!0;continue}if(v.braces+v.parens===0&&A.type!=="bos"&&A.type!=="slash"){X({type:"text",value:k,output:u});continue}X({type:"dot",value:k,output:u});continue}if(k==="?"){if(!(A&&A.value==="(")&&t.noextglob!==!0&&oe()==="("&&oe(2)!=="?"){Di("qmark",k);continue}if(A&&A.type==="paren"){let Q=oe(),pe=k;(A.value==="("&&!/[!=<:]/.test(Q)||Q==="<"&&!/<([!=]|\w+>)/.test(tr()))&&(pe=`\\${k}`),X({type:"text",value:k,output:pe});continue}if(t.dot!==!0&&(A.type==="slash"||A.type==="bos")){X({type:"qmark",value:k,output:w});continue}X({type:"qmark",value:k,output:g});continue}if(k==="!"){if(t.noextglob!==!0&&oe()==="("&&(oe(2)!=="?"||!/[!=<:]/.test(oe(3)))){Di("negate",k);continue}if(t.nonegate!==!0&&v.index===0){F0();continue}}if(k==="+"){if(t.noextglob!==!0&&oe()==="("&&oe(2)!=="?"){Di("plus",k);continue}if(A&&A.value==="("||t.regex===!1){X({type:"plus",value:k,output:d});continue}if(A&&(A.type==="bracket"||A.type==="paren"||A.type==="brace")||v.parens>0){X({type:"plus",value:k});continue}X({type:"plus",value:d});continue}if(k==="@"){if(t.noextglob!==!0&&oe()==="("&&oe(2)!=="?"){X({type:"at",extglob:!0,value:k,output:""});continue}X({type:"text",value:k});continue}if(k!=="*"){(k==="$"||k==="^")&&(k=`\\${k}`);let R=YI.exec(tr());R&&(k+=R[0],v.index+=R[0].length),X({type:"text",value:k});continue}if(A&&(A.type==="globstar"||A.star===!0)){A.type="star",A.star=!0,A.value+=k,A.output=T,v.backtrack=!0,v.globstar=!0,dt(k);continue}let C=tr();if(t.noextglob!==!0&&/^\([^?]/.test(C)){Di("star",k);continue}if(A.type==="star"){if(t.noglobstar===!0){dt(k);continue}let R=A.prev,Q=R.prev,pe=R.type==="slash"||R.type==="bos",xe=Q&&(Q.type==="star"||Q.type==="globstar");if(t.bash===!0&&(!pe||C[0]&&C[0]!=="/")){X({type:"star",value:k,output:""});continue}let ue=v.braces>0&&(R.type==="comma"||R.type==="brace"),jt=F.length&&(R.type==="pipe"||R.type==="paren");if(!pe&&R.type!=="paren"&&!ue&&!jt){X({type:"star",value:k,output:""});continue}for(;C.slice(0,3)==="/**";){let Ft=r[v.index+4];if(Ft&&Ft!=="/")break;C=C.slice(3),dt("/**",3)}if(R.type==="bos"&&Re()){A.type="globstar",A.value+=k,A.output=x(t),v.output=A.output,v.globstar=!0,dt(k);continue}if(R.type==="slash"&&R.prev.type!=="bos"&&!xe&&Re()){v.output=v.output.slice(0,-(R.output+A.output).length),R.output=`(?:${R.output}`,A.type="globstar",A.output=x(t)+(t.strictSlashes?")":"|$)"),A.value+=k,v.globstar=!0,v.output+=R.output+A.output,dt(k);continue}if(R.type==="slash"&&R.prev.type!=="bos"&&C[0]==="/"){let Ft=C[1]!==void 0?"|$":"";v.output=v.output.slice(0,-(R.output+A.output).length),R.output=`(?:${R.output}`,A.type="globstar",A.output=`${x(t)}${f}|${f}${Ft})`,A.value+=k,v.output+=R.output+A.output,v.globstar=!0,dt(k+ae()),X({type:"slash",value:"/",output:""});continue}if(R.type==="bos"&&C[0]==="/"){A.type="globstar",A.value+=k,A.output=`(?:^|${f}|${x(t)}${f})`,v.output=A.output,v.globstar=!0,dt(k+ae()),X({type:"slash",value:"/",output:""});continue}v.output=v.output.slice(0,-A.output.length),A.type="globstar",A.output=x(t),A.value+=k,v.output+=A.output,v.globstar=!0,dt(k);continue}let we={type:"star",value:k,output:T};if(t.bash===!0){we.output=".*?",(A.type==="bos"||A.type==="slash")&&(we.output=I+we.output),X(we);continue}if(A&&(A.type==="bracket"||A.type==="paren")&&t.regex===!0){we.output=k,X(we);continue}(v.index===v.start||A.type==="slash"||A.type==="dot")&&(A.type==="dot"?(v.output+=y,A.output+=y):t.dot===!0?(v.output+=b,A.output+=b):(v.output+=I,A.output+=I),oe()!=="*"&&(v.output+=p,A.output+=p)),X(we)}for(;v.brackets>0;){if(t.strictBrackets===!0)throw new SyntaxError(Bn("closing","]"));v.output=it.escapeLast(v.output,"["),_r("brackets")}for(;v.parens>0;){if(t.strictBrackets===!0)throw new SyntaxError(Bn("closing",")"));v.output=it.escapeLast(v.output,"("),_r("parens")}for(;v.braces>0;){if(t.strictBrackets===!0)throw new SyntaxError(Bn("closing","}"));v.output=it.escapeLast(v.output,"{"),_r("braces")}if(t.strictSlashes!==!0&&(A.type==="star"||A.type==="bracket")&&X({type:"maybe_slash",value:"",output:`${f}?`}),v.backtrack===!0){v.output="";for(let C of v.tokens)v.output+=C.output!=null?C.output:C.value,C.suffix&&(v.output+=C.suffix)}return v};Ud.fastpaths=(r,e)=>{let t={...e},n=typeof t.maxLength=="number"?Math.min(qo,t.maxLength):qo,s=r.length;if(s>n)throw new SyntaxError(`Input length: ${s}, exceeds maximum allowed length: ${n}`);r=Cg[r]||r;let{DOT_LITERAL:i,SLASH_LITERAL:o,ONE_CHAR:a,DOTS_SLASH:c,NO_DOT:l,NO_DOTS:u,NO_DOTS_SLASH:d,STAR:f,START_ANCHOR:p}=ei.globChars(t.windows),m=t.dot?u:l,h=t.dot?d:l,y=t.capture?"":"?:",b={negated:!1,prefix:""},g=t.bash===!0?".*?":f;t.capture&&(g=`(${g})`);let w=I=>I.noglobstar===!0?g:`(${y}(?:(?!${p}${I.dot?c:i}).)*?)`,S=I=>{switch(I){case"*":return`${m}${a}${g}`;case".*":return`${i}${a}${g}`;case"*.*":return`${m}${g}${i}${a}${g}`;case"*/*":return`${m}${g}${o}${a}${h}${g}`;case"**":return m+w(t);case"**/*":return`(?:${m}${w(t)}${o})?${h}${a}${g}`;case"**/*.*":return`(?:${m}${w(t)}${o})?${h}${g}${i}${a}${g}`;case"**/.*":return`(?:${m}${w(t)}${o})?${i}${a}${g}`;default:{let E=/^(.*?)\.(\w+)$/.exec(I);if(!E)return;let T=S(E[1]);return T?T+i+E[2]:void 0}}},_=it.removePrefix(r,b),x=S(_);return x&&t.strictSlashes!==!0&&(x+=`${o}?`),x};Mg.exports=Ud});var jg=$((TN,Dg)=>{"use strict";var iT=Rg(),Bd=Lg(),qg=Qs(),oT=Xs(),aT=r=>r&&typeof r=="object"&&!Array.isArray(r),Ee=(r,e,t=!1)=>{if(Array.isArray(r)){let u=r.map(f=>Ee(f,e,t));return f=>{for(let p of u){let m=p(f);if(m)return m}return!1}}let n=aT(r)&&r.tokens&&r.input;if(r===""||typeof r!="string"&&!n)throw new TypeError("Expected pattern to be a non-empty string");let s=e||{},i=s.windows,o=n?Ee.compileRe(r,e):Ee.makeRe(r,e,!1,!0),a=o.state;delete o.state;let c=()=>!1;if(s.ignore){let u={...e,ignore:null,onMatch:null,onResult:null};c=Ee(s.ignore,u,t)}let l=(u,d=!1)=>{let{isMatch:f,match:p,output:m}=Ee.test(u,o,e,{glob:r,posix:i}),h={glob:r,state:a,regex:o,posix:i,input:u,output:m,match:p,isMatch:f};return typeof s.onResult=="function"&&s.onResult(h),f===!1?(h.isMatch=!1,d?h:!1):c(u)?(typeof s.onIgnore=="function"&&s.onIgnore(h),h.isMatch=!1,d?h:!1):(typeof s.onMatch=="function"&&s.onMatch(h),d?h:!0)};return t&&(l.state=a),l};Ee.test=(r,e,t,{glob:n,posix:s}={})=>{if(typeof r!="string")throw new TypeError("Expected input to be a string");if(r==="")return{isMatch:!1,output:""};let i=t||{},o=i.format||(s?qg.toPosixSlashes:null),a=r===n,c=a&&o?o(r):r;return a===!1&&(c=o?o(r):r,a=c===n),(a===!1||i.capture===!0)&&(i.matchBase===!0||i.basename===!0?a=Ee.matchBase(r,e,t,s):a=e.exec(c)),{isMatch:!!a,match:a,output:c}};Ee.matchBase=(r,e,t,n=t&&t.windows)=>(e instanceof RegExp?e:Ee.makeRe(e,t)).test(qg.basename(r,{windows:n}));Ee.isMatch=(r,e,t)=>Ee(e,t)(r);Ee.parse=(r,e)=>Array.isArray(r)?r.map(t=>Ee.parse(t,e)):Bd(r,{...e,fastpaths:!1});Ee.scan=(r,e)=>iT(r,e);Ee.compileRe=(r,e,t=!1,n=!1)=>{if(t===!0)return r.output;let s=e||{},i=s.contains?"":"^",o=s.contains?"":"$",a=`${i}(?:${r.output})${o}`;r&&r.negated===!0&&(a=`^(?!${a}).*$`);let c=Ee.toRegex(a,e);return n===!0&&(c.state=r),c};Ee.makeRe=(r,e={},t=!1,n=!1)=>{if(!r||typeof r!="string")throw new TypeError("Expected a non-empty string");let s={negated:!1,fastpaths:!0};return e.fastpaths!==!1&&(r[0]==="."||r[0]==="*")&&(s.output=Bd.fastpaths(r,e)),s.output||(s=Bd(r,e)),Ee.compileRe(s,e,t,n)};Ee.toRegex=(r,e)=>{try{let t=e||{};return new RegExp(r,t.flags||(t.nocase?"i":""))}catch(t){if(e&&e.debug===!0)throw t;return/$^/}};Ee.constants=oT;Dg.exports=Ee});var Hd=$((PN,Ug)=>{"use strict";var Fg=jg(),cT=Qs();function Vg(r,e,t=!1){return e&&(e.windows===null||e.windows===void 0)&&(e={...e,windows:cT.isWindows()}),Fg(r,e,t)}Object.assign(Vg,Fg);Ug.exports=Vg});var EO={};W0(EO,{default:()=>Va});module.exports=J0(EO);var M=require("obsidian");var N=class extends Error{constructor(t,n,s){super(n);P(this,"code");P(this,"details");this.code=t,this.details=s,this.name="InteropError"}toPortableError(t){return{code:this.code,message:this.message,...this.details===void 0?{}:{details:this.details},...t===void 0?{}:{retryable:t}}}},ps=class extends Error{constructor(t,n){super(n.message);P(this,"status");P(this,"error");this.status=t,this.error=n,this.name="ActionHandlerError"}};var bm=Hr(Jl(),1),wm=Hr(id(),1);var od={contract:{$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://mdbase.dev/schemas/v0.3/data-contract.schema.json",title:"mdbase v0.3 contract frontmatter",type:"object",required:["kind","contract_type","id","version"],properties:{kind:{const:"mdbase.contract"},contract_type:{enum:["record","event","action"]},id:{$ref:"#/$defs/contractId"},version:{$ref:"#/$defs/semanticVersion"},name:{type:"string",minLength:1},description:{type:"string"},record_schema:{$ref:"#/$defs/schemaWrapper"},binding_schema:{$ref:"#/$defs/schemaWrapper"},data_schema:{$ref:"#/$defs/schemaWrapper"},source_schema:{$ref:"#/$defs/schemaWrapper"},input_schema:{$ref:"#/$defs/schemaWrapper"},output_schema:{$ref:"#/$defs/schemaWrapper"},error_schema:{$ref:"#/$defs/schemaWrapper"},provider_schema:{$ref:"#/$defs/schemaWrapper"},behavior:{$ref:"#/$defs/actionBehavior"}},patternProperties:{"^x-[A-Za-z][A-Za-z0-9._:-]{0,127}$":!0},oneOf:[{properties:{contract_type:{const:"record"},record_schema:!0,binding_schema:!0,data_schema:!1,source_schema:!1,input_schema:!1,output_schema:!1,error_schema:!1,provider_schema:!1,behavior:!1},required:["record_schema"]},{properties:{contract_type:{const:"event"},record_schema:!1,binding_schema:!1,data_schema:!0,source_schema:!0,input_schema:!1,output_schema:!1,error_schema:!1,provider_schema:!1,behavior:!1},required:["data_schema"]},{properties:{contract_type:{const:"action"},record_schema:!1,binding_schema:!1,data_schema:!1,source_schema:!1,input_schema:!0,output_schema:!0,error_schema:!0,provider_schema:!0,behavior:!0},required:["input_schema"]}],additionalProperties:!1,$defs:{contractId:{type:"string",minLength:3,maxLength:128,pattern:"^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)+$"},semanticVersion:{type:"string",pattern:"^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)(?:-[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?(?:\\+[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?$"},schemaWrapper:{type:"object",required:["dialect"],properties:{dialect:{const:"json-schema-2020-12"},value:{type:"object"},ref:{type:"string",minLength:1}},oneOf:[{required:["value"],properties:{value:!0,ref:!1}},{required:["ref"],properties:{ref:!0,value:!1}}],additionalProperties:!1},actionBehavior:{type:"object",properties:{idempotency:{enum:["none","optional","required"]},cancellation:{enum:["none","cooperative"]}},additionalProperties:!1}}},profile:{$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://mdbase.dev/schemas/interop/v0.1/profile.schema.json",title:"mdbase event and action interoperability profile 0.1",oneOf:[{$ref:"#/$defs/event"},{$ref:"#/$defs/actionRequest"},{$ref:"#/$defs/actionInvocation"},{$ref:"#/$defs/actionOutcome"},{$ref:"#/$defs/actionCancellation"},{$ref:"#/$defs/eventSourceDeclaration"},{$ref:"#/$defs/actionProviderDeclaration"},{$ref:"#/$defs/conformanceClaim"}],$defs:{contractId:{type:"string",minLength:3,maxLength:128,pattern:"^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)+$"},semanticVersion:{type:"string",pattern:"^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)(?:-[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?(?:\\+[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?$"},semanticVersionRequirement:{type:"string",minLength:1,maxLength:128},digest:{type:"string",pattern:"^sha256:[0-9a-f]{64}$"},portableId:{type:"string",minLength:1,maxLength:256,pattern:"^[A-Za-z0-9][A-Za-z0-9._:@/-]*$"},exactContract:{type:"object",required:["id","version","digest"],properties:{id:{$ref:"#/$defs/contractId"},version:{$ref:"#/$defs/semanticVersion"},digest:{$ref:"#/$defs/digest"}},additionalProperties:!1},contractRequirement:{type:"object",required:["id","version"],properties:{id:{$ref:"#/$defs/contractId"},version:{$ref:"#/$defs/semanticVersionRequirement"},digest:{$ref:"#/$defs/digest"}},additionalProperties:!1},implementationIdentity:{type:"object",required:["application","implementation","version"],properties:{application:{$ref:"#/$defs/portableId"},implementation:{$ref:"#/$defs/portableId"},version:{$ref:"#/$defs/semanticVersion"},instance_id:{$ref:"#/$defs/portableId"}},additionalProperties:!1},transportCapabilities:{type:"object",required:["delivery","ordering","cancellation","deadlines"],properties:{delivery:{type:"array",minItems:1,uniqueItems:!0,items:{enum:["ephemeral","at_least_once","durable_cursor","offline_queue"]}},ordering:{type:"array",uniqueItems:!0,items:{enum:["none","source","subject"]}},cancellation:{type:"boolean"},deadlines:{type:"boolean"},provider_discovery:{type:"boolean"},max_payload_bytes:{type:"integer",minimum:1},outcome_retention_seconds:{type:"integer",minimum:0},request_deduplication:{type:"boolean"},cross_process_identity:{type:"boolean"}},additionalProperties:!1},extensionValue:{oneOf:[{type:"null"},{type:"boolean"},{type:"integer"},{type:"number"},{type:"string"}]},event:{title:"mdbase CloudEvents event envelope",type:"object",required:["specversion","id","source","type","time","datacontenttype","dataschema","data","mdbaseprofile","mdbasecontractversion","mdbasecontractdigest","mdbaseapplication","mdbaseimplementation","mdbaseimplementationversion"],properties:{specversion:{const:"1.0"},id:{$ref:"#/$defs/portableId"},source:{type:"string",format:"uri-reference",minLength:1},type:{$ref:"#/$defs/contractId"},time:{type:"string",format:"date-time"},subject:{type:"string",format:"uri-reference",minLength:1},datacontenttype:{const:"application/json"},dataschema:{type:"string",format:"uri",minLength:1},data:!0,mdbaseprofile:{const:"0.1"},mdbasecontractversion:{$ref:"#/$defs/semanticVersion"},mdbasecontractdigest:{$ref:"#/$defs/digest"},mdbaseapplication:{$ref:"#/$defs/portableId"},mdbaseimplementation:{$ref:"#/$defs/portableId"},mdbaseimplementationversion:{$ref:"#/$defs/semanticVersion"},mdbaseinstanceid:{$ref:"#/$defs/portableId"},correlationid:{$ref:"#/$defs/portableId"},causationid:{$ref:"#/$defs/portableId"}},propertyNames:{pattern:"^[a-z0-9]+$"},additionalProperties:{$ref:"#/$defs/extensionValue"}},actionRequest:{title:"mdbase action request",type:"object",required:["kind","profile_version","request_id","contract","caller","created_at","input"],properties:{kind:{const:"mdbase.action.request"},profile_version:{const:"0.1"},request_id:{$ref:"#/$defs/portableId"},contract:{$ref:"#/$defs/contractRequirement"},caller:{$ref:"#/$defs/implementationIdentity"},created_at:{type:"string",format:"date-time"},correlation_id:{$ref:"#/$defs/portableId"},causation_id:{$ref:"#/$defs/portableId"},subject:{type:"string",format:"uri-reference",minLength:1},idempotency_key:{type:"string",minLength:1,maxLength:512},deadline:{type:"string",format:"date-time"},requested_provider:{type:"object",properties:{application:{$ref:"#/$defs/portableId"},implementation:{$ref:"#/$defs/portableId"},instance_id:{$ref:"#/$defs/portableId"}},minProperties:1,additionalProperties:!1},authorization_context:{type:"string",format:"uri-reference",minLength:1},input:!0},additionalProperties:!1},actionInvocation:{title:"mdbase admitted action invocation",type:"object",required:["kind","profile_version","invocation_id","attempt_id","request_id","contract","caller","provider","provider_declaration_digest","handler_id","admitted_at","input"],properties:{kind:{const:"mdbase.action.invocation"},profile_version:{const:"0.1"},invocation_id:{$ref:"#/$defs/portableId"},attempt_id:{$ref:"#/$defs/portableId"},request_id:{$ref:"#/$defs/portableId"},contract:{$ref:"#/$defs/exactContract"},caller:{$ref:"#/$defs/implementationIdentity"},provider:{$ref:"#/$defs/implementationIdentity"},provider_declaration_digest:{$ref:"#/$defs/digest"},handler_id:{$ref:"#/$defs/portableId"},admitted_at:{type:"string",format:"date-time"},correlation_id:{$ref:"#/$defs/portableId"},causation_id:{$ref:"#/$defs/portableId"},subject:{type:"string",format:"uri-reference",minLength:1},idempotency_key:{type:"string",minLength:1,maxLength:512},deadline:{type:"string",format:"date-time"},authorization_context:{type:"string",format:"uri-reference",minLength:1},input:!0},additionalProperties:!1},portableError:{type:"object",required:["code","message"],properties:{code:{enum:["unknown_contract","unsupported_contract_version","contract_digest_conflict","invalid_event_data","invalid_action_input","invalid_action_output","no_provider","ambiguous_provider","requested_provider_unavailable","unauthorized","capability_denied","request_rejected","deadline_exceeded","cancellation_unsupported","cancelled","handler_failure","outcome_indeterminate","transport_unavailable","unsupported_transport_capability"]},message:{type:"string",minLength:1},details:!0,retryable:{type:"boolean"}},additionalProperties:!1},actionOutcome:{title:"mdbase action outcome",type:"object",required:["kind","profile_version","outcome_id","request_id","invocation_id","attempt_id","contract","provider","provider_declaration_digest","status","completed_at"],properties:{kind:{const:"mdbase.action.outcome"},profile_version:{const:"0.1"},outcome_id:{$ref:"#/$defs/portableId"},request_id:{$ref:"#/$defs/portableId"},invocation_id:{$ref:"#/$defs/portableId"},attempt_id:{$ref:"#/$defs/portableId"},contract:{$ref:"#/$defs/exactContract"},provider:{$ref:"#/$defs/implementationIdentity"},provider_declaration_digest:{$ref:"#/$defs/digest"},status:{enum:["succeeded","rejected","failed","cancelled","outcome_indeterminate"]},completed_at:{type:"string",format:"date-time"},output:!0,error:{$ref:"#/$defs/portableError"}},allOf:[{if:{properties:{status:{const:"succeeded"}},required:["status"]},then:{required:["output"],not:{required:["error"]}},else:{required:["error"],not:{required:["output"]}}}],additionalProperties:!1},actionCancellation:{title:"mdbase action cancellation request",type:"object",required:["kind","profile_version","cancellation_id","request_id","caller","requested_at"],properties:{kind:{const:"mdbase.action.cancel"},profile_version:{const:"0.1"},cancellation_id:{$ref:"#/$defs/portableId"},request_id:{$ref:"#/$defs/portableId"},caller:{$ref:"#/$defs/implementationIdentity"},requested_at:{type:"string",format:"date-time"},reason:{type:"string",maxLength:1024}},additionalProperties:!1},eventSourceDeclaration:{title:"mdbase event-source declaration",type:"object",required:["kind","profile_version","declaration_id","declaration_digest","source","contracts"],properties:{kind:{const:"mdbase.event-source"},profile_version:{const:"0.1"},declaration_id:{$ref:"#/$defs/portableId"},declaration_digest:{$ref:"#/$defs/digest"},source:{$ref:"#/$defs/implementationIdentity"},contracts:{type:"array",minItems:1,items:{type:"object",required:["requirement","resolved"],properties:{requirement:{$ref:"#/$defs/contractRequirement"},resolved:{$ref:"#/$defs/exactContract"},binding:!0,ordering:{type:"array",uniqueItems:!0,items:{enum:["none","source","subject"]}}},additionalProperties:!1}}},additionalProperties:!1},actionProviderDeclaration:{title:"mdbase action-provider declaration",type:"object",required:["kind","profile_version","declaration_id","declaration_digest","provider","handlers"],properties:{kind:{const:"mdbase.action-provider"},profile_version:{const:"0.1"},declaration_id:{$ref:"#/$defs/portableId"},declaration_digest:{$ref:"#/$defs/digest"},provider:{$ref:"#/$defs/implementationIdentity"},handlers:{type:"array",minItems:1,items:{type:"object",required:["handler_id","requirement","resolved"],properties:{handler_id:{$ref:"#/$defs/portableId"},requirement:{$ref:"#/$defs/contractRequirement"},resolved:{$ref:"#/$defs/exactContract"},binding:!0,idempotency:{type:"object",required:["mode"],properties:{mode:{enum:["none","request"]},retention_seconds:{type:"integer",minimum:1}},additionalProperties:!1},cancellation:{enum:["none","cooperative"]},max_concurrency:{type:"integer",minimum:1}},additionalProperties:!1}}},additionalProperties:!1},conformanceClaim:{title:"mdbase interoperability conformance claim",type:"object",required:["kind","profile_version","implementation","roles","transport"],properties:{kind:{const:"mdbase.interop.conformance"},profile_version:{const:"0.1"},implementation:{$ref:"#/$defs/implementationIdentity"},roles:{type:"array",minItems:1,uniqueItems:!0,items:{enum:["event_source","event_consumer","action_caller","action_provider","bridge"]}},transport:{$ref:"#/$defs/transportCapabilities"},evidence:{type:"array",items:{type:"object",required:["scenario","result"],properties:{scenario:{type:"string",minLength:1},result:{const:"pass"},uri:{type:"string",format:"uri-reference"}},additionalProperties:!1}}},additionalProperties:!1}}},event:{$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://mdbase.dev/schemas/interop/v0.1/event.schema.json",title:"mdbase CloudEvents event envelope",$ref:"profile.schema.json#/$defs/event"},actionRequest:{$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://mdbase.dev/schemas/interop/v0.1/action-request.schema.json",title:"mdbase action request",$ref:"profile.schema.json#/$defs/actionRequest"},actionInvocation:{$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://mdbase.dev/schemas/interop/v0.1/action-invocation.schema.json",title:"mdbase admitted action invocation",$ref:"profile.schema.json#/$defs/actionInvocation"},actionOutcome:{$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://mdbase.dev/schemas/interop/v0.1/action-outcome.schema.json",title:"mdbase action outcome",$ref:"profile.schema.json#/$defs/actionOutcome"},actionCancellation:{$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://mdbase.dev/schemas/interop/v0.1/action-cancellation.schema.json",title:"mdbase action cancellation request",$ref:"profile.schema.json#/$defs/actionCancellation"},eventSourceDeclaration:{$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://mdbase.dev/schemas/interop/v0.1/event-source-declaration.schema.json",title:"mdbase event-source declaration",$ref:"profile.schema.json#/$defs/eventSourceDeclaration"},actionProviderDeclaration:{$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://mdbase.dev/schemas/interop/v0.1/action-provider-declaration.schema.json",title:"mdbase action-provider declaration",$ref:"profile.schema.json#/$defs/actionProviderDeclaration"},conformanceClaim:{$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://mdbase.dev/schemas/interop/v0.1/conformance-claim.schema.json",title:"mdbase interoperability conformance claim",$ref:"profile.schema.json#/$defs/conformanceClaim"}};var uA=wm.default;function _m(){return Object.fromEntries(Object.entries(od).map(([r,e])=>[r,structuredClone(e)]))}function ad(){let r=new bm.Ajv2020({allErrors:!0,strict:!1,validateFormats:!0});uA(r);let e=_m();r.addSchema(e.profile);for(let[t,n]of Object.entries(e))t!=="profile"&&r.addSchema(n);return r}function ir(r,e){let t=String(od[e].$id),n=r.getSchema(t);if(!n)throw new Error(`Canonical interoperability schema is unavailable: ${e}`);return n}function Pr(r){return(r!=null?r:[]).map(e=>{var t;return`${e.instancePath||"/"} ${(t=e.message)!=null?t:e.keyword}`}).join("; ")}function Kt(r,e){if(!("value"in r))throw new N("contract_digest_conflict",`${e} must be resolved to an inline JSON Schema before runtime registration.`);return structuredClone(r.value)}function vm(r){let e={kind:r.kind,contract_type:r.contract_type,id:r.id,version:r.version};switch(r.contract_type){case"record":e.record_schema=Kt(r.record_schema,"record_schema"),r.binding_schema&&(e.binding_schema=Kt(r.binding_schema,"binding_schema"));break;case"event":e.data_schema=Kt(r.data_schema,"data_schema"),r.source_schema&&(e.source_schema=Kt(r.source_schema,"source_schema"));break;case"action":e.input_schema=Kt(r.input_schema,"input_schema"),r.output_schema&&(e.output_schema=Kt(r.output_schema,"output_schema")),r.error_schema&&(e.error_schema=Kt(r.error_schema,"error_schema")),r.provider_schema&&(e.provider_schema=Kt(r.provider_schema,"provider_schema")),r.behavior&&(e.behavior=structuredClone(r.behavior));break}return e}async function _o(r){return Fn(vm(r))}async function Fn(r){return`sha256:${await fA(cd(r))}`}function $m(r,e){return{data:jn(r,e.data_schema,`${e.id} data_schema`),...e.source_schema?{source:jn(r,e.source_schema,`${e.id} source_schema`)}:{}}}function Sm(r,e){return{input:jn(r,e.input_schema,`${e.id} input_schema`),...e.output_schema?{output:jn(r,e.output_schema,`${e.id} output_schema`)}:{},...e.error_schema?{error:jn(r,e.error_schema,`${e.id} error_schema`)}:{},...e.provider_schema?{provider:jn(r,e.provider_schema,`${e.id} provider_schema`)}:{}}}function vo(r,e,t,n){if(!(!r||r(e)))throw new N(t,`${n} failed JSON Schema validation: ${Pr(r.errors)}`)}function jn(r,e,t){try{return r.compile(Kt(e,t))}catch(n){throw new N("contract_digest_conflict",`${t} could not be compiled: ${n instanceof Error?n.message:String(n)}`)}}function cd(r){return r===null||typeof r!="object"?JSON.stringify(r):Array.isArray(r)?`[${r.map(cd).join(",")}]`:`{${Object.entries(r).filter(([,t])=>t!==void 0).sort(([t],[n])=>tn?1:0).map(([t,n])=>`${JSON.stringify(t)}:${cd(n)}`).join(",")}}`}async function fA(r){let e=new TextEncoder().encode(r),t=await globalThis.crypto.subtle.digest("SHA-256",e);return[...new Uint8Array(t)].map(n=>n.toString(16).padStart(2,"0")).join("")}var ar=Hr(hg(),1);var Td={delivery:["ephemeral"],ordering:["none"],cancellation:!0,deadlines:!0,provider_discovery:!0,request_deduplication:!0,cross_process_identity:!1},_I=new Set(["specversion","id","source","type","time","subject","datacontenttype","dataschema","data","mdbaseprofile","mdbasecontractversion","mdbasecontractdigest","mdbaseapplication","mdbaseimplementation","mdbaseimplementationversion","mdbaseinstanceid","correlationid","causationid"]),Ys=class{constructor(e={}){P(this,"options");P(this,"profileVersion","0.1");P(this,"transport");P(this,"ajv",ad());P(this,"contractValidator",ir(this.ajv,"contract"));P(this,"eventValidator",ir(this.ajv,"event"));P(this,"actionRequestValidator",ir(this.ajv,"actionRequest"));P(this,"actionInvocationValidator",ir(this.ajv,"actionInvocation"));P(this,"actionOutcomeValidator",ir(this.ajv,"actionOutcome"));P(this,"eventSourceDeclarationValidator",ir(this.ajv,"eventSourceDeclaration"));P(this,"actionProviderDeclarationValidator",ir(this.ajv,"actionProviderDeclaration"));P(this,"contracts",new Map);P(this,"clients",new Map);P(this,"eventSources",new Map);P(this,"actionProviders",new Map);P(this,"subscriptions",new Map);P(this,"activeActions",new Map);P(this,"completedActions",new Map);P(this,"admissionLocks",new Map);P(this,"recentEvents",new Map);P(this,"authorize");P(this,"now");P(this,"idFactory");P(this,"recentEventLimit");P(this,"completedRequestLimit");P(this,"nextSequence",0);P(this,"disposed",!1);var t,n,s,i,o,a,c,l,u,d;this.options=e,this.authorize=(t=e.authorize)!=null?t:(()=>!1),this.now=(n=e.now)!=null?n:(()=>new Date),this.idFactory=(s=e.idFactory)!=null?s:(f=>{var m;this.nextSequence+=1;let p=typeof((m=globalThis.crypto)==null?void 0:m.randomUUID)=="function"?globalThis.crypto.randomUUID():`${this.now().getTime().toString(36)}-${this.nextSequence.toString(36)}`;return`${f}_${p}`}),this.recentEventLimit=Math.max(1,(i=e.recentEventLimit)!=null?i:1e3),this.completedRequestLimit=Math.max(1,(o=e.completedRequestLimit)!=null?o:1e3),this.transport={...Td,...structuredClone((a=e.transport)!=null?a:{}),delivery:[...(l=(c=e.transport)==null?void 0:c.delivery)!=null?l:Td.delivery],ordering:[...(d=(u=e.transport)==null?void 0:u.ordering)!=null?d:Td.ordering]}}connect(e){this.assertActive(),vI(e);let t=this.idFactory("client"),n={identity:structuredClone(e),disposed:!1,sources:new Set,providers:new Set,subscriptions:new Set};return this.clients.set(t,n),{identity:structuredClone(e),registerEventSource:s=>this.registerEventSource(t,s),publishEvent:s=>this.publishEvent(t,s),subscribeEvents:(s,i)=>this.subscribeEvents(t,s,i),registerActionProvider:s=>this.registerActionProvider(t,s),invokeAction:s=>this.invokeAction(t,s),cancelAction:(s,i)=>this.cancelAction(t,s,i),dispose:()=>this.disposeClient(t)}}describe(){return this.assertActive(),{profile_version:"0.1",transport:structuredClone(this.transport),contracts:[...this.contracts.values()].map(({artifact:e,reference:t})=>({artifact:structuredClone(e),reference:structuredClone(t)})).sort((e,t)=>e.reference.id.localeCompare(t.reference.id)||e.reference.version.localeCompare(t.reference.version)),event_sources:[...this.eventSources.values()].map(({declaration:e})=>structuredClone(e)).sort((e,t)=>e.declaration_id.localeCompare(t.declaration_id)),action_providers:[...this.actionProviders.values()].map(({declaration:e})=>structuredClone(e)).sort((e,t)=>e.declaration_id.localeCompare(t.declaration_id))}}async dispose(){if(!this.disposed){this.disposed=!0;for(let e of[...this.clients.keys()])await this.disposeClient(e,!0);this.contracts.clear(),this.recentEvents.clear(),this.completedActions.clear()}}async registerEventSource(e,t){var l;let n=this.requireClient(e);if(t.contracts.length===0)throw new N("request_rejected","An event-source declaration must include a contract.");let s=`${e}:${t.declaration_id}`;if(this.eventSources.has(s))throw new N("request_rejected",`Event-source declaration ${t.declaration_id} is already registered.`);let i=new Map;for(let u of t.contracts){let d=await this.prepareEventContract(u.contract),f=mg(u.requirement,d.reference);if(yg(f,d.reference),await this.assertAuthorized({operation:"register_event_source",principal:n.identity,contract:d.reference}),d.sourceValidator&&!d.sourceValidator((l=u.binding)!=null?l:{}))throw new N("request_rejected",`${d.reference.id} source binding is invalid: ${Pr(d.sourceValidator.errors)}`);let p=No(d.reference);if(i.has(p))throw new N("contract_digest_conflict",`Event contract ${p} is repeated by one declaration.`);i.set(p,{contract:d,requirement:f,...u.binding===void 0?{}:{binding:structuredClone(u.binding)},...u.ordering===void 0?{}:{ordering:[...u.ordering]}})}let o={kind:"mdbase.event-source",profile_version:"0.1",declaration_id:t.declaration_id,source:structuredClone(n.identity),contracts:[...i.values()].map(({contract:u,requirement:d,binding:f,ordering:p})=>({requirement:structuredClone(d),resolved:structuredClone(u.reference),...f===void 0?{}:{binding:f},...p===void 0?{}:{ordering:p}}))},a={...o,declaration_digest:await Fn(o)};Rr(this.eventSourceDeclarationValidator,a,"request_rejected","Event-source declaration"),this.commitContracts([...i.values()].map(({contract:u})=>u)),this.eventSources.set(s,{id:s,clientId:e,declaration:structuredClone(a),contracts:new Map([...i.entries()].map(([u,d])=>[u,{contract:d.contract,...d.binding===void 0?{}:{binding:d.binding}}]))}),n.sources.add(s);let c=!0;return{declaration:structuredClone(a),dispose:()=>{c&&(c=!1,this.removeEventSource(s))}}}async publishEvent(e,t){var m,h,y,b;let n=this.requireClient(e),s=No(t.contract),i=[...n.sources].map(g=>this.eventSources.get(g)).find(g=>g==null?void 0:g.contracts.has(s));if(!i)throw new N("unknown_contract",`This client has not registered event contract ${t.contract.id} ${t.contract.version}.`);let o=(m=i.contracts.get(s))==null?void 0:m.contract;if(!o)throw new N("unknown_contract",`Event contract ${s} is unavailable.`);if(t.contract.digest&&t.contract.digest!==o.reference.digest)throw new N("contract_digest_conflict",`Event contract ${s} has a different digest.`);await this.assertAuthorized({operation:"publish_event",principal:n.identity,contract:o.reference,...t.subject===void 0?{}:{subject:t.subject}}),Pd(t.data,"invalid_event_data",`Event ${o.reference.id} data`),vo(o.dataValidator,t.data,"invalid_event_data",`Event ${o.reference.id} data`);let a=(h=t.extensions)!=null?h:{};for(let g of Object.keys(a))if(_I.has(g))throw new N("request_rejected",`Event extension ${g} is reserved.`);let c={...structuredClone(a),specversion:"1.0",id:(y=t.id)!=null?y:this.idFactory("evt"),source:$I(n.identity),type:o.reference.id,time:(b=t.time)!=null?b:this.now().toISOString(),...t.subject===void 0?{}:{subject:t.subject},datacontenttype:"application/json",dataschema:wg(o.reference),data:structuredClone(t.data),mdbaseprofile:"0.1",mdbasecontractversion:o.reference.version,mdbasecontractdigest:o.reference.digest,mdbaseapplication:n.identity.application,mdbaseimplementation:n.identity.implementation,mdbaseimplementationversion:n.identity.version,...n.identity.instance_id===void 0?{}:{mdbaseinstanceid:n.identity.instance_id},...t.correlation_id===void 0?{}:{correlationid:t.correlation_id},...t.causation_id===void 0?{}:{causationid:t.causation_id}};Rr(this.eventValidator,c,"invalid_event_data","Event envelope"),Od(this.transport,c),SI(c,o.reference);let l=`${c.source}\0${c.id}`,u=this.recentEvents.get(l);if(u){if(JSON.stringify(u)!==JSON.stringify(c))throw new N("contract_digest_conflict",`Event ${c.source} ${c.id} was reused with different content.`);return{event:structuredClone(u),deliveries:0,duplicate:!0}}this.recentEvents.set(l,structuredClone(c)),bg(this.recentEvents,this.recentEventLimit);let d=[...this.subscriptions.values()].filter(({subscription:g})=>Mo(g.contract,o.reference)),f=await Promise.allSettled(d.map(async g=>await this.isAuthorized({operation:"subscribe_event",principal:g.principal,contract:o.reference,...c.subject===void 0?{}:{subject:c.subject}})?(await g.handler(structuredClone(c)),!0):!1)),p=0;for(let g of f)g.status==="fulfilled"&&g.value?p+=1:g.status==="rejected"&&this.report({severity:"error",code:"event_consumer_failed",message:`An event consumer failed while handling ${c.type}.`,contract:o.reference,cause:g.reason});return{event:structuredClone(c),deliveries:p,duplicate:!1}}async subscribeEvents(e,t,n){let s=this.requireClient(e);Rd(t.contract),kI(this.transport,t.require_transport),await this.assertAuthorized({operation:"subscribe_event",principal:s.identity,contract:t.contract});let i=this.idFactory("subscription");this.subscriptions.set(i,{id:i,clientId:e,principal:structuredClone(s.identity),subscription:structuredClone(t),handler:n}),s.subscriptions.add(i);let o=!0;return{dispose:()=>{o&&(o=!1,this.removeSubscription(i))}}}async registerActionProvider(e,t){var d,f,p,m,h,y,b;let n=this.requireClient(e);if(t.handlers.length===0)throw new N("request_rejected","An action-provider declaration must include a handler.");let s=`${e}:${t.declaration_id}`;if(this.actionProviders.has(s))throw new N("request_rejected",`Action-provider declaration ${t.declaration_id} is already registered.`);let i=[],o=new Set;for(let g of t.handlers){if(o.has(g.handler_id))throw new N("request_rejected",`Handler ${g.handler_id} is repeated.`);o.add(g.handler_id);let w=await this.prepareActionContract(g.contract),S=mg(g.requirement,w.reference);if(yg(S,w.reference),await this.assertAuthorized({operation:"register_action_provider",principal:n.identity,contract:w.reference,provider:n.identity}),w.providerValidator&&!w.providerValidator((d=g.binding)!=null?d:{}))throw new N("request_rejected",`${w.reference.id} provider binding is invalid: ${Pr(w.providerValidator.errors)}`);let _=(p=(f=g.contract.behavior)==null?void 0:f.idempotency)!=null?p:"none";if(((m=g.idempotency)==null?void 0:m.mode)==="request"&&_==="none")throw new N("request_rejected",`${w.reference.id} does not permit request deduplication.`);if(_==="required"&&((h=g.idempotency)==null?void 0:h.mode)!=="request")throw new N("request_rejected",`${w.reference.id} requires a provider with request deduplication.`);let x=(b=(y=g.contract.behavior)==null?void 0:y.cancellation)!=null?b:"none";if(g.cancellation==="cooperative"&&x!=="cooperative")throw new N("request_rejected",`${w.reference.id} does not declare cooperative cancellation.`);i.push({contract:w,declaration:{handler_id:g.handler_id,requirement:S,resolved:structuredClone(w.reference),...g.binding===void 0?{}:{binding:structuredClone(g.binding)},...g.idempotency===void 0?{}:{idempotency:structuredClone(g.idempotency)},...g.cancellation===void 0?{}:{cancellation:g.cancellation},...g.max_concurrency===void 0?{}:{max_concurrency:g.max_concurrency}},handler:g.handler})}let a={kind:"mdbase.action-provider",profile_version:"0.1",declaration_id:t.declaration_id,provider:structuredClone(n.identity),handlers:i.map(({declaration:g})=>structuredClone(g))},c={...a,declaration_digest:await Fn(a)};Rr(this.actionProviderDeclarationValidator,c,"request_rejected","Action-provider declaration"),this.commitContracts(i.map(({contract:g})=>g));let l=i.map(({contract:g,declaration:w,handler:S})=>({registrationId:s,clientId:e,declaration:structuredClone(c),handlerDeclaration:structuredClone(w),contract:g,handler:S,active:0}));this.actionProviders.set(s,{id:s,clientId:e,declaration:structuredClone(c),handlers:l}),n.providers.add(s);let u=!0;return{declaration:structuredClone(c),dispose:()=>{u&&(u=!1,this.removeActionProvider(s))}}}async invokeAction(e,t){var a,c,l,u,d,f,p,m,h,y,b,g;let n=this.requireClient(e);Rd(t.contract);let s=(a=t.request_id)!=null?a:this.idFactory("req");this.cleanCompletedActions(),Pd(t.input,"invalid_action_input",`Action ${t.contract.id} input`);let i={kind:"mdbase.action.request",profile_version:"0.1",request_id:s,contract:structuredClone(t.contract),caller:structuredClone(n.identity),created_at:(c=t.created_at)!=null?c:this.now().toISOString(),...t.correlation_id===void 0?{}:{correlation_id:t.correlation_id},...t.causation_id===void 0?{}:{causation_id:t.causation_id},...t.subject===void 0?{}:{subject:t.subject},...t.idempotency_key===void 0?{}:{idempotency_key:t.idempotency_key},...t.deadline===void 0?{}:{deadline:t.deadline},...t.requested_provider===void 0?{}:{requested_provider:structuredClone(t.requested_provider)},input:structuredClone(t.input)};Rr(this.actionRequestValidator,i,"request_rejected","Action request"),Od(this.transport,i);let o=await this.acquireAdmission(s);try{let w=await Fn(EI(i)),S=this.activeActions.get(s);if(S){if(gg(e,s,w,S),((l=S.handler.handlerDeclaration.idempotency)==null?void 0:l.mode)!=="request")throw new N("request_rejected",`Action request ${s} is already active without deduplication.`);return structuredClone(await S.promise)}let _=this.completedActions.get(s);if(_){if(gg(e,s,w,_),!_.reusable)throw new N("request_rejected",`Action request ${s} was already completed without deduplication.`);return structuredClone(_.outcome)}if(i.deadline&&new Date(i.deadline).getTime()<=this.now().getTime())throw new N("deadline_exceeded",`Action request ${s} passed its deadline before admission.`);if(i.deadline&&!this.transport.deadlines)throw new N("unsupported_transport_capability","The active transport cannot enforce action deadlines.");let x=this.resolveActionCandidates(i.contract,i.requested_provider);x.length===0&&this.throwResolutionFailure(i.contract,i.requested_provider);let I=[];for(let ae of x)await this.isAuthorized({operation:"invoke_action",principal:n.identity,contract:ae.contract.reference,provider:ae.declaration.provider,...i.subject===void 0?{}:{subject:i.subject}})&&I.push(ae);if(I.length===0)throw new N("unauthorized",`No authorized provider can execute ${i.contract.id}.`);if(I.length>1)throw new N("ambiguous_provider",`Action ${i.contract.id} has ${I.length} eligible providers; select one explicitly.`);let E=I[0];if(E.handlerDeclaration.max_concurrency!==void 0&&E.active>=E.handlerDeclaration.max_concurrency)throw new N("request_rejected",`Provider ${E.declaration.provider.implementation} is at capacity.`);if(((d=(u=E.contract.artifact.behavior)==null?void 0:u.idempotency)!=null?d:"none")==="required"&&!i.idempotency_key)throw new N("request_rejected",`${E.contract.reference.id} requires an idempotency key.`);vo(E.contract.inputValidator,i.input,"invalid_action_input",`Action ${E.contract.reference.id} input`);let v={operation:"invoke_action",principal:n.identity,contract:E.contract.reference,provider:E.declaration.provider,...i.subject===void 0?{}:{subject:i.subject}},F=await((p=(f=this.options).authorizationContext)==null?void 0:p.call(f,v)),V={kind:"mdbase.action.invocation",profile_version:"0.1",invocation_id:this.idFactory("inv"),attempt_id:this.idFactory("attempt"),request_id:s,contract:structuredClone(E.contract.reference),caller:structuredClone(n.identity),provider:structuredClone(E.declaration.provider),provider_declaration_digest:E.declaration.declaration_digest,handler_id:E.handlerDeclaration.handler_id,admitted_at:this.now().toISOString(),...i.correlation_id===void 0?{}:{correlation_id:i.correlation_id},...i.causation_id===void 0?{}:{causation_id:i.causation_id},...i.subject===void 0?{}:{subject:i.subject},...i.idempotency_key===void 0?{}:{idempotency_key:i.idempotency_key},...i.deadline===void 0?{}:{deadline:i.deadline},...F===void 0?{}:{authorization_context:F},input:structuredClone(i.input)};Rr(this.actionInvocationValidator,V,"request_rejected","Action invocation"),await((h=(m=this.options).onInvocation)==null?void 0:h.call(m,structuredClone(V)));let G=new AbortController,A;if(V.deadline){let ae=Math.max(0,new Date(V.deadline).getTime()-this.now().getTime());A=setTimeout(()=>G.abort(new N("deadline_exceeded",`Action request ${s} exceeded its deadline.`)),ae)}E.active+=1;let k=this.executeAction(E,V,G).finally(()=>{A!==void 0&&clearTimeout(A),E.active=Math.max(0,E.active-1),this.activeActions.delete(s)});this.activeActions.set(s,{clientId:e,requestId:s,requestDigest:w,handler:E,invocation:V,controller:G,promise:k}),o();let Re=await k,oe=(b=(y=E.handlerDeclaration.idempotency)==null?void 0:y.retention_seconds)!=null?b:300;return this.completedActions.set(s,{clientId:e,requestDigest:w,outcome:structuredClone(Re),reusable:((g=E.handlerDeclaration.idempotency)==null?void 0:g.mode)==="request",expiresAt:this.now().getTime()+oe*1e3}),bg(this.completedActions,this.completedRequestLimit),structuredClone(Re)}finally{o()}}async executeAction(e,t,n){var s;try{let i=await e.handler(structuredClone(t.input),{invocation:structuredClone(t),signal:n.signal});if(n.signal.aborted){let a=n.signal.reason;return a instanceof N&&a.code==="deadline_exceeded"?this.failureOutcome(t,"failed",a.toPortableError()):this.failureOutcome(t,"cancelled",{code:"cancelled",message:`Action request ${t.request_id} was cancelled.`})}Pd(i,"invalid_action_output",`Action ${e.contract.reference.id} output`),vo(e.contract.outputValidator,i,"invalid_action_output",`Action ${e.contract.reference.id} output`);let o={kind:"mdbase.action.outcome",profile_version:"0.1",outcome_id:this.idFactory("outcome"),request_id:t.request_id,invocation_id:t.invocation_id,attempt_id:t.attempt_id,contract:structuredClone(t.contract),provider:structuredClone(t.provider),provider_declaration_digest:t.provider_declaration_digest,status:"succeeded",completed_at:this.now().toISOString(),output:structuredClone(i)};return Rr(this.actionOutcomeValidator,o,"invalid_action_output","Action outcome"),Od(this.transport,o),o}catch(i){if(i instanceof ps)return e.contract.errorValidator&&!e.contract.errorValidator((s=i.error.details)!=null?s:{})?this.failureOutcome(t,"failed",{code:"handler_failure",message:`Provider returned invalid declared error details: ${Pr(e.contract.errorValidator.errors)}`}):this.failureOutcome(t,i.status,i.error);if(i instanceof N)return this.failureOutcome(t,i.code==="cancelled"?"cancelled":i.code==="outcome_indeterminate"?"outcome_indeterminate":"failed",i.toPortableError());if(n.signal.aborted||xI(i)){let o=n.signal.reason;return o instanceof N&&o.code==="deadline_exceeded"?this.failureOutcome(t,"failed",o.toPortableError()):this.failureOutcome(t,"cancelled",{code:"cancelled",message:`Action request ${t.request_id} was cancelled.`})}return this.report({severity:"error",code:"action_handler_failed",message:`Provider ${t.provider.implementation} failed ${t.contract.id}.`,principal:t.provider,contract:t.contract,cause:i}),this.failureOutcome(t,"failed",{code:"handler_failure",message:"The selected provider failed while executing the action."})}}failureOutcome(e,t,n){let s={kind:"mdbase.action.outcome",profile_version:"0.1",outcome_id:this.idFactory("outcome"),request_id:e.request_id,invocation_id:e.invocation_id,attempt_id:e.attempt_id,contract:structuredClone(e.contract),provider:structuredClone(e.provider),provider_declaration_digest:e.provider_declaration_digest,status:t,completed_at:this.now().toISOString(),error:structuredClone(n)};return Rr(this.actionOutcomeValidator,s,"invalid_action_output","Action outcome"),s}async cancelAction(e,t,n){let s=this.requireClient(e),i=this.admissionLocks.get(t);i&&await i;let o=this.activeActions.get(t);if(!o){let a=this.completedActions.get(t);if(a&&a.clientId!==e)throw new N("unauthorized",`Action request ${t} belongs to another caller.`);return a?structuredClone(a.outcome):null}if(o.clientId!==e)throw new N("unauthorized",`Action request ${t} belongs to another caller.`);if(await this.assertAuthorized({operation:"cancel_action",principal:s.identity,contract:o.invocation.contract,provider:o.invocation.provider,...o.invocation.subject===void 0?{}:{subject:o.invocation.subject}}),!this.transport.cancellation)throw new N("unsupported_transport_capability","The active transport cannot deliver cancellation.");if(o.handler.handlerDeclaration.cancellation!=="cooperative")throw new N("cancellation_unsupported",`Provider ${o.invocation.provider.implementation} does not support cancellation.`);return o.controller.abort(new N("cancelled",(n==null?void 0:n.trim())||`Action request ${t} was cancelled.`)),structuredClone(await o.promise)}resolveActionCandidates(e,t){let n=[...this.actionProviders.values()].flatMap(({handlers:i})=>i).filter(({contract:i,declaration:o})=>Mo(e,i.reference)&&AI(t,o.provider)),s=(0,ar.maxSatisfying)([...new Set(n.map(({contract:i})=>i.reference.version))],e.version,{includePrerelease:!0});return s?n.filter(({contract:i})=>i.reference.version===s).sort((i,o)=>{var a,c;return i.declaration.provider.application.localeCompare(o.declaration.provider.application)||i.declaration.provider.implementation.localeCompare(o.declaration.provider.implementation)||((a=i.declaration.provider.instance_id)!=null?a:"").localeCompare((c=o.declaration.provider.instance_id)!=null?c:"")||i.handlerDeclaration.handler_id.localeCompare(o.handlerDeclaration.handler_id)}):[]}throwResolutionFailure(e,t){let n=[...this.contracts.values()].filter(s=>s.artifact.contract_type==="action"&&s.reference.id===e.id);throw n.length===0?new N("unknown_contract",`Action contract ${e.id} is unknown.`):n.some(({reference:s})=>Mo(e,s))?t?new N("requested_provider_unavailable",`The requested provider is unavailable for ${e.id}.`):new N("no_provider",`No provider is registered for ${e.id}.`):new N("unsupported_contract_version",`No ${e.id} artifact satisfies ${e.version}.`)}async prepareEventContract(e){if(this.assertContractArtifact(e),e.contract_type!=="event")throw new N("unknown_contract",`${e.id} is not an event contract.`);let t={id:e.id,version:e.version,digest:await _o(e)};this.assertNoContractConflict(t);let n=$m(this.ajv,e);return{artifact:structuredClone(e),reference:t,dataValidator:n.data,...n.source===void 0?{}:{sourceValidator:n.source}}}async prepareActionContract(e){if(this.assertContractArtifact(e),e.contract_type!=="action")throw new N("unknown_contract",`${e.id} is not an action contract.`);let t={id:e.id,version:e.version,digest:await _o(e)};this.assertNoContractConflict(t);let n=Sm(this.ajv,e);return{artifact:structuredClone(e),reference:t,inputValidator:n.input,...n.output===void 0?{}:{outputValidator:n.output},...n.error===void 0?{}:{errorValidator:n.error},...n.provider===void 0?{}:{providerValidator:n.provider}}}assertContractArtifact(e){if(Rr(this.contractValidator,e,"contract_digest_conflict",`Contract ${e.id||""}`),!(0,ar.valid)(e.version))throw new N("unsupported_contract_version",`${e.id} version must be exact SemVer.`)}assertNoContractConflict(e){let t=this.contracts.get(No(e));if(t&&t.reference.digest!==e.digest)throw new N("contract_digest_conflict",`Contract ${e.id} ${e.version} conflicts with the registered artifact.`)}commitContracts(e){var n;let t=new Map;for(let s of e){let i=No(s.reference),o=(n=t.get(i))!=null?n:this.contracts.get(i);if(o&&o.reference.digest!==s.reference.digest)throw new N("contract_digest_conflict",`Contract ${s.reference.id} ${s.reference.version} conflicts within the registration.`);t.set(i,s)}for(let[s,i]of t)this.contracts.has(s)||this.contracts.set(s,i)}async disposeClient(e,t=!1){let n=this.clients.get(e);if(!(!n||n.disposed)){n.disposed=!0;for(let s of[...n.subscriptions])this.removeSubscription(s);for(let s of[...n.sources])this.removeEventSource(s);for(let s of[...n.providers])this.removeActionProvider(s);for(let s of[...this.activeActions.values()])s.clientId===e&&s.handler.handlerDeclaration.cancellation==="cooperative"&&s.controller.abort(new N("cancelled","The caller unloaded.")),s.handler.clientId===e&&s.handler.handlerDeclaration.cancellation==="cooperative"&&s.controller.abort(new N("cancelled","The provider unloaded."));this.clients.delete(e),t||this.assertActive()}}removeEventSource(e){var n;let t=this.eventSources.get(e);t&&(this.eventSources.delete(e),(n=this.clients.get(t.clientId))==null||n.sources.delete(e))}removeActionProvider(e){var n;let t=this.actionProviders.get(e);if(t){this.actionProviders.delete(e),(n=this.clients.get(t.clientId))==null||n.providers.delete(e);for(let s of this.activeActions.values())s.handler.registrationId===e&&s.handler.handlerDeclaration.cancellation==="cooperative"&&s.controller.abort(new N("cancelled","The provider unloaded."))}}removeSubscription(e){var n;let t=this.subscriptions.get(e);t&&(this.subscriptions.delete(e),(n=this.clients.get(t.clientId))==null||n.subscriptions.delete(e))}requireClient(e){this.assertActive();let t=this.clients.get(e);if(!t||t.disposed)throw new N("transport_unavailable","Interop client is disposed.");return t}assertActive(){if(this.disposed)throw new N("transport_unavailable","Interop bridge is disposed.")}async assertAuthorized(e){if(!await this.isAuthorized(e))throw new N("unauthorized",`${e.operation} is not authorized.`)}async isAuthorized(e){try{return await this.authorize(structuredClone(e))}catch(t){return this.report({severity:"error",code:"authorization_failed",message:`Authorization failed for ${e.operation}.`,principal:e.principal,cause:t}),!1}}cleanCompletedActions(){let e=this.now().getTime();for(let[t,n]of this.completedActions)n.expiresAt<=e&&this.completedActions.delete(t)}async acquireAdmission(e){var a;let t=(a=this.admissionLocks.get(e))!=null?a:Promise.resolve(),n,s=new Promise(c=>{n=c}),i=t.then(()=>s);this.admissionLocks.set(e,i),await t;let o=!1;return()=>{o||(o=!0,n(),this.admissionLocks.get(e)===i&&this.admissionLocks.delete(e))}}report(e){var t,n;(n=(t=this.options).onDiagnostic)==null||n.call(t,structuredClone(e))}};function Rr(r,e,t,n){if(!r(e))throw new N(t,`${n} is invalid: ${Pr(r.errors)}`)}function vI(r){for(let[e,t]of Object.entries(r))if(t!==void 0&&(typeof t!="string"||t.length===0||!/^[A-Za-z0-9][A-Za-z0-9._:@/-]*$/u.test(t)))throw new N("request_rejected",`Implementation identity ${e} is invalid.`);if(!(0,ar.valid)(r.version))throw new N("request_rejected","Implementation identity version must be exact SemVer.")}function Rd(r){if(!/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)+$/u.test(r.id))throw new N("unknown_contract",`Contract ID ${r.id} is invalid.`);if(!(0,ar.validRange)(r.version,{includePrerelease:!0}))throw new N("unsupported_contract_version",`Contract requirement ${r.version} is not a SemVer range.`);if(r.digest&&!/^sha256:[0-9a-f]{64}$/u.test(r.digest))throw new N("contract_digest_conflict","Contract digest is invalid.")}function mg(r,e){let t=r!=null?r:{id:e.id,version:e.version,digest:e.digest};return Rd(t),structuredClone(t)}function yg(r,e){if(!Mo(r,e))throw new N("unsupported_contract_version",`${e.id} ${e.version} does not satisfy its implementation requirement.`)}function Mo(r,e){return r.id===e.id&&(0,ar.satisfies)(e.version,r.version,{includePrerelease:!0})&&(!r.digest||r.digest===e.digest)}function No(r){return`${r.id}@${r.version}`}function wg(r){return`urn:mdbase:contract:${r.id}:${r.version}:${r.digest}`}function $I(r){return`urn:mdbase:app:${[r.application,r.implementation,...r.instance_id?[r.instance_id]:[]].map(encodeURIComponent).join(":")}`}function SI(r,e){if(r.type!==e.id||r.mdbasecontractversion!==e.version||r.mdbasecontractdigest!==e.digest||r.dataschema!==wg(e))throw new N("contract_digest_conflict","Event contract evidence is inconsistent.")}function EI(r){let{created_at:e,...t}=r;return t}function gg(r,e,t,n){if(n.clientId!==r)throw new N("unauthorized",`Action request ${e} belongs to another caller.`);if(n.requestDigest!==t)throw new N("request_rejected",`Action request ${e} was reused with different content.`)}function Pd(r,e,t){let n=new Set,s=(i,o)=>{if(!(i===null||typeof i=="boolean"||typeof i=="string")){if(typeof i=="number"){if(Number.isFinite(i))return;throw new N(e,`${t}${o} must be a finite JSON number.`)}if(typeof i!="object")throw new N(e,`${t}${o} is not a JSON value.`);if(n.has(i))throw new N(e,`${t}${o} contains a cycle.`);if(n.add(i),Array.isArray(i))i.forEach((a,c)=>s(a,`${o}/${c}`));else{let a=Object.getPrototypeOf(i);if(a!==Object.prototype&&a!==null)throw new N(e,`${t}${o} must be a plain JSON object.`);for(let[c,l]of Object.entries(i))s(l,`${o}/${c}`)}n.delete(i)}};s(r,"")}function Od(r,e){if(r.max_payload_bytes===void 0)return;let t=JSON.stringify(e),n=new TextEncoder().encode(t).byteLength;if(n>r.max_payload_bytes)throw new N("unsupported_transport_capability",`The portable envelope is ${n} bytes; the active transport allows ${r.max_payload_bytes}.`)}function AI(r,e){return r?(r.application===void 0||r.application===e.application)&&(r.implementation===void 0||r.implementation===e.implementation)&&(r.instance_id===void 0||r.instance_id===e.instance_id):!0}function kI(r,e){var t,n;if(e){if((t=e.delivery)!=null&&t.some(s=>!r.delivery.includes(s)))throw new N("unsupported_transport_capability","The active transport lacks a required delivery capability.");if((n=e.ordering)!=null&&n.some(s=>!r.ordering.includes(s)))throw new N("unsupported_transport_capability","The active transport lacks a required ordering capability.");for(let s of["cancellation","deadlines","provider_discovery","request_deduplication","cross_process_identity"])if(e[s]===!0&&r[s]!==!0)throw new N("unsupported_transport_capability",`The active transport lacks ${s}.`);if(e.max_payload_bytes!==void 0&&(r.max_payload_bytes===void 0||r.max_payload_bytese;){let t=r.keys().next().value;if(t===void 0)return;r.delete(t)}}function xI(r){return r instanceof Error&&r.name==="AbortError"}var Lo=class{constructor(e,t){this.app=e;this.profileVersion="0.1";this.bridge=new Ys({authorize:()=>t(),transport:{delivery:["ephemeral"],ordering:["none"],cancellation:!0,deadlines:!0,provider_discovery:!0,request_deduplication:!0,cross_process_identity:!1},onDiagnostic:n=>{var i;(n.severity==="error"?console.error:console.warn)(`[mdbase/interop] ${n.code}: ${n.message}`,(i=n.cause)!=null?i:"")}}),this.transport=this.bridge.describe().transport}connect(e){var i,o;let t=(i=e.manifest)==null?void 0:i.id,n=(o=e.manifest)==null?void 0:o.version;if(!t||!n)throw new Error("Only a loaded Obsidian plugin with manifest identity can connect to mdbase interop.");let s=this.app.plugins;if(!s||s.getPlugin(t)!==e)throw new Error(`Obsidian plugin ${t} is not the active loaded instance.`);return this.bridge.connect({application:t,implementation:`${t}.obsidian`,version:n})}describe(){return this.bridge.describe()}dispose(){return this.bridge.dispose()}};var fe=require("obsidian"),Hg=Hr(Jl(),1),zg=Hr(id(),1),Wd=Hr(Hd(),1),Fo=class extends Error{constructor(t,n){super(n);this.code=t;this.name="MdbasePathError"}},kt={spec_version:"0.3.0",name:"My mdbase collection",description:"Typed markdown collection",settings:{types_folder:"_types",explicit_type_keys:["type","types"],default_strict:!1,include_subfolders:!0,exclude:["_types",".obsidian",".git","node_modules",".trash",".mdbase"]}},ti=null;function lT(){return ti||(ti=new Hg.Ajv2020({allErrors:!0,strict:!1,allowUnionTypes:!0}),(0,zg.default)(ti),ti)}function Z(r){return!!r&&typeof r=="object"&&!Array.isArray(r)}function Ge(r){return JSON.parse(JSON.stringify(r))}function dT(r){if(r===!0)return!0;if(r===!1)return!1;if(r==="warn")return"warn"}function zd(r){return Array.isArray(r)?`[${r.map(e=>zd(e)).join(",")}]`:Z(r)?`{${Object.keys(r).sort().map(t=>`${JSON.stringify(t)}:${zd(r[t])}`).join(",")}}`:JSON.stringify(r)}function uT(r){let e=r.indexOf("."),t=r.indexOf("[");return e===-1&&t===-1?r:e===-1?r.slice(0,t):t===-1?r.slice(0,e):r.slice(0,Math.min(e,t))}function fT(r){let e=new Map,t=new Set,n=s=>{var l,u,d,f;let i=e.get(s);if(i)return i;let o=r.get(s);if(!o)return null;if(t.has(s)){let p={...o,fields:Ge(o.fields)};return e.set(s,p),p}t.add(s);let a=o.extends?n(o.extends):null;t.delete(s);let c={...o,fields:a?{...Ge(a.fields),...Ge(o.fields)}:Ge(o.fields),display_name_key:(l=o.display_name_key)!=null?l:a==null?void 0:a.display_name_key,path_pattern:(u=o.path_pattern)!=null?u:a==null?void 0:a.path_pattern,filename_pattern:(d=o.filename_pattern)!=null?d:a==null?void 0:a.filename_pattern,strict:o.strict!==void 0?o.strict:a==null?void 0:a.strict,match:(f=o.match)!=null?f:a==null?void 0:a.match};return e.set(s,c),c};for(let s of r.keys())n(s);return e}function Kg(r){let e=(0,fe.normalizePath)(r),t=e.lastIndexOf("/");return t>=0?e.slice(0,t):""}function Gg(r){let e=r.trim();e.startsWith("[[")&&e.endsWith("]]")&&(e=e.slice(2,-2));let t=e.indexOf("|");t>=0&&(e=e.slice(0,t));let n=e.indexOf("#");return n>=0&&(e=e.slice(0,n)),e.trim()}function Wg(r){return/^[a-z][a-z0-9+.-]*:\/\//i.test(r)}function Jg(r,e,t){var c;let n=Gg(t);if(!n||Wg(n))return null;let s=new Set,i=(0,fe.normalizePath)(n);s.add(i),i.endsWith(".md")||s.add(`${i}.md`);let o=Kg(e);if(o){let l=(0,fe.normalizePath)(`${o}/${n}`);s.add(l),l.endsWith(".md")||s.add(`${l}.md`)}for(let l of s){let u=r.getAbstractFileByPath(l);if(u instanceof fe.TFile)return u}let a=n.replace(/\.md$/i,"");return(c=r.getMarkdownFiles().find(l=>l.basename===a))!=null?c:null}function pT(r,e,t){return Wg(Gg(t))||Jg(r,e,t)!==null}function tt(r){let e=r.match(/^---[ \t]*\r?\n([\s\S]*?)^---[ \t]*(?:\r?\n|$)/m);if(!e)return{hasFrontmatter:!1,frontmatter:{},body:r};try{let t=e[1],n=(0,fe.parseYaml)(t);return n==null&&t.trim()!==""?{hasFrontmatter:!0,frontmatter:{},body:r.slice(e[0].length),error:"Frontmatter must be a YAML object"}:n!=null&&!Z(n)?{hasFrontmatter:!0,frontmatter:{},body:r.slice(e[0].length),error:"Frontmatter must be a YAML object"}:{hasFrontmatter:!0,frontmatter:n!=null?n:{},body:r.slice(e[0].length)}}catch(t){return{hasFrontmatter:!0,frontmatter:{},body:r.slice(e[0].length),error:t instanceof Error?t.message:String(t)}}}function ot(r,e=""){if(Object.keys(r).length===0)return e;let t=(0,fe.stringifyYaml)(r).trimEnd(),n=e.replace(/^\n+/,"");return`--- ${t} --- -${i}`}async function ai(r){let e=r.getAbstractFileByPath("mdbase.yaml");if(!(e instanceof fe.TFile))return null;try{let t=await r.cachedRead(e),i=(0,fe.parseYaml)(t);if(!Q(i))return null;let n=Q(i.settings)?i.settings:{},s=Q(i.runtime)?i.runtime:void 0;return{spec_version:typeof i.spec_version=="string"?i.spec_version:xt.spec_version,name:typeof i.name=="string"?i.name:xt.name,description:typeof i.description=="string"?i.description:xt.description,runtime:s?{profile_version:typeof s.profile_version=="string"?s.profile_version:void 0,enabled:typeof s.enabled=="boolean"?s.enabled:void 0,policy:typeof s.policy=="string"?s.policy:void 0}:void 0,settings:{types_folder:typeof n.types_folder=="string"?n.types_folder:xt.settings.types_folder,explicit_type_keys:Array.isArray(n.explicit_type_keys)?n.explicit_type_keys.filter(o=>typeof o=="string"):[...xt.settings.explicit_type_keys],default_strict:typeof n.default_strict=="boolean"?n.default_strict:xt.settings.default_strict,include_subfolders:typeof n.include_subfolders=="boolean"?n.include_subfolders:xt.settings.include_subfolders,exclude:Array.isArray(n.exclude)?n.exclude.filter(o=>typeof o=="string"):[...xt.settings.exclude]}}}catch(t){return null}}async function wb(r){var c;let e=[];if(!(r.getAbstractFileByPath("mdbase.yaml")instanceof fe.TFile)){let l=(0,fe.stringifyYaml)(xt).trimEnd()+` -`;await r.create("mdbase.yaml",l),e.push("mdbase.yaml")}let i=(c=await ai(r))!=null?c:xt,n=i.settings.types_folder;await r.adapter.exists(n)||(await r.createFolder(n),e.push(n));let o=(0,fe.normalizePath)(`${n}/note.md`);if(!await r.adapter.exists(o)){let l=mR("note",void 0,i.spec_version);await r.create(o,l),e.push(o)}return{created:e}}function $b(r,e){let t=Q(r)?r:{},i=Array.isArray(t.type)?t.type.find(s=>s!=="null"):t.type,n={required:e};return Array.isArray(t.enum)?(n.type="enum",n.values=Je(t.enum)):i==="array"?(n.type="list",n.items=$b(t.items,!1)):i==="object"?(n.type="object",n.fields=ci(t)):i==="string"&&t.format==="date"?n.type="date":i==="string"&&t.format==="date-time"?n.type="datetime":i==="string"&&t.format==="time"?n.type="time":typeof i=="string"?n.type=i:n.type="any",t.default!==void 0&&(n.default=Je(t.default)),typeof t.description=="string"&&(n.description=t.description),typeof t.minimum=="number"&&(n.min=t.minimum),typeof t.maximum=="number"&&(n.max=t.maximum),typeof t.minLength=="number"&&(n.min_length=t.minLength),typeof t.maxLength=="number"&&(n.max_length=t.maxLength),typeof t.pattern=="string"&&(n.pattern=t.pattern),typeof t.minItems=="number"&&(n.min_length=t.minItems),typeof t.maxItems=="number"&&(n.max_length=t.maxItems),n}function ci(r){let e=Q(r.properties)?r.properties:{},t=new Set(Array.isArray(r.required)?r.required.filter(i=>typeof i=="string"):[]);return Object.fromEntries(Object.entries(e).map(([i,n])=>[i,$b(n,t.has(i))]))}function Sb(r,e){var c,l,u,d;let t={...Je(e)},i=(c=r.type)!=null?c:"string",n=()=>{delete t.properties,delete t.required,delete t.additionalProperties},s=()=>{delete t.items};if(i==="enum")delete t.type,t.enum=Je((l=r.values)!=null?l:[]),delete t.format,n(),s();else if(i==="list")t.type="array",delete t.enum,delete t.format,n(),t.items=Sb((u=r.items)!=null?u:{type:"any"},Q(t.items)?t.items:{});else if(i==="object"){t.type="object",delete t.enum,delete t.format,s();let f=hu((d=r.fields)!=null?d:{},Q(t)?t:{},!1);t.properties=f.properties,f.required?t.required=f.required:delete t.required}else i==="link"?(t.type="string",delete t.enum,delete t.format,n(),s()):["date","datetime","time"].includes(i)?(t.type="string",t.format=i==="datetime"?"date-time":i,delete t.enum,n(),s()):["string","integer","number","boolean"].includes(i)?(t.type=i,delete t.format,delete t.enum,n(),s()):(delete t.type,delete t.enum,delete t.format,n(),s());r.default!==void 0?t.default=Je(r.default):delete t.default,typeof r.description=="string"&&r.description.trim()?t.description=r.description:delete t.description;let o=i==="integer"||i==="number";o&&typeof r.min=="number"?t.minimum=r.min:delete t.minimum,o&&typeof r.max=="number"?t.maximum=r.max:delete t.maximum;let a=["string","link","date","datetime","time"].includes(i);return i==="list"&&typeof r.min_length=="number"?t.minItems=r.min_length:delete t.minItems,i==="list"&&typeof r.max_length=="number"?t.maxItems=r.max_length:delete t.maxItems,a&&typeof r.min_length=="number"?t.minLength=r.min_length:delete t.minLength,a&&typeof r.max_length=="number"?t.maxLength=r.max_length:delete t.maxLength,a&&typeof r.pattern=="string"?t.pattern=r.pattern:delete t.pattern,t}function hu(r,e={},t=!1){let i=Q(e.properties)?e.properties:{},n=Object.create(null),s=[];for(let[a,c]of Object.entries(r))n[a]=Sb(c,Q(i[a])?i[a]:{}),c.required===!0&&s.push(a);let o={...Je(e),type:"object",properties:n,additionalProperties:!t};return s.length>0?o.required=s:delete o.required,o}function JI(r,e){if(!e)return r;if(!e.startsWith("/"))return;let t=r;for(let i of e.slice(1).split("/")){let n=i.replace(/~1/g,"/").replace(/~0/g,"~");if(Array.isArray(t)){let s=Number(n);if(!Number.isInteger(s)||s<0||s>=t.length)return;t=t[s]}else if(Q(t)&&n in t)t=t[n];else return}return t}async function YI(r,e,t){let[i,n=""]=t.split("#",2);if(!i||/^[a-z][a-z0-9+.-]*:/i.test(i)||i.startsWith("/"))return null;let s=gb(e),o=[];for(let l of`${s}/${i}`.replace(/\\/g,"/").split("/"))if(!(!l||l==="."))if(l===".."){if(o.length===0)return null;o.pop()}else o.push(l);let a=(0,fe.normalizePath)(o.join("/")),c=r.getAbstractFileByPath(a);if(!(c instanceof fe.TFile))return null;try{let l=JSON.parse(await r.cachedRead(c)),u=JI(l,n);return Q(u)?u:null}catch(l){return null}}async function Eb(r,e){var n,s,o,a;let t=new Map,i=`${(0,fe.normalizePath)(e.settings.types_folder)}/`;for(let c of r.getMarkdownFiles()){if(!c.path.startsWith(i))continue;let l=await r.cachedRead(c),u=Ue(l);if(!u.hasFrontmatter||u.error)continue;let d=u.frontmatter;if(e.spec_version.startsWith("0.3.")){if(d.kind!=="mdbase.type"||typeof d.name!="string"||!Q(d.schema))continue;let m=d.schema,h=Q(m.value)?m.value:null;if(!h&&typeof m.ref=="string"&&(h=await YI(r,c.path,m.ref)),!h)continue;let y=Q(d.collection)?Je(d.collection):void 0,b=ci(h);for(let g of(n=y==null?void 0:y.unique)!=null?n:[])typeof g.field=="string"&&b[g.field]&&(b[g.field].unique=!0);for(let[g,_]of Object.entries((s=y==null?void 0:y.links)!=null?s:{}))b[g]&&(b[g].target=_.target_type,b[g].validate_exists=_.validate_exists);t.set(d.name,{name:d.name,version:typeof d.version=="number"?d.version:void 0,description:typeof d.description=="string"?d.description:void 0,display_name_key:(o=y==null?void 0:y.display)==null?void 0:o.name_field,path_pattern:(a=y==null?void 0:y.path)==null?void 0:a.pattern,strict:h.additionalProperties===!1,match:Q(d.match)?d.match:void 0,fields:b,filePath:c.path,specProfile:"v0.3",schema:Je(h),collection:y,originalFrontmatter:Je(d)});continue}if(!Q(d.fields))continue;let f=typeof d.name=="string"&&d.name.trim().length>0?d.name.trim():c.basename,p={};for(let[m,h]of Object.entries(d.fields))Q(h)&&(p[m]=h);t.set(f,{name:f,extends:typeof d.extends=="string"?d.extends:void 0,display_name_key:typeof d.display_name_key=="string"?d.display_name_key:void 0,path_pattern:typeof d.path_pattern=="string"?d.path_pattern:void 0,filename_pattern:typeof d.filename_pattern=="string"?d.filename_pattern:void 0,strict:HI(d.strict),match:Q(d.match)?d.match:void 0,fields:p,filePath:c.path,specProfile:"v0.2",originalFrontmatter:Je(d)})}return GI(t)}function XI(r,e){for(let t of e){let i=r[t];if(Array.isArray(i))return i.filter(s=>typeof s=="string")}for(let t of e){let i=r[t];if(typeof i=="string"&&i.trim().length>0)return[i.trim()]}return null}function mu(r,e){return r.replace(/\{([^}]+)\}/g,(t,i)=>{let n=e[i];return n==null?"":Array.isArray(n)?n.join("-"):String(n)})}function fs(r){let e=r.replace(/\\/g,"/");if(!e||e.startsWith("/")||/^[A-Za-z]:\//.test(e)||e.includes("\0"))throw new ea("invalid_path",`Invalid collection-relative path: ${r}`);let t=e.split("/");if(t.includes(".."))throw new ea("path_traversal",`Path escapes the collection root: ${r}`);return(0,fe.normalizePath)(t.filter(i=>i&&i!==".").join("/"))}function ZI(r){let e=r.search(/[\*\?\[]/),i=(e===-1?r:r.slice(0,e)).replace(/\/+$/,"");if(i.endsWith(".md")){let n=i.lastIndexOf("/");return n>=0?i.slice(0,n):""}return i}function QI(r,e){var t;if(r.path_pattern){let i=(0,fe.normalizePath)(mu(r.path_pattern,e));if(i.endsWith(".md")){let n=i.lastIndexOf("/");return n>=0?i.slice(0,n):""}return i.replace(/\/+$/,"")}return(t=r.match)!=null&&t.path_glob?ZI(r.match.path_glob):""}function eR(r,e){var o,a;let t=(o=r.display_name_key)!=null?o:"title",i=e[t],n=`${r.name}-${new Date().toISOString().slice(0,10)}`,s=typeof i=="string"&&i.trim().length>0?i:n;if(r.filename_pattern&&r.filename_pattern.trim().length>0){let c=(0,fe.normalizePath)(mu(r.filename_pattern,e)),u=((a=c.split("/").pop())!=null?a:c).replace(/\.md$/i,"").trim();if(u.length>0)return`${hb(u)}.md`}return`${hb(s)}.md`}function Wi(r){return Array.isArray(r)?`[${r.map(Wi).join(",")}]`:Q(r)?`{${Object.keys(r).sort().map(e=>`${JSON.stringify(e)}:${Wi(r[e])}`).join(",")}}`:JSON.stringify(r)}function tR(r,e){let t=[r];for(let i of e.split(".").filter(Boolean)){let n=i.endsWith("[]"),s=n?i.slice(0,-2):i,o=[];for(let a of t){if(!Q(a)||!Object.prototype.hasOwnProperty.call(a,s))continue;let c=a[s];n&&Array.isArray(c)?o.push(...c):n||o.push(c)}if(!o.length)return{present:!1,value:void 0};t=o}return{present:!0,value:t[0]}}function Zo(r,e,t){return(typeof r=="number"&&typeof e=="number"&&Number.isFinite(r)&&Number.isFinite(e)||typeof r=="string"&&typeof e=="string")&&t(r,e)}function rR(r,e,t,i){let n=(s,o)=>Wi(s)===Wi(o);switch(e){case"eq":case"const":return r.present&&r.value!=null&&n(r.value,t);case"neq":return r.present&&r.value!=null&&!n(r.value,t);case"gt":return Zo(r.value,t,(s,o)=>s>o);case"gte":return Zo(r.value,t,(s,o)=>s>=o);case"lt":return Zo(r.value,t,(s,o)=>ss<=o);case"exists":return i.startsWith("0.3.")?t===!0?r.present:!r.present:t===!0?r.present&&r.value!=null:!r.present||r.value==null;case"contains":return Array.isArray(r.value)?r.value.some(s=>n(s,t)):typeof r.value=="string"&&r.value.includes(String(t));case"containsAll":return!Array.isArray(r.value)||!Array.isArray(t)?!1:t.every(s=>r.value.some(o=>n(o,s)));case"containsAny":return!Array.isArray(r.value)||!Array.isArray(t)?!1:t.some(s=>r.value.some(o=>n(o,s)));case"in":return r.value!=null&&Array.isArray(t)&&t.some(s=>n(s,r.value));case"startsWith":case"starts_with":return typeof r.value=="string"&&r.value.startsWith(String(t));case"endsWith":case"ends_with":return typeof r.value=="string"&&r.value.endsWith(String(t));case"matches":try{return r.value!=null&&new RegExp(String(t).replace(/\\\\/g,"\\")).test(String(r.value))}catch(s){return!1}default:return!1}}function Qo(r,e,t){if("and"in r)return Array.isArray(r.and)&&r.and.every(i=>Q(i)&&Qo(i,e,t));if("or"in r)return Array.isArray(r.or)&&r.or.some(i=>Q(i)&&Qo(i,e,t));if("not"in r)return Q(r.not)&&!Qo(r.not,e,t);for(let[i,n]of Object.entries(r)){let s=tR(e,i);if(!Q(n)){if(!s.present||Wi(s.value)!==Wi(n))return!1;continue}for(let[o,a]of Object.entries(n))if(!rR(s,o,a,t))return!1}return!0}function Ji(r,e,t,i){let n=XI(e,t.settings.explicit_type_keys);if(n)return n;let s=[];for(let[o,a]of i.entries()){let c=a.match;if(!c)continue;let l=!0;if(typeof c.path_glob=="string"&&((0,pu.default)(c.path_glob,{dot:!0})(r)||(l=!1)),l&&Array.isArray(c.fields_present)){for(let u of c.fields_present)if(!(u in e)){l=!1;break}}l&&Q(c.where)&&(l=Qo(c.where,e,t.spec_version)),l&&typeof c.where=="string"&&(l=!1),l&&s.push(o)}return s}function Ab(r){return r==null||typeof r=="string"&&r.trim().length===0}function iR(r){return/^\d{4}-\d{2}-\d{2}$/.test(r)}function nR(r){return/^\d{2}:\d{2}(:\d{2})?$/.test(r)}function sR(r){return typeof r=="string"||Array.isArray(r)?r.length:null}function Re(r,e,t,i,n,s){r.push({path:e,code:i,message:n,severity:t,field:s})}function vt(r,e,t,i,n){typeof r=="number"&&(typeof e.min=="number"&&r= ${e.min}`,t),typeof e.max=="number"&&r>e.max&&Re(n,i,"error","above_max",`Field '${t}' must be <= ${e.max}`,t));let s=sR(r);if(s!=null&&(typeof e.min_length=="number"&&s= ${e.min_length}`,t),typeof e.max_length=="number"&&s>e.max_length&&Re(n,i,"error","above_max_length",`Field '${t}' length must be <= ${e.max_length}`,t)),typeof e.pattern=="string"&&typeof r=="string")try{new RegExp(e.pattern).test(r)||Re(n,i,"error","pattern_mismatch",`Field '${t}' must match pattern /${e.pattern}/`,t)}catch(o){Re(n,i,"warn","invalid_pattern",`Field '${t}' has invalid regex pattern: ${o instanceof Error?o.message:String(o)}`,t)}}function uu(r,e,t,i,n,s){var c;let o=(c=e.type)!=null?c:"any";if(r==null)return;e.deprecated===!0&&Re(n,i,"warn","deprecated_field",`Field '${t}' is marked deprecated`,t);let a=l=>{Re(n,i,"error","invalid_type",`Field '${t}' expected ${l}`,t)};switch(o){case"any":vt(r,e,t,i,n);return;case"string":if(typeof r!="string"){a("a string");return}vt(r,e,t,i,n);return;case"integer":if(typeof r!="number"||!Number.isInteger(r)){a("an integer");return}vt(r,e,t,i,n);return;case"number":if(typeof r!="number"||Number.isNaN(r)){a("a number");return}vt(r,e,t,i,n);return;case"boolean":typeof r!="boolean"&&a("a boolean");return;case"date":if(typeof r!="string"||!iR(r)){a("a date (YYYY-MM-DD)");return}vt(r,e,t,i,n);return;case"datetime":if(typeof r!="string"||Number.isNaN(Date.parse(r))){a("a datetime string");return}vt(r,e,t,i,n);return;case"time":if(typeof r!="string"||!nR(r)){a("a time string (HH:MM)");return}vt(r,e,t,i,n);return;case"enum":{let l=Array.isArray(e.values)?e.values:[];if(!l.includes(r)){Re(n,i,"error","invalid_enum",`Field '${t}' must be one of: ${l.map(u=>String(u)).join(", ")}`,t);return}vt(r,e,t,i,n);return}case"list":{if(!Array.isArray(r)){a("a list");return}vt(r,e,t,i,n),e.items&&r.forEach((l,u)=>{uu(l,e.items,`${t}[${u}]`,i,n,s)});return}case"object":{if(!Q(r)){a("an object");return}if(e.fields&&Q(e.fields))for(let[l,u]of Object.entries(e.fields)){if(!Q(u))continue;let d=u,f=`${t}.${l}`,p=r[l];if(d.required&&Ab(p)){Re(n,i,"error","missing_required",`Missing required field '${f}'`,f);continue}uu(p,d,f,i,n,s)}return}case"link":{if(typeof r!="string"&&!Q(r)){a("a link string");return}if(e.validate_exists===!0&&s){let l=typeof r=="string"?r:typeof r.path=="string"?r.path:typeof r.file=="string"?r.file:"";(!l||!WI(s,i,l))&&Re(n,i,"error","missing_link_target",`Field '${t}' references a missing note`,t)}return}case"tags":if(typeof r=="string"){vt(r,e,t,i,n);return}if(Array.isArray(r)&&r.every(l=>typeof l=="string")){vt(r,e,t,i,n);return}a("a tag string or list of strings");return;default:vt(r,e,t,i,n);return}}function oR(r){return r.replace(/^\//,"").split("/").filter(Boolean).map(t=>t.replace(/~1/g,"/").replace(/~0/g,"~")).join(".")||void 0}function aR(r){return r.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase()}function cR(r,e,t){var c;let i=r.params,n=oR(r.instancePath),s=typeof i.missingProperty=="string"?i.missingProperty:typeof i.additionalProperty=="string"?i.additionalProperty:void 0,o=n&&s?`${n}.${s}`:s!=null?s:n,a=r.keyword==="format"?"format_invalid":`schema_${aR(r.keyword)}`;return{path:e,code:a,message:`JSON Schema ${r.keyword} failed for type '${t}': ${(c=r.message)!=null?c:"invalid value"}`,severity:"error",field:o,type:t,schema_location:`embedded://type/schema#${r.schemaPath}`,details:{instance_path:r.instancePath,schema_path:r.schemaPath}}}function fu(r){if(Array.isArray(r)){for(let e of r){let t=fu(e);if(t)return t}return null}if(!Q(r))return null;if(typeof r.$ref=="string"&&!r.$ref.startsWith("#"))return r.$ref;for(let e of Object.values(r)){let t=fu(e);if(t)return t}return null}function lR(r,e,t,i){var s;if(!t.schema)return;let n=fu(t.schema);if(n){i.push({path:r,code:/^[a-z][a-z0-9+.-]*:/i.test(n)?"schema_ref_forbidden":"unsupported_profile",message:`Unsupported JSON Schema reference '${n}' for type '${t.name}'`,severity:"error",type:t.name});return}try{let o=BI().compile(t.schema);if(o(e))return;for(let a of(s=o.errors)!=null?s:[])i.push(cR(a,r,t.name))}catch(o){i.push({path:r,code:"invalid_embedded_schema",message:o instanceof Error?o.message:String(o),severity:"error",type:t.name})}}async function dR(r,e,t,i,n,s,o){var a,c;for(let[l,u]of Object.entries((c=(a=i.collection)==null?void 0:a.links)!=null?c:{})){let d=t[l],f=Array.isArray(d)?d:[d];for(let p of f){if(p==null||typeof p!="string")continue;let m=vb(r,e,p);if(!m&&u.validate_exists===!0){Re(o,e,"error","link_not_found",`Field '${l}' references a missing note`,l);continue}if(m&&u.target_type&&u.target_type!=="any"){let h=Ue(await r.cachedRead(m));Ji(m.path,h.frontmatter,n,s).includes(u.target_type)||Re(o,e,"error","link_wrong_type",`Field '${l}' must reference type '${u.target_type}'`,l)}}}}function uR(r,e,t,i,n){if(t.specProfile==="v0.3"){lR(r,e,t,i);return}for(let[s,o]of Object.entries(t.fields)){if(!Q(o))continue;let a=o,c=e[s];if(a.required&&Ab(c)){Re(i,r,"error","missing_required",`Missing required field '${s}' for type '${t.name}'`,s);continue}uu(c,a,s,r,i,n)}}function fR(r){let e=new Set;for(let t of r)for(let i of Object.keys(t.fields))e.add(i);return e}function pR(r,e){let t=!1,i=!1;for(let n of r){if(n.strict===!0)return!0;n.strict==="warn"&&(t=!0),n.strict===void 0&&(i=!0)}return t||i&&e.settings.default_strict?"warn":!1}function ps(r,e){let t=(0,fe.normalizePath)(r),i=(0,fe.normalizePath)(e.settings.types_folder);if(t.startsWith(`${i}/`)||t===i||!e.settings.include_subfolders&&t.includes("/"))return!0;for(let n of e.settings.exclude)if((0,pu.default)(n,{dot:!0,matchBase:!n.includes("/")})(t)||!n.includes("*")&&!n.includes("?")&&!n.includes("/")&&t.startsWith(`${n}/`))return!0;return!1}async function yu(r,e,t,i){if(ps(e.path,t))return[];let n=[],s=await r.cachedRead(e),o=Ue(s);if(o.error)return Re(n,e.path,"error","invalid_frontmatter",o.error),n;let a=o.frontmatter,c=Ji(e.path,a,t,i);if(c.length===0)return Re(n,e.path,"warn","no_matching_type","No type could be resolved for this file"),n;let l=c.map(d=>i.get(d)).filter(d=>!!d);if(l.length===0)return Re(n,e.path,"error","unknown_type",`Resolved types are not defined: ${c.join(", ")}`),n;for(let d of l)uR(e.path,a,d,n,r),d.specProfile==="v0.3"&&await dR(r,e.path,a,d,t,i,n);let u=t.spec_version.startsWith("0.3.")?!1:pR(l,t);if(u!==!1){let d=fR(l),f=new Set(t.settings.explicit_type_keys),p=u===!0?"error":"warn";for(let m of Object.keys(a))d.has(m)||f.has(m)||Re(n,e.path,p,"unknown_field",`Unknown field '${m}' in strict mode`,m)}return n}async function hR(r,e,t){var s,o;let i=new Map;for(let a of r.getMarkdownFiles()){if(ps(a.path,e))continue;let c=await r.cachedRead(a),l=Ue(c);if(l.error)continue;let d=Ji(a.path,l.frontmatter,e,t).map(f=>t.get(f)).filter(f=>!!f);for(let f of d)for(let[p,m]of Object.entries(f.fields)){if(!Q(m)||m.unique!==!0)continue;let y=l.frontmatter[p];if(y==null)continue;let b=du(y),g=`${f.name}::${p}::${b}`,_=(s=i.get(g))!=null?s:[];_.push({path:a.path,typeName:f.name,fieldName:p,value:y,fingerprint:b}),i.set(g,_)}}let n=[];for(let a of i.values())if(!(a.length<=1))for(let c of a){let l=a.filter(u=>u.path!==c.path).map(u=>u.path).join(", ");Re(n,c.path,"error",((o=t.get(c.typeName))==null?void 0:o.specProfile)==="v0.3"?"duplicate_value":"duplicate_unique",`Field '${c.fieldName}' must be unique for type '${c.typeName}'. Duplicate found in: ${l}`,c.fieldName)}return n}async function kb(r,e,t){let i=[];for(let s of r.getMarkdownFiles()){if(ps(s.path,e))continue;let o=await yu(r,s,e,t);i.push(...o)}let n=await hR(r,e,t);return i.push(...n),i}function mR(r,e,t=xt.spec_version){if(t.startsWith("0.3.")){let n={kind:"mdbase.type",name:r,version:1,description:`${r} type`,schema:{dialect:"json-schema-2020-12",value:{$schema:"https://json-schema.org/draft/2020-12/schema",type:"object",required:["title"],additionalProperties:!0,properties:{title:{type:"string",minLength:1},tags:{type:"array",items:{type:"string"}}}}}};return e&&e.trim()&&(n.match={path_glob:e.trim()}),`${at(n,`# ${r} +${n}`}async function zn(r){let e=r.getAbstractFileByPath("mdbase.yaml");if(!(e instanceof fe.TFile))return null;try{let t=await r.cachedRead(e),n=(0,fe.parseYaml)(t);if(!Z(n))return null;let s=Z(n.settings)?n.settings:{},i=Z(n.runtime)?n.runtime:void 0;return{spec_version:typeof n.spec_version=="string"?n.spec_version:kt.spec_version,name:typeof n.name=="string"?n.name:kt.name,description:typeof n.description=="string"?n.description:kt.description,runtime:i?{profile_version:typeof i.profile_version=="string"?i.profile_version:void 0,enabled:typeof i.enabled=="boolean"?i.enabled:void 0,policy:typeof i.policy=="string"?i.policy:void 0}:void 0,settings:{types_folder:typeof s.types_folder=="string"?s.types_folder:kt.settings.types_folder,explicit_type_keys:Array.isArray(s.explicit_type_keys)?s.explicit_type_keys.filter(o=>typeof o=="string"):[...kt.settings.explicit_type_keys],default_strict:typeof s.default_strict=="boolean"?s.default_strict:kt.settings.default_strict,include_subfolders:typeof s.include_subfolders=="boolean"?s.include_subfolders:kt.settings.include_subfolders,exclude:Array.isArray(s.exclude)?s.exclude.filter(o=>typeof o=="string"):[...kt.settings.exclude]}}}catch(t){return null}}async function Yg(r){var c;let e=[];if(!(r.getAbstractFileByPath("mdbase.yaml")instanceof fe.TFile)){let l=(0,fe.stringifyYaml)(kt).trimEnd()+` +`;await r.create("mdbase.yaml",l),e.push("mdbase.yaml")}let n=(c=await zn(r))!=null?c:kt,s=n.settings.types_folder;await r.adapter.exists(s)||(await r.createFolder(s),e.push(s));let o=(0,fe.normalizePath)(`${s}/note.md`);if(!await r.adapter.exists(o)){let l=NT("note",void 0,n.spec_version);await r.create(o,l),e.push(o)}return{created:e}}function Xg(r,e){let t=Z(r)?r:{},n=Array.isArray(t.type)?t.type.find(i=>i!=="null"):t.type,s={required:e};return Array.isArray(t.enum)?(s.type="enum",s.values=Ge(t.enum)):n==="array"?(s.type="list",s.items=Xg(t.items,!1)):n==="object"?(s.type="object",s.fields=nn(t)):n==="string"&&t.format==="date"?s.type="date":n==="string"&&t.format==="date-time"?s.type="datetime":n==="string"&&t.format==="time"?s.type="time":typeof n=="string"?s.type=n:s.type="any",t.default!==void 0&&(s.default=Ge(t.default)),typeof t.description=="string"&&(s.description=t.description),typeof t.minimum=="number"&&(s.min=t.minimum),typeof t.maximum=="number"&&(s.max=t.maximum),typeof t.minLength=="number"&&(s.min_length=t.minLength),typeof t.maxLength=="number"&&(s.max_length=t.maxLength),typeof t.pattern=="string"&&(s.pattern=t.pattern),typeof t.minItems=="number"&&(s.min_length=t.minItems),typeof t.maxItems=="number"&&(s.max_length=t.maxItems),s}function nn(r){let e=Z(r.properties)?r.properties:{},t=new Set(Array.isArray(r.required)?r.required.filter(n=>typeof n=="string"):[]);return Object.fromEntries(Object.entries(e).map(([n,s])=>[n,Xg(s,t.has(n))]))}function Qg(r,e){var c,l,u,d;let t={...Ge(e)},n=(c=r.type)!=null?c:"string",s=()=>{delete t.properties,delete t.required,delete t.additionalProperties},i=()=>{delete t.items};if(n==="enum")delete t.type,t.enum=Ge((l=r.values)!=null?l:[]),delete t.format,s(),i();else if(n==="list")t.type="array",delete t.enum,delete t.format,s(),t.items=Qg((u=r.items)!=null?u:{type:"any"},Z(t.items)?t.items:{});else if(n==="object"){t.type="object",delete t.enum,delete t.format,i();let f=Jd((d=r.fields)!=null?d:{},Z(t)?t:{},!1);t.properties=f.properties,f.required?t.required=f.required:delete t.required}else n==="link"?(t.type="string",delete t.enum,delete t.format,s(),i()):["date","datetime","time"].includes(n)?(t.type="string",t.format=n==="datetime"?"date-time":n,delete t.enum,s(),i()):["string","integer","number","boolean"].includes(n)?(t.type=n,delete t.format,delete t.enum,s(),i()):(delete t.type,delete t.enum,delete t.format,s(),i());r.default!==void 0?t.default=Ge(r.default):delete t.default,typeof r.description=="string"&&r.description.trim()?t.description=r.description:delete t.description;let o=n==="integer"||n==="number";o&&typeof r.min=="number"?t.minimum=r.min:delete t.minimum,o&&typeof r.max=="number"?t.maximum=r.max:delete t.maximum;let a=["string","link","date","datetime","time"].includes(n);return n==="list"&&typeof r.min_length=="number"?t.minItems=r.min_length:delete t.minItems,n==="list"&&typeof r.max_length=="number"?t.maxItems=r.max_length:delete t.maxItems,a&&typeof r.min_length=="number"?t.minLength=r.min_length:delete t.minLength,a&&typeof r.max_length=="number"?t.maxLength=r.max_length:delete t.maxLength,a&&typeof r.pattern=="string"?t.pattern=r.pattern:delete t.pattern,t}function Jd(r,e={},t=!1){let n=Z(e.properties)?e.properties:{},s=Object.create(null),i=[];for(let[a,c]of Object.entries(r))s[a]=Qg(c,Z(n[a])?n[a]:{}),c.required===!0&&i.push(a);let o={...Ge(e),type:"object",properties:s,additionalProperties:!t};return i.length>0?o.required=i:delete o.required,o}function hT(r,e){if(!e)return r;if(!e.startsWith("/"))return;let t=r;for(let n of e.slice(1).split("/")){let s=n.replace(/~1/g,"/").replace(/~0/g,"~");if(Array.isArray(t)){let i=Number(s);if(!Number.isInteger(i)||i<0||i>=t.length)return;t=t[i]}else if(Z(t)&&s in t)t=t[s];else return}return t}async function mT(r,e,t){let[n,s=""]=t.split("#",2);if(!n||/^[a-z][a-z0-9+.-]*:/i.test(n)||n.startsWith("/"))return null;let i=Kg(e),o=[];for(let l of`${i}/${n}`.replace(/\\/g,"/").split("/"))if(!(!l||l==="."))if(l===".."){if(o.length===0)return null;o.pop()}else o.push(l);let a=(0,fe.normalizePath)(o.join("/")),c=r.getAbstractFileByPath(a);if(!(c instanceof fe.TFile))return null;try{let l=JSON.parse(await r.cachedRead(c)),u=hT(l,s);return Z(u)?u:null}catch(l){return null}}async function Zg(r,e){var s,i,o,a;let t=new Map,n=`${(0,fe.normalizePath)(e.settings.types_folder)}/`;for(let c of r.getMarkdownFiles()){if(!c.path.startsWith(n))continue;let l=await r.cachedRead(c),u=tt(l);if(!u.hasFrontmatter||u.error)continue;let d=u.frontmatter;if(e.spec_version.startsWith("0.3.")){if(d.kind!=="mdbase.type"||typeof d.name!="string"||!Z(d.schema))continue;let m=d.schema,h=Z(m.value)?m.value:null;if(!h&&typeof m.ref=="string"&&(h=await mT(r,c.path,m.ref)),!h)continue;let y=Z(d.collection)?Ge(d.collection):void 0,b=nn(h);for(let g of(s=y==null?void 0:y.unique)!=null?s:[])typeof g.field=="string"&&b[g.field]&&(b[g.field].unique=!0);for(let[g,w]of Object.entries((i=y==null?void 0:y.links)!=null?i:{}))b[g]&&(b[g].target=w.target_type,b[g].validate_exists=w.validate_exists);t.set(d.name,{name:d.name,version:typeof d.version=="number"?d.version:void 0,description:typeof d.description=="string"?d.description:void 0,display_name_key:(o=y==null?void 0:y.display)==null?void 0:o.name_field,path_pattern:(a=y==null?void 0:y.path)==null?void 0:a.pattern,strict:h.additionalProperties===!1,match:Z(d.match)?d.match:void 0,fields:b,filePath:c.path,specProfile:"v0.3",schema:Ge(h),collection:y,originalFrontmatter:Ge(d)});continue}if(!Z(d.fields))continue;let f=typeof d.name=="string"&&d.name.trim().length>0?d.name.trim():c.basename,p={};for(let[m,h]of Object.entries(d.fields))Z(h)&&(p[m]=h);t.set(f,{name:f,extends:typeof d.extends=="string"?d.extends:void 0,display_name_key:typeof d.display_name_key=="string"?d.display_name_key:void 0,path_pattern:typeof d.path_pattern=="string"?d.path_pattern:void 0,filename_pattern:typeof d.filename_pattern=="string"?d.filename_pattern:void 0,strict:dT(d.strict),match:Z(d.match)?d.match:void 0,fields:p,filePath:c.path,specProfile:"v0.2",originalFrontmatter:Ge(d)})}return fT(t)}function yT(r,e){for(let t of e){let n=r[t];if(Array.isArray(n))return n.filter(i=>typeof i=="string")}for(let t of e){let n=r[t];if(typeof n=="string"&&n.trim().length>0)return[n.trim()]}return null}function Yd(r,e){return r.replace(/\{([^}]+)\}/g,(t,n)=>{let s=e[n];return s==null?"":Array.isArray(s)?s.join("-"):String(s)})}function ri(r){let e=r.replace(/\\/g,"/");if(!e||e.startsWith("/")||/^[A-Za-z]:\//.test(e)||e.includes("\0"))throw new Fo("invalid_path",`Invalid collection-relative path: ${r}`);let t=e.split("/");if(t.includes(".."))throw new Fo("path_traversal",`Path escapes the collection root: ${r}`);return(0,fe.normalizePath)(t.filter(n=>n&&n!==".").join("/"))}function gT(r){let e=r.search(/[\*\?\[]/),n=(e===-1?r:r.slice(0,e)).replace(/\/+$/,"");if(n.endsWith(".md")){let s=n.lastIndexOf("/");return s>=0?n.slice(0,s):""}return n}function bT(r,e){var t;if(r.path_pattern){let n=(0,fe.normalizePath)(Yd(r.path_pattern,e));if(n.endsWith(".md")){let s=n.lastIndexOf("/");return s>=0?n.slice(0,s):""}return n.replace(/\/+$/,"")}return(t=r.match)!=null&&t.path_glob?gT(r.match.path_glob):""}function wT(r,e){var o,a;let t=(o=r.display_name_key)!=null?o:"title",n=e[t],s=`${r.name}-${new Date().toISOString().slice(0,10)}`,i=typeof n=="string"&&n.trim().length>0?n:s;if(r.filename_pattern&&r.filename_pattern.trim().length>0){let c=(0,fe.normalizePath)(Yd(r.filename_pattern,e)),u=((a=c.split("/").pop())!=null?a:c).replace(/\.md$/i,"").trim();if(u.length>0)return`${Bg(u)}.md`}return`${Bg(i)}.md`}function Hn(r){return Array.isArray(r)?`[${r.map(Hn).join(",")}]`:Z(r)?`{${Object.keys(r).sort().map(e=>`${JSON.stringify(e)}:${Hn(r[e])}`).join(",")}}`:JSON.stringify(r)}function _T(r,e){let t=[r];for(let n of e.split(".").filter(Boolean)){let s=n.endsWith("[]"),i=s?n.slice(0,-2):n,o=[];for(let a of t){if(!Z(a)||!Object.prototype.hasOwnProperty.call(a,i))continue;let c=a[i];s&&Array.isArray(c)?o.push(...c):s||o.push(c)}if(!o.length)return{present:!1,value:void 0};t=o}return{present:!0,value:t[0]}}function Do(r,e,t){return(typeof r=="number"&&typeof e=="number"&&Number.isFinite(r)&&Number.isFinite(e)||typeof r=="string"&&typeof e=="string")&&t(r,e)}function vT(r,e,t,n){let s=(i,o)=>Hn(i)===Hn(o);switch(e){case"eq":case"const":return r.present&&r.value!=null&&s(r.value,t);case"neq":return r.present&&r.value!=null&&!s(r.value,t);case"gt":return Do(r.value,t,(i,o)=>i>o);case"gte":return Do(r.value,t,(i,o)=>i>=o);case"lt":return Do(r.value,t,(i,o)=>ii<=o);case"exists":return n.startsWith("0.3.")?t===!0?r.present:!r.present:t===!0?r.present&&r.value!=null:!r.present||r.value==null;case"contains":return Array.isArray(r.value)?r.value.some(i=>s(i,t)):typeof r.value=="string"&&r.value.includes(String(t));case"containsAll":return!Array.isArray(r.value)||!Array.isArray(t)?!1:t.every(i=>r.value.some(o=>s(o,i)));case"containsAny":return!Array.isArray(r.value)||!Array.isArray(t)?!1:t.some(i=>r.value.some(o=>s(o,i)));case"in":return r.value!=null&&Array.isArray(t)&&t.some(i=>s(i,r.value));case"startsWith":case"starts_with":return typeof r.value=="string"&&r.value.startsWith(String(t));case"endsWith":case"ends_with":return typeof r.value=="string"&&r.value.endsWith(String(t));case"matches":try{return r.value!=null&&new RegExp(String(t).replace(/\\\\/g,"\\")).test(String(r.value))}catch(i){return!1}default:return!1}}function jo(r,e,t){if("and"in r)return Array.isArray(r.and)&&r.and.every(n=>Z(n)&&jo(n,e,t));if("or"in r)return Array.isArray(r.or)&&r.or.some(n=>Z(n)&&jo(n,e,t));if("not"in r)return Z(r.not)&&!jo(r.not,e,t);for(let[n,s]of Object.entries(r)){let i=_T(e,n);if(!Z(s)){if(!i.present||Hn(i.value)!==Hn(s))return!1;continue}for(let[o,a]of Object.entries(s))if(!vT(i,o,a,t))return!1}return!0}function Kn(r,e,t,n){let s=yT(e,t.settings.explicit_type_keys);if(s)return s;let i=[];for(let[o,a]of n.entries()){let c=a.match;if(!c)continue;let l=!0;if(typeof c.path_glob=="string"&&((0,Wd.default)(c.path_glob,{dot:!0})(r)||(l=!1)),l&&Array.isArray(c.fields_present)){for(let u of c.fields_present)if(!(u in e)){l=!1;break}}l&&Z(c.where)&&(l=jo(c.where,e,t.spec_version)),l&&typeof c.where=="string"&&(l=!1),l&&i.push(o)}return i}function eb(r){return r==null||typeof r=="string"&&r.trim().length===0}function $T(r){return/^\d{4}-\d{2}-\d{2}$/.test(r)}function ST(r){return/^\d{2}:\d{2}(:\d{2})?$/.test(r)}function ET(r){return typeof r=="string"||Array.isArray(r)?r.length:null}function Te(r,e,t,n,s,i){r.push({path:e,code:n,message:s,severity:t,field:i})}function bt(r,e,t,n,s){typeof r=="number"&&(typeof e.min=="number"&&r= ${e.min}`,t),typeof e.max=="number"&&r>e.max&&Te(s,n,"error","above_max",`Field '${t}' must be <= ${e.max}`,t));let i=ET(r);if(i!=null&&(typeof e.min_length=="number"&&i= ${e.min_length}`,t),typeof e.max_length=="number"&&i>e.max_length&&Te(s,n,"error","above_max_length",`Field '${t}' length must be <= ${e.max_length}`,t)),typeof e.pattern=="string"&&typeof r=="string")try{new RegExp(e.pattern).test(r)||Te(s,n,"error","pattern_mismatch",`Field '${t}' must match pattern /${e.pattern}/`,t)}catch(o){Te(s,n,"warn","invalid_pattern",`Field '${t}' has invalid regex pattern: ${o instanceof Error?o.message:String(o)}`,t)}}function Kd(r,e,t,n,s,i){var c;let o=(c=e.type)!=null?c:"any";if(r==null)return;e.deprecated===!0&&Te(s,n,"warn","deprecated_field",`Field '${t}' is marked deprecated`,t);let a=l=>{Te(s,n,"error","invalid_type",`Field '${t}' expected ${l}`,t)};switch(o){case"any":bt(r,e,t,n,s);return;case"string":if(typeof r!="string"){a("a string");return}bt(r,e,t,n,s);return;case"integer":if(typeof r!="number"||!Number.isInteger(r)){a("an integer");return}bt(r,e,t,n,s);return;case"number":if(typeof r!="number"||Number.isNaN(r)){a("a number");return}bt(r,e,t,n,s);return;case"boolean":typeof r!="boolean"&&a("a boolean");return;case"date":if(typeof r!="string"||!$T(r)){a("a date (YYYY-MM-DD)");return}bt(r,e,t,n,s);return;case"datetime":if(typeof r!="string"||Number.isNaN(Date.parse(r))){a("a datetime string");return}bt(r,e,t,n,s);return;case"time":if(typeof r!="string"||!ST(r)){a("a time string (HH:MM)");return}bt(r,e,t,n,s);return;case"enum":{let l=Array.isArray(e.values)?e.values:[];if(!l.includes(r)){Te(s,n,"error","invalid_enum",`Field '${t}' must be one of: ${l.map(u=>String(u)).join(", ")}`,t);return}bt(r,e,t,n,s);return}case"list":{if(!Array.isArray(r)){a("a list");return}bt(r,e,t,n,s),e.items&&r.forEach((l,u)=>{Kd(l,e.items,`${t}[${u}]`,n,s,i)});return}case"object":{if(!Z(r)){a("an object");return}if(e.fields&&Z(e.fields))for(let[l,u]of Object.entries(e.fields)){if(!Z(u))continue;let d=u,f=`${t}.${l}`,p=r[l];if(d.required&&eb(p)){Te(s,n,"error","missing_required",`Missing required field '${f}'`,f);continue}Kd(p,d,f,n,s,i)}return}case"link":{if(typeof r!="string"&&!Z(r)){a("a link string");return}if(e.validate_exists===!0&&i){let l=typeof r=="string"?r:typeof r.path=="string"?r.path:typeof r.file=="string"?r.file:"";(!l||!pT(i,n,l))&&Te(s,n,"error","missing_link_target",`Field '${t}' references a missing note`,t)}return}case"tags":if(typeof r=="string"){bt(r,e,t,n,s);return}if(Array.isArray(r)&&r.every(l=>typeof l=="string")){bt(r,e,t,n,s);return}a("a tag string or list of strings");return;default:bt(r,e,t,n,s);return}}function AT(r){return r.replace(/^\//,"").split("/").filter(Boolean).map(t=>t.replace(/~1/g,"/").replace(/~0/g,"~")).join(".")||void 0}function kT(r){return r.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase()}function xT(r,e,t){var c;let n=r.params,s=AT(r.instancePath),i=typeof n.missingProperty=="string"?n.missingProperty:typeof n.additionalProperty=="string"?n.additionalProperty:void 0,o=s&&i?`${s}.${i}`:i!=null?i:s,a=r.keyword==="format"?"format_invalid":`schema_${kT(r.keyword)}`;return{path:e,code:a,message:`JSON Schema ${r.keyword} failed for type '${t}': ${(c=r.message)!=null?c:"invalid value"}`,severity:"error",field:o,type:t,schema_location:`embedded://type/schema#${r.schemaPath}`,details:{instance_path:r.instancePath,schema_path:r.schemaPath}}}function Gd(r){if(Array.isArray(r)){for(let e of r){let t=Gd(e);if(t)return t}return null}if(!Z(r))return null;if(typeof r.$ref=="string"&&!r.$ref.startsWith("#"))return r.$ref;for(let e of Object.values(r)){let t=Gd(e);if(t)return t}return null}function IT(r,e,t,n){var i;if(!t.schema)return;let s=Gd(t.schema);if(s){n.push({path:r,code:/^[a-z][a-z0-9+.-]*:/i.test(s)?"schema_ref_forbidden":"unsupported_profile",message:`Unsupported JSON Schema reference '${s}' for type '${t.name}'`,severity:"error",type:t.name});return}try{let o=lT().compile(t.schema);if(o(e))return;for(let a of(i=o.errors)!=null?i:[])n.push(xT(a,r,t.name))}catch(o){n.push({path:r,code:"invalid_embedded_schema",message:o instanceof Error?o.message:String(o),severity:"error",type:t.name})}}async function TT(r,e,t,n,s,i,o){var a,c;for(let[l,u]of Object.entries((c=(a=n.collection)==null?void 0:a.links)!=null?c:{})){let d=t[l],f=Array.isArray(d)?d:[d];for(let p of f){if(p==null||typeof p!="string")continue;let m=Jg(r,e,p);if(!m&&u.validate_exists===!0){Te(o,e,"error","link_not_found",`Field '${l}' references a missing note`,l);continue}if(m&&u.target_type&&u.target_type!=="any"){let h=tt(await r.cachedRead(m));Kn(m.path,h.frontmatter,s,i).includes(u.target_type)||Te(o,e,"error","link_wrong_type",`Field '${l}' must reference type '${u.target_type}'`,l)}}}}function PT(r,e,t,n,s){if(t.specProfile==="v0.3"){IT(r,e,t,n);return}for(let[i,o]of Object.entries(t.fields)){if(!Z(o))continue;let a=o,c=e[i];if(a.required&&eb(c)){Te(n,r,"error","missing_required",`Missing required field '${i}' for type '${t.name}'`,i);continue}Kd(c,a,i,r,n,s)}}function OT(r){let e=new Set;for(let t of r)for(let n of Object.keys(t.fields))e.add(n);return e}function RT(r,e){let t=!1,n=!1;for(let s of r){if(s.strict===!0)return!0;s.strict==="warn"&&(t=!0),s.strict===void 0&&(n=!0)}return t||n&&e.settings.default_strict?"warn":!1}function ni(r,e){let t=(0,fe.normalizePath)(r),n=(0,fe.normalizePath)(e.settings.types_folder);if(t.startsWith(`${n}/`)||t===n||!e.settings.include_subfolders&&t.includes("/"))return!0;for(let s of e.settings.exclude)if((0,Wd.default)(s,{dot:!0,matchBase:!s.includes("/")})(t)||!s.includes("*")&&!s.includes("?")&&!s.includes("/")&&t.startsWith(`${s}/`))return!0;return!1}async function Xd(r,e,t,n){if(ni(e.path,t))return[];let s=[],i=await r.cachedRead(e),o=tt(i);if(o.error)return Te(s,e.path,"error","invalid_frontmatter",o.error),s;let a=o.frontmatter,c=Kn(e.path,a,t,n);if(c.length===0)return Te(s,e.path,"warn","no_matching_type","No type could be resolved for this file"),s;let l=c.map(d=>n.get(d)).filter(d=>!!d);if(l.length===0)return Te(s,e.path,"error","unknown_type",`Resolved types are not defined: ${c.join(", ")}`),s;for(let d of l)PT(e.path,a,d,s,r),d.specProfile==="v0.3"&&await TT(r,e.path,a,d,t,n,s);let u=t.spec_version.startsWith("0.3.")?!1:RT(l,t);if(u!==!1){let d=OT(l),f=new Set(t.settings.explicit_type_keys),p=u===!0?"error":"warn";for(let m of Object.keys(a))d.has(m)||f.has(m)||Te(s,e.path,p,"unknown_field",`Unknown field '${m}' in strict mode`,m)}return s}async function CT(r,e,t){var i,o;let n=new Map;for(let a of r.getMarkdownFiles()){if(ni(a.path,e))continue;let c=await r.cachedRead(a),l=tt(c);if(l.error)continue;let d=Kn(a.path,l.frontmatter,e,t).map(f=>t.get(f)).filter(f=>!!f);for(let f of d)for(let[p,m]of Object.entries(f.fields)){if(!Z(m)||m.unique!==!0)continue;let y=l.frontmatter[p];if(y==null)continue;let b=zd(y),g=`${f.name}::${p}::${b}`,w=(i=n.get(g))!=null?i:[];w.push({path:a.path,typeName:f.name,fieldName:p,value:y,fingerprint:b}),n.set(g,w)}}let s=[];for(let a of n.values())if(!(a.length<=1))for(let c of a){let l=a.filter(u=>u.path!==c.path).map(u=>u.path).join(", ");Te(s,c.path,"error",((o=t.get(c.typeName))==null?void 0:o.specProfile)==="v0.3"?"duplicate_value":"duplicate_unique",`Field '${c.fieldName}' must be unique for type '${c.typeName}'. Duplicate found in: ${l}`,c.fieldName)}return s}async function tb(r,e,t){let n=[];for(let i of r.getMarkdownFiles()){if(ni(i.path,e))continue;let o=await Xd(r,i,e,t);n.push(...o)}let s=await CT(r,e,t);return n.push(...s),n}function NT(r,e,t=kt.spec_version){if(t.startsWith("0.3.")){let s={kind:"mdbase.type",name:r,version:1,description:`${r} type`,schema:{dialect:"json-schema-2020-12",value:{$schema:"https://json-schema.org/draft/2020-12/schema",type:"object",required:["title"],additionalProperties:!0,properties:{title:{type:"string",minLength:1},tags:{type:"array",items:{type:"string"}}}}}};return e&&e.trim()&&(s.match={path_glob:e.trim()}),`${ot(s,`# ${r} Type definition for ${r}.`)} -`}let i={name:r,description:`${r} type`,strict:!1,fields:{title:{type:"string",required:!0}}};return e&&e.trim().length>0&&(i.match={path_glob:e.trim()}),`${at(i,`# ${r} +`}let n={name:r,description:`${r} type`,strict:!1,fields:{title:{type:"string",required:!0}}};return e&&e.trim().length>0&&(n.match={path_glob:e.trim()}),`${ot(n,`# ${r} Type definition for ${r}.`)} -`}function Pb(r,e){var n;let t={},i=(n=e.settings.explicit_type_keys[0])!=null?n:"type";t[i]=i==="types"?[r.name]:r.name;for(let[s,o]of Object.entries(r.fields)){if(!Q(o))continue;let a=o;a.default!==void 0&&(t[s]=Je(a.default))}return t}function xb(r,e){let t=[];for(let[i,n]of Object.entries(r.fields)){if(!Q(n))continue;let s=n;s.computed||s.required&&e[i]===void 0&&t.push([i,s])}return t}function gu(r,e){var n;let t=r.trim();switch((n=e.type)!=null?n:"string"){case"string":case"date":case"datetime":case"time":case"link":case"enum":case"any":return t;case"integer":{let s=Number.parseInt(t,10);if(!Number.isInteger(s))throw new Error("Expected integer input");return s}case"number":{let s=Number.parseFloat(t);if(Number.isNaN(s))throw new Error("Expected numeric input");return s}case"boolean":{let s=t.toLowerCase();if(["true","1","yes","y"].includes(s))return!0;if(["false","0","no","n"].includes(s))return!1;throw new Error("Expected boolean input: true/false")}case"list":{let s=t.split(",").map(o=>o.trim()).filter(o=>o.length>0);return e.items?s.map(o=>gu(o,e.items)):s}case"object":{let s=(0,fe.parseYaml)(t);if(!Q(s))throw new Error("Expected YAML object value");return s}case"tags":return t.split(",").map(s=>s.trim()).filter(s=>s.length>0);default:return t}}function hb(r){let e=r.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").replace(/-+/g,"-").replace(/^-+/,"").replace(/-+$/,"");return e.length>0?e:"note"}async function Ib(r,e){let t=(0,fe.normalizePath)(e).replace(/\/+$/,"");if(!t)return;let i=t.split("/"),n="";for(let s of i)n=n?`${n}/${s}`:s,await r.adapter.exists(n)||await r.createFolder(n)}function yR(r,e){if(!r.path_pattern||r.path_pattern.trim().length===0)return null;let t=(0,fe.normalizePath)(mu(r.path_pattern,e));return t.endsWith(".md")?t:null}async function Rb(r,e,t){var u;let i=yR(e,t),n=QI(e,t),s=i?(u=i.split("/").pop())!=null?u:i:eR(e,t),o=fs(i||`${n?`${n}/`:""}${s.endsWith(".md")?s:`${s}.md`}`),a=o,c=2;for(;r.getAbstractFileByPath(a);)a=o.replace(/\.md$/,`-${c}.md`),c+=1;let l=a.lastIndexOf("/");return l>0&&await Ib(r,a.slice(0,l)),a}async function Tb(r,e,t,i=""){let n=fs(e),s=n.lastIndexOf("/");if(s>0&&await Ib(r,n.slice(0,s)),await r.adapter.exists(n))throw new Error(`File already exists: ${n}`);let o=`${at(t,i)} -`;return r.create(n,o)}function ta(r){return KI(r)}var ra=require("obsidian");async function Cb(r,e){var c;if(!e||!e.spec_version.startsWith("0.3.")||!e.runtime||e.runtime.enabled===!1)return bu();if(e.runtime.profile_version!=="0.1.0")return Yi("unsupported_profile",`Unsupported runtime profile ${String(e.runtime.profile_version)}.`);if(!e.runtime.policy)return bu();let t=gR(e.runtime.policy);if(!t)return Yi("path_traversal","Runtime policy path must remain inside the vault.",e.runtime.policy);let i=r.getAbstractFileByPath(t);if(!(i instanceof ra.TFile))return Yi("policy_not_selected",`Selected runtime policy was not found: ${t}.`,t);let n=Ue(await r.cachedRead(i));if(!n.hasFrontmatter||n.error)return Yi("invalid_runtime_policy",(c=n.error)!=null?c:"Runtime policy must be a Markdown record with frontmatter.",t);let s=zd("runtimePolicy",n.frontmatter);if(!s.valid){let l=s.errors.map(u=>{var d;return`${u.instancePath||"/"} ${(d=u.message)!=null?d:u.keyword}`}).join("; ");return Yi("invalid_runtime_policy",`Runtime policy failed canonical validation: ${l}`,t)}if(n.frontmatter.enabled===!1)return Yi("policy_not_selected",`Selected runtime policy is disabled: ${t}.`,t);let o={},a=Ob(n.frontmatter.capabilities);for(let[l,u]of Object.entries(a)){let d=Ob(u).mode;o[l]=d==="allow"?"allow":"deny"}return{policy:{id:String(n.frontmatter.id),selected:!0,capabilities:o},path:t,diagnostics:[]}}function gR(r){let e=r.replace(/\\/g,"/").replace(/^\.\//,"");if(!e||e.startsWith("/")||e.split("/").includes(".."))return null;let t=(0,ra.normalizePath)(e);return t.endsWith(".md")?t:null}function bu(){return{policy:Nb(),diagnostics:[]}}function Yi(r,e,t){return{policy:Nb(),diagnostics:[{code:r,message:e,path:t}]}}function Nb(){return{...Nr,capabilities:{...Nr.capabilities}}}function Ob(r){return r&&typeof r=="object"&&!Array.isArray(r)?r:{}}var le=require("obsidian"),i_=ft(lu(),1);var T=class extends Error{constructor(t,i){super(i);I(this,"code");this.code=t}};function bR(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in r&&r.BYTES_PER_ELEMENT===1}function ia(r,e,t=""){let i=bR(r),n=r==null?void 0:r.length,s=e!==void 0;if(!i||s&&n!==e){let o=t&&`"${t}" `,a=s?` of length ${e}`:"",c=i?`length=${n}`:`type=${typeof r}`,l=o+"expected Uint8Array"+a+", got "+c;throw i?new RangeError(l):new TypeError(l)}return r}function _u(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function Mb(r,e){ia(r,void 0,"digestInto() output");let t=e.outputLen;if(r.length='+t)}function Lr(...r){for(let e=0;e>>e}function sa(r,e){return r<>>32-e>>>0}var _R=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",vR=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function jr(r){if(ia(r),_R)return r.toHex();let e="";for(let t=0;tr(s).update(n).digest(),i=r(void 0);return t.outputLen=i.outputLen,t.blockLen=i.blockLen,t.canXOF=i.canXOF,t.create=n=>r(n),Object.assign(t,e),Object.freeze(t)}var qb=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function aa(r,e,t){return r&e^~r&t}function ca(r,e,t){return r&e^r&t^e&t}var Xi=class{constructor(e,t,i,n){I(this,"blockLen");I(this,"outputLen");I(this,"canXOF",!1);I(this,"padOffset");I(this,"isLE");I(this,"buffer");I(this,"view");I(this,"finished",!1);I(this,"length",0);I(this,"pos",0);I(this,"destroyed",!1);this.blockLen=e,this.outputLen=t,this.padOffset=i,this.isLE=n,this.buffer=new Uint8Array(e),this.view=na(this.buffer)}update(e){_u(this),ia(e);let{view:t,buffer:i,blockLen:n}=this,s=e.length;for(let o=0;on-o&&(this.process(i,0),o=0);for(let d=o;du.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;dnew vu);var wR=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Fr=new Uint32Array(64),wu=class extends Xi{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:i,D:n,E:s,F:o,G:a,H:c}=this;return[e,t,i,n,s,o,a,c]}set(e,t,i,n,s,o,a,c){this.A=e|0,this.B=t|0,this.C=i|0,this.D=n|0,this.E=s|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,t){for(let d=0;d<16;d++,t+=4)Fr[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){let f=Fr[d-15],p=Fr[d-2],m=It(f,7)^It(f,18)^f>>>3,h=It(p,17)^It(p,19)^p>>>10;Fr[d]=h+Fr[d-7]+m+Fr[d-16]|0}let{A:i,B:n,C:s,D:o,E:a,F:c,G:l,H:u}=this;for(let d=0;d<64;d++){let f=It(a,6)^It(a,11)^It(a,25),p=u+f+aa(a,c,l)+wR[d]+Fr[d]|0,h=(It(i,2)^It(i,13)^It(i,22))+ca(i,n,s)|0;u=l,l=c,c=a,a=o+p|0,o=s,s=n,n=i,i=p+h|0}i=i+this.A|0,n=n+this.B|0,s=s+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(i,n,s,o,a,c,l,u)}roundClean(){Lr(Fr)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),Lr(this.buffer)}},$u=class extends wu{constructor(){super(32);I(this,"A",dr[0]|0);I(this,"B",dr[1]|0);I(this,"C",dr[2]|0);I(this,"D",dr[3]|0);I(this,"E",dr[4]|0);I(this,"F",dr[5]|0);I(this,"G",dr[6]|0);I(this,"H",dr[7]|0)}};var li=oa(()=>new $u,qb(1));var Su=1500,$R=250,SR=3e4,zb=1440*60*1e3,ur=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,la=class{constructor(e={}){I(this,"request");I(this,"now");I(this,"wait");var t,i,n;this.request=(t=e.request)!=null?t:ER,this.now=(i=e.now)!=null?i:Date.now,this.wait=(n=e.wait)!=null?n:xR}async begin(e,t={}){di(t.signal);let i=fr(e.controlUrl),n=e.mirrorName.trim();if(!n||n.length>200)throw new ze("invalid_mirror_name","Mirror name must contain between 1 and 200 characters.");if(!["read_only","read_write"].includes(e.mode))throw new ze("invalid_mirror_mode","Mirror mode must be read-only or read-write.");if(e.collectionId!==void 0&&!ur.test(e.collectionId))throw new ze("invalid_collection_id","Collection ID must be a UUID.");let s;try{s=await this.request({url:`${i}/v1/mirror-pairing-requests`,method:"POST",headers:{"content-type":"application/json"},body:{mirror_name:n,mode:e.mode,...e.collectionId?{collection_id:e.collectionId}:{}},...t.signal?{signal:t.signal}:{}})}catch(c){throw di(t.signal),Vb()}let o=Fb(s,201);if(!Zi(o)||!ur.test(ct(o.pairing_id))||!ms(o.pairing_secret)||!IR(o.expires_in)||Number(o.expires_in)*1e3>zb)throw Rt("Connect returned an invalid mirror approval.");let a=Hb(i,ct(o.verification_uri),ct(o.pairing_id));return{controlUrl:i,pairingId:ct(o.pairing_id),refreshCredential:ct(o.pairing_secret),verificationUri:a,expiresAt:new Date(this.now()+Number(o.expires_in)*1e3).toISOString(),requested:{mirrorName:n,mode:e.mode,...e.collectionId?{collectionId:e.collectionId}:{}}}}async enroll(e,t){let i=await this.begin(e,t),{refreshCredential:n,...s}=i;return await t.onVerification(s),this.waitForApproval(i,t)}async waitForApproval(e,t={}){var o,a;AR(e,this.now());let i=Ub(t.pollIntervalMs),n=Date.parse(e.expiresAt),s=0;for(;this.now()=500){let l=Eu(c);if(await this.retry(n,(a=c.retryAfterMs)!=null?a:i,t,s,{code:l.code,message:l.message})===null)break;continue}throw Eu(c)}throw new ze("mirror_enrollment_expired","Mirror approval expired before it was completed.")}async renew(e,t={}){kR(e),di(t.signal);let i;try{i=await this.request({url:Db(e.controlUrl,e.enrollmentId,"renew"),method:"POST",headers:{authorization:`Bearer ${e.refreshCredential}`},...t.signal?{signal:t.signal}:{}})}catch(s){throw di(t.signal),Vb()}let n={controlUrl:e.controlUrl,pairingId:e.enrollmentId,refreshCredential:e.refreshCredential,verificationUri:`${e.controlUrl}/mirror/${e.enrollmentId}`,expiresAt:new Date(this.now()+6e4).toISOString(),requested:{mirrorName:e.name,mode:e.mode,collectionId:e.collectionId}};return jb(n,Fb(i,200),{replicaId:e.replicaId})}async retry(e,t,i,n,s){var l;let o=e-this.now();if(o<=0)return null;let a=Math.min(Ub(t),o),c=new Date(this.now()+a).toISOString();return(l=i.onStatus)==null||l.call(i,{state:s?"retrying":"waiting_for_approval",attempt:n,expiresAt:new Date(e).toISOString(),retryAt:c,...s?{error:s}:{}}),await this.wait(a,i.signal),c}},ze=class extends T{constructor(t,i,n){super(t,i);I(this,"status");this.status=n,this.name="MirrorEnrollmentError"}};function fr(r){let e;try{e=new URL(r)}catch(i){throw new ze("invalid_connect_url","Connect URL must be an absolute HTTPS origin.")}if(e.pathname!=="/"||e.search||e.hash||e.username||e.password)throw new ze("invalid_connect_url","Connect URL must be an origin without credentials, path, query, or fragment.");let t=["localhost","127.0.0.1","[::1]","::1"].includes(e.hostname);if(e.protocol!=="https:"&&!(e.protocol==="http:"&&t))throw new ze("invalid_connect_url","Connect URL must use HTTPS outside loopback development.");return e.origin}async function ER(r){let e=await fetch(r.url,{method:r.method,headers:r.headers,...r.body===void 0?{}:{body:JSON.stringify(r.body)},...r.signal?{signal:r.signal}:{}}),t=await e.json().catch(()=>null),i=e.headers.get("retry-after");return{status:e.status,body:t,...i===null?{}:{retryAfterMs:PR(i)}}}function jb(r,e,t){if(!Zi(e)||e.status!=="paired"||!Zi(e.replica))throw Rt("Connect returned an invalid mirror enrollment.");let i=e.replica,n=ct(i.id),s=ct(i.collection_id),o=ct(i.name).trim(),a=i.mode,c=ct(e.token),l=ct(e.token_expires_at);if(!ur.test(n)||!ur.test(s)||!o||!["read_only","read_write"].includes(String(a))||!ms(c)||!Gb(l))throw Rt("Connect returned invalid mirror credentials.");if(a!==r.requested.mode)throw Rt("Connect returned a mirror with a different access mode.");if(r.requested.collectionId&&s!==r.requested.collectionId)throw Rt("Connect returned a different collection.");if(t.mirrorName!==void 0&&o!==t.mirrorName)throw Rt("Connect returned a mirror with a different name.");if(t.replicaId!==void 0&&n!==t.replicaId)throw Rt("Connect returned a different mirror replica.");let u;try{u=Bb(ct(e.sync_url),s)}catch(d){throw Rt("Connect returned an invalid authority sync URL.")}return{controlUrl:fr(r.controlUrl),syncUrl:u,collectionId:s,replicaId:n,mode:a,name:o,enrollmentId:r.pairingId,accessToken:c,refreshCredential:r.refreshCredential,accessTokenExpiresAt:l}}function AR(r,e){fr(r.controlUrl);let t=Date.parse(r.expiresAt);if(!ur.test(r.pairingId)||!ms(r.refreshCredential)||!Number.isFinite(t)||t-e>zb||!r.requested.mirrorName.trim()||r.requested.mirrorName.length>200||!["read_only","read_write"].includes(r.requested.mode)||r.requested.collectionId!==void 0&&!ur.test(r.requested.collectionId))throw new ze("invalid_mirror_enrollment_session","Mirror enrollment session is invalid.");Hb(r.controlUrl,r.verificationUri,r.pairingId)}function kR(r){if(fr(r.controlUrl),Bb(r.syncUrl,r.collectionId),!ur.test(r.collectionId)||!ur.test(r.replicaId)||!ur.test(r.enrollmentId)||!ms(r.accessToken)||!ms(r.refreshCredential)||!Gb(r.accessTokenExpiresAt)||!r.name.trim()||r.name.length>200||!["read_only","read_write"].includes(r.mode))throw new ze("invalid_mirror_enrollment","Stored mirror enrollment is invalid.")}function Bb(r,e){let t=new URL(r),i=`/v1/authorities/${encodeURIComponent(e)}/sync`;if(!(t.protocol==="https:"||t.protocol==="http:"&&["localhost","127.0.0.1","[::1]","::1"].includes(t.hostname))||t.username||t.password||t.pathname.replace(/\/$/,"")!==i||t.search||t.hash)throw new Error("invalid sync URL");return`${t.origin}${i}`}function Hb(r,e,t){let i;try{i=new URL(e)}catch(s){throw Rt("Connect returned an invalid mirror verification URI.")}let n=new URL(`/mirror/${encodeURIComponent(t)}`,r);if(i.origin!==n.origin||i.pathname!==n.pathname||i.search||i.hash||i.username||i.password)throw Rt("Connect returned an untrusted mirror verification URI.");return i.href}function Db(r,e,t){return`${fr(r)}/v1/mirror-pairing-requests/${encodeURIComponent(e)}/${t}`}function Fb(r,e){if(r.status!==e)throw Eu(r);return r.body}function Eu(r){let e=Zi(r.body)&&Zi(r.body.error)?r.body.error:{};return new ze(ct(e.code)||"mirror_enrollment_request_failed",ct(e.message)||`Mirror enrollment request failed with status ${r.status}.`,r.status)}function Rt(r){return new ze("invalid_mirror_enrollment_response",r)}function Kb(r){return{code:"mirror_enrollment_unreachable",message:"Connect could not be reached for mirror enrollment."}}function Vb(){let r=Kb(void 0);return new ze(r.code,r.message)}function Ub(r=Su){return Number.isFinite(r)?Math.min(SR,Math.max($R,Math.round(r))):Su}function PR(r){let e=Number(r);if(Number.isFinite(e)&&e>=0)return e*1e3;let t=Date.parse(r);return Number.isFinite(t)?Math.max(0,t-Date.now()):Su}function xR(r,e){return di(e),new Promise((t,i)=>{let n=setTimeout(o,r),s=()=>{clearTimeout(n),e==null||e.removeEventListener("abort",s),i(new ze("mirror_enrollment_cancelled","Mirror enrollment was cancelled."))};function o(){e==null||e.removeEventListener("abort",s),t()}e==null||e.addEventListener("abort",s,{once:!0})})}function di(r){if(r!=null&&r.aborted)throw new ze("mirror_enrollment_cancelled","Mirror enrollment was cancelled.")}function Gb(r){let e=Date.parse(r);return Number.isFinite(e)}function IR(r){return typeof r=="number"&&Number.isSafeInteger(r)&&r>0}function ms(r){return typeof r=="string"&&r.length>=16}function ct(r){return typeof r=="string"?r:""}function Zi(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}var da=Symbol.for("yaml.alias"),ua=Symbol.for("yaml.document"),Tt=Symbol.for("yaml.map"),Au=Symbol.for("yaml.pair"),lt=Symbol.for("yaml.scalar"),pr=Symbol.for("yaml.seq"),Ye=Symbol.for("yaml.node.type"),Ot=r=>!!r&&typeof r=="object"&&r[Ye]===da,Ct=r=>!!r&&typeof r=="object"&&r[Ye]===ua,Nt=r=>!!r&&typeof r=="object"&&r[Ye]===Tt,ee=r=>!!r&&typeof r=="object"&&r[Ye]===Au,K=r=>!!r&&typeof r=="object"&&r[Ye]===lt,Mt=r=>!!r&&typeof r=="object"&&r[Ye]===pr;function se(r){if(r&&typeof r=="object")switch(r[Ye]){case Tt:case pr:return!0}return!1}function re(r){if(r&&typeof r=="object")switch(r[Ye]){case da:case Tt:case lt:case pr:return!0}return!1}var fa=r=>(K(r)||se(r))&&!!r.anchor;var it=Symbol("break visit"),Wb=Symbol("skip children"),Yt=Symbol("remove node");function Xt(r,e){let t=Jb(e);Ct(r)?Qi(null,r.contents,t,Object.freeze([r]))===Yt&&(r.contents=null):Qi(null,r,t,Object.freeze([]))}Xt.BREAK=it;Xt.SKIP=Wb;Xt.REMOVE=Yt;function Qi(r,e,t,i){let n=Yb(r,e,t,i);if(re(n)||ee(n))return Xb(r,i,n),Qi(r,n,t,i);if(typeof n!="symbol"){if(se(e)){i=Object.freeze(i.concat(e));for(let s=0;sr.replace(/[!,[\]{}]/g,e=>RR[e]),Zt=class r{constructor(e,t){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},r.defaultYaml,e),this.tags=Object.assign({},r.defaultTags,t)}clone(){let e=new r(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){let e=new r(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:r.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},r.defaultTags);break}return e}add(e,t){this.atNextDocument&&(this.yaml={explicit:r.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},r.defaultTags),this.atNextDocument=!1);let i=e.trim().split(/[ \t]+/),n=i.shift();switch(n){case"%TAG":{if(i.length!==2&&(t(0,"%TAG directive should contain exactly two parts"),i.length<2))return!1;let[s,o]=i;return this.tags[s]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,i.length!==1)return t(0,"%YAML directive should contain exactly one part"),!1;let[s]=i;if(s==="1.1"||s==="1.2")return this.yaml.version=s,!0;{let o=/^\d+\.\d+$/.test(s);return t(6,`Unsupported YAML version ${s}`,o),!1}}default:return t(0,`Unknown directive ${n}`,!0),!1}}tagName(e,t){if(e==="!")return"!";if(e[0]!=="!")return t(`Not a valid tag: ${e}`),null;if(e[1]==="<"){let o=e.slice(2,-1);return o==="!"||o==="!!"?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==">"&&t("Verbatim tags must end with a >"),o)}let[,i,n]=e.match(/^(.*!)([^!]*)$/s);n||t(`The ${e} tag has no suffix`);let s=this.tags[i];if(s)try{return s+decodeURIComponent(n)}catch(o){return t(String(o)),null}return i==="!"?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[t,i]of Object.entries(this.tags))if(e.startsWith(i))return t+TR(e.substring(i.length));return e[0]==="!"?e:`!<${e}>`}toString(e){let t=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],i=Object.entries(this.tags),n;if(e&&i.length>0&&re(e.contents)){let s={};Xt(e.contents,(o,a)=>{re(a)&&a.tag&&(s[a.tag]=!0)}),n=Object.keys(s)}else n=[];for(let[s,o]of i)s==="!!"&&o==="tag:yaml.org,2002:"||(!e||n.some(a=>a.startsWith(o)))&&t.push(`%TAG ${s} ${o}`);return t.join(` -`)}};Zt.defaultYaml={explicit:!1,version:"1.2"};Zt.defaultTags={"!!":"tag:yaml.org,2002:"};function ha(r){if(/[\x00-\x19\s,[\]{}]/.test(r)){let t=`Anchor must not contain whitespace or control characters: ${JSON.stringify(r)}`;throw new Error(t)}return!0}function ku(r){let e=new Set;return Xt(r,{Value(t,i){i.anchor&&e.add(i.anchor)}}),e}function Pu(r,e){for(let t=1;;++t){let i=`${r}${t}`;if(!e.has(i))return i}}function Zb(r,e){let t=[],i=new Map,n=null;return{onAnchor:s=>{t.push(s),n!=null||(n=ku(r));let o=Pu(e,n);return n.add(o),o},setAnchors:()=>{for(let s of t){let o=i.get(s);if(typeof o=="object"&&o.anchor&&(K(o.node)||se(o.node)))o.node.anchor=o.anchor;else{let a=new Error("Failed to resolve repeated object (this should not happen)");throw a.source=s,a}}},sourceObjects:i}}function Vr(r,e,t,i){if(i&&typeof i=="object")if(Array.isArray(i))for(let n=0,s=i.length;nTe(i,String(n),t));if(r&&typeof r.toJSON=="function"){if(!t||!fa(r))return r.toJSON(e,t);let i={aliasCount:0,count:1,res:void 0};t.anchors.set(r,i),t.onCreate=s=>{i.res=s,delete t.onCreate};let n=r.toJSON(e,t);return t.onCreate&&t.onCreate(n),n}return typeof r=="bigint"&&!(t!=null&&t.keep)?Number(r):r}var Ur=class{constructor(e){Object.defineProperty(this,Ye,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:t,maxAliasCount:i,onAnchor:n,reviver:s}={}){if(!Ct(e))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:e,keep:!0,mapAsMap:t===!0,mapKeyWarned:!1,maxAliasCount:typeof i=="number"?i:100},a=Te(this,"",o);if(typeof n=="function")for(let{count:c,res:l}of o.anchors.values())n(l,c);return typeof s=="function"?Vr(s,{"":a},"",a):a}};var hr=class extends Ur{constructor(e){super(da),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,t){if((t==null?void 0:t.maxAliasCount)===0)throw new ReferenceError("Alias resolution is disabled");let i;t!=null&&t.aliasResolveCache?i=t.aliasResolveCache:(i=[],Xt(e,{Node:(s,o)=>{(Ot(o)||fa(o))&&i.push(o)}}),t&&(t.aliasResolveCache=i));let n;for(let s of i){if(s===this)break;s.anchor===this.source&&(n=s)}return n}toJSON(e,t){if(!t)return{source:this.source};let{anchors:i,doc:n,maxAliasCount:s}=t,o=this.resolve(n,t);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let a=i.get(o);if(a||(Te(o,null,t),a=i.get(o)),(a==null?void 0:a.res)===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(s>=0&&(a.count+=1,a.aliasCount===0&&(a.aliasCount=ma(n,o,i)),a.count*a.aliasCount>s)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return a.res}toString(e,t,i){let n=`*${this.source}`;if(e){if(ha(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let s=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(s)}if(e.implicitKey)return`${n} `}return n}};function ma(r,e,t){if(Ot(e)){let i=e.resolve(r),n=t&&i&&t.get(i);return n?n.count*n.aliasCount:0}else if(se(e)){let i=0;for(let n of e.items){let s=ma(r,n,t);s>i&&(i=s)}return i}else if(ee(e)){let i=ma(r,e.key,t),n=ma(r,e.value,t);return Math.max(i,n)}return 1}var ya=r=>!r||typeof r!="function"&&typeof r!="object",j=class extends Ur{constructor(e){super(lt),this.value=e}toJSON(e,t){return t!=null&&t.keep?this.value:Te(this.value,e,t)}toString(){return String(this.value)}};j.BLOCK_FOLDED="BLOCK_FOLDED";j.BLOCK_LITERAL="BLOCK_LITERAL";j.PLAIN="PLAIN";j.QUOTE_DOUBLE="QUOTE_DOUBLE";j.QUOTE_SINGLE="QUOTE_SINGLE";var OR="tag:yaml.org,2002:";function CR(r,e,t){var i;if(e){let n=t.filter(o=>o.tag===e),s=(i=n.find(o=>!o.format))!=null?i:n[0];if(!s)throw new Error(`Tag ${e} not found`);return s}return t.find(n=>{var s;return((s=n.identify)==null?void 0:s.call(n,r))&&!n.format})}function mr(r,e,t){var d,f,p,m;if(Ct(r)&&(r=r.contents),re(r))return r;if(ee(r)){let h=(f=(d=t.schema[Tt]).createNode)==null?void 0:f.call(d,t.schema,null,t);return h.items.push(r),h}(r instanceof String||r instanceof Number||r instanceof Boolean||typeof BigInt!="undefined"&&r instanceof BigInt)&&(r=r.valueOf());let{aliasDuplicateObjects:i,onAnchor:n,onTagObj:s,schema:o,sourceObjects:a}=t,c;if(i&&r&&typeof r=="object"){if(c=a.get(r),c)return(p=c.anchor)!=null||(c.anchor=n(r)),new hr(c.anchor);c={anchor:null,node:null},a.set(r,c)}e!=null&&e.startsWith("!!")&&(e=OR+e.slice(2));let l=CR(r,e,o.tags);if(!l){if(r&&typeof r.toJSON=="function"&&(r=r.toJSON()),!r||typeof r!="object"){let h=new j(r);return c&&(c.node=h),h}l=r instanceof Map?o[Tt]:Symbol.iterator in Object(r)?o[pr]:o[Tt]}s&&(s(l),delete t.onTagObj);let u=l!=null&&l.createNode?l.createNode(t.schema,r,t):typeof((m=l==null?void 0:l.nodeClass)==null?void 0:m.from)=="function"?l.nodeClass.from(t.schema,r,t):new j(r);return e?u.tag=e:l.default||(u.tag=l.tag),c&&(c.node=u),u}function ys(r,e,t){let i=t;for(let n=e.length-1;n>=0;--n){let s=e[n];if(typeof s=="number"&&Number.isInteger(s)&&s>=0){let o=[];o[s]=i,i=o}else i=new Map([[s,i]])}return mr(i,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:r,sourceObjects:new Map})}var rn=r=>r==null||typeof r=="object"&&!!r[Symbol.iterator]().next().done,tn=class extends Ur{constructor(e,t){super(e),Object.defineProperty(this,"schema",{value:t,configurable:!0,enumerable:!1,writable:!0})}clone(e){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(t.schema=e),t.items=t.items.map(i=>re(i)||ee(i)?i.clone(e):i),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(rn(e))this.add(t);else{let[i,...n]=e,s=this.get(i,!0);if(se(s))s.addIn(n,t);else if(s===void 0&&this.schema)this.set(i,ys(this.schema,n,t));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}}deleteIn(e){let[t,...i]=e;if(i.length===0)return this.delete(t);let n=this.get(t,!0);if(se(n))return n.deleteIn(i);throw new Error(`Expected YAML collection at ${t}. Remaining path: ${i}`)}getIn(e,t){let[i,...n]=e,s=this.get(i,!0);return n.length===0?!t&&K(s)?s.value:s:se(s)?s.getIn(n,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!ee(t))return!1;let i=t.value;return i==null||e&&K(i)&&i.value==null&&!i.commentBefore&&!i.comment&&!i.tag})}hasIn(e){let[t,...i]=e;if(i.length===0)return this.has(t);let n=this.get(t,!0);return se(n)?n.hasIn(i):!1}setIn(e,t){let[i,...n]=e;if(n.length===0)this.set(i,t);else{let s=this.get(i,!0);if(se(s))s.setIn(n,t);else if(s===void 0&&this.schema)this.set(i,ys(this.schema,n,t));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}}};var Qb=r=>r.replace(/^(?!$)(?: $)?/gm,"#");function wt(r,e){return/^\n+$/.test(r)?r.substring(1):e?r.replace(/^(?! *$)/gm,e):r}var Qt=(r,e,t)=>r.endsWith(` +`}function rb(r,e){var s;let t={},n=(s=e.settings.explicit_type_keys[0])!=null?s:"type";t[n]=n==="types"?[r.name]:r.name;for(let[i,o]of Object.entries(r.fields)){if(!Z(o))continue;let a=o;a.default!==void 0&&(t[i]=Ge(a.default))}return t}function nb(r,e){let t=[];for(let[n,s]of Object.entries(r.fields)){if(!Z(s))continue;let i=s;i.computed||i.required&&e[n]===void 0&&t.push([n,i])}return t}function Qd(r,e){var s;let t=r.trim();switch((s=e.type)!=null?s:"string"){case"string":case"date":case"datetime":case"time":case"link":case"enum":case"any":return t;case"integer":{let i=Number.parseInt(t,10);if(!Number.isInteger(i))throw new Error("Expected integer input");return i}case"number":{let i=Number.parseFloat(t);if(Number.isNaN(i))throw new Error("Expected numeric input");return i}case"boolean":{let i=t.toLowerCase();if(["true","1","yes","y"].includes(i))return!0;if(["false","0","no","n"].includes(i))return!1;throw new Error("Expected boolean input: true/false")}case"list":{let i=t.split(",").map(o=>o.trim()).filter(o=>o.length>0);return e.items?i.map(o=>Qd(o,e.items)):i}case"object":{let i=(0,fe.parseYaml)(t);if(!Z(i))throw new Error("Expected YAML object value");return i}case"tags":return t.split(",").map(i=>i.trim()).filter(i=>i.length>0);default:return t}}function Bg(r){let e=r.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").replace(/-+/g,"-").replace(/^-+/,"").replace(/-+$/,"");return e.length>0?e:"note"}async function sb(r,e){let t=(0,fe.normalizePath)(e).replace(/\/+$/,"");if(!t)return;let n=t.split("/"),s="";for(let i of n)s=s?`${s}/${i}`:i,await r.adapter.exists(s)||await r.createFolder(s)}function MT(r,e){if(!r.path_pattern||r.path_pattern.trim().length===0)return null;let t=(0,fe.normalizePath)(Yd(r.path_pattern,e));return t.endsWith(".md")?t:null}async function ib(r,e,t){var u;let n=MT(e,t),s=bT(e,t),i=n?(u=n.split("/").pop())!=null?u:n:wT(e,t),o=ri(n||`${s?`${s}/`:""}${i.endsWith(".md")?i:`${i}.md`}`),a=o,c=2;for(;r.getAbstractFileByPath(a);)a=o.replace(/\.md$/,`-${c}.md`),c+=1;let l=a.lastIndexOf("/");return l>0&&await sb(r,a.slice(0,l)),a}async function ob(r,e,t,n=""){let s=ri(e),i=s.lastIndexOf("/");if(i>0&&await sb(r,s.slice(0,i)),await r.adapter.exists(s))throw new Error(`File already exists: ${s}`);let o=`${ot(t,n)} +`;return r.create(s,o)}function Vo(r){return uT(r)}var le=require("obsidian"),T0=Hr(Hd(),1);var O=class extends Error{constructor(t,n){super(n);P(this,"code");this.code=t}};function LT(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in r&&r.BYTES_PER_ELEMENT===1}function Uo(r,e,t=""){let n=LT(r),s=r==null?void 0:r.length,i=e!==void 0;if(!n||i&&s!==e){let o=t&&`"${t}" `,a=i?` of length ${e}`:"",c=n?`length=${s}`:`type=${typeof r}`,l=o+"expected Uint8Array"+a+", got "+c;throw n?new RangeError(l):new TypeError(l)}return r}function Zd(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function ab(r,e){Uo(r,void 0,"digestInto() output");let t=e.outputLen;if(r.length='+t)}function Cr(...r){for(let e=0;e>>e}function Ho(r,e){return r<>>32-e>>>0}var qT=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",DT=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function Nr(r){if(Uo(r),qT)return r.toHex();let e="";for(let t=0;tr(i).update(s).digest(),n=r(void 0);return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.canXOF=n.canXOF,t.create=s=>r(s),Object.assign(t,e),Object.freeze(t)}var cb=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function Ko(r,e,t){return r&e^~r&t}function Go(r,e,t){return r&e^r&t^e&t}var Gn=class{constructor(e,t,n,s){P(this,"blockLen");P(this,"outputLen");P(this,"canXOF",!1);P(this,"padOffset");P(this,"isLE");P(this,"buffer");P(this,"view");P(this,"finished",!1);P(this,"length",0);P(this,"pos",0);P(this,"destroyed",!1);this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=s,this.buffer=new Uint8Array(e),this.view=Bo(this.buffer)}update(e){Zd(this),Uo(e);let{view:t,buffer:n,blockLen:s}=this,i=e.length;for(let o=0;os-o&&(this.process(n,0),o=0);for(let d=o;du.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;dnew eu);var jT=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Lr=new Uint32Array(64),tu=class extends Gn{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:n,D:s,E:i,F:o,G:a,H:c}=this;return[e,t,n,s,i,o,a,c]}set(e,t,n,s,i,o,a,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=s|0,this.E=i|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,t){for(let d=0;d<16;d++,t+=4)Lr[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){let f=Lr[d-15],p=Lr[d-2],m=xt(f,7)^xt(f,18)^f>>>3,h=xt(p,17)^xt(p,19)^p>>>10;Lr[d]=h+Lr[d-7]+m+Lr[d-16]|0}let{A:n,B:s,C:i,D:o,E:a,F:c,G:l,H:u}=this;for(let d=0;d<64;d++){let f=xt(a,6)^xt(a,11)^xt(a,25),p=u+f+Ko(a,c,l)+jT[d]+Lr[d]|0,h=(xt(n,2)^xt(n,13)^xt(n,22))+Go(n,s,i)|0;u=l,l=c,c=a,a=o+p|0,o=i,i=s,s=n,n=p+h|0}n=n+this.A|0,s=s+this.B|0,i=i+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(n,s,i,o,a,c,l,u)}roundClean(){Cr(Lr)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),Cr(this.buffer)}},ru=class extends tu{constructor(){super(32);P(this,"A",cr[0]|0);P(this,"B",cr[1]|0);P(this,"C",cr[2]|0);P(this,"D",cr[3]|0);P(this,"E",cr[4]|0);P(this,"F",cr[5]|0);P(this,"G",cr[6]|0);P(this,"H",cr[7]|0)}};var sn=zo(()=>new ru,cb(1));var nu=1500,FT=250,VT=3e4,mb=1440*60*1e3,lr=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,Wo=class{constructor(e={}){P(this,"request");P(this,"now");P(this,"wait");var t,n,s;this.request=(t=e.request)!=null?t:UT,this.now=(n=e.now)!=null?n:Date.now,this.wait=(s=e.wait)!=null?s:KT}async begin(e,t={}){on(t.signal);let n=dr(e.controlUrl),s=e.mirrorName.trim();if(!s||s.length>200)throw new Ve("invalid_mirror_name","Mirror name must contain between 1 and 200 characters.");if(!["read_only","read_write"].includes(e.mode))throw new Ve("invalid_mirror_mode","Mirror mode must be read-only or read-write.");if(e.collectionId!==void 0&&!lr.test(e.collectionId))throw new Ve("invalid_collection_id","Collection ID must be a UUID.");let i;try{i=await this.request({url:`${n}/v1/mirror-pairing-requests`,method:"POST",headers:{"content-type":"application/json"},body:{mirror_name:s,mode:e.mode,...e.collectionId?{collection_id:e.collectionId}:{}},...t.signal?{signal:t.signal}:{}})}catch(c){throw on(t.signal),pb()}let o=fb(i,201);if(!Wn(o)||!lr.test(at(o.pairing_id))||!ii(o.pairing_secret)||!GT(o.expires_in)||Number(o.expires_in)*1e3>mb)throw It("Connect returned an invalid mirror approval.");let a=gb(n,at(o.verification_uri),at(o.pairing_id));return{controlUrl:n,pairingId:at(o.pairing_id),refreshCredential:at(o.pairing_secret),verificationUri:a,expiresAt:new Date(this.now()+Number(o.expires_in)*1e3).toISOString(),requested:{mirrorName:s,mode:e.mode,...e.collectionId?{collectionId:e.collectionId}:{}}}}async enroll(e,t){let n=await this.begin(e,t),{refreshCredential:s,...i}=n;return await t.onVerification(i),this.waitForApproval(n,t)}async waitForApproval(e,t={}){var o,a;BT(e,this.now());let n=hb(t.pollIntervalMs),s=Date.parse(e.expiresAt),i=0;for(;this.now()=500){let l=su(c);if(await this.retry(s,(a=c.retryAfterMs)!=null?a:n,t,i,{code:l.code,message:l.message})===null)break;continue}throw su(c)}throw new Ve("mirror_enrollment_expired","Mirror approval expired before it was completed.")}async renew(e,t={}){HT(e),on(t.signal);let n;try{n=await this.request({url:ub(e.controlUrl,e.enrollmentId,"renew"),method:"POST",headers:{authorization:`Bearer ${e.refreshCredential}`},...t.signal?{signal:t.signal}:{}})}catch(i){throw on(t.signal),pb()}let s={controlUrl:e.controlUrl,pairingId:e.enrollmentId,refreshCredential:e.refreshCredential,verificationUri:`${e.controlUrl}/mirror/${e.enrollmentId}`,expiresAt:new Date(this.now()+6e4).toISOString(),requested:{mirrorName:e.name,mode:e.mode,collectionId:e.collectionId}};return db(s,fb(n,200),{replicaId:e.replicaId})}async retry(e,t,n,s,i){var l;let o=e-this.now();if(o<=0)return null;let a=Math.min(hb(t),o),c=new Date(this.now()+a).toISOString();return(l=n.onStatus)==null||l.call(n,{state:i?"retrying":"waiting_for_approval",attempt:s,expiresAt:new Date(e).toISOString(),retryAt:c,...i?{error:i}:{}}),await this.wait(a,n.signal),c}},Ve=class extends O{constructor(t,n,s){super(t,n);P(this,"status");this.status=s,this.name="MirrorEnrollmentError"}};function dr(r){let e;try{e=new URL(r)}catch(n){throw new Ve("invalid_connect_url","Connect URL must be an absolute HTTPS origin.")}if(e.pathname!=="/"||e.search||e.hash||e.username||e.password)throw new Ve("invalid_connect_url","Connect URL must be an origin without credentials, path, query, or fragment.");let t=["localhost","127.0.0.1","[::1]","::1"].includes(e.hostname);if(e.protocol!=="https:"&&!(e.protocol==="http:"&&t))throw new Ve("invalid_connect_url","Connect URL must use HTTPS outside loopback development.");return e.origin}async function UT(r){let e=await fetch(r.url,{method:r.method,headers:r.headers,...r.body===void 0?{}:{body:JSON.stringify(r.body)},...r.signal?{signal:r.signal}:{}}),t=await e.json().catch(()=>null),n=e.headers.get("retry-after");return{status:e.status,body:t,...n===null?{}:{retryAfterMs:zT(n)}}}function db(r,e,t){if(!Wn(e)||e.status!=="paired"||!Wn(e.replica))throw It("Connect returned an invalid mirror enrollment.");let n=e.replica,s=at(n.id),i=at(n.collection_id),o=at(n.name).trim(),a=n.mode,c=at(e.token),l=at(e.token_expires_at);if(!lr.test(s)||!lr.test(i)||!o||!["read_only","read_write"].includes(String(a))||!ii(c)||!wb(l))throw It("Connect returned invalid mirror credentials.");if(a!==r.requested.mode)throw It("Connect returned a mirror with a different access mode.");if(r.requested.collectionId&&i!==r.requested.collectionId)throw It("Connect returned a different collection.");if(t.mirrorName!==void 0&&o!==t.mirrorName)throw It("Connect returned a mirror with a different name.");if(t.replicaId!==void 0&&s!==t.replicaId)throw It("Connect returned a different mirror replica.");let u;try{u=yb(at(e.sync_url),i)}catch(d){throw It("Connect returned an invalid authority sync URL.")}return{controlUrl:dr(r.controlUrl),syncUrl:u,collectionId:i,replicaId:s,mode:a,name:o,enrollmentId:r.pairingId,accessToken:c,refreshCredential:r.refreshCredential,accessTokenExpiresAt:l}}function BT(r,e){dr(r.controlUrl);let t=Date.parse(r.expiresAt);if(!lr.test(r.pairingId)||!ii(r.refreshCredential)||!Number.isFinite(t)||t-e>mb||!r.requested.mirrorName.trim()||r.requested.mirrorName.length>200||!["read_only","read_write"].includes(r.requested.mode)||r.requested.collectionId!==void 0&&!lr.test(r.requested.collectionId))throw new Ve("invalid_mirror_enrollment_session","Mirror enrollment session is invalid.");gb(r.controlUrl,r.verificationUri,r.pairingId)}function HT(r){if(dr(r.controlUrl),yb(r.syncUrl,r.collectionId),!lr.test(r.collectionId)||!lr.test(r.replicaId)||!lr.test(r.enrollmentId)||!ii(r.accessToken)||!ii(r.refreshCredential)||!wb(r.accessTokenExpiresAt)||!r.name.trim()||r.name.length>200||!["read_only","read_write"].includes(r.mode))throw new Ve("invalid_mirror_enrollment","Stored mirror enrollment is invalid.")}function yb(r,e){let t=new URL(r),n=`/v1/authorities/${encodeURIComponent(e)}/sync`;if(!(t.protocol==="https:"||t.protocol==="http:"&&["localhost","127.0.0.1","[::1]","::1"].includes(t.hostname))||t.username||t.password||t.pathname.replace(/\/$/,"")!==n||t.search||t.hash)throw new Error("invalid sync URL");return`${t.origin}${n}`}function gb(r,e,t){let n;try{n=new URL(e)}catch(i){throw It("Connect returned an invalid mirror verification URI.")}let s=new URL(`/mirror/${encodeURIComponent(t)}`,r);if(n.origin!==s.origin||n.pathname!==s.pathname||n.search||n.hash||n.username||n.password)throw It("Connect returned an untrusted mirror verification URI.");return n.href}function ub(r,e,t){return`${dr(r)}/v1/mirror-pairing-requests/${encodeURIComponent(e)}/${t}`}function fb(r,e){if(r.status!==e)throw su(r);return r.body}function su(r){let e=Wn(r.body)&&Wn(r.body.error)?r.body.error:{};return new Ve(at(e.code)||"mirror_enrollment_request_failed",at(e.message)||`Mirror enrollment request failed with status ${r.status}.`,r.status)}function It(r){return new Ve("invalid_mirror_enrollment_response",r)}function bb(r){return{code:"mirror_enrollment_unreachable",message:"Connect could not be reached for mirror enrollment."}}function pb(){let r=bb(void 0);return new Ve(r.code,r.message)}function hb(r=nu){return Number.isFinite(r)?Math.min(VT,Math.max(FT,Math.round(r))):nu}function zT(r){let e=Number(r);if(Number.isFinite(e)&&e>=0)return e*1e3;let t=Date.parse(r);return Number.isFinite(t)?Math.max(0,t-Date.now()):nu}function KT(r,e){return on(e),new Promise((t,n)=>{let s=setTimeout(o,r),i=()=>{clearTimeout(s),e==null||e.removeEventListener("abort",i),n(new Ve("mirror_enrollment_cancelled","Mirror enrollment was cancelled."))};function o(){e==null||e.removeEventListener("abort",i),t()}e==null||e.addEventListener("abort",i,{once:!0})})}function on(r){if(r!=null&&r.aborted)throw new Ve("mirror_enrollment_cancelled","Mirror enrollment was cancelled.")}function wb(r){let e=Date.parse(r);return Number.isFinite(e)}function GT(r){return typeof r=="number"&&Number.isSafeInteger(r)&&r>0}function ii(r){return typeof r=="string"&&r.length>=16}function at(r){return typeof r=="string"?r:""}function Wn(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}var Jo=Symbol.for("yaml.alias"),Yo=Symbol.for("yaml.document"),Tt=Symbol.for("yaml.map"),iu=Symbol.for("yaml.pair"),ct=Symbol.for("yaml.scalar"),ur=Symbol.for("yaml.seq"),We=Symbol.for("yaml.node.type"),Pt=r=>!!r&&typeof r=="object"&&r[We]===Jo,Ot=r=>!!r&&typeof r=="object"&&r[We]===Yo,Rt=r=>!!r&&typeof r=="object"&&r[We]===Tt,ee=r=>!!r&&typeof r=="object"&&r[We]===iu,K=r=>!!r&&typeof r=="object"&&r[We]===ct,Ct=r=>!!r&&typeof r=="object"&&r[We]===ur;function ie(r){if(r&&typeof r=="object")switch(r[We]){case Tt:case ur:return!0}return!1}function re(r){if(r&&typeof r=="object")switch(r[We]){case Jo:case Tt:case ct:case ur:return!0}return!1}var Xo=r=>(K(r)||ie(r))&&!!r.anchor;var rt=Symbol("break visit"),_b=Symbol("skip children"),Wt=Symbol("remove node");function Jt(r,e){let t=vb(e);Ot(r)?Jn(null,r.contents,t,Object.freeze([r]))===Wt&&(r.contents=null):Jn(null,r,t,Object.freeze([]))}Jt.BREAK=rt;Jt.SKIP=_b;Jt.REMOVE=Wt;function Jn(r,e,t,n){let s=$b(r,e,t,n);if(re(s)||ee(s))return Sb(r,n,s),Jn(r,s,t,n);if(typeof s!="symbol"){if(ie(e)){n=Object.freeze(n.concat(e));for(let i=0;ir.replace(/[!,[\]{}]/g,e=>WT[e]),Yt=class r{constructor(e,t){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},r.defaultYaml,e),this.tags=Object.assign({},r.defaultTags,t)}clone(){let e=new r(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){let e=new r(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:r.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},r.defaultTags);break}return e}add(e,t){this.atNextDocument&&(this.yaml={explicit:r.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},r.defaultTags),this.atNextDocument=!1);let n=e.trim().split(/[ \t]+/),s=n.shift();switch(s){case"%TAG":{if(n.length!==2&&(t(0,"%TAG directive should contain exactly two parts"),n.length<2))return!1;let[i,o]=n;return this.tags[i]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,n.length!==1)return t(0,"%YAML directive should contain exactly one part"),!1;let[i]=n;if(i==="1.1"||i==="1.2")return this.yaml.version=i,!0;{let o=/^\d+\.\d+$/.test(i);return t(6,`Unsupported YAML version ${i}`,o),!1}}default:return t(0,`Unknown directive ${s}`,!0),!1}}tagName(e,t){if(e==="!")return"!";if(e[0]!=="!")return t(`Not a valid tag: ${e}`),null;if(e[1]==="<"){let o=e.slice(2,-1);return o==="!"||o==="!!"?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==">"&&t("Verbatim tags must end with a >"),o)}let[,n,s]=e.match(/^(.*!)([^!]*)$/s);s||t(`The ${e} tag has no suffix`);let i=this.tags[n];if(i)try{return i+decodeURIComponent(s)}catch(o){return t(String(o)),null}return n==="!"?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[t,n]of Object.entries(this.tags))if(e.startsWith(n))return t+JT(e.substring(n.length));return e[0]==="!"?e:`!<${e}>`}toString(e){let t=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],n=Object.entries(this.tags),s;if(e&&n.length>0&&re(e.contents)){let i={};Jt(e.contents,(o,a)=>{re(a)&&a.tag&&(i[a.tag]=!0)}),s=Object.keys(i)}else s=[];for(let[i,o]of n)i==="!!"&&o==="tag:yaml.org,2002:"||(!e||s.some(a=>a.startsWith(o)))&&t.push(`%TAG ${i} ${o}`);return t.join(` +`)}};Yt.defaultYaml={explicit:!1,version:"1.2"};Yt.defaultTags={"!!":"tag:yaml.org,2002:"};function Zo(r){if(/[\x00-\x19\s,[\]{}]/.test(r)){let t=`Anchor must not contain whitespace or control characters: ${JSON.stringify(r)}`;throw new Error(t)}return!0}function ou(r){let e=new Set;return Jt(r,{Value(t,n){n.anchor&&e.add(n.anchor)}}),e}function au(r,e){for(let t=1;;++t){let n=`${r}${t}`;if(!e.has(n))return n}}function Eb(r,e){let t=[],n=new Map,s=null;return{onAnchor:i=>{t.push(i),s!=null||(s=ou(r));let o=au(e,s);return s.add(o),o},setAnchors:()=>{for(let i of t){let o=n.get(i);if(typeof o=="object"&&o.anchor&&(K(o.node)||ie(o.node)))o.node.anchor=o.anchor;else{let a=new Error("Failed to resolve repeated object (this should not happen)");throw a.source=i,a}}},sourceObjects:n}}function qr(r,e,t,n){if(n&&typeof n=="object")if(Array.isArray(n))for(let s=0,i=n.length;sPe(n,String(s),t));if(r&&typeof r.toJSON=="function"){if(!t||!Xo(r))return r.toJSON(e,t);let n={aliasCount:0,count:1,res:void 0};t.anchors.set(r,n),t.onCreate=i=>{n.res=i,delete t.onCreate};let s=r.toJSON(e,t);return t.onCreate&&t.onCreate(s),s}return typeof r=="bigint"&&!(t!=null&&t.keep)?Number(r):r}var Dr=class{constructor(e){Object.defineProperty(this,We,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:t,maxAliasCount:n,onAnchor:s,reviver:i}={}){if(!Ot(e))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:e,keep:!0,mapAsMap:t===!0,mapKeyWarned:!1,maxAliasCount:typeof n=="number"?n:100},a=Pe(this,"",o);if(typeof s=="function")for(let{count:c,res:l}of o.anchors.values())s(l,c);return typeof i=="function"?qr(i,{"":a},"",a):a}};var fr=class extends Dr{constructor(e){super(Jo),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,t){if((t==null?void 0:t.maxAliasCount)===0)throw new ReferenceError("Alias resolution is disabled");let n;t!=null&&t.aliasResolveCache?n=t.aliasResolveCache:(n=[],Jt(e,{Node:(i,o)=>{(Pt(o)||Xo(o))&&n.push(o)}}),t&&(t.aliasResolveCache=n));let s;for(let i of n){if(i===this)break;i.anchor===this.source&&(s=i)}return s}toJSON(e,t){if(!t)return{source:this.source};let{anchors:n,doc:s,maxAliasCount:i}=t,o=this.resolve(s,t);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let a=n.get(o);if(a||(Pe(o,null,t),a=n.get(o)),(a==null?void 0:a.res)===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(i>=0&&(a.count+=1,a.aliasCount===0&&(a.aliasCount=ea(s,o,n)),a.count*a.aliasCount>i)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return a.res}toString(e,t,n){let s=`*${this.source}`;if(e){if(Zo(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let i=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(i)}if(e.implicitKey)return`${s} `}return s}};function ea(r,e,t){if(Pt(e)){let n=e.resolve(r),s=t&&n&&t.get(n);return s?s.count*s.aliasCount:0}else if(ie(e)){let n=0;for(let s of e.items){let i=ea(r,s,t);i>n&&(n=i)}return n}else if(ee(e)){let n=ea(r,e.key,t),s=ea(r,e.value,t);return Math.max(n,s)}return 1}var ta=r=>!r||typeof r!="function"&&typeof r!="object",D=class extends Dr{constructor(e){super(ct),this.value=e}toJSON(e,t){return t!=null&&t.keep?this.value:Pe(this.value,e,t)}toString(){return String(this.value)}};D.BLOCK_FOLDED="BLOCK_FOLDED";D.BLOCK_LITERAL="BLOCK_LITERAL";D.PLAIN="PLAIN";D.QUOTE_DOUBLE="QUOTE_DOUBLE";D.QUOTE_SINGLE="QUOTE_SINGLE";var YT="tag:yaml.org,2002:";function XT(r,e,t){var n;if(e){let s=t.filter(o=>o.tag===e),i=(n=s.find(o=>!o.format))!=null?n:s[0];if(!i)throw new Error(`Tag ${e} not found`);return i}return t.find(s=>{var i;return((i=s.identify)==null?void 0:i.call(s,r))&&!s.format})}function pr(r,e,t){var d,f,p,m;if(Ot(r)&&(r=r.contents),re(r))return r;if(ee(r)){let h=(f=(d=t.schema[Tt]).createNode)==null?void 0:f.call(d,t.schema,null,t);return h.items.push(r),h}(r instanceof String||r instanceof Number||r instanceof Boolean||typeof BigInt!="undefined"&&r instanceof BigInt)&&(r=r.valueOf());let{aliasDuplicateObjects:n,onAnchor:s,onTagObj:i,schema:o,sourceObjects:a}=t,c;if(n&&r&&typeof r=="object"){if(c=a.get(r),c)return(p=c.anchor)!=null||(c.anchor=s(r)),new fr(c.anchor);c={anchor:null,node:null},a.set(r,c)}e!=null&&e.startsWith("!!")&&(e=YT+e.slice(2));let l=XT(r,e,o.tags);if(!l){if(r&&typeof r.toJSON=="function"&&(r=r.toJSON()),!r||typeof r!="object"){let h=new D(r);return c&&(c.node=h),h}l=r instanceof Map?o[Tt]:Symbol.iterator in Object(r)?o[ur]:o[Tt]}i&&(i(l),delete t.onTagObj);let u=l!=null&&l.createNode?l.createNode(t.schema,r,t):typeof((m=l==null?void 0:l.nodeClass)==null?void 0:m.from)=="function"?l.nodeClass.from(t.schema,r,t):new D(r);return e?u.tag=e:l.default||(u.tag=l.tag),c&&(c.node=u),u}function oi(r,e,t){let n=t;for(let s=e.length-1;s>=0;--s){let i=e[s];if(typeof i=="number"&&Number.isInteger(i)&&i>=0){let o=[];o[i]=n,n=o}else n=new Map([[i,n]])}return pr(n,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:r,sourceObjects:new Map})}var Qn=r=>r==null||typeof r=="object"&&!!r[Symbol.iterator]().next().done,Xn=class extends Dr{constructor(e,t){super(e),Object.defineProperty(this,"schema",{value:t,configurable:!0,enumerable:!1,writable:!0})}clone(e){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(t.schema=e),t.items=t.items.map(n=>re(n)||ee(n)?n.clone(e):n),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(Qn(e))this.add(t);else{let[n,...s]=e,i=this.get(n,!0);if(ie(i))i.addIn(s,t);else if(i===void 0&&this.schema)this.set(n,oi(this.schema,s,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${s}`)}}deleteIn(e){let[t,...n]=e;if(n.length===0)return this.delete(t);let s=this.get(t,!0);if(ie(s))return s.deleteIn(n);throw new Error(`Expected YAML collection at ${t}. Remaining path: ${n}`)}getIn(e,t){let[n,...s]=e,i=this.get(n,!0);return s.length===0?!t&&K(i)?i.value:i:ie(i)?i.getIn(s,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!ee(t))return!1;let n=t.value;return n==null||e&&K(n)&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn(e){let[t,...n]=e;if(n.length===0)return this.has(t);let s=this.get(t,!0);return ie(s)?s.hasIn(n):!1}setIn(e,t){let[n,...s]=e;if(s.length===0)this.set(n,t);else{let i=this.get(n,!0);if(ie(i))i.setIn(s,t);else if(i===void 0&&this.schema)this.set(n,oi(this.schema,s,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${s}`)}}};var Ab=r=>r.replace(/^(?!$)(?: $)?/gm,"#");function wt(r,e){return/^\n+$/.test(r)?r.substring(1):e?r.replace(/^(?! *$)/gm,e):r}var Xt=(r,e,t)=>r.endsWith(` `)?wt(t,e):t.includes(` `)?` -`+wt(t,e):(r.endsWith(" ")?"":" ")+t;var xu="flow",ga="block",gs="quoted";function bs(r,e,t="flow",{indentAtStart:i,lineWidth:n=80,minContentWidth:s=20,onFold:o,onOverflow:a}={}){if(!n||n<0)return r;nn-Math.max(2,s)?l.push(0):d=n-i);let f,p,m=!1,h=-1,y=-1,b=-1;t===ga&&(h=e0(r,h,e.length),h!==-1&&(d=h+c));for(let _;_=r[h+=1];){if(t===gs&&_==="\\"){switch(y=h,r[h+1]){case"x":h+=3;break;case"u":h+=5;break;case"U":h+=9;break;default:h+=1}b=h}if(_===` -`)t===ga&&(h=e0(r,h,e.length)),d=h+e.length+c,f=void 0;else{if(_===" "&&p&&p!==" "&&p!==` +`+wt(t,e):(r.endsWith(" ")?"":" ")+t;var cu="flow",ra="block",ai="quoted";function ci(r,e,t="flow",{indentAtStart:n,lineWidth:s=80,minContentWidth:i=20,onFold:o,onOverflow:a}={}){if(!s||s<0)return r;ss-Math.max(2,i)?l.push(0):d=s-n);let f,p,m=!1,h=-1,y=-1,b=-1;t===ra&&(h=kb(r,h,e.length),h!==-1&&(d=h+c));for(let w;w=r[h+=1];){if(t===ai&&w==="\\"){switch(y=h,r[h+1]){case"x":h+=3;break;case"u":h+=5;break;case"U":h+=9;break;default:h+=1}b=h}if(w===` +`)t===ra&&(h=kb(r,h,e.length)),d=h+e.length+c,f=void 0;else{if(w===" "&&p&&p!==" "&&p!==` `&&p!==" "){let S=r[h+1];S&&S!==" "&&S!==` -`&&S!==" "&&(f=h)}if(h>=d)if(f)l.push(f),d=f+c,f=void 0;else if(t===gs){for(;p===" "||p===" ";)p=_,_=r[h+=1],m=!0;let S=h>b+1?h-2:y-1;if(u[S])return r;l.push(S),u[S]=!0,d=S+c,f=void 0}else m=!0}p=_}if(m&&a&&a(),l.length===0)return r;o&&o();let g=r.slice(0,l[0]);for(let _=0;_({indentAtStart:e?r.indent.length:r.indentAtStart,lineWidth:r.options.lineWidth,minContentWidth:r.options.minContentWidth}),va=r=>/^(%|---|\.\.\.)/m.test(r);function NR(r,e,t){if(!e||e<0)return!1;let i=e-t,n=r.length;if(n<=i)return!1;for(let s=0,o=0;si)return!0;if(o=s+1,n-o<=i)return!1}return!0}function _s(r,e){let t=JSON.stringify(r);if(e.options.doubleQuotedAsJSON)return t;let{implicitKey:i}=e,n=e.options.doubleQuotedMinMultiLineLength,s=e.indent||(va(r)?" ":""),o="",a=0;for(let c=0,l=t[c];l;l=t[++c])if(l===" "&&t[c+1]==="\\"&&t[c+2]==="n"&&(o+=t.slice(a,c)+"\\ ",c+=1,a=c,l="\\"),l==="\\")switch(t[c+1]){case"u":{o+=t.slice(a,c);let u=t.substr(c+2,4);switch(u){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:u.substr(0,2)==="00"?o+="\\x"+u.substr(2):o+=t.substr(c,6)}c+=5,a=c+1}break;case"n":if(i||t[c+2]==='"'||t.length=d)if(f)l.push(f),d=f+c,f=void 0;else if(t===ai){for(;p===" "||p===" ";)p=w,w=r[h+=1],m=!0;let S=h>b+1?h-2:y-1;if(u[S])return r;l.push(S),u[S]=!0,d=S+c,f=void 0}else m=!0}p=w}if(m&&a&&a(),l.length===0)return r;o&&o();let g=r.slice(0,l[0]);for(let w=0;w({indentAtStart:e?r.indent.length:r.indentAtStart,lineWidth:r.options.lineWidth,minContentWidth:r.options.minContentWidth}),ia=r=>/^(%|---|\.\.\.)/m.test(r);function QT(r,e,t){if(!e||e<0)return!1;let n=e-t,s=r.length;if(s<=n)return!1;for(let i=0,o=0;in)return!0;if(o=i+1,s-o<=n)return!1}return!0}function li(r,e){let t=JSON.stringify(r);if(e.options.doubleQuotedAsJSON)return t;let{implicitKey:n}=e,s=e.options.doubleQuotedMinMultiLineLength,i=e.indent||(ia(r)?" ":""),o="",a=0;for(let c=0,l=t[c];l;l=t[++c])if(l===" "&&t[c+1]==="\\"&&t[c+2]==="n"&&(o+=t.slice(a,c)+"\\ ",c+=1,a=c,l="\\"),l==="\\")switch(t[c+1]){case"u":{o+=t.slice(a,c);let u=t.substr(c+2,4);switch(u){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:u.substr(0,2)==="00"?o+="\\x"+u.substr(2):o+=t.substr(c,6)}c+=5,a=c+1}break;case"n":if(n||t[c+2]==='"'||t.length -`;let d,f;for(f=t.length;f>0;--f){let v=t[f-1];if(v!==` -`&&v!==" "&&v!==" ")break}let p=t.substring(f),m=p.indexOf(` -`);m===-1?d="-":t===p||m!==p.length-1?(d="+",s&&s()):d="",p&&(t=t.slice(0,-p.length),p[p.length-1]===` -`&&(p=p.slice(0,-1)),p=p.replace(Ru,`$&${l}`));let h=!1,y,b=-1;for(y=0;y{P=!0});let E=bs(`${g}${v}${p}`,l,ga,x);if(!P)return`>${S} +`;let d,f;for(f=t.length;f>0;--f){let _=t[f-1];if(_!==` +`&&_!==" "&&_!==" ")break}let p=t.substring(f),m=p.indexOf(` +`);m===-1?d="-":t===p||m!==p.length-1?(d="+",i&&i()):d="",p&&(t=t.slice(0,-p.length),p[p.length-1]===` +`&&(p=p.slice(0,-1)),p=p.replace(du,`$&${l}`));let h=!1,y,b=-1;for(y=0;y{x=!0});let E=ci(`${g}${_}${p}`,l,ra,I);if(!x)return`>${S} ${l}${E}`}return t=t.replace(/\n+/g,`$&${l}`),`|${S} -${l}${g}${t}${p}`}function MR(r,e,t,i){let{type:n,value:s}=r,{actualString:o,implicitKey:a,indent:c,indentStep:l,inFlow:u}=e;if(a&&s.includes(` -`)||u&&/[[\]{},]/.test(s))return nn(s,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(s))return a||u||!s.includes(` -`)?nn(s,e):ba(r,e,t,i);if(!a&&!u&&n!==j.PLAIN&&s.includes(` -`))return ba(r,e,t,i);if(va(s)){if(c==="")return e.forceBlockIndent=!0,ba(r,e,t,i);if(a&&c===l)return nn(s,e)}let d=s.replace(/\n+/g,`$& -${c}`);if(o){let f=h=>{var y;return h.default&&h.tag!=="tag:yaml.org,2002:str"&&((y=h.test)==null?void 0:y.test(d))},{compat:p,tags:m}=e.doc.schema;if(m.some(f)||p!=null&&p.some(f))return nn(s,e)}return a?d:bs(d,c,xu,_a(e,!1))}function ui(r,e,t,i){let{implicitKey:n,inFlow:s}=e,o=typeof r.value=="string"?r:Object.assign({},r,{value:String(r.value)}),{type:a}=r;a!==j.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=j.QUOTE_DOUBLE);let c=u=>{switch(u){case j.BLOCK_FOLDED:case j.BLOCK_LITERAL:return n||s?nn(o.value,e):ba(o,e,t,i);case j.QUOTE_DOUBLE:return _s(o.value,e);case j.QUOTE_SINGLE:return Iu(o.value,e);case j.PLAIN:return MR(o,e,t,i);default:return null}},l=c(a);if(l===null){let{defaultKeyType:u,defaultStringType:d}=e.options,f=n&&u||d;if(l=c(f),l===null)throw new Error(`Unsupported default string type ${f}`)}return l}function wa(r,e){let t=Object.assign({blockQuote:!0,commentString:Qb,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},r.schema.toStringOptions,e),i;switch(t.collectionStyle){case"block":i=!1;break;case"flow":i=!0;break;default:i=null}return{anchors:new Set,doc:r,flowCollectionPadding:t.flowCollectionPadding?" ":"",indent:"",indentStep:typeof t.indent=="number"?" ".repeat(t.indent):" ",inFlow:i,options:t}}function qR(r,e){var n,s,o,a;if(e.tag){let c=r.filter(l=>l.tag===e.tag);if(c.length>0)return(n=c.find(l=>l.format===e.format))!=null?n:c[0]}let t,i;if(K(e)){i=e.value;let c=r.filter(l=>{var u;return(u=l.identify)==null?void 0:u.call(l,i)});if(c.length>1){let l=c.filter(u=>u.test);l.length>0&&(c=l)}t=(s=c.find(l=>l.format===e.format))!=null?s:c.find(l=>!l.format)}else i=e,t=r.find(c=>c.nodeClass&&i instanceof c.nodeClass);if(!t){let c=(a=(o=i==null?void 0:i.constructor)==null?void 0:o.name)!=null?a:i===null?"null":typeof i;throw new Error(`Tag not resolved for ${c} value`)}return t}function LR(r,e,{anchors:t,doc:i}){var a;if(!i.directives)return"";let n=[],s=(K(r)||se(r))&&r.anchor;s&&ha(s)&&(t.add(s),n.push(`&${s}`));let o=(a=r.tag)!=null?a:e.default?null:e.tag;return o&&n.push(i.directives.tagString(o)),n.join(" ")}function yr(r,e,t,i){var c,l;if(ee(r))return r.toString(e,t,i);if(Ot(r)){if(e.doc.directives)return r.toString(e);if((c=e.resolvedAliases)!=null&&c.has(r))throw new TypeError("Cannot stringify circular structure without alias nodes");e.resolvedAliases?e.resolvedAliases.add(r):e.resolvedAliases=new Set([r]),r=r.resolve(e.doc)}let n,s=re(r)?r:e.doc.createNode(r,{onTagObj:u=>n=u});n!=null||(n=qR(e.doc.schema.tags,s));let o=LR(s,n,e);o.length>0&&(e.indentAtStart=((l=e.indentAtStart)!=null?l:0)+o.length+1);let a=typeof n.stringify=="function"?n.stringify(s,e,t,i):K(s)?ui(s,e,t,i):s.toString(e,t,i);return o?K(s)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o} -${e.indent}${a}`:a}function t0({key:r,value:e},t,i,n){var x,E;let{allNullValues:s,doc:o,indent:a,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:d}}=t,f=re(r)&&r.comment||null;if(d){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(se(r)||!re(r)&&typeof r=="object"){let R="With simple keys, collection cannot be used as a key value";throw new Error(R)}}let p=!d&&(!r||f&&e==null&&!t.inFlow||se(r)||(K(r)?r.type===j.BLOCK_FOLDED||r.type===j.BLOCK_LITERAL:typeof r=="object"));t=Object.assign({},t,{allNullValues:!1,implicitKey:!p&&(d||!s),indent:a+c});let m=!1,h=!1,y=yr(r,t,()=>m=!0,()=>h=!0);if(!p&&!t.inFlow&&y.length>1024){if(d)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");p=!0}if(t.inFlow){if(s||e==null)return m&&i&&i(),y===""?"?":p?`? ${y}`:y}else if(s&&!d||e==null&&p)return y=`? ${y}`,f&&!m?y+=Qt(y,t.indent,l(f)):h&&n&&n(),y;m&&(f=null),p?(f&&(y+=Qt(y,t.indent,l(f))),y=`? ${y} -${a}:`):(y=`${y}:`,f&&(y+=Qt(y,t.indent,l(f))));let b,g,_;re(e)?(b=!!e.spaceBefore,g=e.commentBefore,_=e.comment):(b=!1,g=null,_=null,e&&typeof e=="object"&&(e=o.createNode(e))),t.implicitKey=!1,!p&&!f&&K(e)&&(t.indentAtStart=y.length+1),h=!1,!u&&c.length>=2&&!t.inFlow&&!p&&Mt(e)&&!e.flow&&!e.tag&&!e.anchor&&(t.indent=t.indent.substring(2));let S=!1,v=yr(e,t,()=>S=!0,()=>h=!0),P=" ";if(f||b||g){if(P=b?` -`:"",g){let R=l(g);P+=` -${wt(R,t.indent)}`}v===""&&!t.inFlow?P===` -`&&_&&(P=` +${l}${g}${t}${p}`}function ZT(r,e,t,n){let{type:s,value:i}=r,{actualString:o,implicitKey:a,indent:c,indentStep:l,inFlow:u}=e;if(a&&i.includes(` +`)||u&&/[[\]{},]/.test(i))return Zn(i,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(i))return a||u||!i.includes(` +`)?Zn(i,e):na(r,e,t,n);if(!a&&!u&&s!==D.PLAIN&&i.includes(` +`))return na(r,e,t,n);if(ia(i)){if(c==="")return e.forceBlockIndent=!0,na(r,e,t,n);if(a&&c===l)return Zn(i,e)}let d=i.replace(/\n+/g,`$& +${c}`);if(o){let f=h=>{var y;return h.default&&h.tag!=="tag:yaml.org,2002:str"&&((y=h.test)==null?void 0:y.test(d))},{compat:p,tags:m}=e.doc.schema;if(m.some(f)||p!=null&&p.some(f))return Zn(i,e)}return a?d:ci(d,c,cu,sa(e,!1))}function an(r,e,t,n){let{implicitKey:s,inFlow:i}=e,o=typeof r.value=="string"?r:Object.assign({},r,{value:String(r.value)}),{type:a}=r;a!==D.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=D.QUOTE_DOUBLE);let c=u=>{switch(u){case D.BLOCK_FOLDED:case D.BLOCK_LITERAL:return s||i?Zn(o.value,e):na(o,e,t,n);case D.QUOTE_DOUBLE:return li(o.value,e);case D.QUOTE_SINGLE:return lu(o.value,e);case D.PLAIN:return ZT(o,e,t,n);default:return null}},l=c(a);if(l===null){let{defaultKeyType:u,defaultStringType:d}=e.options,f=s&&u||d;if(l=c(f),l===null)throw new Error(`Unsupported default string type ${f}`)}return l}function oa(r,e){let t=Object.assign({blockQuote:!0,commentString:Ab,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},r.schema.toStringOptions,e),n;switch(t.collectionStyle){case"block":n=!1;break;case"flow":n=!0;break;default:n=null}return{anchors:new Set,doc:r,flowCollectionPadding:t.flowCollectionPadding?" ":"",indent:"",indentStep:typeof t.indent=="number"?" ".repeat(t.indent):" ",inFlow:n,options:t}}function eP(r,e){var s,i,o,a;if(e.tag){let c=r.filter(l=>l.tag===e.tag);if(c.length>0)return(s=c.find(l=>l.format===e.format))!=null?s:c[0]}let t,n;if(K(e)){n=e.value;let c=r.filter(l=>{var u;return(u=l.identify)==null?void 0:u.call(l,n)});if(c.length>1){let l=c.filter(u=>u.test);l.length>0&&(c=l)}t=(i=c.find(l=>l.format===e.format))!=null?i:c.find(l=>!l.format)}else n=e,t=r.find(c=>c.nodeClass&&n instanceof c.nodeClass);if(!t){let c=(a=(o=n==null?void 0:n.constructor)==null?void 0:o.name)!=null?a:n===null?"null":typeof n;throw new Error(`Tag not resolved for ${c} value`)}return t}function tP(r,e,{anchors:t,doc:n}){var a;if(!n.directives)return"";let s=[],i=(K(r)||ie(r))&&r.anchor;i&&Zo(i)&&(t.add(i),s.push(`&${i}`));let o=(a=r.tag)!=null?a:e.default?null:e.tag;return o&&s.push(n.directives.tagString(o)),s.join(" ")}function hr(r,e,t,n){var c,l;if(ee(r))return r.toString(e,t,n);if(Pt(r)){if(e.doc.directives)return r.toString(e);if((c=e.resolvedAliases)!=null&&c.has(r))throw new TypeError("Cannot stringify circular structure without alias nodes");e.resolvedAliases?e.resolvedAliases.add(r):e.resolvedAliases=new Set([r]),r=r.resolve(e.doc)}let s,i=re(r)?r:e.doc.createNode(r,{onTagObj:u=>s=u});s!=null||(s=eP(e.doc.schema.tags,i));let o=tP(i,s,e);o.length>0&&(e.indentAtStart=((l=e.indentAtStart)!=null?l:0)+o.length+1);let a=typeof s.stringify=="function"?s.stringify(i,e,t,n):K(i)?an(i,e,t,n):i.toString(e,t,n);return o?K(i)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o} +${e.indent}${a}`:a}function xb({key:r,value:e},t,n,s){var I,E;let{allNullValues:i,doc:o,indent:a,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:d}}=t,f=re(r)&&r.comment||null;if(d){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(ie(r)||!re(r)&&typeof r=="object"){let T="With simple keys, collection cannot be used as a key value";throw new Error(T)}}let p=!d&&(!r||f&&e==null&&!t.inFlow||ie(r)||(K(r)?r.type===D.BLOCK_FOLDED||r.type===D.BLOCK_LITERAL:typeof r=="object"));t=Object.assign({},t,{allNullValues:!1,implicitKey:!p&&(d||!i),indent:a+c});let m=!1,h=!1,y=hr(r,t,()=>m=!0,()=>h=!0);if(!p&&!t.inFlow&&y.length>1024){if(d)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");p=!0}if(t.inFlow){if(i||e==null)return m&&n&&n(),y===""?"?":p?`? ${y}`:y}else if(i&&!d||e==null&&p)return y=`? ${y}`,f&&!m?y+=Xt(y,t.indent,l(f)):h&&s&&s(),y;m&&(f=null),p?(f&&(y+=Xt(y,t.indent,l(f))),y=`? ${y} +${a}:`):(y=`${y}:`,f&&(y+=Xt(y,t.indent,l(f))));let b,g,w;re(e)?(b=!!e.spaceBefore,g=e.commentBefore,w=e.comment):(b=!1,g=null,w=null,e&&typeof e=="object"&&(e=o.createNode(e))),t.implicitKey=!1,!p&&!f&&K(e)&&(t.indentAtStart=y.length+1),h=!1,!u&&c.length>=2&&!t.inFlow&&!p&&Ct(e)&&!e.flow&&!e.tag&&!e.anchor&&(t.indent=t.indent.substring(2));let S=!1,_=hr(e,t,()=>S=!0,()=>h=!0),x=" ";if(f||b||g){if(x=b?` +`:"",g){let T=l(g);x+=` +${wt(T,t.indent)}`}_===""&&!t.inFlow?x===` +`&&w&&(x=` -`):P+=` -${t.indent}`}else if(!p&&se(e)){let R=v[0],w=v.indexOf(` -`),F=w!==-1,V=(E=(x=t.inFlow)!=null?x:e.flow)!=null?E:e.items.length===0;if(F||!V){let G=!1;if(F&&(R==="&"||R==="!")){let A=v.indexOf(" ");R==="&"&&A!==-1&&Ar===Sa||typeof r=="symbol"&&r.description===Sa,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new j(Symbol(Sa)),{addToJSMap:Ou}),stringify:()=>Sa},r0=(r,e)=>(qt.identify(e)||K(e)&&(!e.type||e.type===j.PLAIN)&&qt.identify(e.value))&&(r==null?void 0:r.doc.schema.tags.some(t=>t.tag===qt.tag&&t.default));function Ou(r,e,t){let i=i0(r,t);if(Mt(i))for(let n of i.items)Tu(r,e,n);else if(Array.isArray(i))for(let n of i)Tu(r,e,n);else Tu(r,e,i)}function Tu(r,e,t){let i=i0(r,t);if(!Nt(i))throw new Error("Merge sources must be maps or map aliases");let n=i.toJSON(null,r,Map);for(let[s,o]of n)e instanceof Map?e.has(s)||e.set(s,o):e instanceof Set?e.add(s):Object.prototype.hasOwnProperty.call(e,s)||Object.defineProperty(e,s,{value:o,writable:!0,enumerable:!0,configurable:!0});return e}function i0(r,e){return r&&Ot(e)?e.resolve(r.doc,r):e}function Ea(r,e,{key:t,value:i}){if(re(t)&&t.addToJSMap)t.addToJSMap(r,e,i);else if(r0(r,t))Ou(r,e,i);else{let n=Te(t,"",r);if(e instanceof Map)e.set(n,Te(i,n,r));else if(e instanceof Set)e.add(n);else{let s=jR(t,n,r),o=Te(i,s,r);s in e?Object.defineProperty(e,s,{value:o,writable:!0,enumerable:!0,configurable:!0}):e[s]=o}}return e}function jR(r,e,t){if(e===null)return"";if(typeof e!="object")return String(e);if(re(r)&&(t!=null&&t.doc)){let i=wa(t.doc,{});i.anchors=new Set;for(let s of t.anchors.keys())i.anchors.add(s.anchor);i.inFlow=!0,i.inStringifyKey=!0;let n=r.toString(i);if(!t.mapKeyWarned){let s=JSON.stringify(n);s.length>40&&(s=s.substring(0,36)+'..."'),$a(t.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${s}. Set mapAsMap: true to use object keys.`),t.mapKeyWarned=!0}return n}return JSON.stringify(e)}function sn(r,e,t){let i=mr(r,void 0,t),n=mr(e,void 0,t);return new $e(i,n)}var $e=class r{constructor(e,t=null){Object.defineProperty(this,Ye,{value:Au}),this.key=e,this.value=t}clone(e){let{key:t,value:i}=this;return re(t)&&(t=t.clone(e)),re(i)&&(i=i.clone(e)),new r(t,i)}toJSON(e,t){let i=t!=null&&t.mapAsMap?new Map:{};return Ea(t,i,this)}toString(e,t,i){return e!=null&&e.doc?t0(this,e,t,i):JSON.stringify(this)}};function ka(r,e,t){var s;return(((s=e.inFlow)!=null?s:r.flow)?FR:DR)(r,e,t)}function DR({comment:r,items:e},t,{blockItemPrefix:i,flowChars:n,itemIndent:s,onChompKeep:o,onComment:a}){let{indent:c,options:{commentString:l}}=t,u=Object.assign({},t,{indent:s,type:null}),d=!1,f=[];for(let m=0;my=null,()=>d=!0);y&&(b+=Qt(b,s,l(y))),d&&y&&(d=!1),f.push(i+b)}let p;if(f.length===0)p=n.start+n.end;else{p=f[0];for(let m=1;mr===ca||typeof r=="symbol"&&r.description===ca,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new D(Symbol(ca)),{addToJSMap:fu}),stringify:()=>ca},Ib=(r,e)=>(Nt.identify(e)||K(e)&&(!e.type||e.type===D.PLAIN)&&Nt.identify(e.value))&&(r==null?void 0:r.doc.schema.tags.some(t=>t.tag===Nt.tag&&t.default));function fu(r,e,t){let n=Tb(r,t);if(Ct(n))for(let s of n.items)uu(r,e,s);else if(Array.isArray(n))for(let s of n)uu(r,e,s);else uu(r,e,n)}function uu(r,e,t){let n=Tb(r,t);if(!Rt(n))throw new Error("Merge sources must be maps or map aliases");let s=n.toJSON(null,r,Map);for(let[i,o]of s)e instanceof Map?e.has(i)||e.set(i,o):e instanceof Set?e.add(i):Object.prototype.hasOwnProperty.call(e,i)||Object.defineProperty(e,i,{value:o,writable:!0,enumerable:!0,configurable:!0});return e}function Tb(r,e){return r&&Pt(e)?e.resolve(r.doc,r):e}function la(r,e,{key:t,value:n}){if(re(t)&&t.addToJSMap)t.addToJSMap(r,e,n);else if(Ib(r,t))fu(r,e,n);else{let s=Pe(t,"",r);if(e instanceof Map)e.set(s,Pe(n,s,r));else if(e instanceof Set)e.add(s);else{let i=rP(t,s,r),o=Pe(n,i,r);i in e?Object.defineProperty(e,i,{value:o,writable:!0,enumerable:!0,configurable:!0}):e[i]=o}}return e}function rP(r,e,t){if(e===null)return"";if(typeof e!="object")return String(e);if(re(r)&&(t!=null&&t.doc)){let n=oa(t.doc,{});n.anchors=new Set;for(let i of t.anchors.keys())n.anchors.add(i.anchor);n.inFlow=!0,n.inStringifyKey=!0;let s=r.toString(n);if(!t.mapKeyWarned){let i=JSON.stringify(s);i.length>40&&(i=i.substring(0,36)+'..."'),aa(t.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${i}. Set mapAsMap: true to use object keys.`),t.mapKeyWarned=!0}return s}return JSON.stringify(e)}function es(r,e,t){let n=pr(r,void 0,t),s=pr(e,void 0,t);return new ve(n,s)}var ve=class r{constructor(e,t=null){Object.defineProperty(this,We,{value:iu}),this.key=e,this.value=t}clone(e){let{key:t,value:n}=this;return re(t)&&(t=t.clone(e)),re(n)&&(n=n.clone(e)),new r(t,n)}toJSON(e,t){let n=t!=null&&t.mapAsMap?new Map:{};return la(t,n,this)}toString(e,t,n){return e!=null&&e.doc?xb(this,e,t,n):JSON.stringify(this)}};function ua(r,e,t){var i;return(((i=e.inFlow)!=null?i:r.flow)?sP:nP)(r,e,t)}function nP({comment:r,items:e},t,{blockItemPrefix:n,flowChars:s,itemIndent:i,onChompKeep:o,onComment:a}){let{indent:c,options:{commentString:l}}=t,u=Object.assign({},t,{indent:i,type:null}),d=!1,f=[];for(let m=0;my=null,()=>d=!0);y&&(b+=Xt(b,i,l(y))),d&&y&&(d=!1),f.push(n+b)}let p;if(f.length===0)p=s.start+s.end;else{p=f[0];for(let m=1;my=null);l||(l=d.length>u||b.includes(` -`)),m0&&(l||(l=d.reduce((g,_)=>g+_.length+2,2)+(b.length+2)>e.options.lineWidth)),l&&(b+=",")),y&&(b+=Qt(b,i,a(y))),d.push(b),u=d.length}let{start:f,end:p}=t;if(d.length===0)return f+p;if(!l){let m=d.reduce((h,y)=>h+y.length+2,2);l=e.options.lineWidth>0&&m>e.options.lineWidth}if(l){let m=f;for(let h of d)m+=h?` -${s}${n}${h}`:` +`+wt(l(r),c),a&&a()):d&&o&&o(),p}function sP({items:r},e,{flowChars:t,itemIndent:n}){let{indent:s,indentStep:i,flowCollectionPadding:o,options:{commentString:a}}=e;n+=i;let c=Object.assign({},e,{indent:n,inFlow:!0,type:null}),l=!1,u=0,d=[];for(let m=0;my=null);l||(l=d.length>u||b.includes(` +`)),m0&&(l||(l=d.reduce((g,w)=>g+w.length+2,2)+(b.length+2)>e.options.lineWidth)),l&&(b+=",")),y&&(b+=Xt(b,n,a(y))),d.push(b),u=d.length}let{start:f,end:p}=t;if(d.length===0)return f+p;if(!l){let m=d.reduce((h,y)=>h+y.length+2,2);l=e.options.lineWidth>0&&m>e.options.lineWidth}if(l){let m=f;for(let h of d)m+=h?` +${i}${s}${h}`:` `;return`${m} -${n}${p}`}else return`${f}${o}${d.join(" ")}${o}${p}`}function Aa({indent:r,options:{commentString:e}},t,i,n){if(i&&n&&(i=i.replace(/^\n+/,"")),i){let s=wt(e(i),r);t.push(s.trimStart())}}function zr(r,e){let t=K(e)?e.value:e;for(let i of r)if(ee(i)&&(i.key===e||i.key===t||K(i.key)&&i.key.value===t))return i}var ke=class extends tn{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(Tt,e),this.items=[]}static from(e,t,i){let{keepUndefined:n,replacer:s}=i,o=new this(e),a=(c,l)=>{if(typeof s=="function")l=s.call(t,c,l);else if(Array.isArray(s)&&!s.includes(c))return;(l!==void 0||n)&&o.items.push(sn(c,l,i))};if(t instanceof Map)for(let[c,l]of t)a(c,l);else if(t&&typeof t=="object")for(let c of Object.keys(t))a(c,t[c]);return typeof e.sortMapEntries=="function"&&o.items.sort(e.sortMapEntries),o}add(e,t){var o;let i;ee(e)?i=e:!e||typeof e!="object"||!("key"in e)?i=new $e(e,e==null?void 0:e.value):i=new $e(e.key,e.value);let n=zr(this.items,i.key),s=(o=this.schema)==null?void 0:o.sortMapEntries;if(n){if(!t)throw new Error(`Key ${i.key} already set`);K(n.value)&&ya(i.value)?n.value.value=i.value:n.value=i.value}else if(s){let a=this.items.findIndex(c=>s(i,c)<0);a===-1?this.items.push(i):this.items.splice(a,0,i)}else this.items.push(i)}delete(e){let t=zr(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){var s;let i=zr(this.items,e),n=i==null?void 0:i.value;return(s=!t&&K(n)?n.value:n)!=null?s:void 0}has(e){return!!zr(this.items,e)}set(e,t){this.add(new $e(e,t),!0)}toJSON(e,t,i){let n=i?new i:t!=null&&t.mapAsMap?new Map:{};t!=null&&t.onCreate&&t.onCreate(n);for(let s of this.items)Ea(t,n,s);return n}toString(e,t,i){if(!e)return JSON.stringify(this);for(let n of this.items)if(!ee(n))throw new Error(`Map items must all be pairs; found ${JSON.stringify(n)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),ka(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:i,onComment:t})}};var Lt={collection:"map",default:!0,nodeClass:ke,tag:"tag:yaml.org,2002:map",resolve(r,e){return Nt(r)||e("Expected a mapping for this tag"),r},createNode:(r,e,t)=>ke.from(r,e,t)};var Be=class extends tn{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(pr,e),this.items=[]}add(e){this.items.push(e)}delete(e){let t=Pa(e);return typeof t!="number"?!1:this.items.splice(t,1).length>0}get(e,t){let i=Pa(e);if(typeof i!="number")return;let n=this.items[i];return!t&&K(n)?n.value:n}has(e){let t=Pa(e);return typeof t=="number"&&t=0?e:null}var jt={collection:"seq",default:!0,nodeClass:Be,tag:"tag:yaml.org,2002:seq",resolve(r,e){return Mt(r)||e("Expected a sequence for this tag"),r},createNode:(r,e,t)=>Be.from(r,e,t)};var Br={identify:r=>typeof r=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:r=>r,stringify(r,e,t,i){return e=Object.assign({actualString:!0},e),ui(r,e,t,i)}};var fi={identify:r=>r==null,createNode:()=>new j(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new j(null),stringify:({source:r},e)=>typeof r=="string"&&fi.test.test(r)?r:e.options.nullStr};var vs={identify:r=>typeof r=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:r=>new j(r[0]==="t"||r[0]==="T"),stringify({source:r,value:e},t){if(r&&vs.test.test(r)){let i=r[0]==="t"||r[0]==="T";if(e===i)return r}return e?t.options.trueStr:t.options.falseStr}};function He({format:r,minFractionDigits:e,tag:t,value:i}){if(typeof i=="bigint")return String(i);let n=typeof i=="number"?i:Number(i);if(!isFinite(n))return isNaN(n)?".nan":n<0?"-.inf":".inf";let s=Object.is(i,-0)?"-0":JSON.stringify(i);if(!r&&e&&(!t||t==="tag:yaml.org,2002:float")&&/^-?\d/.test(s)&&!s.includes("e")){let o=s.indexOf(".");o<0&&(o=s.length,s+=".");let a=e-(s.length-o-1);for(;a-- >0;)s+="0"}return s}var xa={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:r=>r.slice(-3).toLowerCase()==="nan"?NaN:r[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:He},Ia={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:r=>parseFloat(r),stringify(r){let e=Number(r.value);return isFinite(e)?e.toExponential():He(r)}},Ra={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(r){let e=new j(parseFloat(r)),t=r.indexOf(".");return t!==-1&&r[r.length-1]==="0"&&(e.minFractionDigits=r.length-t-1),e},stringify:He};var Ta=r=>typeof r=="bigint"||Number.isInteger(r),Cu=(r,e,t,{intAsBigInt:i})=>i?BigInt(r):parseInt(r.substring(e),t);function n0(r,e,t){let{value:i}=r;return Ta(i)&&i>=0?t+i.toString(e):He(r)}var Oa={identify:r=>Ta(r)&&r>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(r,e,t)=>Cu(r,2,8,t),stringify:r=>n0(r,8,"0o")},Ca={identify:Ta,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(r,e,t)=>Cu(r,0,10,t),stringify:He},Na={identify:r=>Ta(r)&&r>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(r,e,t)=>Cu(r,2,16,t),stringify:r=>n0(r,16,"0x")};var s0=[Lt,jt,Br,fi,vs,Oa,Ca,Na,xa,Ia,Ra];function o0(r){return typeof r=="bigint"||Number.isInteger(r)}var Ma=({value:r})=>JSON.stringify(r),VR=[{identify:r=>typeof r=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:r=>r,stringify:Ma},{identify:r=>r==null,createNode:()=>new j(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Ma},{identify:r=>typeof r=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:r=>r==="true",stringify:Ma},{identify:o0,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(r,e,{intAsBigInt:t})=>t?BigInt(r):parseInt(r,10),stringify:({value:r})=>o0(r)?r.toString():JSON.stringify(r)},{identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:r=>parseFloat(r),stringify:Ma}],UR={default:!0,tag:"",test:/^/,resolve(r,e){return e(`Unresolved plain scalar ${JSON.stringify(r)}`),r}},a0=[Lt,jt].concat(VR,UR);var ws={identify:r=>r instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(r,e){if(typeof atob=="function"){let t=atob(r.replace(/[\n\r]/g,"")),i=new Uint8Array(t.length);for(let n=0;n1&&e("Each pair must have its own sequence indicator");let s=n.items[0]||new $e(new j(null));if(n.commentBefore&&(s.key.commentBefore=s.key.commentBefore?`${n.commentBefore} -${s.key.commentBefore}`:n.commentBefore),n.comment){let o=(t=s.value)!=null?t:s.key;o.comment=o.comment?`${n.comment} -${o.comment}`:n.comment}n=s}r.items[i]=ee(n)?n:new $e(n)}}else e("Expected a sequence for this tag");return r}function Mu(r,e,t){let{replacer:i}=t,n=new Be(r);n.tag="tag:yaml.org,2002:pairs";let s=0;if(e&&Symbol.iterator in Object(e))for(let o of e){typeof i=="function"&&(o=i.call(e,String(s++),o));let a,c;if(Array.isArray(o))if(o.length===2)a=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)a=l[0],c=o[a];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else a=o;n.items.push(sn(a,c,t))}return n}var $s={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Nu,createNode:Mu};var on=class r extends Be{constructor(){super(),this.add=ke.prototype.add.bind(this),this.delete=ke.prototype.delete.bind(this),this.get=ke.prototype.get.bind(this),this.has=ke.prototype.has.bind(this),this.set=ke.prototype.set.bind(this),this.tag=r.tag}toJSON(e,t){if(!t)return super.toJSON(e);let i=new Map;t!=null&&t.onCreate&&t.onCreate(i);for(let n of this.items){let s,o;if(ee(n)?(s=Te(n.key,"",t),o=Te(n.value,s,t)):s=Te(n,"",t),i.has(s))throw new Error("Ordered maps must not include duplicate keys");i.set(s,o)}return i}static from(e,t,i){let n=Mu(e,t,i),s=new this;return s.items=n.items,s}};on.tag="tag:yaml.org,2002:omap";var Ss={collection:"seq",identify:r=>r instanceof Map,nodeClass:on,default:!1,tag:"tag:yaml.org,2002:omap",resolve(r,e){let t=Nu(r,e),i=[];for(let{key:n}of t.items)K(n)&&(i.includes(n.value)?e(`Ordered maps must not include duplicate keys: ${n.value}`):i.push(n.value));return Object.assign(new on,t)},createNode:(r,e,t)=>on.from(r,e,t)};function c0({value:r,source:e},t){return e&&(r?qu:Lu).test.test(e)?e:r?t.options.trueStr:t.options.falseStr}var qu={identify:r=>r===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new j(!0),stringify:c0},Lu={identify:r=>r===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new j(!1),stringify:c0};var l0={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:r=>r.slice(-3).toLowerCase()==="nan"?NaN:r[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:He},d0={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:r=>parseFloat(r.replace(/_/g,"")),stringify(r){let e=Number(r.value);return isFinite(e)?e.toExponential():He(r)}},u0={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(r){let e=new j(parseFloat(r.replace(/_/g,""))),t=r.indexOf(".");if(t!==-1){let i=r.substring(t+1).replace(/_/g,"");i[i.length-1]==="0"&&(e.minFractionDigits=i.length)}return e},stringify:He};var Es=r=>typeof r=="bigint"||Number.isInteger(r);function qa(r,e,t,{intAsBigInt:i}){let n=r[0];if((n==="-"||n==="+")&&(e+=1),r=r.substring(e).replace(/_/g,""),i){switch(t){case 2:r=`0b${r}`;break;case 8:r=`0o${r}`;break;case 16:r=`0x${r}`;break}let o=BigInt(r);return n==="-"?BigInt(-1)*o:o}let s=parseInt(r,t);return n==="-"?-1*s:s}function ju(r,e,t){let{value:i}=r;if(Es(i)){let n=i.toString(e);return i<0?"-"+t+n.substr(1):t+n}return He(r)}var f0={identify:Es,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(r,e,t)=>qa(r,2,2,t),stringify:r=>ju(r,2,"0b")},p0={identify:Es,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(r,e,t)=>qa(r,1,8,t),stringify:r=>ju(r,8,"0")},h0={identify:Es,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(r,e,t)=>qa(r,0,10,t),stringify:He},m0={identify:Es,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(r,e,t)=>qa(r,2,16,t),stringify:r=>ju(r,16,"0x")};var an=class r extends ke{constructor(e){super(e),this.tag=r.tag}add(e){let t;ee(e)?t=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?t=new $e(e.key,null):t=new $e(e,null),zr(this.items,t.key)||this.items.push(t)}get(e,t){let i=zr(this.items,e);return!t&&ee(i)?K(i.key)?i.key.value:i.key:i}set(e,t){if(typeof t!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof t}`);let i=zr(this.items,e);i&&!t?this.items.splice(this.items.indexOf(i),1):!i&&t&&this.items.push(new $e(e))}toJSON(e,t){return super.toJSON(e,t,Set)}toString(e,t,i){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),t,i);throw new Error("Set items must all have null values")}static from(e,t,i){let{replacer:n}=i,s=new this(e);if(t&&Symbol.iterator in Object(t))for(let o of t)typeof n=="function"&&(o=n.call(t,o,o)),s.items.push(sn(o,null,i));return s}};an.tag="tag:yaml.org,2002:set";var As={collection:"map",identify:r=>r instanceof Set,nodeClass:an,default:!1,tag:"tag:yaml.org,2002:set",createNode:(r,e,t)=>an.from(r,e,t),resolve(r,e){if(Nt(r)){if(r.hasAllNullValues(!0))return Object.assign(new an,r);e("Set items must all have null values")}else e("Expected a mapping for this tag");return r}};function Du(r,e){let t=r[0],i=t==="-"||t==="+"?r.substring(1):r,n=o=>e?BigInt(o):Number(o),s=i.replace(/_/g,"").split(":").reduce((o,a)=>o*n(60)+n(a),n(0));return t==="-"?n(-1)*s:s}function y0(r){let{value:e}=r,t=o=>o;if(typeof e=="bigint")t=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return He(r);let i="";e<0&&(i="-",e*=t(-1));let n=t(60),s=[e%n];return e<60?s.unshift(0):(e=(e-s[0])/n,s.unshift(e%n),e>=60&&(e=(e-s[0])/n,s.unshift(e))),i+s.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var La={identify:r=>typeof r=="bigint"||Number.isInteger(r),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(r,e,{intAsBigInt:t})=>Du(r,t),stringify:y0},ja={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:r=>Du(r,!1),stringify:y0},cn={identify:r=>r instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(r){let e=r.match(cn.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,t,i,n,s,o,a]=e.map(Number),c=e[7]?Number((e[7]+"00").substr(1,3)):0,l=Date.UTC(t,i-1,n,s||0,o||0,a||0,c),u=e[8];if(u&&u!=="Z"){let d=Du(u,!1);Math.abs(d)<30&&(d*=60),l-=6e4*d}return new Date(l)},stringify:({value:r})=>{var e;return(e=r==null?void 0:r.toISOString().replace(/(T00:00:00)?\.000Z$/,""))!=null?e:""}};var Fu=[Lt,jt,Br,fi,qu,Lu,f0,p0,h0,m0,l0,d0,u0,ws,qt,Ss,$s,As,La,ja,cn];var g0=new Map([["core",s0],["failsafe",[Lt,jt,Br]],["json",a0],["yaml11",Fu],["yaml-1.1",Fu]]),b0={binary:ws,bool:vs,float:Ra,floatExp:Ia,floatNaN:xa,floatTime:ja,int:Ca,intHex:Na,intOct:Oa,intTime:La,map:Lt,merge:qt,null:fi,omap:Ss,pairs:$s,seq:jt,set:As,timestamp:cn},_0={"tag:yaml.org,2002:binary":ws,"tag:yaml.org,2002:merge":qt,"tag:yaml.org,2002:omap":Ss,"tag:yaml.org,2002:pairs":$s,"tag:yaml.org,2002:set":As,"tag:yaml.org,2002:timestamp":cn};function Da(r,e,t){let i=g0.get(e);if(i&&!r)return t&&!i.includes(qt)?i.concat(qt):i.slice();let n=i;if(!n)if(Array.isArray(r))n=[];else{let s=Array.from(g0.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${e}"; use one of ${s} or define customTags array`)}if(Array.isArray(r))for(let s of r)n=n.concat(s);else typeof r=="function"&&(n=r(n.slice()));return t&&(n=n.concat(qt)),n.reduce((s,o)=>{let a=typeof o=="string"?b0[o]:o;if(!a){let c=JSON.stringify(o),l=Object.keys(b0).map(u=>JSON.stringify(u)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return s.includes(a)||s.push(a),s},[])}var zR=(r,e)=>r.keye.key?1:0,ks=class r{constructor({compat:e,customTags:t,merge:i,resolveKnownTags:n,schema:s,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?Da(e,"compat"):e?Da(null,e):null,this.name=typeof s=="string"&&s||"core",this.knownTags=n?_0:{},this.tags=Da(t,this.name,i),this.toStringOptions=a!=null?a:null,Object.defineProperty(this,Tt,{value:Lt}),Object.defineProperty(this,lt,{value:Br}),Object.defineProperty(this,pr,{value:jt}),this.sortMapEntries=typeof o=="function"?o:o===!0?zR:null}clone(){let e=Object.create(r.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};function v0(r,e){var c;let t=[],i=e.directives===!0;if(e.directives!==!1&&r.directives){let l=r.directives.toString(r);l?(t.push(l),i=!0):r.directives.docStart&&(i=!0)}i&&t.push("---");let n=wa(r,e),{commentString:s}=n.options;if(r.commentBefore){t.length!==1&&t.unshift("");let l=s(r.commentBefore);t.unshift(wt(l,""))}let o=!1,a=null;if(r.contents){if(re(r.contents)){if(r.contents.spaceBefore&&i&&t.push(""),r.contents.commentBefore){let d=s(r.contents.commentBefore);t.push(wt(d,""))}n.forceBlockIndent=!!r.comment,a=r.contents.comment}let l=a?void 0:()=>o=!0,u=yr(r.contents,n,()=>a=null,l);a&&(u+=Qt(u,"",s(a))),(u[0]==="|"||u[0]===">")&&t[t.length-1]==="---"?t[t.length-1]=`--- ${u}`:t.push(u)}else t.push(yr(r.contents,n));if((c=r.directives)!=null&&c.docEnd)if(r.comment){let l=s(r.comment);l.includes(` -`)?(t.push("..."),t.push(wt(l,""))):t.push(`... ${l}`)}else t.push("...");else{let l=r.comment;l&&o&&(l=l.replace(/^\n+/,"")),l&&((!o||a)&&t[t.length-1]!==""&&t.push(""),t.push(wt(s(l),"")))}return t.join(` +${s}${p}`}else return`${f}${o}${d.join(" ")}${o}${p}`}function da({indent:r,options:{commentString:e}},t,n,s){if(n&&s&&(n=n.replace(/^\n+/,"")),n){let i=wt(e(n),r);t.push(i.trimStart())}}function jr(r,e){let t=K(e)?e.value:e;for(let n of r)if(ee(n)&&(n.key===e||n.key===t||K(n.key)&&n.key.value===t))return n}var Ae=class extends Xn{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(Tt,e),this.items=[]}static from(e,t,n){let{keepUndefined:s,replacer:i}=n,o=new this(e),a=(c,l)=>{if(typeof i=="function")l=i.call(t,c,l);else if(Array.isArray(i)&&!i.includes(c))return;(l!==void 0||s)&&o.items.push(es(c,l,n))};if(t instanceof Map)for(let[c,l]of t)a(c,l);else if(t&&typeof t=="object")for(let c of Object.keys(t))a(c,t[c]);return typeof e.sortMapEntries=="function"&&o.items.sort(e.sortMapEntries),o}add(e,t){var o;let n;ee(e)?n=e:!e||typeof e!="object"||!("key"in e)?n=new ve(e,e==null?void 0:e.value):n=new ve(e.key,e.value);let s=jr(this.items,n.key),i=(o=this.schema)==null?void 0:o.sortMapEntries;if(s){if(!t)throw new Error(`Key ${n.key} already set`);K(s.value)&&ta(n.value)?s.value.value=n.value:s.value=n.value}else if(i){let a=this.items.findIndex(c=>i(n,c)<0);a===-1?this.items.push(n):this.items.splice(a,0,n)}else this.items.push(n)}delete(e){let t=jr(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){var i;let n=jr(this.items,e),s=n==null?void 0:n.value;return(i=!t&&K(s)?s.value:s)!=null?i:void 0}has(e){return!!jr(this.items,e)}set(e,t){this.add(new ve(e,t),!0)}toJSON(e,t,n){let s=n?new n:t!=null&&t.mapAsMap?new Map:{};t!=null&&t.onCreate&&t.onCreate(s);for(let i of this.items)la(t,s,i);return s}toString(e,t,n){if(!e)return JSON.stringify(this);for(let s of this.items)if(!ee(s))throw new Error(`Map items must all be pairs; found ${JSON.stringify(s)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),ua(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:n,onComment:t})}};var Mt={collection:"map",default:!0,nodeClass:Ae,tag:"tag:yaml.org,2002:map",resolve(r,e){return Rt(r)||e("Expected a mapping for this tag"),r},createNode:(r,e,t)=>Ae.from(r,e,t)};var Ue=class extends Xn{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(ur,e),this.items=[]}add(e){this.items.push(e)}delete(e){let t=fa(e);return typeof t!="number"?!1:this.items.splice(t,1).length>0}get(e,t){let n=fa(e);if(typeof n!="number")return;let s=this.items[n];return!t&&K(s)?s.value:s}has(e){let t=fa(e);return typeof t=="number"&&t=0?e:null}var Lt={collection:"seq",default:!0,nodeClass:Ue,tag:"tag:yaml.org,2002:seq",resolve(r,e){return Ct(r)||e("Expected a sequence for this tag"),r},createNode:(r,e,t)=>Ue.from(r,e,t)};var Fr={identify:r=>typeof r=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:r=>r,stringify(r,e,t,n){return e=Object.assign({actualString:!0},e),an(r,e,t,n)}};var cn={identify:r=>r==null,createNode:()=>new D(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new D(null),stringify:({source:r},e)=>typeof r=="string"&&cn.test.test(r)?r:e.options.nullStr};var di={identify:r=>typeof r=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:r=>new D(r[0]==="t"||r[0]==="T"),stringify({source:r,value:e},t){if(r&&di.test.test(r)){let n=r[0]==="t"||r[0]==="T";if(e===n)return r}return e?t.options.trueStr:t.options.falseStr}};function Be({format:r,minFractionDigits:e,tag:t,value:n}){if(typeof n=="bigint")return String(n);let s=typeof n=="number"?n:Number(n);if(!isFinite(s))return isNaN(s)?".nan":s<0?"-.inf":".inf";let i=Object.is(n,-0)?"-0":JSON.stringify(n);if(!r&&e&&(!t||t==="tag:yaml.org,2002:float")&&/^-?\d/.test(i)&&!i.includes("e")){let o=i.indexOf(".");o<0&&(o=i.length,i+=".");let a=e-(i.length-o-1);for(;a-- >0;)i+="0"}return i}var pa={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:r=>r.slice(-3).toLowerCase()==="nan"?NaN:r[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Be},ha={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:r=>parseFloat(r),stringify(r){let e=Number(r.value);return isFinite(e)?e.toExponential():Be(r)}},ma={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(r){let e=new D(parseFloat(r)),t=r.indexOf(".");return t!==-1&&r[r.length-1]==="0"&&(e.minFractionDigits=r.length-t-1),e},stringify:Be};var ya=r=>typeof r=="bigint"||Number.isInteger(r),pu=(r,e,t,{intAsBigInt:n})=>n?BigInt(r):parseInt(r.substring(e),t);function Pb(r,e,t){let{value:n}=r;return ya(n)&&n>=0?t+n.toString(e):Be(r)}var ga={identify:r=>ya(r)&&r>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(r,e,t)=>pu(r,2,8,t),stringify:r=>Pb(r,8,"0o")},ba={identify:ya,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(r,e,t)=>pu(r,0,10,t),stringify:Be},wa={identify:r=>ya(r)&&r>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(r,e,t)=>pu(r,2,16,t),stringify:r=>Pb(r,16,"0x")};var Ob=[Mt,Lt,Fr,cn,di,ga,ba,wa,pa,ha,ma];function Rb(r){return typeof r=="bigint"||Number.isInteger(r)}var _a=({value:r})=>JSON.stringify(r),iP=[{identify:r=>typeof r=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:r=>r,stringify:_a},{identify:r=>r==null,createNode:()=>new D(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:_a},{identify:r=>typeof r=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:r=>r==="true",stringify:_a},{identify:Rb,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(r,e,{intAsBigInt:t})=>t?BigInt(r):parseInt(r,10),stringify:({value:r})=>Rb(r)?r.toString():JSON.stringify(r)},{identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:r=>parseFloat(r),stringify:_a}],oP={default:!0,tag:"",test:/^/,resolve(r,e){return e(`Unresolved plain scalar ${JSON.stringify(r)}`),r}},Cb=[Mt,Lt].concat(iP,oP);var ui={identify:r=>r instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(r,e){if(typeof atob=="function"){let t=atob(r.replace(/[\n\r]/g,"")),n=new Uint8Array(t.length);for(let s=0;s1&&e("Each pair must have its own sequence indicator");let i=s.items[0]||new ve(new D(null));if(s.commentBefore&&(i.key.commentBefore=i.key.commentBefore?`${s.commentBefore} +${i.key.commentBefore}`:s.commentBefore),s.comment){let o=(t=i.value)!=null?t:i.key;o.comment=o.comment?`${s.comment} +${o.comment}`:s.comment}s=i}r.items[n]=ee(s)?s:new ve(s)}}else e("Expected a sequence for this tag");return r}function mu(r,e,t){let{replacer:n}=t,s=new Ue(r);s.tag="tag:yaml.org,2002:pairs";let i=0;if(e&&Symbol.iterator in Object(e))for(let o of e){typeof n=="function"&&(o=n.call(e,String(i++),o));let a,c;if(Array.isArray(o))if(o.length===2)a=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)a=l[0],c=o[a];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else a=o;s.items.push(es(a,c,t))}return s}var fi={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:hu,createNode:mu};var ts=class r extends Ue{constructor(){super(),this.add=Ae.prototype.add.bind(this),this.delete=Ae.prototype.delete.bind(this),this.get=Ae.prototype.get.bind(this),this.has=Ae.prototype.has.bind(this),this.set=Ae.prototype.set.bind(this),this.tag=r.tag}toJSON(e,t){if(!t)return super.toJSON(e);let n=new Map;t!=null&&t.onCreate&&t.onCreate(n);for(let s of this.items){let i,o;if(ee(s)?(i=Pe(s.key,"",t),o=Pe(s.value,i,t)):i=Pe(s,"",t),n.has(i))throw new Error("Ordered maps must not include duplicate keys");n.set(i,o)}return n}static from(e,t,n){let s=mu(e,t,n),i=new this;return i.items=s.items,i}};ts.tag="tag:yaml.org,2002:omap";var pi={collection:"seq",identify:r=>r instanceof Map,nodeClass:ts,default:!1,tag:"tag:yaml.org,2002:omap",resolve(r,e){let t=hu(r,e),n=[];for(let{key:s}of t.items)K(s)&&(n.includes(s.value)?e(`Ordered maps must not include duplicate keys: ${s.value}`):n.push(s.value));return Object.assign(new ts,t)},createNode:(r,e,t)=>ts.from(r,e,t)};function Nb({value:r,source:e},t){return e&&(r?yu:gu).test.test(e)?e:r?t.options.trueStr:t.options.falseStr}var yu={identify:r=>r===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new D(!0),stringify:Nb},gu={identify:r=>r===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new D(!1),stringify:Nb};var Mb={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:r=>r.slice(-3).toLowerCase()==="nan"?NaN:r[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Be},Lb={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:r=>parseFloat(r.replace(/_/g,"")),stringify(r){let e=Number(r.value);return isFinite(e)?e.toExponential():Be(r)}},qb={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(r){let e=new D(parseFloat(r.replace(/_/g,""))),t=r.indexOf(".");if(t!==-1){let n=r.substring(t+1).replace(/_/g,"");n[n.length-1]==="0"&&(e.minFractionDigits=n.length)}return e},stringify:Be};var hi=r=>typeof r=="bigint"||Number.isInteger(r);function va(r,e,t,{intAsBigInt:n}){let s=r[0];if((s==="-"||s==="+")&&(e+=1),r=r.substring(e).replace(/_/g,""),n){switch(t){case 2:r=`0b${r}`;break;case 8:r=`0o${r}`;break;case 16:r=`0x${r}`;break}let o=BigInt(r);return s==="-"?BigInt(-1)*o:o}let i=parseInt(r,t);return s==="-"?-1*i:i}function bu(r,e,t){let{value:n}=r;if(hi(n)){let s=n.toString(e);return n<0?"-"+t+s.substr(1):t+s}return Be(r)}var Db={identify:hi,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(r,e,t)=>va(r,2,2,t),stringify:r=>bu(r,2,"0b")},jb={identify:hi,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(r,e,t)=>va(r,1,8,t),stringify:r=>bu(r,8,"0")},Fb={identify:hi,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(r,e,t)=>va(r,0,10,t),stringify:Be},Vb={identify:hi,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(r,e,t)=>va(r,2,16,t),stringify:r=>bu(r,16,"0x")};var rs=class r extends Ae{constructor(e){super(e),this.tag=r.tag}add(e){let t;ee(e)?t=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?t=new ve(e.key,null):t=new ve(e,null),jr(this.items,t.key)||this.items.push(t)}get(e,t){let n=jr(this.items,e);return!t&&ee(n)?K(n.key)?n.key.value:n.key:n}set(e,t){if(typeof t!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof t}`);let n=jr(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new ve(e))}toJSON(e,t){return super.toJSON(e,t,Set)}toString(e,t,n){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),t,n);throw new Error("Set items must all have null values")}static from(e,t,n){let{replacer:s}=n,i=new this(e);if(t&&Symbol.iterator in Object(t))for(let o of t)typeof s=="function"&&(o=s.call(t,o,o)),i.items.push(es(o,null,n));return i}};rs.tag="tag:yaml.org,2002:set";var mi={collection:"map",identify:r=>r instanceof Set,nodeClass:rs,default:!1,tag:"tag:yaml.org,2002:set",createNode:(r,e,t)=>rs.from(r,e,t),resolve(r,e){if(Rt(r)){if(r.hasAllNullValues(!0))return Object.assign(new rs,r);e("Set items must all have null values")}else e("Expected a mapping for this tag");return r}};function wu(r,e){let t=r[0],n=t==="-"||t==="+"?r.substring(1):r,s=o=>e?BigInt(o):Number(o),i=n.replace(/_/g,"").split(":").reduce((o,a)=>o*s(60)+s(a),s(0));return t==="-"?s(-1)*i:i}function Ub(r){let{value:e}=r,t=o=>o;if(typeof e=="bigint")t=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return Be(r);let n="";e<0&&(n="-",e*=t(-1));let s=t(60),i=[e%s];return e<60?i.unshift(0):(e=(e-i[0])/s,i.unshift(e%s),e>=60&&(e=(e-i[0])/s,i.unshift(e))),n+i.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var $a={identify:r=>typeof r=="bigint"||Number.isInteger(r),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(r,e,{intAsBigInt:t})=>wu(r,t),stringify:Ub},Sa={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:r=>wu(r,!1),stringify:Ub},ns={identify:r=>r instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(r){let e=r.match(ns.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,t,n,s,i,o,a]=e.map(Number),c=e[7]?Number((e[7]+"00").substr(1,3)):0,l=Date.UTC(t,n-1,s,i||0,o||0,a||0,c),u=e[8];if(u&&u!=="Z"){let d=wu(u,!1);Math.abs(d)<30&&(d*=60),l-=6e4*d}return new Date(l)},stringify:({value:r})=>{var e;return(e=r==null?void 0:r.toISOString().replace(/(T00:00:00)?\.000Z$/,""))!=null?e:""}};var _u=[Mt,Lt,Fr,cn,yu,gu,Db,jb,Fb,Vb,Mb,Lb,qb,ui,Nt,pi,fi,mi,$a,Sa,ns];var Bb=new Map([["core",Ob],["failsafe",[Mt,Lt,Fr]],["json",Cb],["yaml11",_u],["yaml-1.1",_u]]),Hb={binary:ui,bool:di,float:ma,floatExp:ha,floatNaN:pa,floatTime:Sa,int:ba,intHex:wa,intOct:ga,intTime:$a,map:Mt,merge:Nt,null:cn,omap:pi,pairs:fi,seq:Lt,set:mi,timestamp:ns},zb={"tag:yaml.org,2002:binary":ui,"tag:yaml.org,2002:merge":Nt,"tag:yaml.org,2002:omap":pi,"tag:yaml.org,2002:pairs":fi,"tag:yaml.org,2002:set":mi,"tag:yaml.org,2002:timestamp":ns};function Ea(r,e,t){let n=Bb.get(e);if(n&&!r)return t&&!n.includes(Nt)?n.concat(Nt):n.slice();let s=n;if(!s)if(Array.isArray(r))s=[];else{let i=Array.from(Bb.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${e}"; use one of ${i} or define customTags array`)}if(Array.isArray(r))for(let i of r)s=s.concat(i);else typeof r=="function"&&(s=r(s.slice()));return t&&(s=s.concat(Nt)),s.reduce((i,o)=>{let a=typeof o=="string"?Hb[o]:o;if(!a){let c=JSON.stringify(o),l=Object.keys(Hb).map(u=>JSON.stringify(u)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return i.includes(a)||i.push(a),i},[])}var aP=(r,e)=>r.keye.key?1:0,yi=class r{constructor({compat:e,customTags:t,merge:n,resolveKnownTags:s,schema:i,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?Ea(e,"compat"):e?Ea(null,e):null,this.name=typeof i=="string"&&i||"core",this.knownTags=s?zb:{},this.tags=Ea(t,this.name,n),this.toStringOptions=a!=null?a:null,Object.defineProperty(this,Tt,{value:Mt}),Object.defineProperty(this,ct,{value:Fr}),Object.defineProperty(this,ur,{value:Lt}),this.sortMapEntries=typeof o=="function"?o:o===!0?aP:null}clone(){let e=Object.create(r.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};function Kb(r,e){var c;let t=[],n=e.directives===!0;if(e.directives!==!1&&r.directives){let l=r.directives.toString(r);l?(t.push(l),n=!0):r.directives.docStart&&(n=!0)}n&&t.push("---");let s=oa(r,e),{commentString:i}=s.options;if(r.commentBefore){t.length!==1&&t.unshift("");let l=i(r.commentBefore);t.unshift(wt(l,""))}let o=!1,a=null;if(r.contents){if(re(r.contents)){if(r.contents.spaceBefore&&n&&t.push(""),r.contents.commentBefore){let d=i(r.contents.commentBefore);t.push(wt(d,""))}s.forceBlockIndent=!!r.comment,a=r.contents.comment}let l=a?void 0:()=>o=!0,u=hr(r.contents,s,()=>a=null,l);a&&(u+=Xt(u,"",i(a))),(u[0]==="|"||u[0]===">")&&t[t.length-1]==="---"?t[t.length-1]=`--- ${u}`:t.push(u)}else t.push(hr(r.contents,s));if((c=r.directives)!=null&&c.docEnd)if(r.comment){let l=i(r.comment);l.includes(` +`)?(t.push("..."),t.push(wt(l,""))):t.push(`... ${l}`)}else t.push("...");else{let l=r.comment;l&&o&&(l=l.replace(/^\n+/,"")),l&&((!o||a)&&t[t.length-1]!==""&&t.push(""),t.push(wt(i(l),"")))}return t.join(` `)+` -`}var gr=class r{constructor(e,t,i){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,Ye,{value:ua});let n=null;typeof t=="function"||Array.isArray(t)?n=t:i===void 0&&t&&(i=t,t=void 0);let s=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},i);this.options=s;let{version:o}=s;i!=null&&i._directives?(this.directives=i._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new Zt({version:o}),this.setSchema(o,i),this.contents=e===void 0?null:this.createNode(e,n,i)}clone(){let e=Object.create(r.prototype,{[Ye]:{value:ua}});return e.commentBefore=this.commentBefore,e.comment=this.comment,e.errors=this.errors.slice(),e.warnings=this.warnings.slice(),e.options=Object.assign({},this.options),this.directives&&(e.directives=this.directives.clone()),e.schema=this.schema.clone(),e.contents=re(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){ln(this.contents)&&this.contents.add(e)}addIn(e,t){ln(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){let i=ku(this);e.anchor=!t||i.has(t)?Pu(t||"a",i):t}return new hr(e.anchor)}createNode(e,t,i){let n;if(typeof t=="function")e=t.call({"":e},"",e),n=t;else if(Array.isArray(t)){let y=g=>typeof g=="number"||g instanceof String||g instanceof Number,b=t.filter(y).map(String);b.length>0&&(t=t.concat(b)),n=t}else i===void 0&&t&&(i=t,t=void 0);let{aliasDuplicateObjects:s,anchorPrefix:o,flow:a,keepUndefined:c,onTagObj:l,tag:u}=i!=null?i:{},{onAnchor:d,setAnchors:f,sourceObjects:p}=Zb(this,o||"a"),m={aliasDuplicateObjects:s!=null?s:!0,keepUndefined:c!=null?c:!1,onAnchor:d,onTagObj:l,replacer:n,schema:this.schema,sourceObjects:p},h=mr(e,u,m);return a&&se(h)&&(h.flow=!0),f(),h}createPair(e,t,i={}){let n=this.createNode(e,null,i),s=this.createNode(t,null,i);return new $e(n,s)}delete(e){return ln(this.contents)?this.contents.delete(e):!1}deleteIn(e){return rn(e)?this.contents==null?!1:(this.contents=null,!0):ln(this.contents)?this.contents.deleteIn(e):!1}get(e,t){return se(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return rn(e)?!t&&K(this.contents)?this.contents.value:this.contents:se(this.contents)?this.contents.getIn(e,t):void 0}has(e){return se(this.contents)?this.contents.has(e):!1}hasIn(e){return rn(e)?this.contents!==void 0:se(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=ys(this.schema,[e],t):ln(this.contents)&&this.contents.set(e,t)}setIn(e,t){rn(e)?this.contents=t:this.contents==null?this.contents=ys(this.schema,Array.from(e),t):ln(this.contents)&&this.contents.setIn(e,t)}setSchema(e,t={}){typeof e=="number"&&(e=String(e));let i;switch(e){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new Zt({version:"1.1"}),i={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=e:this.directives=new Zt({version:e}),i={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,i=null;break;default:{let n=JSON.stringify(e);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${n}`)}}if(t.schema instanceof Object)this.schema=t.schema;else if(i)this.schema=new ks(Object.assign(i,t));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:e,jsonArg:t,mapAsMap:i,maxAliasCount:n,onAnchor:s,reviver:o}={}){let a={anchors:new Map,doc:this,keep:!e,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof n=="number"?n:100},c=Te(this.contents,t!=null?t:"",a);if(typeof s=="function")for(let{count:l,res:u}of a.anchors.values())s(u,l);return typeof o=="function"?Vr(o,{"":c},"",c):c}toJSON(e,t){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:t})}toString(e={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){let t=JSON.stringify(e.indent);throw new Error(`"indent" option must be a positive integer, not ${t}`)}return v0(this,e)}};function ln(r){if(se(r))return!0;throw new Error("Expected a YAML collection as document contents")}var Ps=class extends Error{constructor(e,t,i,n){super(),this.name=e,this.code=i,this.message=n,this.pos=t}},Dt=class extends Ps{constructor(e,t,i){super("YAMLParseError",e,t,i)}},xs=class extends Ps{constructor(e,t,i){super("YAMLWarning",e,t,i)}},Vu=(r,e)=>t=>{if(t.pos[0]===-1)return;t.linePos=t.pos.map(a=>e.linePos(a));let{line:i,col:n}=t.linePos[0];t.message+=` at line ${i}, column ${n}`;let s=n-1,o=r.substring(e.lineStarts[i-1],e.lineStarts[i]).replace(/[\n\r]+$/,"");if(s>=60&&o.length>80){let a=Math.min(s-39,o.length-79);o="\u2026"+o.substring(a),s-=a-1}if(o.length>80&&(o=o.substring(0,79)+"\u2026"),i>1&&/^ *$/.test(o.substring(0,s))){let a=r.substring(e.lineStarts[i-2],e.lineStarts[i-1]);a.length>80&&(a=a.substring(0,79)+`\u2026 -`),o=a+o}if(/[^ ]/.test(o)){let a=1,c=t.linePos[1];(c==null?void 0:c.line)===i&&c.col>n&&(a=Math.max(1,Math.min(c.col-n,80-s)));let l=" ".repeat(s)+"^".repeat(a);t.message+=`: +`}var mr=class r{constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,We,{value:Yo});let s=null;typeof t=="function"||Array.isArray(t)?s=t:n===void 0&&t&&(n=t,t=void 0);let i=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},n);this.options=i;let{version:o}=i;n!=null&&n._directives?(this.directives=n._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new Yt({version:o}),this.setSchema(o,n),this.contents=e===void 0?null:this.createNode(e,s,n)}clone(){let e=Object.create(r.prototype,{[We]:{value:Yo}});return e.commentBefore=this.commentBefore,e.comment=this.comment,e.errors=this.errors.slice(),e.warnings=this.warnings.slice(),e.options=Object.assign({},this.options),this.directives&&(e.directives=this.directives.clone()),e.schema=this.schema.clone(),e.contents=re(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){ss(this.contents)&&this.contents.add(e)}addIn(e,t){ss(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){let n=ou(this);e.anchor=!t||n.has(t)?au(t||"a",n):t}return new fr(e.anchor)}createNode(e,t,n){let s;if(typeof t=="function")e=t.call({"":e},"",e),s=t;else if(Array.isArray(t)){let y=g=>typeof g=="number"||g instanceof String||g instanceof Number,b=t.filter(y).map(String);b.length>0&&(t=t.concat(b)),s=t}else n===void 0&&t&&(n=t,t=void 0);let{aliasDuplicateObjects:i,anchorPrefix:o,flow:a,keepUndefined:c,onTagObj:l,tag:u}=n!=null?n:{},{onAnchor:d,setAnchors:f,sourceObjects:p}=Eb(this,o||"a"),m={aliasDuplicateObjects:i!=null?i:!0,keepUndefined:c!=null?c:!1,onAnchor:d,onTagObj:l,replacer:s,schema:this.schema,sourceObjects:p},h=pr(e,u,m);return a&&ie(h)&&(h.flow=!0),f(),h}createPair(e,t,n={}){let s=this.createNode(e,null,n),i=this.createNode(t,null,n);return new ve(s,i)}delete(e){return ss(this.contents)?this.contents.delete(e):!1}deleteIn(e){return Qn(e)?this.contents==null?!1:(this.contents=null,!0):ss(this.contents)?this.contents.deleteIn(e):!1}get(e,t){return ie(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return Qn(e)?!t&&K(this.contents)?this.contents.value:this.contents:ie(this.contents)?this.contents.getIn(e,t):void 0}has(e){return ie(this.contents)?this.contents.has(e):!1}hasIn(e){return Qn(e)?this.contents!==void 0:ie(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=oi(this.schema,[e],t):ss(this.contents)&&this.contents.set(e,t)}setIn(e,t){Qn(e)?this.contents=t:this.contents==null?this.contents=oi(this.schema,Array.from(e),t):ss(this.contents)&&this.contents.setIn(e,t)}setSchema(e,t={}){typeof e=="number"&&(e=String(e));let n;switch(e){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new Yt({version:"1.1"}),n={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=e:this.directives=new Yt({version:e}),n={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,n=null;break;default:{let s=JSON.stringify(e);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${s}`)}}if(t.schema instanceof Object)this.schema=t.schema;else if(n)this.schema=new yi(Object.assign(n,t));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:e,jsonArg:t,mapAsMap:n,maxAliasCount:s,onAnchor:i,reviver:o}={}){let a={anchors:new Map,doc:this,keep:!e,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof s=="number"?s:100},c=Pe(this.contents,t!=null?t:"",a);if(typeof i=="function")for(let{count:l,res:u}of a.anchors.values())i(u,l);return typeof o=="function"?qr(o,{"":c},"",c):c}toJSON(e,t){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:t})}toString(e={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){let t=JSON.stringify(e.indent);throw new Error(`"indent" option must be a positive integer, not ${t}`)}return Kb(this,e)}};function ss(r){if(ie(r))return!0;throw new Error("Expected a YAML collection as document contents")}var gi=class extends Error{constructor(e,t,n,s){super(),this.name=e,this.code=n,this.message=s,this.pos=t}},qt=class extends gi{constructor(e,t,n){super("YAMLParseError",e,t,n)}},bi=class extends gi{constructor(e,t,n){super("YAMLWarning",e,t,n)}},vu=(r,e)=>t=>{if(t.pos[0]===-1)return;t.linePos=t.pos.map(a=>e.linePos(a));let{line:n,col:s}=t.linePos[0];t.message+=` at line ${n}, column ${s}`;let i=s-1,o=r.substring(e.lineStarts[n-1],e.lineStarts[n]).replace(/[\n\r]+$/,"");if(i>=60&&o.length>80){let a=Math.min(i-39,o.length-79);o="\u2026"+o.substring(a),i-=a-1}if(o.length>80&&(o=o.substring(0,79)+"\u2026"),n>1&&/^ *$/.test(o.substring(0,i))){let a=r.substring(e.lineStarts[n-2],e.lineStarts[n-1]);a.length>80&&(a=a.substring(0,79)+`\u2026 +`),o=a+o}if(/[^ ]/.test(o)){let a=1,c=t.linePos[1];(c==null?void 0:c.line)===n&&c.col>s&&(a=Math.max(1,Math.min(c.col-s,80-i)));let l=" ".repeat(i)+"^".repeat(a);t.message+=`: ${o} ${l} -`}};function er(r,{flow:e,indicator:t,next:i,offset:n,onError:s,parentIndent:o,startOnNewline:a}){let c=!1,l=a,u=a,d="",f="",p=!1,m=!1,h=null,y=null,b=null,g=null,_=null,S=null,v=null;for(let E of r)switch(m&&(E.type!=="space"&&E.type!=="newline"&&E.type!=="comma"&&s(E.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),m=!1),h&&(l&&E.type!=="comment"&&E.type!=="newline"&&s(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),h=null),E.type){case"space":!e&&(t!=="doc-start"||(i==null?void 0:i.type)!=="flow-collection")&&E.source.includes(" ")&&(h=E),u=!0;break;case"comment":{u||s(E,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let R=E.source.substring(1)||" ";d?d+=f+R:d=R,f="",l=!1;break}case"newline":l?d?d+=E.source:(!S||t!=="seq-item-ind")&&(c=!0):f+=E.source,l=!0,p=!0,(y||b)&&(g=E),u=!0;break;case"anchor":y&&s(E,"MULTIPLE_ANCHORS","A node can have at most one anchor"),E.source.endsWith(":")&&s(E.offset+E.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),y=E,v!=null||(v=E.offset),l=!1,u=!1,m=!0;break;case"tag":{b&&s(E,"MULTIPLE_TAGS","A node can have at most one tag"),b=E,v!=null||(v=E.offset),l=!1,u=!1,m=!0;break}case t:(y||b)&&s(E,"BAD_PROP_ORDER",`Anchors and tags must be after the ${E.source} indicator`),S&&s(E,"UNEXPECTED_TOKEN",`Unexpected ${E.source} in ${e!=null?e:"collection"}`),S=E,l=t==="seq-item-ind"||t==="explicit-key-ind",u=!1;break;case"comma":if(e){_&&s(E,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),_=E,l=!1,u=!1;break}default:s(E,"UNEXPECTED_TOKEN",`Unexpected ${E.type} token`),l=!1,u=!1}let P=r[r.length-1],x=P?P.offset+P.source.length:n;return m&&i&&i.type!=="space"&&i.type!=="newline"&&i.type!=="comma"&&(i.type!=="scalar"||i.source!=="")&&s(i.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),h&&(l&&h.indent<=o||(i==null?void 0:i.type)==="block-map"||(i==null?void 0:i.type)==="block-seq")&&s(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:_,found:S,spaceBefore:c,comment:d,hasNewline:p,anchor:y,tag:b,newlineAfterProp:g,end:x,start:v!=null?v:x}}function Hr(r){if(!r)return null;switch(r.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(r.source.includes(` -`))return!0;if(r.end){for(let e of r.end)if(e.type==="newline")return!0}return!1;case"flow-collection":for(let e of r.items){for(let t of e.start)if(t.type==="newline")return!0;if(e.sep){for(let t of e.sep)if(t.type==="newline")return!0}if(Hr(e.key)||Hr(e.value))return!0}return!1;default:return!0}}function Is(r,e,t){if((e==null?void 0:e.type)==="flow-collection"){let i=e.end[0];i.indent===r&&(i.source==="]"||i.source==="}")&&Hr(e)&&t(i,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}function Fa(r,e,t){let{uniqueKeys:i}=r.options;if(i===!1)return!1;let n=typeof i=="function"?i:(s,o)=>s===o||K(s)&&K(o)&&s.value===o.value;return e.some(s=>n(s.key,t))}var w0="All mapping items must start at the same column";function $0({composeNode:r,composeEmptyNode:e},t,i,n,s){var u,d;let o=(u=s==null?void 0:s.nodeClass)!=null?u:ke,a=new o(t.schema);t.atRoot&&(t.atRoot=!1);let c=i.offset,l=null;for(let f of i.items){let{start:p,key:m,sep:h,value:y}=f,b=er(p,{indicator:"explicit-key-ind",next:m!=null?m:h==null?void 0:h[0],offset:c,onError:n,parentIndent:i.indent,startOnNewline:!0}),g=!b.found;if(g){if(m&&(m.type==="block-seq"?n(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in m&&m.indent!==i.indent&&n(c,"BAD_INDENT",w0)),!b.anchor&&!b.tag&&!h){l=b.end,b.comment&&(a.comment?a.comment+=` -`+b.comment:a.comment=b.comment);continue}(b.newlineAfterProp||Hr(m))&&n(m!=null?m:p[p.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else((d=b.found)==null?void 0:d.indent)!==i.indent&&n(c,"BAD_INDENT",w0);t.atKey=!0;let _=b.end,S=m?r(t,m,b,n):e(t,_,p,null,b,n);t.schema.compat&&Is(i.indent,m,n),t.atKey=!1,Fa(t,a.items,S)&&n(_,"DUPLICATE_KEY","Map keys must be unique");let v=er(h!=null?h:[],{indicator:"map-value-ind",next:y,offset:S.range[2],onError:n,parentIndent:i.indent,startOnNewline:!m||m.type==="block-scalar"});if(c=v.end,v.found){g&&((y==null?void 0:y.type)==="block-map"&&!v.hasNewline&&n(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),t.options.strict&&b.startr&&(r.type==="block-map"||r.type==="block-seq");function E0({composeNode:r,composeEmptyNode:e},t,i,n,s){var y,b,g;let o=i.start.source==="{",a=o?"flow map":"flow sequence",c=(y=s==null?void 0:s.nodeClass)!=null?y:o?ke:Be,l=new c(t.schema);l.flow=!0;let u=t.atRoot;u&&(t.atRoot=!1),t.atKey&&(t.atKey=!1);let d=i.offset+i.start.source.length;for(let _=0;_0){let _=tr(m,h,t.options.strict,n);_.comment&&(l.comment?l.comment+=` -`+_.comment:l.comment=_.comment),l.range=[i.offset,h,_.offset]}else l.range=[i.offset,h,h];return l}function Bu(r,e,t,i,n,s){let o=t.type==="block-map"?$0(r,e,t,i,s):t.type==="block-seq"?S0(r,e,t,i,s):E0(r,e,t,i,s),a=o.constructor;return n==="!"||n===a.tagName?(o.tag=a.tagName,o):(n&&(o.tag=n),o)}function A0(r,e,t,i,n){var f,p,m;let s=i.tag,o=s?e.directives.tagName(s.source,h=>n(s,"TAG_RESOLVE_FAILED",h)):null;if(t.type==="block-seq"){let{anchor:h,newlineAfterProp:y}=i,b=h&&s?h.offset>s.offset?h:s:h!=null?h:s;b&&(!y||y.offseth.tag===o&&h.collection===a);if(!c){let h=e.schema.knownTags[o];if((h==null?void 0:h.collection)===a)e.schema.tags.push(Object.assign({},h,{default:!1})),c=h;else return h?n(s,"BAD_COLLECTION_TYPE",`${h.tag} used for ${a} collection, but expects ${(f=h.collection)!=null?f:"scalar"}`,!0):n(s,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),Bu(r,e,t,n,o)}let l=Bu(r,e,t,n,o,c),u=(m=(p=c.resolve)==null?void 0:p.call(c,l,h=>n(s,"TAG_RESOLVE_FAILED",h),e.options))!=null?m:l,d=re(u)?u:new j(u);return d.range=l.range,d.tag=o,c!=null&&c.format&&(d.format=c.format),d}function Hu(r,e,t){let i=e.offset,n=BR(e,r.options.strict,t);if(!n)return{value:"",type:null,comment:"",range:[i,i,i]};let s=n.mode===">"?j.BLOCK_FOLDED:j.BLOCK_LITERAL,o=e.source?HR(e.source):[],a=o.length;for(let h=o.length-1;h>=0;--h){let y=o[h][1];if(y===""||y==="\r")a=h;else break}if(a===0){let h=n.chomp==="+"&&o.length>0?` -`.repeat(Math.max(1,o.length-1)):"",y=i+n.length;return e.source&&(y+=e.source.length),{value:h,type:s,comment:n.comment,range:[i,y,y]}}let c=e.indent+n.indent,l=e.offset+n.length,u=0;for(let h=0;hc&&(c=y.length);else{y.length=a;--h)o[h][0].length>c&&(a=h+1);let d="",f="",p=!1;for(let h=0;hi===o||K(i)&&K(o)&&i.value===o.value;return e.some(i=>s(i.key,t))}var Gb="All mapping items must start at the same column";function Wb({composeNode:r,composeEmptyNode:e},t,n,s,i){var u,d;let o=(u=i==null?void 0:i.nodeClass)!=null?u:Ae,a=new o(t.schema);t.atRoot&&(t.atRoot=!1);let c=n.offset,l=null;for(let f of n.items){let{start:p,key:m,sep:h,value:y}=f,b=Qt(p,{indicator:"explicit-key-ind",next:m!=null?m:h==null?void 0:h[0],offset:c,onError:s,parentIndent:n.indent,startOnNewline:!0}),g=!b.found;if(g){if(m&&(m.type==="block-seq"?s(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in m&&m.indent!==n.indent&&s(c,"BAD_INDENT",Gb)),!b.anchor&&!b.tag&&!h){l=b.end,b.comment&&(a.comment?a.comment+=` +`+b.comment:a.comment=b.comment);continue}(b.newlineAfterProp||Vr(m))&&s(m!=null?m:p[p.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else((d=b.found)==null?void 0:d.indent)!==n.indent&&s(c,"BAD_INDENT",Gb);t.atKey=!0;let w=b.end,S=m?r(t,m,b,s):e(t,w,p,null,b,s);t.schema.compat&&wi(n.indent,m,s),t.atKey=!1,Aa(t,a.items,S)&&s(w,"DUPLICATE_KEY","Map keys must be unique");let _=Qt(h!=null?h:[],{indicator:"map-value-ind",next:y,offset:S.range[2],onError:s,parentIndent:n.indent,startOnNewline:!m||m.type==="block-scalar"});if(c=_.end,_.found){g&&((y==null?void 0:y.type)==="block-map"&&!_.hasNewline&&s(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),t.options.strict&&b.start<_.found.offset-1024&&s(S.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let x=y?r(t,y,_,s):e(t,c,h,null,_,s);t.schema.compat&&wi(n.indent,y,s),c=x.range[2];let I=new ve(S,x);t.options.keepSourceTokens&&(I.srcToken=f),a.items.push(I)}else{g&&s(S.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),_.comment&&(S.comment?S.comment+=` +`+_.comment:S.comment=_.comment);let x=new ve(S);t.options.keepSourceTokens&&(x.srcToken=f),a.items.push(x)}}return l&&lr&&(r.type==="block-map"||r.type==="block-seq");function Yb({composeNode:r,composeEmptyNode:e},t,n,s,i){var y,b,g;let o=n.start.source==="{",a=o?"flow map":"flow sequence",c=(y=i==null?void 0:i.nodeClass)!=null?y:o?Ae:Ue,l=new c(t.schema);l.flow=!0;let u=t.atRoot;u&&(t.atRoot=!1),t.atKey&&(t.atKey=!1);let d=n.offset+n.start.source.length;for(let w=0;w0){let w=Zt(m,h,t.options.strict,s);w.comment&&(l.comment?l.comment+=` +`+w.comment:l.comment=w.comment),l.range=[n.offset,h,w.offset]}else l.range=[n.offset,h,h];return l}function Eu(r,e,t,n,s,i){let o=t.type==="block-map"?Wb(r,e,t,n,i):t.type==="block-seq"?Jb(r,e,t,n,i):Yb(r,e,t,n,i),a=o.constructor;return s==="!"||s===a.tagName?(o.tag=a.tagName,o):(s&&(o.tag=s),o)}function Xb(r,e,t,n,s){var f,p,m;let i=n.tag,o=i?e.directives.tagName(i.source,h=>s(i,"TAG_RESOLVE_FAILED",h)):null;if(t.type==="block-seq"){let{anchor:h,newlineAfterProp:y}=n,b=h&&i?h.offset>i.offset?h:i:h!=null?h:i;b&&(!y||y.offseth.tag===o&&h.collection===a);if(!c){let h=e.schema.knownTags[o];if((h==null?void 0:h.collection)===a)e.schema.tags.push(Object.assign({},h,{default:!1})),c=h;else return h?s(i,"BAD_COLLECTION_TYPE",`${h.tag} used for ${a} collection, but expects ${(f=h.collection)!=null?f:"scalar"}`,!0):s(i,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),Eu(r,e,t,s,o)}let l=Eu(r,e,t,s,o,c),u=(m=(p=c.resolve)==null?void 0:p.call(c,l,h=>s(i,"TAG_RESOLVE_FAILED",h),e.options))!=null?m:l,d=re(u)?u:new D(u);return d.range=l.range,d.tag=o,c!=null&&c.format&&(d.format=c.format),d}function Au(r,e,t){let n=e.offset,s=cP(e,r.options.strict,t);if(!s)return{value:"",type:null,comment:"",range:[n,n,n]};let i=s.mode===">"?D.BLOCK_FOLDED:D.BLOCK_LITERAL,o=e.source?lP(e.source):[],a=o.length;for(let h=o.length-1;h>=0;--h){let y=o[h][1];if(y===""||y==="\r")a=h;else break}if(a===0){let h=s.chomp==="+"&&o.length>0?` +`.repeat(Math.max(1,o.length-1)):"",y=n+s.length;return e.source&&(y+=e.source.length),{value:h,type:i,comment:s.comment,range:[n,y,y]}}let c=e.indent+s.indent,l=e.offset+s.length,u=0;for(let h=0;hc&&(c=y.length);else{y.length=a;--h)o[h][0].length>c&&(a=h+1);let d="",f="",p=!1;for(let h=0;hc||b[0]===" "?(f===" "?f=` `:!p&&f===` `&&(f=` @@ -101,72 +101,72 @@ ${l} `,p=!0):b===""?f===` `?d+=` `:f=` -`:(d+=f+b,f=" ",p=!1)}switch(n.chomp){case"-":break;case"+":for(let h=a;ht(i+f,p,m);switch(n){case"scalar":a=j.PLAIN,c=KR(s,l);break;case"single-quoted-scalar":a=j.QUOTE_SINGLE,c=GR(s,l);break;case"double-quoted-scalar":a=j.QUOTE_DOUBLE,c=WR(s,l);break;default:return t(r,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${n}`),{value:"",type:null,comment:"",range:[i,i+s.length,i+s.length]}}let u=i+s.length,d=tr(o,u,e,t);return{value:c,type:a,comment:d.comment,range:[i,u,d.offset]}}function KR(r,e){let t="";switch(r[0]){case" ":t="a tab character";break;case",":t="flow indicator character ,";break;case"%":t="directive indicator character %";break;case"|":case">":{t=`block scalar indicator ${r[0]}`;break}case"@":case"`":{t=`reserved character ${r[0]}`;break}}return t&&e(0,"BAD_SCALAR_START",`Plain value cannot start with ${t}`),k0(r)}function GR(r,e){return(r[r.length-1]!=="'"||r.length===1)&&e(r.length,"MISSING_CHAR","Missing closing 'quote"),k0(r.slice(1,-1)).replace(/''/g,"'")}function k0(r){var c;let e,t;try{e=new RegExp(`(.*?)(?t(n+f,p,m);switch(s){case"scalar":a=D.PLAIN,c=dP(i,l);break;case"single-quoted-scalar":a=D.QUOTE_SINGLE,c=uP(i,l);break;case"double-quoted-scalar":a=D.QUOTE_DOUBLE,c=fP(i,l);break;default:return t(r,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${s}`),{value:"",type:null,comment:"",range:[n,n+i.length,n+i.length]}}let u=n+i.length,d=Zt(o,u,e,t);return{value:c,type:a,comment:d.comment,range:[n,u,d.offset]}}function dP(r,e){let t="";switch(r[0]){case" ":t="a tab character";break;case",":t="flow indicator character ,";break;case"%":t="directive indicator character %";break;case"|":case">":{t=`block scalar indicator ${r[0]}`;break}case"@":case"`":{t=`reserved character ${r[0]}`;break}}return t&&e(0,"BAD_SCALAR_START",`Plain value cannot start with ${t}`),Qb(r)}function uP(r,e){return(r[r.length-1]!=="'"||r.length===1)&&e(r.length,"MISSING_CHAR","Missing closing 'quote"),Qb(r.slice(1,-1)).replace(/''/g,"'")}function Qb(r){var c;let e,t;try{e=new RegExp(`(.*?)(?s?r.slice(s,i+1):n)}else t+=n}return(r[r.length-1]!=='"'||r.length===1)&&e(r.length,"MISSING_CHAR",'Missing closing "quote'),t}function JR(r,e){let t="",i=r[e+1];for(;(i===" "||i===" "||i===` -`||i==="\r")&&!(i==="\r"&&r[e+2]!==` -`);)i===` +`,"sy")}catch(l){e=/(.*?)[ \t]*\r?\n/sy,t=/[ \t]*(.*?)[ \t]*\r?\n/sy}let n=e.exec(r);if(!n)return r;let s=n[1],i=" ",o=e.lastIndex;for(t.lastIndex=o;n=t.exec(r);)n[1]===""?i===` +`?s+=i:i=` +`:(s+=i+n[1],i=" "),o=t.lastIndex;let a=/[ \t]*(.*)/sy;return a.lastIndex=o,n=a.exec(r),s+i+((c=n==null?void 0:n[1])!=null?c:"")}function fP(r,e){let t="";for(let n=1;ni?r.slice(i,n+1):s)}else t+=s}return(r[r.length-1]!=='"'||r.length===1)&&e(r.length,"MISSING_CHAR",'Missing closing "quote'),t}function pP(r,e){let t="",n=r[e+1];for(;(n===" "||n===" "||n===` +`||n==="\r")&&!(n==="\r"&&r[e+2]!==` +`);)n===` `&&(t+=` -`),e+=1,i=r[e+1];return t||(t=" "),{fold:t,offset:e}}var YR={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:` -`,r:"\r",t:" ",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function XR(r,e,t,i){let n=r.substr(e,t),o=n.length===t&&/^[0-9a-fA-F]+$/.test(n)?parseInt(n,16):NaN;try{return String.fromCodePoint(o)}catch(a){let c=r.substr(e-2,t+2);return i(e-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${c}`),c}}function Gu(r,e,t,i){let{value:n,type:s,comment:o,range:a}=e.type==="block-scalar"?Hu(r,e,i):Ku(e,r.options.strict,i),c=t?r.directives.tagName(t.source,d=>i(t,"TAG_RESOLVE_FAILED",d)):null,l;r.options.stringKeys&&r.atKey?l=r.schema[lt]:c?l=ZR(r.schema,n,c,t,i):e.type==="scalar"?l=QR(r,n,e,i):l=r.schema[lt];let u;try{let d=l.resolve(n,f=>i(t!=null?t:e,"TAG_RESOLVE_FAILED",f),r.options);u=K(d)?d:new j(d)}catch(d){let f=d instanceof Error?d.message:String(d);i(t!=null?t:e,"TAG_RESOLVE_FAILED",f),u=new j(n)}return u.range=a,u.source=n,s&&(u.type=s),c&&(u.tag=c),l.format&&(u.format=l.format),o&&(u.comment=o),u}function ZR(r,e,t,i,n){var a;if(t==="!")return r[lt];let s=[];for(let c of r.tags)if(!c.collection&&c.tag===t)if(c.default&&c.test)s.push(c);else return c;for(let c of s)if((a=c.test)!=null&&a.test(e))return c;let o=r.knownTags[t];return o&&!o.collection?(r.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(n(i,"TAG_RESOLVE_FAILED",`Unresolved tag: ${t}`,t!=="tag:yaml.org,2002:str"),r[lt])}function QR({atKey:r,directives:e,schema:t},i,n,s){var a;let o=t.tags.find(c=>{var l;return(c.default===!0||r&&c.default==="key")&&((l=c.test)==null?void 0:l.test(i))})||t[lt];if(t.compat){let c=(a=t.compat.find(l=>{var u;return l.default&&((u=l.test)==null?void 0:u.test(i))}))!=null?a:t[lt];if(o.tag!==c.tag){let l=e.tagString(o.tag),u=e.tagString(c.tag),d=`Value may be parsed as either ${l} or ${u}`;s(n,"TAG_RESOLVE_FAILED",d,!0)}}return o}function P0(r,e,t){if(e){t!=null||(t=e.length);for(let i=t-1;i>=0;--i){let n=e[i];switch(n.type){case"space":case"comment":case"newline":r-=n.source.length;continue}for(n=e[++i];(n==null?void 0:n.type)==="space";)r+=n.source.length,n=e[++i];break}}return r}var eT={composeNode:Wu,composeEmptyNode:Va};function Wu(r,e,t,i){let n=r.atKey,{spaceBefore:s,comment:o,anchor:a,tag:c}=t,l,u=!0;switch(e.type){case"alias":l=tT(r,e,i),(a||c)&&i(e,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":l=Gu(r,e,c,i),a&&(l.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=A0(eT,r,e,t,i),a&&(l.anchor=a.source.substring(1))}catch(d){let f=d instanceof Error?d.message:String(d);i(e,"RESOURCE_EXHAUSTION",f)}break;default:{let d=e.type==="error"?e.message:`Unsupported token (type: ${e.type})`;i(e,"UNEXPECTED_TOKEN",d),u=!1}}return l!=null||(l=Va(r,e.offset,void 0,null,t,i)),a&&l.anchor===""&&i(a,"BAD_ALIAS","Anchor cannot be an empty string"),n&&r.options.stringKeys&&(!K(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&i(c!=null?c:e,"NON_STRING_KEY","With stringKeys, all keys must be strings"),s&&(l.spaceBefore=!0),o&&(e.type==="scalar"&&e.source===""?l.comment=o:l.commentBefore=o),r.options.keepSourceTokens&&u&&(l.srcToken=e),l}function Va(r,e,t,i,{spaceBefore:n,comment:s,anchor:o,tag:a,end:c},l){let u={type:"scalar",offset:P0(e,t,i),indent:-1,source:""},d=Gu(r,u,a,l);return o&&(d.anchor=o.source.substring(1),d.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),n&&(d.spaceBefore=!0),s&&(d.comment=s,d.range[2]=c),d}function tT({options:r},{offset:e,source:t,end:i},n){let s=new hr(t.substring(1));s.source===""&&n(e,"BAD_ALIAS","Alias cannot be an empty string"),s.source.endsWith(":")&&n(e+t.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=e+t.length,a=tr(i,o,r.strict,n);return s.range=[e,o,a.offset],a.comment&&(s.comment=a.comment),s}function x0(r,e,{offset:t,start:i,value:n,end:s},o){let a=Object.assign({_directives:e},r),c=new gr(void 0,a),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=er(i,{indicator:"doc-start",next:n!=null?n:s==null?void 0:s[0],offset:t,onError:o,parentIndent:0,startOnNewline:!0});u.found&&(c.directives.docStart=!0,n&&(n.type==="block-map"||n.type==="block-seq")&&!u.hasNewline&&o(u.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=n?Wu(l,n,u,o):Va(l,u.end,i,null,u,o);let d=c.contents.range[2],f=tr(s,d,!1,o);return f.comment&&(c.comment=f.comment),c.range=[t,d,f.offset],c}function Rs(r){if(typeof r=="number")return[r,r+1];if(Array.isArray(r))return r.length===2?r:[r[0],r[1]];let{offset:e,source:t}=r;return[e,e+(typeof t=="string"?t.length:1)]}function I0(r){var n;let e="",t=!1,i=!1;for(let s=0;sn(t,"TAG_RESOLVE_FAILED",d)):null,l;r.options.stringKeys&&r.atKey?l=r.schema[ct]:c?l=yP(r.schema,s,c,t,n):e.type==="scalar"?l=gP(r,s,e,n):l=r.schema[ct];let u;try{let d=l.resolve(s,f=>n(t!=null?t:e,"TAG_RESOLVE_FAILED",f),r.options);u=K(d)?d:new D(d)}catch(d){let f=d instanceof Error?d.message:String(d);n(t!=null?t:e,"TAG_RESOLVE_FAILED",f),u=new D(s)}return u.range=a,u.source=s,i&&(u.type=i),c&&(u.tag=c),l.format&&(u.format=l.format),o&&(u.comment=o),u}function yP(r,e,t,n,s){var a;if(t==="!")return r[ct];let i=[];for(let c of r.tags)if(!c.collection&&c.tag===t)if(c.default&&c.test)i.push(c);else return c;for(let c of i)if((a=c.test)!=null&&a.test(e))return c;let o=r.knownTags[t];return o&&!o.collection?(r.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(s(n,"TAG_RESOLVE_FAILED",`Unresolved tag: ${t}`,t!=="tag:yaml.org,2002:str"),r[ct])}function gP({atKey:r,directives:e,schema:t},n,s,i){var a;let o=t.tags.find(c=>{var l;return(c.default===!0||r&&c.default==="key")&&((l=c.test)==null?void 0:l.test(n))})||t[ct];if(t.compat){let c=(a=t.compat.find(l=>{var u;return l.default&&((u=l.test)==null?void 0:u.test(n))}))!=null?a:t[ct];if(o.tag!==c.tag){let l=e.tagString(o.tag),u=e.tagString(c.tag),d=`Value may be parsed as either ${l} or ${u}`;i(s,"TAG_RESOLVE_FAILED",d,!0)}}return o}function Zb(r,e,t){if(e){t!=null||(t=e.length);for(let n=t-1;n>=0;--n){let s=e[n];switch(s.type){case"space":case"comment":case"newline":r-=s.source.length;continue}for(s=e[++n];(s==null?void 0:s.type)==="space";)r+=s.source.length,s=e[++n];break}}return r}var bP={composeNode:Iu,composeEmptyNode:ka};function Iu(r,e,t,n){let s=r.atKey,{spaceBefore:i,comment:o,anchor:a,tag:c}=t,l,u=!0;switch(e.type){case"alias":l=wP(r,e,n),(a||c)&&n(e,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":l=xu(r,e,c,n),a&&(l.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=Xb(bP,r,e,t,n),a&&(l.anchor=a.source.substring(1))}catch(d){let f=d instanceof Error?d.message:String(d);n(e,"RESOURCE_EXHAUSTION",f)}break;default:{let d=e.type==="error"?e.message:`Unsupported token (type: ${e.type})`;n(e,"UNEXPECTED_TOKEN",d),u=!1}}return l!=null||(l=ka(r,e.offset,void 0,null,t,n)),a&&l.anchor===""&&n(a,"BAD_ALIAS","Anchor cannot be an empty string"),s&&r.options.stringKeys&&(!K(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&n(c!=null?c:e,"NON_STRING_KEY","With stringKeys, all keys must be strings"),i&&(l.spaceBefore=!0),o&&(e.type==="scalar"&&e.source===""?l.comment=o:l.commentBefore=o),r.options.keepSourceTokens&&u&&(l.srcToken=e),l}function ka(r,e,t,n,{spaceBefore:s,comment:i,anchor:o,tag:a,end:c},l){let u={type:"scalar",offset:Zb(e,t,n),indent:-1,source:""},d=xu(r,u,a,l);return o&&(d.anchor=o.source.substring(1),d.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),s&&(d.spaceBefore=!0),i&&(d.comment=i,d.range[2]=c),d}function wP({options:r},{offset:e,source:t,end:n},s){let i=new fr(t.substring(1));i.source===""&&s(e,"BAD_ALIAS","Alias cannot be an empty string"),i.source.endsWith(":")&&s(e+t.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=e+t.length,a=Zt(n,o,r.strict,s);return i.range=[e,o,a.offset],a.comment&&(i.comment=a.comment),i}function e0(r,e,{offset:t,start:n,value:s,end:i},o){let a=Object.assign({_directives:e},r),c=new mr(void 0,a),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=Qt(n,{indicator:"doc-start",next:s!=null?s:i==null?void 0:i[0],offset:t,onError:o,parentIndent:0,startOnNewline:!0});u.found&&(c.directives.docStart=!0,s&&(s.type==="block-map"||s.type==="block-seq")&&!u.hasNewline&&o(u.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=s?Iu(l,s,u,o):ka(l,u.end,n,null,u,o);let d=c.contents.range[2],f=Zt(i,d,!1,o);return f.comment&&(c.comment=f.comment),c.range=[t,d,f.offset],c}function _i(r){if(typeof r=="number")return[r,r+1];if(Array.isArray(r))return r.length===2?r:[r[0],r[1]];let{offset:e,source:t}=r;return[e,e+(typeof t=="string"?t.length:1)]}function t0(r){var s;let e="",t=!1,n=!1;for(let i=0;i{let o=Rs(t);s?this.warnings.push(new xs(o,i,n)):this.errors.push(new Dt(o,i,n))},this.directives=new Zt({version:e.version||"1.2"}),this.options=e}decorate(e,t){let{comment:i,afterEmptyLine:n}=I0(this.prelude);if(i){let s=e.contents;if(t)e.comment=e.comment?`${e.comment} -${i}`:i;else if(n||e.directives.docStart||!s)e.commentBefore=i;else if(se(s)&&!s.flow&&s.items.length>0){let o=s.items[0];ee(o)&&(o=o.key);let a=o.commentBefore;o.commentBefore=a?`${i} -${a}`:i}else{let o=s.commentBefore;s.commentBefore=o?`${i} -${o}`:i}}if(t){for(let s=0;s{let s=Rs(e);s[0]+=t,this.onError(s,"BAD_DIRECTIVE",i,n)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{let t=x0(this.options,this.directives,e,this.onError);this.atDirectives&&!t.directives.docStart&&this.onError(e,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(t,!1),this.doc&&(yield this.doc),this.doc=t,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(e.source);break;case"error":{let t=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,i=new Dt(Rs(e),"UNEXPECTED_TOKEN",t);this.atDirectives||!this.doc?this.errors.push(i):this.doc.errors.push(i);break}case"doc-end":{if(!this.doc){let i="Unexpected doc-end without preceding document";this.errors.push(new Dt(Rs(e),"UNEXPECTED_TOKEN",i));break}this.doc.directives.docEnd=!0;let t=tr(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),t.comment){let i=this.doc.comment;this.doc.comment=i?`${i} -${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.push(new Dt(Rs(e),"UNEXPECTED_TOKEN",`Unsupported token ${e.type}`))}}*end(e=!1,t=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){let i=Object.assign({_directives:this.directives},this.options),n=new gr(void 0,i);this.atDirectives&&this.onError(t,"MISSING_CHAR","Missing directives-end indicator line"),n.range=[0,t,t],this.decorate(n,!1),yield n}}};var Ju=Symbol("break visit"),rT=Symbol("skip children"),R0=Symbol("remove item");function pi(r,e){"type"in r&&r.type==="document"&&(r={start:r.start,value:r.value}),T0(Object.freeze([]),r,e)}pi.BREAK=Ju;pi.SKIP=rT;pi.REMOVE=R0;pi.itemAtPath=(r,e)=>{let t=r;for(let[i,n]of e){let s=t==null?void 0:t[i];if(s&&"items"in s)t=s.items[n];else return}return t};pi.parentCollection=(r,e)=>{let t=pi.itemAtPath(r,e.slice(0,-1)),i=e[e.length-1][0],n=t==null?void 0:t[i];if(n&&"items"in n)return n;throw new Error("Parent collection not found")};function T0(r,e,t){let i=t(e,r);if(typeof i=="symbol")return i;for(let n of["key","value"]){let s=e[n];if(s&&"items"in s){for(let o=0;o{let o=_i(t);i?this.warnings.push(new bi(o,n,s)):this.errors.push(new qt(o,n,s))},this.directives=new Yt({version:e.version||"1.2"}),this.options=e}decorate(e,t){let{comment:n,afterEmptyLine:s}=t0(this.prelude);if(n){let i=e.contents;if(t)e.comment=e.comment?`${e.comment} +${n}`:n;else if(s||e.directives.docStart||!i)e.commentBefore=n;else if(ie(i)&&!i.flow&&i.items.length>0){let o=i.items[0];ee(o)&&(o=o.key);let a=o.commentBefore;o.commentBefore=a?`${n} +${a}`:n}else{let o=i.commentBefore;i.commentBefore=o?`${n} +${o}`:n}}if(t){for(let i=0;i{let i=_i(e);i[0]+=t,this.onError(i,"BAD_DIRECTIVE",n,s)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{let t=e0(this.options,this.directives,e,this.onError);this.atDirectives&&!t.directives.docStart&&this.onError(e,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(t,!1),this.doc&&(yield this.doc),this.doc=t,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(e.source);break;case"error":{let t=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,n=new qt(_i(e),"UNEXPECTED_TOKEN",t);this.atDirectives||!this.doc?this.errors.push(n):this.doc.errors.push(n);break}case"doc-end":{if(!this.doc){let n="Unexpected doc-end without preceding document";this.errors.push(new qt(_i(e),"UNEXPECTED_TOKEN",n));break}this.doc.directives.docEnd=!0;let t=Zt(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),t.comment){let n=this.doc.comment;this.doc.comment=n?`${n} +${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.push(new qt(_i(e),"UNEXPECTED_TOKEN",`Unsupported token ${e.type}`))}}*end(e=!1,t=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){let n=Object.assign({_directives:this.directives},this.options),s=new mr(void 0,n);this.atDirectives&&this.onError(t,"MISSING_CHAR","Missing directives-end indicator line"),s.range=[0,t,t],this.decorate(s,!1),yield s}}};var Tu=Symbol("break visit"),_P=Symbol("skip children"),r0=Symbol("remove item");function ln(r,e){"type"in r&&r.type==="document"&&(r={start:r.start,value:r.value}),n0(Object.freeze([]),r,e)}ln.BREAK=Tu;ln.SKIP=_P;ln.REMOVE=r0;ln.itemAtPath=(r,e)=>{let t=r;for(let[n,s]of e){let i=t==null?void 0:t[n];if(i&&"items"in i)t=i.items[s];else return}return t};ln.parentCollection=(r,e)=>{let t=ln.itemAtPath(r,e.slice(0,-1)),n=e[e.length-1][0],s=t==null?void 0:t[n];if(s&&"items"in s)return s;throw new Error("Parent collection not found")};function n0(r,e,t){let n=t(e,r);if(typeof n=="symbol")return n;for(let s of["key","value"]){let i=e[s];if(i&&"items"in i){for(let o=0;o":return"block-scalar-header"}return null}function Ft(r){switch(r){case void 0:case" ":case` -`:case"\r":case" ":return!0;default:return!1}}var C0=new Set("0123456789ABCDEFabcdef"),nT=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),za=new Set(",[]{}"),sT=new Set(` ,[]{} -\r `),Qu=r=>!r||sT.has(r),Os=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,t=!1){var n;if(e){if(typeof e!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!t;let i=(n=this.next)!=null?n:"stream";for(;i&&(t||this.hasChars(1));)i=yield*this.parseNext(i)}atLineEnd(){let e=this.pos,t=this.buffer[e];for(;t===" "||t===" ";)t=this.buffer[++e];return!t||t==="#"||t===` +`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(r[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}function Dt(r){switch(r){case void 0:case" ":case` +`:case"\r":case" ":return!0;default:return!1}}var i0=new Set("0123456789ABCDEFabcdef"),$P=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Ia=new Set(",[]{}"),SP=new Set(` ,[]{} +\r `),Cu=r=>!r||SP.has(r),$i=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,t=!1){var s;if(e){if(typeof e!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!t;let n=(s=this.next)!=null?s:"stream";for(;n&&(t||this.hasChars(1));)n=yield*this.parseNext(n)}atLineEnd(){let e=this.pos,t=this.buffer[e];for(;t===" "||t===" ";)t=this.buffer[++e];return!t||t==="#"||t===` `?!0:t==="\r"?this.buffer[e+1]===` -`:!1}charAt(e){return this.buffer[this.pos+e]}continueScalar(e){let t=this.buffer[e];if(this.indentNext>0){let i=0;for(;t===" ";)t=this.buffer[++i+e];if(t==="\r"){let n=this.buffer[i+e+1];if(n===` -`||!n&&!this.atEnd)return e+i+1}return t===` -`||i>=this.indentNext||!t&&!this.atEnd?e+i:-1}if(t==="-"||t==="."){let i=this.buffer.substr(e,3);if((i==="---"||i==="...")&&Ft(this.buffer[e+3]))return-1}return e}getLine(){let e=this.lineEndPos;return(typeof e!="number"||e!==-1&&ethis.indentValue&&!Ft(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[e,t]=this.peek(2);if(!t&&!this.atEnd)return this.setNext("block-start");if((e==="-"||e==="?"||e===":")&&Ft(t)){let i=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=i,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let e=this.getLine();if(e===null)return this.setNext("doc");let t=yield*this.pushIndicators();switch(e[t]){case"#":yield*this.pushCount(e.length-t);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(Qu),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return t+=yield*this.parseBlockScalarHeader(),t+=yield*this.pushSpaces(!0),yield*this.pushCount(e.length-t),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let e,t,i=-1;do e=yield*this.pushNewline(),e>0?(t=yield*this.pushSpaces(!1),this.indentValue=i=t):t=0,t+=yield*this.pushSpaces(!0);while(e+t>0);let n=this.getLine();if(n===null)return this.setNext("flow");if((i!==-1&&i"0"&&t<="9")this.blockScalarIndent=Number(t)-1;else if(t!=="-")break}return yield*this.pushUntil(t=>Ft(t)||t==="#")}*parseBlockScalar(){let e=this.pos-1,t=0,i;e:for(let s=this.pos;i=this.buffer[s];++s)switch(i){case" ":t+=1;break;case` -`:e=s,t=0;break;case"\r":{let o=this.buffer[s+1];if(!o&&!this.atEnd)return this.setNext("block-scalar");if(o===` -`)break}default:break e}if(!i&&!this.atEnd)return this.setNext("block-scalar");if(t>=this.indentNext){this.blockScalarIndent===-1?this.indentNext=t:this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let s=this.continueScalar(e+1);if(s===-1)break;e=this.buffer.indexOf(` -`,s)}while(e!==-1);if(e===-1){if(!this.atEnd)return this.setNext("block-scalar");e=this.buffer.length}}let n=e+1;for(i=this.buffer[n];i===" ";)i=this.buffer[++n];if(i===" "){for(;i===" "||i===" "||i==="\r"||i===` -`;)i=this.buffer[++n];e=n-1}else if(!this.blockScalarKeep)do{let s=e-1,o=this.buffer[s];o==="\r"&&(o=this.buffer[--s]);let a=s;for(;o===" ";)o=this.buffer[--s];if(o===` -`&&s>=this.pos&&s+1+t>a)e=s;else break}while(!0);return yield Ua,yield*this.pushToIndex(e+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let e=this.flowLevel>0,t=this.pos-1,i=this.pos-1,n;for(;n=this.buffer[++i];)if(n===":"){let s=this.buffer[i+1];if(Ft(s)||e&&za.has(s))break;t=i}else if(Ft(n)){let s=this.buffer[i+1];if(n==="\r"&&(s===` -`?(i+=1,n=` -`,s=this.buffer[i+1]):t=i),s==="#"||e&&za.has(s))break;if(n===` -`){let o=this.continueScalar(i+1);if(o===-1)break;i=Math.max(i,o-2)}}else{if(e&&za.has(n))break;t=i}return!n&&!this.atEnd?this.setNext("plain-scalar"):(yield Ua,yield*this.pushToIndex(t+1,!0),e?"flow":"doc")}*pushCount(e){return e>0?(yield this.buffer.substr(this.pos,e),this.pos+=e,e):0}*pushToIndex(e,t){let i=this.buffer.slice(this.pos,e);return i?(yield i,this.pos+=i.length,i.length):(t&&(yield""),0)}*pushIndicators(){let e=0;e:for(;;){switch(this.charAt(0)){case"!":e+=yield*this.pushTag(),e+=yield*this.pushSpaces(!0);continue e;case"&":e+=yield*this.pushUntil(Qu),e+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let t=this.flowLevel>0,i=this.charAt(1);if(Ft(i)||t&&za.has(i)){t?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,e+=yield*this.pushCount(1),e+=yield*this.pushSpaces(!0);continue e}}}break e}return e}*pushTag(){if(this.charAt(1)==="<"){let e=this.pos+2,t=this.buffer[e];for(;!Ft(t)&&t!==">";)t=this.buffer[++e];return yield*this.pushToIndex(t===">"?e+1:e,!1)}else{let e=this.pos+1,t=this.buffer[e];for(;t;)if(nT.has(t))t=this.buffer[++e];else if(t==="%"&&C0.has(this.buffer[e+1])&&C0.has(this.buffer[e+2]))t=this.buffer[e+=3];else break;return yield*this.pushToIndex(e,!1)}}*pushNewline(){let e=this.buffer[this.pos];return e===` +`:!1}charAt(e){return this.buffer[this.pos+e]}continueScalar(e){let t=this.buffer[e];if(this.indentNext>0){let n=0;for(;t===" ";)t=this.buffer[++n+e];if(t==="\r"){let s=this.buffer[n+e+1];if(s===` +`||!s&&!this.atEnd)return e+n+1}return t===` +`||n>=this.indentNext||!t&&!this.atEnd?e+n:-1}if(t==="-"||t==="."){let n=this.buffer.substr(e,3);if((n==="---"||n==="...")&&Dt(this.buffer[e+3]))return-1}return e}getLine(){let e=this.lineEndPos;return(typeof e!="number"||e!==-1&&ethis.indentValue&&!Dt(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[e,t]=this.peek(2);if(!t&&!this.atEnd)return this.setNext("block-start");if((e==="-"||e==="?"||e===":")&&Dt(t)){let n=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=n,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let e=this.getLine();if(e===null)return this.setNext("doc");let t=yield*this.pushIndicators();switch(e[t]){case"#":yield*this.pushCount(e.length-t);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(Cu),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return t+=yield*this.parseBlockScalarHeader(),t+=yield*this.pushSpaces(!0),yield*this.pushCount(e.length-t),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let e,t,n=-1;do e=yield*this.pushNewline(),e>0?(t=yield*this.pushSpaces(!1),this.indentValue=n=t):t=0,t+=yield*this.pushSpaces(!0);while(e+t>0);let s=this.getLine();if(s===null)return this.setNext("flow");if((n!==-1&&n"0"&&t<="9")this.blockScalarIndent=Number(t)-1;else if(t!=="-")break}return yield*this.pushUntil(t=>Dt(t)||t==="#")}*parseBlockScalar(){let e=this.pos-1,t=0,n;e:for(let i=this.pos;n=this.buffer[i];++i)switch(n){case" ":t+=1;break;case` +`:e=i,t=0;break;case"\r":{let o=this.buffer[i+1];if(!o&&!this.atEnd)return this.setNext("block-scalar");if(o===` +`)break}default:break e}if(!n&&!this.atEnd)return this.setNext("block-scalar");if(t>=this.indentNext){this.blockScalarIndent===-1?this.indentNext=t:this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let i=this.continueScalar(e+1);if(i===-1)break;e=this.buffer.indexOf(` +`,i)}while(e!==-1);if(e===-1){if(!this.atEnd)return this.setNext("block-scalar");e=this.buffer.length}}let s=e+1;for(n=this.buffer[s];n===" ";)n=this.buffer[++s];if(n===" "){for(;n===" "||n===" "||n==="\r"||n===` +`;)n=this.buffer[++s];e=s-1}else if(!this.blockScalarKeep)do{let i=e-1,o=this.buffer[i];o==="\r"&&(o=this.buffer[--i]);let a=i;for(;o===" ";)o=this.buffer[--i];if(o===` +`&&i>=this.pos&&i+1+t>a)e=i;else break}while(!0);return yield xa,yield*this.pushToIndex(e+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let e=this.flowLevel>0,t=this.pos-1,n=this.pos-1,s;for(;s=this.buffer[++n];)if(s===":"){let i=this.buffer[n+1];if(Dt(i)||e&&Ia.has(i))break;t=n}else if(Dt(s)){let i=this.buffer[n+1];if(s==="\r"&&(i===` +`?(n+=1,s=` +`,i=this.buffer[n+1]):t=n),i==="#"||e&&Ia.has(i))break;if(s===` +`){let o=this.continueScalar(n+1);if(o===-1)break;n=Math.max(n,o-2)}}else{if(e&&Ia.has(s))break;t=n}return!s&&!this.atEnd?this.setNext("plain-scalar"):(yield xa,yield*this.pushToIndex(t+1,!0),e?"flow":"doc")}*pushCount(e){return e>0?(yield this.buffer.substr(this.pos,e),this.pos+=e,e):0}*pushToIndex(e,t){let n=this.buffer.slice(this.pos,e);return n?(yield n,this.pos+=n.length,n.length):(t&&(yield""),0)}*pushIndicators(){let e=0;e:for(;;){switch(this.charAt(0)){case"!":e+=yield*this.pushTag(),e+=yield*this.pushSpaces(!0);continue e;case"&":e+=yield*this.pushUntil(Cu),e+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let t=this.flowLevel>0,n=this.charAt(1);if(Dt(n)||t&&Ia.has(n)){t?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,e+=yield*this.pushCount(1),e+=yield*this.pushSpaces(!0);continue e}}}break e}return e}*pushTag(){if(this.charAt(1)==="<"){let e=this.pos+2,t=this.buffer[e];for(;!Dt(t)&&t!==">";)t=this.buffer[++e];return yield*this.pushToIndex(t===">"?e+1:e,!1)}else{let e=this.pos+1,t=this.buffer[e];for(;t;)if($P.has(t))t=this.buffer[++e];else if(t==="%"&&i0.has(this.buffer[e+1])&&i0.has(this.buffer[e+2]))t=this.buffer[e+=3];else break;return yield*this.pushToIndex(e,!1)}}*pushNewline(){let e=this.buffer[this.pos];return e===` `?yield*this.pushCount(1):e==="\r"&&this.charAt(1)===` -`?yield*this.pushCount(2):0}*pushSpaces(e){let t=this.pos-1,i;do i=this.buffer[++t];while(i===" "||e&&i===" ");let n=t-this.pos;return n>0&&(yield this.buffer.substr(this.pos,n),this.pos=t),n}*pushUntil(e){let t=this.pos,i=this.buffer[t];for(;!e(i);)i=this.buffer[++t];return yield*this.pushToIndex(t,!1)}};var Cs=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let t=0,i=this.lineStarts.length;for(;t>1;this.lineStarts[s]=0;)switch(r[e].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;((t=r[++e])==null?void 0:t.type)==="space";);return r.splice(e,r.length)}function Ha(r,e){if(e.length<1e5)Array.prototype.push.apply(r,e);else for(let t=0;t0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let e=this.peek(1);if(this.type==="doc-end"&&(e==null?void 0:e.type)!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!e)return yield*this.stream();switch(e.type){case"document":return yield*this.document(e);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(e);case"block-scalar":return yield*this.blockScalar(e);case"block-map":return yield*this.blockMap(e);case"block-seq":return yield*this.blockSequence(e);case"flow-collection":return yield*this.flowCollection(e);case"doc-end":return yield*this.documentEnd(e)}yield*this.pop()}peek(e){return this.stack[this.stack.length-e]}*pop(e){let t=e!=null?e:this.stack.pop();if(!t)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield t;else{let i=this.peek(1);switch(t.type==="block-scalar"?t.indent="indent"in i?i.indent:0:t.type==="flow-collection"&&i.type==="document"&&(t.indent=0),t.type==="flow-collection"&&M0(t),i.type){case"document":i.value=t;break;case"block-scalar":i.props.push(t);break;case"block-map":{let n=i.items[i.items.length-1];if(n.value){i.items.push({start:[],key:t,sep:[]}),this.onKeyLine=!0;return}else if(n.sep)n.value=t;else{Object.assign(n,{key:t,sep:[]}),this.onKeyLine=!n.explicitKey;return}break}case"block-seq":{let n=i.items[i.items.length-1];n.value?i.items.push({start:[],value:t}):n.value=t;break}case"flow-collection":{let n=i.items[i.items.length-1];!n||n.value?i.items.push({start:[],key:t,sep:[]}):n.sep?n.value=t:Object.assign(n,{key:t,sep:[]});return}default:yield*this.pop(),yield*this.pop(t)}if((i.type==="document"||i.type==="block-map"||i.type==="block-seq")&&(t.type==="block-map"||t.type==="block-seq")){let n=t.items[t.items.length-1];n&&!n.sep&&!n.value&&n.start.length>0&&N0(n.start)===-1&&(t.indent===0||n.start.every(s=>s.type!=="comment"||s.indent0&&(yield this.buffer.substr(this.pos,s),this.pos=t),s}*pushUntil(e){let t=this.pos,n=this.buffer[t];for(;!e(n);)n=this.buffer[++t];return yield*this.pushToIndex(t,!1)}};var Si=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let t=0,n=this.lineStarts.length;for(;t>1;this.lineStarts[i]=0;)switch(r[e].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;((t=r[++e])==null?void 0:t.type)==="space";);return r.splice(e,r.length)}function Pa(r,e){if(e.length<1e5)Array.prototype.push.apply(r,e);else for(let t=0;t0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let e=this.peek(1);if(this.type==="doc-end"&&(e==null?void 0:e.type)!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!e)return yield*this.stream();switch(e.type){case"document":return yield*this.document(e);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(e);case"block-scalar":return yield*this.blockScalar(e);case"block-map":return yield*this.blockMap(e);case"block-seq":return yield*this.blockSequence(e);case"flow-collection":return yield*this.flowCollection(e);case"doc-end":return yield*this.documentEnd(e)}yield*this.pop()}peek(e){return this.stack[this.stack.length-e]}*pop(e){let t=e!=null?e:this.stack.pop();if(!t)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield t;else{let n=this.peek(1);switch(t.type==="block-scalar"?t.indent="indent"in n?n.indent:0:t.type==="flow-collection"&&n.type==="document"&&(t.indent=0),t.type==="flow-collection"&&a0(t),n.type){case"document":n.value=t;break;case"block-scalar":n.props.push(t);break;case"block-map":{let s=n.items[n.items.length-1];if(s.value){n.items.push({start:[],key:t,sep:[]}),this.onKeyLine=!0;return}else if(s.sep)s.value=t;else{Object.assign(s,{key:t,sep:[]}),this.onKeyLine=!s.explicitKey;return}break}case"block-seq":{let s=n.items[n.items.length-1];s.value?n.items.push({start:[],value:t}):s.value=t;break}case"flow-collection":{let s=n.items[n.items.length-1];!s||s.value?n.items.push({start:[],key:t,sep:[]}):s.sep?s.value=t:Object.assign(s,{key:t,sep:[]});return}default:yield*this.pop(),yield*this.pop(t)}if((n.type==="document"||n.type==="block-map"||n.type==="block-seq")&&(t.type==="block-map"||t.type==="block-seq")){let s=t.items[t.items.length-1];s&&!s.sep&&!s.value&&s.start.length>0&&o0(s.start)===-1&&(t.indent===0||s.start.every(i=>i.type!=="comment"||i.indent=e.indent){let n=!this.onKeyLine&&this.indent===e.indent,s=n&&(t.sep||t.explicitKey)&&this.type!=="seq-item-ind",o=[];if(s&&t.sep&&!t.value){let a=[];for(let c=0;ce.indent&&(a.length=0);break;default:a.length=0}}a.length>=2&&(o=t.sep.splice(a[1]))}switch(this.type){case"anchor":case"tag":s||t.value?(o.push(this.sourceToken),e.items.push({start:o}),this.onKeyLine=!0):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"explicit-key-ind":!t.sep&&!t.explicitKey?(t.start.push(this.sourceToken),t.explicitKey=!0):s||t.value?(o.push(this.sourceToken),e.items.push({start:o,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(t.explicitKey)if(t.sep)if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(Kr(t.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]});else if(q0(t.key)&&!Kr(t.sep,"newline")){let a=dn(t.start),c=t.key,l=t.sep;l.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:a,key:c,sep:l}]})}else o.length>0?t.sep=t.sep.concat(o,this.sourceToken):t.sep.push(this.sourceToken);else if(Kr(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{let a=dn(t.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:a,key:null,sep:[this.sourceToken]}]})}else t.sep?t.value||s?e.items.push({start:o,key:null,sep:[this.sourceToken]}):Kr(t.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let a=this.flowScalar(this.type);s||t.value?(e.items.push({start:o,key:a,sep:[]}),this.onKeyLine=!0):t.sep?this.stack.push(a):(Object.assign(t,{key:a,sep:[]}),this.onKeyLine=!0);return}default:{let a=this.startBlockValue(e);if(a){if(a.type==="block-seq"){if(!t.explicitKey&&t.sep&&!Kr(t.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else n&&e.items.push({start:o});this.stack.push(a);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){var i;let t=e.items[e.items.length-1];switch(this.type){case"newline":if(t.value){let n="end"in t.value?t.value.end:void 0,s=Array.isArray(n)?n[n.length-1]:void 0;(s==null?void 0:s.type)==="comment"?n==null||n.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(t.start,e.indent)){let n=e.items[e.items.length-2],s=(i=n==null?void 0:n.value)==null?void 0:i.end;if(Array.isArray(s)){Ha(s,t.start),s.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return;case"anchor":case"tag":if(t.value||this.indent<=e.indent)break;t.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==e.indent)break;t.value||Kr(t.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return}if(this.indent>e.indent){let n=this.startBlockValue(e);if(n){this.stack.push(n);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let t=e.items[e.items.length-1];if(this.type==="flow-error-end"){let i;do yield*this.pop(),i=this.peek(1);while((i==null?void 0:i.type)==="flow-collection")}else if(e.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!t||t.sep?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return;case"map-value-ind":!t||t.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!t||t.value?e.items.push({start:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let n=this.flowScalar(this.type);!t||t.value?e.items.push({start:[],key:n,sep:[]}):t.sep?this.stack.push(n):Object.assign(t,{key:n,sep:[]});return}case"flow-map-end":case"flow-seq-end":e.end.push(this.sourceToken);return}let i=this.startBlockValue(e);i?this.stack.push(i):(yield*this.pop(),yield*this.step())}else{let i=this.peek(2);if(i.type==="block-map"&&(this.type==="map-value-ind"&&i.indent===e.indent||this.type==="newline"&&!i.items[i.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&i.type!=="flow-collection"){let n=Ba(i),s=dn(n);M0(e);let o=e.end.splice(1,e.end.length);o.push(this.sourceToken);let a={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:s,key:e,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let t=this.source.indexOf(` +`,t)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){var n;let t=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,t.value){let s="end"in t.value?t.value.end:void 0,i=Array.isArray(s)?s[s.length-1]:void 0;(i==null?void 0:i.type)==="comment"?s==null||s.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else{if(this.atIndentedComment(t.start,e.indent)){let s=e.items[e.items.length-2],i=(n=s==null?void 0:s.value)==null?void 0:n.end;if(Array.isArray(i)){Pa(i,t.start),i.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let s=!this.onKeyLine&&this.indent===e.indent,i=s&&(t.sep||t.explicitKey)&&this.type!=="seq-item-ind",o=[];if(i&&t.sep&&!t.value){let a=[];for(let c=0;ce.indent&&(a.length=0);break;default:a.length=0}}a.length>=2&&(o=t.sep.splice(a[1]))}switch(this.type){case"anchor":case"tag":i||t.value?(o.push(this.sourceToken),e.items.push({start:o}),this.onKeyLine=!0):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"explicit-key-ind":!t.sep&&!t.explicitKey?(t.start.push(this.sourceToken),t.explicitKey=!0):i||t.value?(o.push(this.sourceToken),e.items.push({start:o,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(t.explicitKey)if(t.sep)if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(Ur(t.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]});else if(c0(t.key)&&!Ur(t.sep,"newline")){let a=is(t.start),c=t.key,l=t.sep;l.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:a,key:c,sep:l}]})}else o.length>0?t.sep=t.sep.concat(o,this.sourceToken):t.sep.push(this.sourceToken);else if(Ur(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{let a=is(t.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:a,key:null,sep:[this.sourceToken]}]})}else t.sep?t.value||i?e.items.push({start:o,key:null,sep:[this.sourceToken]}):Ur(t.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let a=this.flowScalar(this.type);i||t.value?(e.items.push({start:o,key:a,sep:[]}),this.onKeyLine=!0):t.sep?this.stack.push(a):(Object.assign(t,{key:a,sep:[]}),this.onKeyLine=!0);return}default:{let a=this.startBlockValue(e);if(a){if(a.type==="block-seq"){if(!t.explicitKey&&t.sep&&!Ur(t.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else s&&e.items.push({start:o});this.stack.push(a);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){var n;let t=e.items[e.items.length-1];switch(this.type){case"newline":if(t.value){let s="end"in t.value?t.value.end:void 0,i=Array.isArray(s)?s[s.length-1]:void 0;(i==null?void 0:i.type)==="comment"?s==null||s.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(t.start,e.indent)){let s=e.items[e.items.length-2],i=(n=s==null?void 0:s.value)==null?void 0:n.end;if(Array.isArray(i)){Pa(i,t.start),i.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return;case"anchor":case"tag":if(t.value||this.indent<=e.indent)break;t.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==e.indent)break;t.value||Ur(t.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return}if(this.indent>e.indent){let s=this.startBlockValue(e);if(s){this.stack.push(s);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let t=e.items[e.items.length-1];if(this.type==="flow-error-end"){let n;do yield*this.pop(),n=this.peek(1);while((n==null?void 0:n.type)==="flow-collection")}else if(e.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!t||t.sep?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return;case"map-value-ind":!t||t.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!t||t.value?e.items.push({start:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let s=this.flowScalar(this.type);!t||t.value?e.items.push({start:[],key:s,sep:[]}):t.sep?this.stack.push(s):Object.assign(t,{key:s,sep:[]});return}case"flow-map-end":case"flow-seq-end":e.end.push(this.sourceToken);return}let n=this.startBlockValue(e);n?this.stack.push(n):(yield*this.pop(),yield*this.step())}else{let n=this.peek(2);if(n.type==="block-map"&&(this.type==="map-value-ind"&&n.indent===e.indent||this.type==="newline"&&!n.items[n.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&n.type!=="flow-collection"){let s=Ta(n),i=is(s);a0(e);let o=e.end.splice(1,e.end.length);o.push(this.sourceToken);let a={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:i,key:e,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let t=this.source.indexOf(` `)+1;for(;t!==0;)this.onNewLine(this.offset+t),t=this.source.indexOf(` -`,t)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let t=Ba(e),i=dn(t);return i.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let t=Ba(e),i=dn(t);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!=="comment"||this.indent<=t?!1:e.every(i=>i.type==="newline"||i.type==="space")}*documentEnd(e){this.type!=="doc-mode"&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;case"space":case"comment":default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};function oT(r){let e=r.prettyErrors!==!1;return{lineCounter:r.lineCounter||e&&new Cs||null,prettyErrors:e}}function L0(r,e={}){let{lineCounter:t,prettyErrors:i}=oT(e),n=new Ns(t==null?void 0:t.addNewLine),s=new Ts(e),o=null;for(let a of s.compose(n.parse(r),!0,r.length))if(!o)o=a;else if(o.options.logLevel!=="silent"){o.errors.push(new Dt(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return i&&t&&(o.errors.forEach(Vu(r,t)),o.warnings.forEach(Vu(r,t))),o}function ef(r,e,t){let i;typeof e=="function"?i=e:t===void 0&&e&&typeof e=="object"&&(t=e);let n=L0(r,t);if(!n)return null;if(n.warnings.forEach(s=>$a(n.options.logLevel,s)),n.errors.length>0){if(n.options.logLevel!=="silent")throw n.errors[0];n.errors=[]}return n.toJS(Object.assign({reviver:i},t))}function tf(r,e,t){var n;let i=null;if(typeof e=="function"||Array.isArray(e)?i=e:t===void 0&&e&&(t=e),typeof t=="string"&&(t=t.length),typeof t=="number"){let s=Math.round(t);t=s<1?void 0:s>8?{indent:8}:{indent:s}}if(r===void 0){let{keepUndefined:s}=(n=t!=null?t:e)!=null?n:{};if(!s)return}return Ct(r)&&!i?r.toString(t):new gr(r,i,t).toString(t)}var j0=64,hi=new TextEncoder,of=Object.freeze({digest:r=>jr(li(hi.encode(r))),randomId:()=>{var r;if(typeof((r=globalThis.crypto)==null?void 0:r.randomUUID)!="function")throw new T("mirror_random_unavailable","This runtime must provide crypto.randomUUID() or a MirrorRuntime adapter.");return globalThis.crypto.randomUUID()},now:()=>new Date().toISOString()});var nf=class{constructor(){I(this,"held",!1)}async runExclusive(e){if(this.held)throw new T("mirror_folder_in_use","Another mdbase mirror process is already using this folder.");this.held=!0;try{return await e()}finally{this.held=!1}}},qs=class{constructor(e,t,i,n="read_only"){I(this,"replicaId");I(this,"transport");I(this,"mode");I(this,"stateStore");I(this,"fileSystem");I(this,"lease");I(this,"runtime");I(this,"onProgress");var s,o;this.replicaId=e,this.transport=t,this.mode=n,this.stateStore=i.stateStore,this.fileSystem=i.fileSystem,this.lease=(s=i.lease)!=null?s:new nf,this.runtime=(o=i.runtime)!=null?o:of,this.onProgress=i.onProgress}async sync(){await this.lease.runExclusive(()=>this.syncUnlocked())}async syncUnlocked(){var i,n;let e=await this.readState();if(!e){await this.rebuild(),this.mode==="read_write"&&await this.syncUnlocked();return}this.mode==="read_write"?(await this.flushPending(e),await this.captureLocalChanges(e),await this.flushPending(e)):await this.assertUndiverged(e);let t=0;for(;;){let s=await this.transport.changes(e.cursor,200);if(s.scope_epoch!==e.scope_epoch||s.reset_required){await this.rebuild(e);return}for(let o of s.events){let a=o.type==="put"?o.record.record_id:o.record_id,c=e.records[a],l=c==null?void 0:c.path;this.mode==="read_write"&&o.type==="put"&&(c==null?void 0:c.record)!==void 0&&c.path===o.record.path&&c.revision===o.record.revision||l&&((i=e.local_issues)!=null&&i[l])||((n=e.conflicts)!=null&&n[a]?this.refreshConflict(e,o):o.type==="put"?await this.put(e,o.record):await this.remove(e,o.record_id,o.previous_path)),t+=1,this.reportProgress({phase:"applying",completed:t,total:null,done:!1})}if(e.cursor=s.cursor,!s.has_more){e.last_synced_at=this.runtime.now(),await this.writeState(e),t>0&&this.reportProgress({phase:"applying",completed:t,total:null,done:!0});return}await this.writeState(e)}}async status(){var s,o,a,c,l,u,d,f,p,m,h,y;let e=await this.readState();if(!e)return{state:"not_initialized",mode:this.mode,pending:0,conflicts:[],local_issues:[],cursor:null,last_synced_at:null};let t=[];for(let[b,g]of Object.entries((s=e.conflicts)!=null?s:{})){let _=e.records[b],S=(o=e.pending)==null?void 0:o.find(v=>v.mutation.record_id===b);g.status==="conflicted"?t.push({record_id:b,path:(u=(l=(a=S==null?void 0:S.local_path)!=null?a:_==null?void 0:_.path)!=null?l:(c=g.conflict.current)==null?void 0:c.path)!=null?u:null,kind:"conflicted",message:"Local and remote changes need a decision."}):g.status==="rejected"&&t.push({record_id:b,path:(f=(d=S==null?void 0:S.local_path)!=null?d:_==null?void 0:_.path)!=null?f:null,kind:"rejected",message:g.error.message})}let i=Object.values((p=e.local_issues)!=null?p:{}).map(({path:b,code:g,message:_})=>({path:b,code:g,message:_})).sort((b,g)=>b.path.localeCompare(g.path)),n=(h=(m=e.pending)==null?void 0:m.length)!=null?h:0;return{state:t.length||i.length?"attention":n?"changes_waiting":"up_to_date",mode:this.mode,pending:n,conflicts:t,local_issues:i,cursor:e.cursor,last_synced_at:(y=e.last_synced_at)!=null?y:null}}async authorityPromotionManifest(){return this.lease.runExclusive(()=>this.authorityPromotionManifestUnlocked())}async authorityPromotionManifestUnlocked(){var s,o,a,c,l,u;if(this.mode!=="read_write")throw new T("promotion_requires_writable_mirror","Only a two-way full collection mirror can become the local source of truth.");let e=await this.readState();if(!e)throw new T("promotion_not_initialized","Synchronize this folder before moving the source of truth.");if(((o=(s=e.pending)==null?void 0:s.length)!=null?o:0)>0||Object.keys((a=e.conflicts)!=null?a:{}).length>0||Object.keys((c=e.local_issues)!=null?c:{}).length>0)throw new T("promotion_not_converged","Upload or resolve every local change before moving the source of truth.");await this.assertUndiverged(e);let t=new Set(Object.keys((l=e.resources)!=null?l:{})),i=new Set(Object.values(e.records).map(d=>d.path)),n=(await this.fileSystem.listMarkdown(t)).filter(d=>!i.has(d));if(n.length>0)throw new T("promotion_unmanaged_files",`Synchronize unmanaged Markdown before promotion: ${n.join(", ")}.`);return{cursor:e.cursor,digest:af([...Object.entries((u=e.resources)!=null?u:{}).map(([d,f])=>({kind:"resource",path:d,document_hash:f.hash})),...Object.values(e.records).map(d=>({kind:"record",path:d.path,document_hash:d.revision}))])}}async previewInitialization(){var d;if(await this.readState())return{already_initialized:!0,download_documents:0,upload_documents:0,unchanged_documents:0,collisions:[],local_issues:[]};let e=await this.openSnapshot(),t=(d=e.resources.documents)!=null?d:[],i=new Set,n=0,s=0,o=[],a=async(f,p)=>{i.add(f);let m=await this.fileSystem.read(f);m===null?n+=1:m===p?s+=1:o.push(f)};for(let f of t)await a(f.path,f.document);await this.visitSnapshotPages(e,async f=>{for(let p of f)await a(p.path,Ms(p))});let c=await this.fileSystem.listMarkdown(new Set(t.map(f=>f.path))),l=[],u=0;if(this.mode==="read_write")for(let f of c.filter(p=>!i.has(p))){let p=await this.fileSystem.read(f);if(p!==null)try{rf(p,f),u+=1}catch(m){let h=D0(m,f);if(!h)throw m;l.push(h)}}return{already_initialized:!1,download_documents:n,upload_documents:u,unchanged_documents:s,collisions:o,local_issues:l.sort((f,p)=>f.path.localeCompare(p.path))}}async rebuild(e){var u,d,f,p,m;let t=await this.openSnapshot(),i=(u=t.resources.documents)!=null?u:[],n={protocol_version:1,replica_id:this.replicaId,scope_epoch:t.scope_epoch,cursor:t.head,records:{},resources:{},mode:this.mode,pending:[],conflicts:{},local_issues:{}},s=[];for(let h of i){let y=await this.fileSystem.read(h.path),b=(d=e==null?void 0:e.resources)==null?void 0:d[h.path];y!==null&&y!==h.document&&(!b||this.runtime.digest(y)!==b.hash)&&s.push(h.path)}let o=[],a=e?new Set:null;if(await this.visitSnapshotPages(t,async h=>{for(let y of h){let b=Ms(y),g=await this.fileSystem.read(y.path),_=e==null?void 0:e.records[y.record_id];g!==null&&g!==b&&(!_||_.path!==y.path||this.runtime.digest(g)!==_.hash)&&s.push(y.path),a==null||a.add(y.record_id),o.push({record:y,document:b,hash:this.runtime.digest(b)})}}),e){for(let[y,b]of Object.entries(e.records)){if(a.has(y))continue;let g=await this.fileSystem.read(b.path);g!==null&&this.runtime.digest(g)!==b.hash&&s.push(b.path)}let h=new Set(i.map(y=>y.path));for(let y of Object.values((f=e.resources)!=null?f:{})){if(h.has(y.path))continue;let b=await this.fileSystem.read(y.path);b!==null&&this.runtime.digest(b)!==y.hash&&s.push(y.path)}}if(s.length)throw new sf([...new Set(s)].sort());let c=i.length+o.length,l=0;for(let h of i)await this.putResource(n,h,e),l+=1,this.reportProgress({phase:"applying",completed:l,total:c,done:l===c});for(let h of o)await this.put(n,h.record,e,void 0,!1,h),l+=1,this.reportProgress({phase:"applying",completed:l,total:c,done:l===c});if(e){for(let[h,y]of Object.entries(e.records))n.records[h]||await this.remove(e,h,y.path);for(let[h,y]of Object.entries((p=e.resources)!=null?p:{}))(m=n.resources)!=null&&m[h]||await this.removeResource(e,h,y)}n.last_synced_at=this.runtime.now(),await this.writeState(n)}async openSnapshot(){let e=await this.transport.openSession();if(e.replica_id!==this.replicaId||e.mode!==this.mode)throw new T("invalid_mirror_session",`Filesystem mirror requires its own ${this.mode.replace("_","-")} replica.`);return e}async visitSnapshotPages(e,t){let i;do{let n=await this.transport.snapshot(e.snapshot_id,i);if(n.scope_epoch!==e.scope_epoch||n.cursor!==e.head)throw new T("invalid_snapshot","Authority snapshot boundary changed during download.");await t(n.records),i=n.next_page}while(i)}async put(e,t,i=e,n,s=!1,o){var d,f;let a=(d=o==null?void 0:o.document)!=null?d:Ms(t),c=await this.fileSystem.read(t.path),l=i==null?void 0:i.records[t.record_id];if(c!==null&&c!==a){let p=this.runtime.digest(c);if((!l||l.path!==t.path||p!==l.hash)&&(n===void 0||p!==n))throw new br(t.record_id,t.path)}l&&l.path!==t.path&&await this.remove(i,t.record_id,l.path);let u=s&&typeof n=="string"&&c!==null&&this.runtime.digest(c)===n?n:null;u===null&&await this.fileSystem.write(t.path,a),e.records[t.record_id]={path:t.path,revision:t.revision,hash:(f=u!=null?u:o==null?void 0:o.hash)!=null?f:this.runtime.digest(a),...this.mode==="read_write"?{record:t}:{}}}async remove(e,t,i){var a;let n=e.records[t],s=(a=n==null?void 0:n.path)!=null?a:i,o=await this.fileSystem.read(s);if(o!==null&&n&&this.runtime.digest(o)!==n.hash)throw new br(t,n.path);o!==null&&await this.fileSystem.remove(s),delete e.records[t]}async putResource(e,t,i){var o,a;let n=await this.fileSystem.read(t.path),s=(o=i==null?void 0:i.resources)==null?void 0:o[t.path];if(n!==null&&n!==t.document&&(!s||this.runtime.digest(n)!==s.hash))throw new br(`resource:${t.path}`,t.path);await this.fileSystem.write(t.path,t.document),(a=e.resources)!=null||(e.resources={}),e.resources[t.path]={path:t.path,revision:t.revision,hash:this.runtime.digest(t.document)}}async removeResource(e,t,i){let n=await this.fileSystem.read(t);if(n!==null&&this.runtime.digest(n)!==i.hash)throw new br(`resource:${t}`,t);n!==null&&await this.fileSystem.remove(t),e.resources&&delete e.resources[t]}async resolveConflict(e,t){await this.lease.runExclusive(()=>this.resolveConflictUnlocked(e,t))}async resolveConflictUnlocked(e,t){var o,a,c,l,u;if(this.mode!=="read_write")throw new T("mirror_read_only","Receive-only mirrors do not contain writable conflicts.");let i=await this.readState(),n=(o=i==null?void 0:i.conflicts)==null?void 0:o[e];if(!i||!n)throw new T("mirror_conflict_not_found","Writable mirror conflict was not found.");let s=((a=i.pending)!=null?a:[]).filter(d=>d.mutation.record_id===e);if(t==="remote"){let d=n.status==="conflicted"?n.conflict.current:(c=i.records[e])==null?void 0:c.record;await this.installRemoteResolution(i,e,d,s),i.pending=((l=i.pending)!=null?l:[]).filter(f=>f.mutation.record_id!==e)}else if(n.status==="rejected")i.pending=((u=i.pending)!=null?u:[]).filter(d=>d.mutation.record_id!==e);else{if(n.status!=="conflicted")throw new T("invalid_mirror_state","Mirror conflict metadata is invalid.");let d=s.at(-1);if(!d)throw new T("conflict_mutation_missing","The local change for this sync issue is unavailable.");let f=n.conflict.current,p=await this.fileSystem.read(d.local_path),m=this.localResolutionMutations(i,e,d.local_path,p,f),h=i.pending.findIndex(y=>y.mutation.record_id===e);i.pending=i.pending.filter(y=>y.mutation.record_id!==e),i.pending.splice(h<0?i.pending.length:h,0,...m),f?i.records[e]={path:f.path,revision:f.revision,hash:this.runtime.digest(Ms(f)),record:f}:delete i.records[e]}delete i.conflicts[e],await this.writeState(i)}async installRemoteResolution(e,t,i,n){let s=new Set(n.map(a=>a.local_path));if(i){for(let c of s)c!==i.path&&await this.fileSystem.read(c)!==null&&await this.fileSystem.remove(c);let a=await this.fileSystem.read(i.path);await this.put(e,i,e,a===null?null:this.runtime.digest(a));return}let o=e.records[t];o&&s.add(o.path);for(let a of s)await this.fileSystem.read(a)!==null&&await this.fileSystem.remove(a);delete e.records[t]}localResolutionMutations(e,t,i,n,s){let o=[],a,c=(d,f)=>{let p=this.runtime.randomId();o.push({mutation:{...d,mutation_id:p,replica_id:this.replicaId,scope_epoch:e.scope_epoch,created_at:this.runtime.now(),...a?{causal_predecessor:a}:{}},local_path:i,local_hash:f}),a=p};if(n===null)return s&&c({operation:"delete",record_id:t,base_revision:s.revision,input:{}},null),o;let l=rf(n,i),u=this.runtime.digest(n);return s?(n!==Ms(s)&&c({operation:"update",record_id:t,base_revision:s.revision,input:{patch:F0(s.frontmatter,l.frontmatter),body:l.body}},u),i!==s.path&&c({operation:"rename",record_id:t,base_revision:s.revision,input:{path:i}},u),o):(c({operation:"create",record_id:t,input:{path:i,frontmatter:l.frontmatter,body:l.body}},u),o)}async captureLocalChanges(e){var p,m,h,y,b,g;let t=new Set(Object.keys((p=e.resources)!=null?p:{}));for(let[_,S]of Object.entries((m=e.resources)!=null?m:{})){let v=await this.fileSystem.read(_);if(v===null||this.runtime.digest(v)!==S.hash)throw new br(`resource:${_}`,_)}let i=await this.fileSystem.listMarkdown(t),n=new Map(Object.entries(e.records).map(([_,S])=>[S.path,_])),s=new Map;for(let _ of i){let S=await this.fileSystem.read(_);if(S===null)continue;let v=this.runtime.digest(S),P=n.get(_),x=P!==void 0&&((h=e.records[P])==null?void 0:h.hash)===v;s.set(_,x?{hash:v}:{document:S,hash:v})}let o=new Set([...s.keys()].filter(_=>!n.has(_))),a=new Set(Object.entries(e.records).filter(([,_])=>!s.has(_.path)).map(([_])=>_)),c=[],l={},u=(_,S,v)=>{try{return rf(_,S)}catch(P){let x=D0(P,S);if(!x)throw P;return l[S]={...x,hash:v},null}},d=new Map,f=(_,S,v)=>{let P=this.runtime.randomId(),x=d.get(_.record_id);c.push({mutation:{..._,mutation_id:P,replica_id:this.replicaId,scope_epoch:e.scope_epoch,created_at:this.runtime.now(),...x?{causal_predecessor:x}:{}},local_path:S,local_hash:v}),d.set(_.record_id,P)};for(let _ of[...a]){if((y=e.conflicts)!=null&&y[_]){a.delete(_);continue}let S=e.records[_],v=[...o].filter(x=>{var E;return((E=s.get(x))==null?void 0:E.hash)===S.hash});if(v.length!==1)continue;let P=v[0];f({operation:"rename",record_id:_,base_revision:S.revision,input:{path:P}},P,s.get(P).hash),a.delete(_),o.delete(P)}for(let[_,S]of Object.entries(e.records)){if((b=e.conflicts)!=null&&b[_]||a.has(_))continue;let v=s.get(S.path);if(!v||v.hash===S.hash)continue;let P=S.record;if(!P)throw new T("mirror_state_upgrade_required","Run a receive sync before editing this older writable mirror.");let x=u(v.document,S.path,v.hash);x&&f({operation:"update",record_id:_,base_revision:S.revision,input:{patch:F0(P.frontmatter,x.frontmatter),body:x.body}},S.path,v.hash)}for(let _ of a){if((g=e.conflicts)!=null&&g[_])continue;let S=e.records[_];f({operation:"delete",record_id:_,base_revision:S.revision,input:{}},S.path,null)}for(let _ of o){let S=s.get(_),v=u(S.document,_,S.hash);v&&f({operation:"create",record_id:this.runtime.randomId(),input:{path:_,frontmatter:v.frontmatter,body:v.body}},_,S.hash)}e.local_issues=l,c.length&&(e.pending.push(...c),await this.writeState(e))}async flushPending(e){var a,c,l;let t=(a=e.pending)!=null?a:e.pending=[],i=0,n=0,s=t.filter(u=>{var d;return!((d=e.conflicts)!=null&&d[u.mutation.record_id])}).length,o=0;for(;i=j0&&(await this.writeState(e),n=0);continue}(l=e.conflicts)!=null||(e.conflicts={}),e.conflicts[u.mutation.record_id]=p,n+=1,n>=j0&&(await this.writeState(e),n=0),i+=1}n>0&&await this.writeState(e),s>0&&this.reportProgress({phase:"uploading",completed:o,total:s,done:!0})}refreshConflict(e,t){var s;let i=t.type==="put"?t.record.record_id:t.record_id,n=(s=e.conflicts)==null?void 0:s[i];!n||n.status!=="conflicted"||(e.conflicts[i]={...n,conflict:{...n.conflict,...t.type==="put"?{current:t.record,current_revision:t.record.revision}:{current:void 0,current_revision:t.revision}}})}async readState(){var t,i,n,s;let e=await this.stateStore.read();if(e===null)return null;try{if(e.protocol_version!==1||e.replica_id!==this.replicaId)throw new Error;if((t=e.resources)!=null||(e.resources={}),(i=e.pending)!=null||(e.pending=[]),(n=e.conflicts)!=null||(e.conflicts={}),(s=e.mode)!=null||(e.mode="read_only"),e.mode!==this.mode)throw new T("mirror_mode_mismatch",`Mirror metadata belongs to a ${e.mode.replace("_","-")} replica.`);return e}catch(o){throw o instanceof T?o:new T("invalid_mirror_state","Mirror metadata is corrupt or belongs to another replica.")}}async writeState(e){await this.stateStore.write(e)}reportProgress(e){var t;(t=this.onProgress)==null||t.call(this,e)}async assertUndiverged(e){var t;for(let[i,n]of Object.entries(e.records)){let s=await this.fileSystem.read(n.path);if(s===null||this.runtime.digest(s)!==n.hash)throw new br(i,n.path)}for(let[i,n]of Object.entries((t=e.resources)!=null?t:{})){let s=await this.fileSystem.read(n.path);if(s===null||this.runtime.digest(s)!==n.hash)throw new br(`resource:${i}`,n.path)}}},br=class extends T{constructor(t,i){super("mirror_diverged",`Local edits at ${i} must be resolved before the mirror can continue.`);I(this,"recordId");I(this,"path");this.recordId=t,this.path=i}},sf=class extends T{constructor(t){super("mirror_initialization_conflict",`Existing files differ from remote Markdown: ${t.join(", ")}. Move or reconcile them before syncing.`);I(this,"paths");this.paths=t}},Ka=class extends qs{constructor(e,t,i){super(e,t,i,"read_write")}};function Ms(r){if(Object.keys(r.frontmatter).length===0)return r.body;let e=tf(r.frontmatter,{lineWidth:0}).trimEnd(),t=r.body?` +`,t)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let t=Ta(e),n=is(t);return n.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let t=Ta(e),n=is(t);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!=="comment"||this.indent<=t?!1:e.every(n=>n.type==="newline"||n.type==="space")}*documentEnd(e){this.type!=="doc-mode"&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;case"space":case"comment":default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};function EP(r){let e=r.prettyErrors!==!1;return{lineCounter:r.lineCounter||e&&new Si||null,prettyErrors:e}}function l0(r,e={}){let{lineCounter:t,prettyErrors:n}=EP(e),s=new Ei(t==null?void 0:t.addNewLine),i=new vi(e),o=null;for(let a of i.compose(s.parse(r),!0,r.length))if(!o)o=a;else if(o.options.logLevel!=="silent"){o.errors.push(new qt(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&t&&(o.errors.forEach(vu(r,t)),o.warnings.forEach(vu(r,t))),o}function Nu(r,e,t){let n;typeof e=="function"?n=e:t===void 0&&e&&typeof e=="object"&&(t=e);let s=l0(r,t);if(!s)return null;if(s.warnings.forEach(i=>aa(s.options.logLevel,i)),s.errors.length>0){if(s.options.logLevel!=="silent")throw s.errors[0];s.errors=[]}return s.toJS(Object.assign({reviver:n},t))}function Mu(r,e,t){var s;let n=null;if(typeof e=="function"||Array.isArray(e)?n=e:t===void 0&&e&&(t=e),typeof t=="string"&&(t=t.length),typeof t=="number"){let i=Math.round(t);t=i<1?void 0:i>8?{indent:8}:{indent:i}}if(r===void 0){let{keepUndefined:i}=(s=t!=null?t:e)!=null?s:{};if(!i)return}return Ot(r)&&!n?r.toString(t):new mr(r,n,t).toString(t)}var d0=64,dn=new TextEncoder,ju=Object.freeze({digest:r=>Nr(sn(dn.encode(r))),randomId:()=>{var r;if(typeof((r=globalThis.crypto)==null?void 0:r.randomUUID)!="function")throw new O("mirror_random_unavailable","This runtime must provide crypto.randomUUID() or a MirrorRuntime adapter.");return globalThis.crypto.randomUUID()},now:()=>new Date().toISOString()});var qu=class{constructor(){P(this,"held",!1)}async runExclusive(e){if(this.held)throw new O("mirror_folder_in_use","Another mdbase mirror process is already using this folder.");this.held=!0;try{return await e()}finally{this.held=!1}}},ki=class{constructor(e,t,n,s="read_only"){P(this,"replicaId");P(this,"transport");P(this,"mode");P(this,"stateStore");P(this,"fileSystem");P(this,"lease");P(this,"runtime");P(this,"onProgress");var i,o;this.replicaId=e,this.transport=t,this.mode=s,this.stateStore=n.stateStore,this.fileSystem=n.fileSystem,this.lease=(i=n.lease)!=null?i:new qu,this.runtime=(o=n.runtime)!=null?o:ju,this.onProgress=n.onProgress}async sync(){await this.lease.runExclusive(()=>this.syncUnlocked())}async syncUnlocked(){var n,s;let e=await this.readState();if(!e){await this.rebuild(),this.mode==="read_write"&&await this.syncUnlocked();return}this.mode==="read_write"?(await this.flushPending(e),await this.captureLocalChanges(e),await this.flushPending(e)):await this.assertUndiverged(e);let t=0;for(;;){let i=await this.transport.changes(e.cursor,200);if(i.scope_epoch!==e.scope_epoch||i.reset_required){await this.rebuild(e);return}for(let o of i.events){let a=o.type==="put"?o.record.record_id:o.record_id,c=e.records[a],l=c==null?void 0:c.path;this.mode==="read_write"&&o.type==="put"&&(c==null?void 0:c.record)!==void 0&&c.path===o.record.path&&c.revision===o.record.revision||l&&((n=e.local_issues)!=null&&n[l])||((s=e.conflicts)!=null&&s[a]?this.refreshConflict(e,o):o.type==="put"?await this.put(e,o.record):await this.remove(e,o.record_id,o.previous_path)),t+=1,this.reportProgress({phase:"applying",completed:t,total:null,done:!1})}if(e.cursor=i.cursor,!i.has_more){e.last_synced_at=this.runtime.now(),await this.writeState(e),t>0&&this.reportProgress({phase:"applying",completed:t,total:null,done:!0});return}await this.writeState(e)}}async status(){var i,o,a,c,l,u,d,f,p,m,h,y;let e=await this.readState();if(!e)return{state:"not_initialized",mode:this.mode,pending:0,conflicts:[],local_issues:[],cursor:null,last_synced_at:null};let t=[];for(let[b,g]of Object.entries((i=e.conflicts)!=null?i:{})){let w=e.records[b],S=(o=e.pending)==null?void 0:o.find(_=>_.mutation.record_id===b);g.status==="conflicted"?t.push({record_id:b,path:(u=(l=(a=S==null?void 0:S.local_path)!=null?a:w==null?void 0:w.path)!=null?l:(c=g.conflict.current)==null?void 0:c.path)!=null?u:null,kind:"conflicted",message:"Local and remote changes need a decision."}):g.status==="rejected"&&t.push({record_id:b,path:(f=(d=S==null?void 0:S.local_path)!=null?d:w==null?void 0:w.path)!=null?f:null,kind:"rejected",message:g.error.message})}let n=Object.values((p=e.local_issues)!=null?p:{}).map(({path:b,code:g,message:w})=>({path:b,code:g,message:w})).sort((b,g)=>b.path.localeCompare(g.path)),s=(h=(m=e.pending)==null?void 0:m.length)!=null?h:0;return{state:t.length||n.length?"attention":s?"changes_waiting":"up_to_date",mode:this.mode,pending:s,conflicts:t,local_issues:n,cursor:e.cursor,last_synced_at:(y=e.last_synced_at)!=null?y:null}}async authorityPromotionManifest(){return this.lease.runExclusive(()=>this.authorityPromotionManifestUnlocked())}async authorityPromotionManifestUnlocked(){var i,o,a,c,l,u;if(this.mode!=="read_write")throw new O("promotion_requires_writable_mirror","Only a two-way full collection mirror can become the local source of truth.");let e=await this.readState();if(!e)throw new O("promotion_not_initialized","Synchronize this folder before moving the source of truth.");if(((o=(i=e.pending)==null?void 0:i.length)!=null?o:0)>0||Object.keys((a=e.conflicts)!=null?a:{}).length>0||Object.keys((c=e.local_issues)!=null?c:{}).length>0)throw new O("promotion_not_converged","Upload or resolve every local change before moving the source of truth.");await this.assertUndiverged(e);let t=new Set(Object.keys((l=e.resources)!=null?l:{})),n=new Set(Object.values(e.records).map(d=>d.path)),s=(await this.fileSystem.listMarkdown(t)).filter(d=>!n.has(d));if(s.length>0)throw new O("promotion_unmanaged_files",`Synchronize unmanaged Markdown before promotion: ${s.join(", ")}.`);return{cursor:e.cursor,digest:Fu([...Object.entries((u=e.resources)!=null?u:{}).map(([d,f])=>({kind:"resource",path:d,document_hash:f.hash})),...Object.values(e.records).map(d=>({kind:"record",path:d.path,document_hash:d.revision}))])}}async previewInitialization(){var d;if(await this.readState())return{already_initialized:!0,download_documents:0,upload_documents:0,unchanged_documents:0,collisions:[],local_issues:[]};let e=await this.openSnapshot(),t=(d=e.resources.documents)!=null?d:[],n=new Set,s=0,i=0,o=[],a=async(f,p)=>{n.add(f);let m=await this.fileSystem.read(f);m===null?s+=1:m===p?i+=1:o.push(f)};for(let f of t)await a(f.path,f.document);await this.visitSnapshotPages(e,async f=>{for(let p of f)await a(p.path,Ai(p))});let c=await this.fileSystem.listMarkdown(new Set(t.map(f=>f.path))),l=[],u=0;if(this.mode==="read_write")for(let f of c.filter(p=>!n.has(p))){let p=await this.fileSystem.read(f);if(p!==null)try{Lu(p,f),u+=1}catch(m){let h=u0(m,f);if(!h)throw m;l.push(h)}}return{already_initialized:!1,download_documents:s,upload_documents:u,unchanged_documents:i,collisions:o,local_issues:l.sort((f,p)=>f.path.localeCompare(p.path))}}async rebuild(e){var u,d,f,p,m;let t=await this.openSnapshot(),n=(u=t.resources.documents)!=null?u:[],s={protocol_version:1,replica_id:this.replicaId,scope_epoch:t.scope_epoch,cursor:t.head,records:{},resources:{},mode:this.mode,pending:[],conflicts:{},local_issues:{}},i=[];for(let h of n){let y=await this.fileSystem.read(h.path),b=(d=e==null?void 0:e.resources)==null?void 0:d[h.path];y!==null&&y!==h.document&&(!b||this.runtime.digest(y)!==b.hash)&&i.push(h.path)}let o=[],a=e?new Set:null;if(await this.visitSnapshotPages(t,async h=>{for(let y of h){let b=Ai(y),g=await this.fileSystem.read(y.path),w=e==null?void 0:e.records[y.record_id];g!==null&&g!==b&&(!w||w.path!==y.path||this.runtime.digest(g)!==w.hash)&&i.push(y.path),a==null||a.add(y.record_id),o.push({record:y,document:b,hash:this.runtime.digest(b)})}}),e){for(let[y,b]of Object.entries(e.records)){if(a.has(y))continue;let g=await this.fileSystem.read(b.path);g!==null&&this.runtime.digest(g)!==b.hash&&i.push(b.path)}let h=new Set(n.map(y=>y.path));for(let y of Object.values((f=e.resources)!=null?f:{})){if(h.has(y.path))continue;let b=await this.fileSystem.read(y.path);b!==null&&this.runtime.digest(b)!==y.hash&&i.push(y.path)}}if(i.length)throw new Du([...new Set(i)].sort());let c=n.length+o.length,l=0;for(let h of n)await this.putResource(s,h,e),l+=1,this.reportProgress({phase:"applying",completed:l,total:c,done:l===c});for(let h of o)await this.put(s,h.record,e,void 0,!1,h),l+=1,this.reportProgress({phase:"applying",completed:l,total:c,done:l===c});if(e){for(let[h,y]of Object.entries(e.records))s.records[h]||await this.remove(e,h,y.path);for(let[h,y]of Object.entries((p=e.resources)!=null?p:{}))(m=s.resources)!=null&&m[h]||await this.removeResource(e,h,y)}s.last_synced_at=this.runtime.now(),await this.writeState(s)}async openSnapshot(){let e=await this.transport.openSession();if(e.replica_id!==this.replicaId||e.mode!==this.mode)throw new O("invalid_mirror_session",`Filesystem mirror requires its own ${this.mode.replace("_","-")} replica.`);return e}async visitSnapshotPages(e,t){let n;do{let s=await this.transport.snapshot(e.snapshot_id,n);if(s.scope_epoch!==e.scope_epoch||s.cursor!==e.head)throw new O("invalid_snapshot","Authority snapshot boundary changed during download.");await t(s.records),n=s.next_page}while(n)}async put(e,t,n=e,s,i=!1,o){var d,f;let a=(d=o==null?void 0:o.document)!=null?d:Ai(t),c=await this.fileSystem.read(t.path),l=n==null?void 0:n.records[t.record_id];if(c!==null&&c!==a){let p=this.runtime.digest(c);if((!l||l.path!==t.path||p!==l.hash)&&(s===void 0||p!==s))throw new yr(t.record_id,t.path)}l&&l.path!==t.path&&await this.remove(n,t.record_id,l.path);let u=i&&typeof s=="string"&&c!==null&&this.runtime.digest(c)===s?s:null;u===null&&await this.fileSystem.write(t.path,a),e.records[t.record_id]={path:t.path,revision:t.revision,hash:(f=u!=null?u:o==null?void 0:o.hash)!=null?f:this.runtime.digest(a),...this.mode==="read_write"?{record:t}:{}}}async remove(e,t,n){var a;let s=e.records[t],i=(a=s==null?void 0:s.path)!=null?a:n,o=await this.fileSystem.read(i);if(o!==null&&s&&this.runtime.digest(o)!==s.hash)throw new yr(t,s.path);o!==null&&await this.fileSystem.remove(i),delete e.records[t]}async putResource(e,t,n){var o,a;let s=await this.fileSystem.read(t.path),i=(o=n==null?void 0:n.resources)==null?void 0:o[t.path];if(s!==null&&s!==t.document&&(!i||this.runtime.digest(s)!==i.hash))throw new yr(`resource:${t.path}`,t.path);await this.fileSystem.write(t.path,t.document),(a=e.resources)!=null||(e.resources={}),e.resources[t.path]={path:t.path,revision:t.revision,hash:this.runtime.digest(t.document)}}async removeResource(e,t,n){let s=await this.fileSystem.read(t);if(s!==null&&this.runtime.digest(s)!==n.hash)throw new yr(`resource:${t}`,t);s!==null&&await this.fileSystem.remove(t),e.resources&&delete e.resources[t]}async resolveConflict(e,t){await this.lease.runExclusive(()=>this.resolveConflictUnlocked(e,t))}async resolveConflictUnlocked(e,t){var o,a,c,l,u;if(this.mode!=="read_write")throw new O("mirror_read_only","Receive-only mirrors do not contain writable conflicts.");let n=await this.readState(),s=(o=n==null?void 0:n.conflicts)==null?void 0:o[e];if(!n||!s)throw new O("mirror_conflict_not_found","Writable mirror conflict was not found.");let i=((a=n.pending)!=null?a:[]).filter(d=>d.mutation.record_id===e);if(t==="remote"){let d=s.status==="conflicted"?s.conflict.current:(c=n.records[e])==null?void 0:c.record;await this.installRemoteResolution(n,e,d,i),n.pending=((l=n.pending)!=null?l:[]).filter(f=>f.mutation.record_id!==e)}else if(s.status==="rejected")n.pending=((u=n.pending)!=null?u:[]).filter(d=>d.mutation.record_id!==e);else{if(s.status!=="conflicted")throw new O("invalid_mirror_state","Mirror conflict metadata is invalid.");let d=i.at(-1);if(!d)throw new O("conflict_mutation_missing","The local change for this sync issue is unavailable.");let f=s.conflict.current,p=await this.fileSystem.read(d.local_path),m=this.localResolutionMutations(n,e,d.local_path,p,f),h=n.pending.findIndex(y=>y.mutation.record_id===e);n.pending=n.pending.filter(y=>y.mutation.record_id!==e),n.pending.splice(h<0?n.pending.length:h,0,...m),f?n.records[e]={path:f.path,revision:f.revision,hash:this.runtime.digest(Ai(f)),record:f}:delete n.records[e]}delete n.conflicts[e],await this.writeState(n)}async installRemoteResolution(e,t,n,s){let i=new Set(s.map(a=>a.local_path));if(n){for(let c of i)c!==n.path&&await this.fileSystem.read(c)!==null&&await this.fileSystem.remove(c);let a=await this.fileSystem.read(n.path);await this.put(e,n,e,a===null?null:this.runtime.digest(a));return}let o=e.records[t];o&&i.add(o.path);for(let a of i)await this.fileSystem.read(a)!==null&&await this.fileSystem.remove(a);delete e.records[t]}localResolutionMutations(e,t,n,s,i){let o=[],a,c=(d,f)=>{let p=this.runtime.randomId();o.push({mutation:{...d,mutation_id:p,replica_id:this.replicaId,scope_epoch:e.scope_epoch,created_at:this.runtime.now(),...a?{causal_predecessor:a}:{}},local_path:n,local_hash:f}),a=p};if(s===null)return i&&c({operation:"delete",record_id:t,base_revision:i.revision,input:{}},null),o;let l=Lu(s,n),u=this.runtime.digest(s);return i?(s!==Ai(i)&&c({operation:"update",record_id:t,base_revision:i.revision,input:{patch:f0(i.frontmatter,l.frontmatter),body:l.body}},u),n!==i.path&&c({operation:"rename",record_id:t,base_revision:i.revision,input:{path:n}},u),o):(c({operation:"create",record_id:t,input:{path:n,frontmatter:l.frontmatter,body:l.body}},u),o)}async captureLocalChanges(e){var p,m,h,y,b,g;let t=new Set(Object.keys((p=e.resources)!=null?p:{}));for(let[w,S]of Object.entries((m=e.resources)!=null?m:{})){let _=await this.fileSystem.read(w);if(_===null||this.runtime.digest(_)!==S.hash)throw new yr(`resource:${w}`,w)}let n=await this.fileSystem.listMarkdown(t),s=new Map(Object.entries(e.records).map(([w,S])=>[S.path,w])),i=new Map;for(let w of n){let S=await this.fileSystem.read(w);if(S===null)continue;let _=this.runtime.digest(S),x=s.get(w),I=x!==void 0&&((h=e.records[x])==null?void 0:h.hash)===_;i.set(w,I?{hash:_}:{document:S,hash:_})}let o=new Set([...i.keys()].filter(w=>!s.has(w))),a=new Set(Object.entries(e.records).filter(([,w])=>!i.has(w.path)).map(([w])=>w)),c=[],l={},u=(w,S,_)=>{try{return Lu(w,S)}catch(x){let I=u0(x,S);if(!I)throw x;return l[S]={...I,hash:_},null}},d=new Map,f=(w,S,_)=>{let x=this.runtime.randomId(),I=d.get(w.record_id);c.push({mutation:{...w,mutation_id:x,replica_id:this.replicaId,scope_epoch:e.scope_epoch,created_at:this.runtime.now(),...I?{causal_predecessor:I}:{}},local_path:S,local_hash:_}),d.set(w.record_id,x)};for(let w of[...a]){if((y=e.conflicts)!=null&&y[w]){a.delete(w);continue}let S=e.records[w],_=[...o].filter(I=>{var E;return((E=i.get(I))==null?void 0:E.hash)===S.hash});if(_.length!==1)continue;let x=_[0];f({operation:"rename",record_id:w,base_revision:S.revision,input:{path:x}},x,i.get(x).hash),a.delete(w),o.delete(x)}for(let[w,S]of Object.entries(e.records)){if((b=e.conflicts)!=null&&b[w]||a.has(w))continue;let _=i.get(S.path);if(!_||_.hash===S.hash)continue;let x=S.record;if(!x)throw new O("mirror_state_upgrade_required","Run a receive sync before editing this older writable mirror.");let I=u(_.document,S.path,_.hash);I&&f({operation:"update",record_id:w,base_revision:S.revision,input:{patch:f0(x.frontmatter,I.frontmatter),body:I.body}},S.path,_.hash)}for(let w of a){if((g=e.conflicts)!=null&&g[w])continue;let S=e.records[w];f({operation:"delete",record_id:w,base_revision:S.revision,input:{}},S.path,null)}for(let w of o){let S=i.get(w),_=u(S.document,w,S.hash);_&&f({operation:"create",record_id:this.runtime.randomId(),input:{path:w,frontmatter:_.frontmatter,body:_.body}},w,S.hash)}e.local_issues=l,c.length&&(e.pending.push(...c),await this.writeState(e))}async flushPending(e){var a,c,l;let t=(a=e.pending)!=null?a:e.pending=[],n=0,s=0,i=t.filter(u=>{var d;return!((d=e.conflicts)!=null&&d[u.mutation.record_id])}).length,o=0;for(;n=d0&&(await this.writeState(e),s=0);continue}(l=e.conflicts)!=null||(e.conflicts={}),e.conflicts[u.mutation.record_id]=p,s+=1,s>=d0&&(await this.writeState(e),s=0),n+=1}s>0&&await this.writeState(e),i>0&&this.reportProgress({phase:"uploading",completed:o,total:i,done:!0})}refreshConflict(e,t){var i;let n=t.type==="put"?t.record.record_id:t.record_id,s=(i=e.conflicts)==null?void 0:i[n];!s||s.status!=="conflicted"||(e.conflicts[n]={...s,conflict:{...s.conflict,...t.type==="put"?{current:t.record,current_revision:t.record.revision}:{current:void 0,current_revision:t.revision}}})}async readState(){var t,n,s,i;let e=await this.stateStore.read();if(e===null)return null;try{if(e.protocol_version!==1||e.replica_id!==this.replicaId)throw new Error;if((t=e.resources)!=null||(e.resources={}),(n=e.pending)!=null||(e.pending=[]),(s=e.conflicts)!=null||(e.conflicts={}),(i=e.mode)!=null||(e.mode="read_only"),e.mode!==this.mode)throw new O("mirror_mode_mismatch",`Mirror metadata belongs to a ${e.mode.replace("_","-")} replica.`);return e}catch(o){throw o instanceof O?o:new O("invalid_mirror_state","Mirror metadata is corrupt or belongs to another replica.")}}async writeState(e){await this.stateStore.write(e)}reportProgress(e){var t;(t=this.onProgress)==null||t.call(this,e)}async assertUndiverged(e){var t;for(let[n,s]of Object.entries(e.records)){let i=await this.fileSystem.read(s.path);if(i===null||this.runtime.digest(i)!==s.hash)throw new yr(n,s.path)}for(let[n,s]of Object.entries((t=e.resources)!=null?t:{})){let i=await this.fileSystem.read(s.path);if(i===null||this.runtime.digest(i)!==s.hash)throw new yr(`resource:${n}`,s.path)}}},yr=class extends O{constructor(t,n){super("mirror_diverged",`Local edits at ${n} must be resolved before the mirror can continue.`);P(this,"recordId");P(this,"path");this.recordId=t,this.path=n}},Du=class extends O{constructor(t){super("mirror_initialization_conflict",`Existing files differ from remote Markdown: ${t.join(", ")}. Move or reconcile them before syncing.`);P(this,"paths");this.paths=t}},Oa=class extends ki{constructor(e,t,n){super(e,t,n,"read_write")}};function Ai(r){if(Object.keys(r.frontmatter).length===0)return r.body;let e=Mu(r.frontmatter,{lineWidth:0}).trimEnd(),t=r.body?` ${r.body.replace(/^\n/,"")}`:"";return`--- ${e} --- -${t}`}function rf(r,e){var n;let t=r.match(/^---[ \t]*\r?\n([\s\S]*?)^---[ \t]*(?:\r?\n|$)([\s\S]*)$/m);if(!t)return{frontmatter:{},body:r};let i;try{i=ef(t[1])}catch(s){throw new T("invalid_frontmatter",`Writable mirror file ${e} has invalid YAML frontmatter.`)}if(i===null&&t[1].trim()===""&&(i={}),!i||typeof i!="object"||Array.isArray(i))throw new T("invalid_frontmatter",`Writable mirror file ${e} requires object frontmatter.`);return{frontmatter:i,body:(n=t[2])!=null?n:""}}function D0(r,e){return!(r instanceof T)||r.code!=="invalid_frontmatter"?null:{path:e,code:"invalid_frontmatter",message:r.message}}function F0(r,e){let t={...e};for(let i of Object.keys(r))i in e||(t[i]=null);return t}function af(r){let e=li.create().update(hi.encode(`mdbase-authority-manifest-v1 -`));for(let t of[...r].sort((i,n)=>i.kind!==n.kind?i.kinduf)throw nt("Connect returned an invalid collection adoption request.");let d=e_(i,dt(u.verification_uri),dt(u.adoption_id));return{controlUrl:i,adoptionId:dt(u.adoption_id),credential:dt(u.adoption_secret),verificationUri:d,expiresAt:new Date(this.now()+Number(u.expires_in)*1e3).toISOString(),requested:{collectionId:n,displayName:s,sourceName:o,retainMirror:a,...c?{mirrorName:c}:{}}}}async start(e,t){let i=await this.begin(e,t),{credential:n,...s}=i;return await t.onVerification(s),{session:i,prepared:await this.waitForApproval(i,t)}}async waitForApproval(e,t={}){var o,a;un(e,this.now());let i=W0(t.pollIntervalMs),n=Date.parse(e.expiresAt),s=0;for(;this.now()=500){let l=mi(c);if(!await this.retry(n,(a=c.retryAfterMs)!=null?a:i,s,t,{code:l.code,message:l.message}))break;continue}throw mi(c)}throw new we("authority_adoption_expired","Collection adoption approval expired before upload began.")}async exchange(e,t={}){un(e,this.now(),!0);let i=await this.controlRequest(e,"exchange","POST",{},t.signal);if(i.status===202)throw new we("authority_adoption_pending","Collection adoption is still awaiting approval.",202);if(i.status!==200)throw mi(i);return H0(e,i.body)}async uploadSnapshot(e,t,i,n={}){un(e,this.now(),!0),Z0(e,t),B0(e,i);let s={protocol_version:1,collection_id:i.collection_id,source_head:i.source_head,source_revision:i.source_revision,manifest_digest:i.manifest_digest,resources:i.resources,record_count:i.records.length};await this.importRequest(t.import.manifest_url,"PUT",t.import.access_token,s,n.signal);let o=0,a=[],c=0;for(let l of i.records){let u=Gr.encode(JSON.stringify(l)).length;if(u>V0)throw new we("authority_adoption_record_too_large",`Record ${l.path} is too large to adopt.`);a.length>0&&(a.length===uT||c+u>V0)&&(await this.uploadPage(t.import,o,a,n.signal),o+=1,a=[],c=0),a.push(l),c+=u}a.length>0&&await this.uploadPage(t.import,o,a,n.signal),await this.importRequest(t.import.finalize_url,"POST",t.import.access_token,void 0,n.signal)}async complete(e,t,i={}){un(e,this.now(),!0),B0(e,t);let n;try{n=await this.controlRequest(e,"complete","POST",{manifest_digest:t.manifest_digest,source_revision:t.source_revision,source_head:t.source_head},i.signal)}catch(a){throw yi(i.signal),new gi("Connect could not confirm whether hosted authority activated.",{cause:a})}if(n.status>=500)throw new gi("Connect could not confirm whether hosted authority activated.");if(n.status!==200)throw mi(n);let s=n.body;if(!_r(s)||s.status!=="completed")throw nt("Connect returned an invalid adoption completion.");let o=Q0(e,s.adoption);if(o.state!=="completed"||o.manifest_digest!==t.manifest_digest||o.source_revision!==t.source_revision||o.final_head!==t.source_head)throw nt("Connect completed a different adoption snapshot.");return{status:"completed",adoption:o}}async cancel(e,t={}){un(e,this.now(),!0);let i=await this.controlRequest(e,void 0,"DELETE",void 0,t.signal);if(i.status!==200)throw mi(i)}mirrorEnrollmentSession(e,t){var i;if(un(e,this.now(),!0),t.status!=="completed"||t.adoption.collection_id!==e.requested.collectionId)throw nt("Completed adoption does not belong to this session.");return e.requested.retainMirror?{controlUrl:e.controlUrl,pairingId:e.adoptionId,refreshCredential:e.credential,verificationUri:`${e.controlUrl}/mirror/${e.adoptionId}`,expiresAt:new Date(this.now()+uf).toISOString(),requested:{mirrorName:(i=e.requested.mirrorName)!=null?i:e.requested.sourceName,mode:"read_write",collectionId:e.requested.collectionId}}:null}async uploadPage(e,t,i,n){let s={protocol_version:1,page:t,records:i};await this.importRequest(e.records_url,"PUT",e.access_token,s,n)}async importRequest(e,t,i,n,s){let o;try{o=await this.request({url:e,method:t,headers:{authorization:`Bearer ${i}`,...n===void 0?{}:{"content-type":"application/json"}},...n===void 0?{}:{body:n},...s?{signal:s}:{}})}catch(a){throw yi(s),G0()}if(o.status<200||o.status>=300)throw mi(o)}controlRequest(e,t,i,n,s){return this.request({url:K0(e,t),method:i,headers:{authorization:`Bearer ${e.credential}`,...n===void 0?{}:{"content-type":"application/json"}},...n===void 0?{}:{body:n},...s?{signal:s}:{}})}async retry(e,t,i,n,s){var l;let o=e-this.now();if(o<=0)return!1;let a=Math.min(W0(t),o),c=new Date(this.now()+a).toISOString();return(l=n.onStatus)==null||l.call(n,{state:s?"retrying":"waiting_for_approval",attempt:i,expiresAt:new Date(e).toISOString(),retryAt:c,...s?{error:s}:{}}),await this.wait(a,n.signal),!0}},we=class extends T{constructor(t,i,n,s){super(t,i);I(this,"status");this.status=n,this.name="AuthorityAdoptionError",(s==null?void 0:s.cause)!==void 0&&(this.cause=s.cause)}},gi=class extends we{constructor(t,i){super("authority_adoption_outcome_unknown",t,void 0,i);I(this,"sourceMustRemainFenced",!0);this.name="AuthorityAdoptionOutcomeUnknownError"}};function Y0(r){var l,u,d,f;let e=Ja(r.collectionId,"Collection ID"),t=(l=r.sourceHead)!=null?l:0;if(!Number.isSafeInteger(t)||t<0)throw new we("invalid_authority_snapshot","Source head must be a non-negative integer.");let i=new Set,n=r.resources.map(p=>{let m=ff(p.path);if(i.add(m)||z0(m),!["configuration","contract","schema","type","view"].includes(p.kind))throw new we("invalid_authority_snapshot",`Unsupported collection resource kind for ${m}.`);return{path:m,kind:p.kind,revision:cf(p.document),document:p.document}}).sort(pT);if(((u=n[0])==null?void 0:u.path)!=="mdbase.yaml"||n[0].kind!=="configuration"||n.filter(({kind:p})=>p==="configuration").length!==1)throw new we("invalid_authority_snapshot","A portable snapshot requires one mdbase.yaml configuration resource.");let s=r.records.map(p=>{let m=ff(p.path);return i.add(m)||z0(m),{record_id:p.recordId?Ja(p.recordId,`Record ID for ${m}`):fT(e,m),path:m,document:p.document}}).sort((p,m)=>X0(p.path,m.path)),o=U0(n.flatMap(({path:p,revision:m})=>[p,m])),a=U0([...n.flatMap(({path:p,revision:m})=>["resource",p,m]),...s.flatMap(p=>["record",p.path,cf(p.document)])]),c=af([...n.map(({path:p,document:m})=>({kind:"resource",path:p,document_hash:jr(li(Gr.encode(m)))})),...s.map(p=>({kind:"record",path:p.path,document_hash:cf(p.document)}))]);return{protocol_version:1,collection_id:e,source_head:t,source_revision:a,manifest_digest:c,resources:{revision:o,spec_version:r.specVersion,types:(d=r.types)!=null?d:[],contracts:(f=r.contracts)!=null?f:[],documents:n},records:s}}function fT(r,e){let t=hT(Ja(r,"Collection ID")),n=Lb(new Uint8Array([...t,...Gr.encode(ff(e))])).slice(0,16);n[6]=n[6]&15|80,n[8]=n[8]&63|128;let s=jr(n);return`${s.slice(0,8)}-${s.slice(8,12)}-${s.slice(12,16)}-${s.slice(16,20)}-${s.slice(20)}`}function cf(r){return`sha256:${jr(li(Gr.encode(r)))}`}function U0(r){let e=li.create();for(let t of r){let i=BigInt(Gr.encode(t).length),n=new Uint8Array(8);new DataView(n.buffer).setBigUint64(0,i),e.update(n),e.update(Gr.encode(t))}return`sha256:${jr(e.digest())}`}function pT(r,e){return r.kind==="configuration"&&e.kind!=="configuration"?-1:e.kind==="configuration"&&r.kind!=="configuration"?1:X0(r.path,e.path)}function X0(r,e){let t=Gr.encode(r),i=Gr.encode(e),n=Math.min(t.length,i.length);for(let s=0;s!t||t==="."||t===".."))throw new we("invalid_authority_snapshot",`Collection path is unsafe: ${r}`);return e}function z0(r){throw new we("invalid_authority_snapshot",`Collection snapshot contains the path more than once: ${r}`)}function hT(r){return Uint8Array.from(r.replaceAll("-","").match(/../g).map(e=>Number.parseInt(e,16)))}function un(r,e,t=!1){fr(r.controlUrl);let i=Date.parse(r.expiresAt);if(!Ga.test(r.adoptionId)||!r_(r.credential)||!Number.isFinite(i)||i-e>uf||!t&&i<=e||!Ga.test(r.requested.collectionId)||!r.requested.displayName.trim()||!r.requested.sourceName.trim())throw new we("invalid_authority_adoption_session","Stored collection adoption state is invalid.");e_(r.controlUrl,r.verificationUri,r.adoptionId)}function Z0(r,e){if(e.status!=="ready"||e.adoption.id!==r.adoptionId||e.adoption.collection_id!==r.requested.collectionId)throw nt("Prepared adoption does not belong to this session.");for(let[t,i]of Object.entries(e.import))if(!i||t!=="access_token"&&!mT(i))throw nt("Connect returned an invalid authority import capability.")}function B0(r,e){var t;if(e.protocol_version!==1||e.collection_id!==r.requested.collectionId||!Number.isSafeInteger(e.source_head)||e.source_head<0||!lT.test(e.source_revision)||!dT.test(e.manifest_digest)||((t=e.resources.documents)==null?void 0:t.length)===0)throw new we("invalid_authority_snapshot","Authority snapshot does not belong to this adoption.")}function H0(r,e){if(!_r(e)||!["ready","activating","completed"].includes(dt(e.status)))throw nt("Connect returned an invalid adoption exchange.");let t=Q0(r,e.adoption);if(e.status==="completed")return{status:"completed",adoption:t};if(e.status==="activating")return{status:"activating",adoption:t};if(!_r(e.import)||!_r(e.staged))throw nt("Connect omitted the authority import capability.");let i=e.import,n=e.staged,s={status:"ready",adoption:t,import:{manifest_url:dt(i.manifest_url),records_url:dt(i.records_url),finalize_url:dt(i.finalize_url),access_token:dt(i.access_token)},staged:{state:n.state,manifest_digest:J0(n.manifest_digest),source_revision:J0(n.source_revision),source_head:wT(n.source_head)}};if(Z0(r,s),!["receiving","uploaded"].includes(s.staged.state))throw nt("Connect returned an invalid staged import state.");return s}function Q0(r,e){if(!_r(e))throw nt("Connect omitted collection adoption state.");let t=e;if(t.id!==r.adoptionId||t.collection_id!==r.requested.collectionId||!["requested","approved","prepared","activating","completed","cancelled","expired"].includes(t.state)||!Number.isSafeInteger(t.authority_epoch)||t.authority_epoch<2||!vT(t.expires_at))throw nt("Connect returned invalid collection adoption state.");return t}function mT(r){try{let e=new URL(r);return(e.protocol==="https:"||e.protocol==="http:"&&["localhost","127.0.0.1","[::1]","::1"].includes(e.hostname))&&!e.username&&!e.password&&!e.search&&!e.hash&&/^\/v1\/authority-imports\/[0-9a-f-]+\/(manifest|records|finalize)$/i.test(e.pathname)}catch(e){return!1}}function e_(r,e,t){let i;try{i=new URL(e)}catch(s){throw nt("Connect returned an invalid adoption verification URI.")}let n=new URL(`/adopt/${encodeURIComponent(t)}`,r);if(i.origin!==n.origin||i.pathname!==n.pathname||i.search||i.hash||i.username||i.password)throw nt("Connect returned an untrusted adoption verification URI.");return i.href}function K0(r,e){let t=e?`/${e}`:"";return`${fr(r.controlUrl)}/v1/authority-adoptions/${encodeURIComponent(r.adoptionId)}${t}`}function Ja(r,e){if(!Ga.test(r))throw new we("invalid_authority_adoption",`${e} must be a UUID.`);return r.toLowerCase()}function lf(r,e){let t=r.trim();if(!t||t.length>200)throw new we("invalid_authority_adoption",`${e} must contain between 1 and 200 characters.`);return t}function yT(r,e){if(r.status!==e)throw mi(r);return r.body}function mi(r){let e=_r(r.body)&&_r(r.body.error)?r.body.error:{};return new we(dt(e.code)||"authority_adoption_request_failed",dt(e.message)||`Collection adoption request failed with status ${r.status}.`,r.status)}function nt(r){return new we("invalid_authority_adoption_response",r)}function t_(r){return{code:"authority_adoption_unreachable",message:"Connect could not be reached for collection adoption."}}function G0(){let r=t_(void 0);return new we(r.code,r.message)}function W0(r=df){return Number.isFinite(r)?Math.min(3e4,Math.max(250,Math.round(r))):df}function gT(r,e){return yi(e),new Promise((t,i)=>{let n=setTimeout(o,r),s=()=>{clearTimeout(n),e==null||e.removeEventListener("abort",s),i(new we("authority_adoption_cancelled","Collection adoption was cancelled."))};function o(){e==null||e.removeEventListener("abort",s),t()}e==null||e.addEventListener("abort",s,{once:!0})})}function yi(r){if(r!=null&&r.aborted)throw new we("authority_adoption_cancelled","Collection adoption was cancelled.")}async function bT(r){let e=await fetch(r.url,{method:r.method,headers:r.headers,...r.body===void 0?{}:{body:JSON.stringify(r.body)},...r.signal?{signal:r.signal}:{}}),t=await e.json().catch(()=>({})),i=e.headers.get("retry-after");return{status:e.status,body:t,...i?{retryAfterMs:_T(i)}:{}}}function _T(r){let e=Number(r);if(Number.isFinite(e)&&e>=0)return e*1e3;let t=Date.parse(r);return Number.isFinite(t)?Math.max(0,t-Date.now()):df}function vT(r){return Number.isFinite(Date.parse(r))}function J0(r){return r===null?null:dt(r)}function wT(r){return r===null?null:typeof r=="number"&&Number.isSafeInteger(r)&&r>=0?r:Number.NaN}function $T(r){return typeof r=="number"&&Number.isSafeInteger(r)&&r>0}function r_(r){return typeof r=="string"&&r.length>=16}function dt(r){return typeof r=="string"?r:""}function _r(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}var Ls=".mdbase/connect-role.json",js=".mdbase/authority-adoption.json",Ds=".mdbase/authority-adoption-snapshot.json",ST="mdbase-obsidian-connect",fn="mirrors",ET="mdbase-connect-access-",AT="mdbase-connect-refresh-",kT="mdbase-connect-adoption-",PT=300*1e3,n_=[".git/",".obsidian/",".trash/",".mdbase/"],Fs=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function st(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function _f(r,e){if(e!=null)return e;if(!r.trim())return{};try{return JSON.parse(r)}catch(t){return{}}}function s_(r){var n;let e=(n=r["retry-after"])!=null?n:r["Retry-After"];if(!e)return;let t=Number(e);if(Number.isFinite(t)&&t>=0)return t*1e3;let i=Date.parse(e);if(Number.isFinite(i))return Math.max(0,i-Date.now())}function xT(){return async r=>{var t,i;if((t=r.signal)!=null&&t.aborted)throw new DOMException("Enrollment cancelled.","AbortError");let e=await(0,le.requestUrl)({url:r.url,method:r.method,headers:r.headers,body:r.body===void 0?void 0:JSON.stringify(r.body),contentType:r.body===void 0?void 0:"application/json",throw:!1});if((i=r.signal)!=null&&i.aborted)throw new DOMException("Enrollment cancelled.","AbortError");return{status:e.status,body:_f(e.text,e.json),retryAfterMs:s_(e.headers)}}}function IT(){return async r=>{var t,i;if((t=r.signal)!=null&&t.aborted)throw new DOMException("Collection adoption cancelled.","AbortError");let e=await(0,le.requestUrl)({url:r.url,method:r.method,headers:r.headers,body:r.body===void 0?void 0:JSON.stringify(r.body),contentType:r.body===void 0?void 0:"application/json",throw:!1});if((i=r.signal)!=null&&i.aborted)throw new DOMException("Collection adoption cancelled.","AbortError");return{status:e.status,body:_f(e.text,e.json),retryAfterMs:s_(e.headers)}}}var mf=class{constructor(e,t){this.accessToken=t;let i;try{i=new URL(e)}catch(n){throw new T("invalid_sync_url","Sync URL must be an absolute authority endpoint.")}if(!(i.protocol==="https:"||i.protocol==="http:"&&["localhost","127.0.0.1","[::1]","::1"].includes(i.hostname))||i.username||i.password||i.search||i.hash||!/^\/v1\/authorities\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\/sync\/?$/i.test(i.pathname))throw new T("invalid_sync_url","Sync URL must identify one authority sync endpoint.");this.syncUrl=i.href.replace(/\/$/,"")}openSession(){return this.request("POST","sessions")}snapshot(e,t){let i=new URLSearchParams({snapshot_id:e});return t&&i.set("page",t),this.request("GET",`snapshot?${i.toString()}`)}changes(e,t=200){let i=new URLSearchParams({after:String(e),limit:String(t)});return this.request("GET",`changes?${i.toString()}`)}mutate(e){return this.request("POST","mutations",e)}async request(e,t,i){let n=await(0,le.requestUrl)({url:`${this.syncUrl}/${t}`,method:e,headers:{authorization:`Bearer ${this.accessToken}`},body:i===void 0?void 0:JSON.stringify(i),contentType:i===void 0?void 0:"application/json",throw:!1}),s=_f(n.text,n.json);if(n.status<200||n.status>=300){let o=st(s)&&st(s.error)?s.error:{};throw new T(typeof o.code=="string"?o.code:"sync_failed",typeof o.message=="string"?o.message:`Sync request failed (${n.status}).`)}return s}};function pf(r){let e=fs(r);if(e===".mdbase"||n_.some(t=>e.startsWith(t)))throw new T("unsafe_mirror_path",`The collection authority attempted to write a reserved path: ${e}`);return e}async function Ya(r,e){let t=(0,le.normalizePath)(e).replace(/\/+$/,"");if(!t)return;let i="";for(let n of t.split("/")){i=i?`${i}/${n}`:n;let s=r.getAbstractFileByPath(i);if(!(s instanceof le.TFolder)){if(s)throw new T("mirror_path_collision",`A file blocks the mirror folder ${i}.`);await r.adapter.exists(i)||await r.createFolder(i)}}}var yf=class{constructor(e){this.vault=e}async read(e){let t=pf(e),i=this.vault.getAbstractFileByPath(t);if(i==null)return null;if(!(i instanceof le.TFile))throw new T("mirror_path_collision",`Expected a file at ${t}.`);return this.vault.cachedRead(i)}async write(e,t){let i=pf(e),n=i.lastIndexOf("/");n>=0&&await Ya(this.vault,i.slice(0,n));let s=this.vault.getAbstractFileByPath(i);if(s instanceof le.TFolder)throw new T("mirror_path_collision",`A folder blocks the mirror file ${i}.`);s instanceof le.TFile?await this.vault.modify(s,t):await this.vault.create(i,t)}async remove(e){let t=pf(e),i=this.vault.getAbstractFileByPath(t);if(i!=null){if(!(i instanceof le.TFile))throw new T("mirror_path_collision",`Expected a file at ${t}.`);await this.vault.delete(i,!0)}}async listMarkdown(e){return this.vault.getMarkdownFiles().map(t=>(0,le.normalizePath)(t.path)).filter(t=>!e.has(t)).filter(t=>!n_.some(i=>t.startsWith(i))).sort()}},gf=class{constructor(e){this.key=e;this.database=null}async read(){let e=await this.open();return new Promise((t,i)=>{let n=e.transaction(fn,"readonly").objectStore(fn).get(this.key);n.onsuccess=()=>{var s;return t((s=n.result)!=null?s:null)},n.onerror=()=>i(n.error)})}async write(e){let t=await this.open();await new Promise((i,n)=>{let s=t.transaction(fn,"readwrite");s.objectStore(fn).put(e,this.key),s.oncomplete=()=>i(),s.onerror=()=>n(s.error),s.onabort=()=>n(s.error)})}open(){var e;if(typeof indexedDB=="undefined")throw new T("storage_unavailable","IndexedDB is required for persistent mirror state.");return(e=this.database)!=null||(this.database=new Promise((t,i)=>{let n=indexedDB.open(ST,1);n.onupgradeneeded=()=>{n.result.objectStoreNames.contains(fn)||n.result.createObjectStore(fn)},n.onerror=()=>i(n.error),n.onsuccess=()=>t(n.result)})),this.database}},pn=class pn{constructor(e){this.key=e}async runExclusive(e){if(pn.active.has(this.key))throw new T("mirror_busy","A mirror operation is already running for this vault.");pn.active.add(this.key);try{return await e()}finally{pn.active.delete(this.key)}}};pn.active=new Set;var bf=pn,Xa=class{constructor(e,t,i={}){this.app=e;this.settingsHost=t;this.options=i;this.progress=null;this.adoptionMarker=null;var n,s,o;this.fileSystem=(n=i.fileSystem)!=null?n:new yf(e.vault),this.enrollmentClient=(s=i.enrollmentClient)!=null?s:new la({request:xT()}),this.adoptionClient=(o=i.adoptionClient)!=null?o:new Wa({request:IT()})}async initialize(){if(this.adoptionMarker=await this.readAdoptionMarker(),this.adoptionMarker&&this.settingsHost.getMirrorProfile())throw new T("authority_adoption_state_conflict","This vault contains both an authority-adoption checkpoint and a mirror profile.")}getProgress(){return this.progress?{...this.progress}:null}getAdoptionMarker(){return this.adoptionMarker?JSON.parse(JSON.stringify(this.adoptionMarker)):null}assertLocalAuthorityWritable(){if(this.adoptionMarker&&["fenced","activating","adopted"].includes(this.adoptionMarker.phase))throw new T("local_authority_fenced",this.adoptionMarker.phase==="adopted"?"Hosted mdbase is now authoritative. Finish reconnecting this vault as its mirror before editing.":"This local authority is frozen while its exact snapshot is adopted by hosted mdbase.")}async adoptLocalCollection(e,t){if(this.settingsHost.getMirrorProfile())throw new T("mirror_already_configured","This vault already mirrors a collection authority.");if(this.adoptionMarker)return this.resumeAdoption(t);let i=await this.ensurePortableCollectionIdentity(),n=await this.adoptionClient.begin({controlUrl:e.controlUrl,collectionId:i.collectionId,displayName:i.displayName,sourceName:e.mirrorName,retainMirror:!0,mirrorName:e.mirrorName},t);return await this.storeAdoptionSecret(n),await this.writeAdoptionMarker({version:1,phase:"waiting_for_approval",session:hf(n),manifest_digest:null,source_revision:null,source_head:null}),await t.onVerification(hf(n)),this.runAdoptionWithRecovery(n,t)}async resumeAdoption(e={}){var s,o,a;let t=(s=this.adoptionMarker)!=null?s:await this.readAdoptionMarker();if(!t)throw new T("authority_adoption_not_found","This vault has no collection-adoption checkpoint.");this.adoptionMarker=t;let i=this.app.secretStorage.getSecret(this.adoptionSecretId(t.session.adoptionId));if(!i)throw new T("authority_adoption_credentials_missing","The collection-adoption credential is missing from Obsidian's secret store.");let n={...t.session,credential:i};return t.phase==="waiting_for_approval"&&await((o=e.onVerification)==null?void 0:o.call(e,hf(n))),this.runAdoptionWithRecovery(n,{...e,onVerification:(a=e.onVerification)!=null?a:(()=>{})})}async cancelAdoption(e){var n;let t=(n=this.adoptionMarker)!=null?n:await this.readAdoptionMarker();if(!t)return;if(["activating","adopted"].includes(t.phase))throw new T("authority_adoption_activation_started","Hosted activation has started and must be resumed; it can no longer be cancelled.");let i=this.app.secretStorage.getSecret(this.adoptionSecretId(t.session.adoptionId));if(!i)throw new T("authority_adoption_credentials_missing","The collection-adoption credential is missing from Obsidian's secret store.");await this.adoptionClient.cancel({...t.session,credential:i},{signal:e}),await this.clearAdoptionCheckpoint(t.session.adoptionId)}async enroll(e,t){let i=await this.assertCanBecomeMirror(e.collectionId),n=await this.enrollmentClient.enroll({...e,...i?{collectionId:i}:{}},t),s=await this.markMirror(n.collectionId);try{await this.persistEnrollment(n)}catch(o){if(s)try{await this.app.vault.adapter.remove(Ls)}catch(a){throw new T("enrollment_recovery_required",`Enrollment settings could not be saved and the temporary role marker could not be removed: ${o instanceof Error?o.message:String(o)}`)}throw o}return this.requireProfile()}async preview(){return(await this.createMirror()).previewInitialization()}async status(){let e=this.settingsHost.getMirrorProfile();return e?(await this.assertMirror(e.collectionId),(await this.createMirror()).status()):null}async sync(e){let t=await this.createMirror(i=>{this.progress=i,e==null||e({...i})});try{return await t.sync(),t.status()}finally{this.progress=null}}async resolveConflict(e,t){let i=await this.createMirror();return await i.resolveConflict(e,t),i.status()}async runAdoption(e,t){let i=this.requireAdoptionMarker(e.adoptionId),n=null;if(i.phase==="adopted"){let s=await this.adoptionClient.exchange(e,t);if(s.status!=="completed")throw new T("authority_adoption_state_conflict","The local checkpoint says adoption completed, but Connect does not.");n=s}else if(i.phase==="activating"){let s=await this.readAdoptionSnapshot(i),o=await this.adoptionClient.exchange(e,t);n=o.status==="completed"?o:await this.adoptionClient.complete(e,s,t)}else if(i.phase==="fenced"){let s=await this.readAdoptionSnapshot(i),o=await this.adoptionClient.exchange(e,t);o.status==="completed"?n=o:(o.status==="ready"&&await this.adoptionClient.uploadSnapshot(e,o,s,t),await this.updateAdoptionPhase("activating",s),n=await this.adoptionClient.complete(e,s,t))}else{let s=i.phase==="waiting_for_approval"?await this.adoptionClient.waitForApproval(e,t):await this.requirePreparedAdoption(e,t);await this.updateAdoptionPhase("uploading");let o=await this.captureAuthoritySnapshot(e.requested.collectionId);await this.adoptionClient.uploadSnapshot(e,s,o,t);let a=await this.captureAuthoritySnapshot(e.requested.collectionId);await this.writeAdoptionSnapshot(a),await this.updateAdoptionPhase("fenced",a);let c=await this.requirePreparedAdoption(e,t);await this.adoptionClient.uploadSnapshot(e,c,a,t),await this.updateAdoptionPhase("activating",a),n=await this.adoptionClient.complete(e,a,t)}return await this.updateAdoptionPhase("adopted"),this.finishRetainedMirror(e,n,t)}async runAdoptionWithRecovery(e,t){try{return await this.runAdoption(e,t)}catch(i){throw RT(i)?(await this.adoptionClient.cancel(e,{signal:t.signal}).catch(()=>{}),await this.clearAdoptionCheckpoint(e.adoptionId),new T(i.code,"This adoption ended before hosted activation. The vault remains the writable local authority; start a new adoption to try again.")):i}}async requirePreparedAdoption(e,t){let i=await this.adoptionClient.exchange(e,t);if(i.status==="ready")return i;throw i.status==="activating"?new gi("Hosted authority activation has already started. Resume using the saved fenced snapshot."):new T("authority_adoption_already_completed","Hosted authority has already adopted this collection.")}async finishRetainedMirror(e,t,i){var a,c;let n,s=this.adoptionClient.mirrorEnrollmentSession(e,t);if(!s)throw new T("authority_adoption_mirror_missing","Hosted authority activated without retaining this vault as a mirror.");try{n=await this.enrollmentClient.waitForApproval(s,{signal:i.signal,onStatus:l=>{var u;return(u=i.onStatus)==null?void 0:u.call(i,{...l,state:l.state})}})}catch(l){if((a=i.signal)!=null&&a.aborted)throw l;n=await this.enrollmentClient.enroll({controlUrl:e.controlUrl,collectionId:e.requested.collectionId,mirrorName:(c=e.requested.mirrorName)!=null?c:e.requested.sourceName,mode:"read_write"},{signal:i.signal,onVerification:i.onVerification})}let o=await this.markMirror(n.collectionId);try{await this.persistEnrollment(n)}catch(l){throw o&&await this.app.vault.adapter.remove(Ls),l}return await this.clearAdoptionCheckpoint(e.adoptionId),this.requireProfile()}async captureAuthoritySnapshot(e){let t=await ai(this.app.vault);if(!t)throw new T("invalid_collection_configuration","A valid mdbase.yaml is required.");let i=await this.app.vault.adapter.read("mdbase.yaml"),n=(0,le.parseYaml)(i),s=[{path:"mdbase.yaml",kind:"configuration",document:i}],o=`${(0,le.normalizePath)(t.settings.types_folder)}/`,a=this.app.vault.getMarkdownFiles().filter(u=>(0,le.normalizePath)(u.path).startsWith(o)).sort((u,d)=>u.path.localeCompare(d.path));for(let u of a)s.push({path:(0,le.normalizePath)(u.path),kind:"type",document:await this.app.vault.cachedRead(u)});let c=TT(n);if(c.length){let u=c.map(f=>(0,i_.default)(f,{dot:!0})),d=OT(this.app.vault).filter(f=>f.extension==="base").filter(f=>u.some(p=>p((0,le.normalizePath)(f.path)))).sort((f,p)=>f.path.localeCompare(p.path));for(let f of d)s.push({path:(0,le.normalizePath)(f.path),kind:"view",document:await this.app.vault.cachedRead(f)})}let l=[];for(let u of this.app.vault.getMarkdownFiles().sort((d,f)=>d.path.localeCompare(f.path))){let d=(0,le.normalizePath)(u.path);if(ps(d,t))continue;let f=await this.app.vault.cachedRead(u),p=Ue(f);if(p.error)throw new T("invalid_authority_record",`${d} has invalid frontmatter: ${p.error}`);l.push({path:d,document:f})}return Y0({collectionId:e,sourceHead:0,specVersion:t.spec_version,resources:s,records:l})}async ensurePortableCollectionIdentity(){if(!await this.app.vault.adapter.exists("mdbase.yaml"))throw new T("collection_not_initialized","Initialize an mdbase collection before hosting it.");let e=await this.app.vault.adapter.read("mdbase.yaml"),t;try{t=(0,le.parseYaml)(e)}catch(o){throw new T("invalid_collection_configuration","mdbase.yaml must contain valid YAML.")}if(!st(t))throw new T("invalid_collection_configuration","mdbase.yaml must contain a YAML mapping.");let i=st(t["x-mdbase-connect"])?t["x-mdbase-connect"].collection_id:void 0,n;if(i===void 0){n=crypto.randomUUID();let o=st(t["x-mdbase-connect"])?t["x-mdbase-connect"]:{};t["x-mdbase-connect"]={...o,collection_id:n},await this.app.vault.adapter.write("mdbase.yaml",(0,le.stringifyYaml)(t))}else if(typeof i=="string"&&Fs.test(i))n=i;else throw new T("invalid_collection_configuration","x-mdbase-connect.collection_id must be a UUID string.");let s=typeof t.name=="string"&&t.name.trim()?t.name.trim():this.app.vault.getName();return{collectionId:n,displayName:s}}async createMirror(e){var o,a,c,l,u,d,f,p,m;let t=this.requireProfile();await this.assertMirror(t.collectionId);let i=await this.freshAccessToken(t),n=(c=(a=(o=this.options).transportFactory)==null?void 0:a.call(o,t,i))!=null?c:new mf(t.syncUrl,i),s={stateStore:(d=(u=(l=this.options).stateStoreFactory)==null?void 0:u.call(l,t))!=null?d:new gf(`${t.collectionId}:${t.replicaId}`),fileSystem:this.fileSystem,lease:(m=(p=(f=this.options).leaseFactory)==null?void 0:p.call(f,t))!=null?m:new bf(`${t.collectionId}:${t.replicaId}`),onProgress:e};return t.mode==="read_write"?new Ka(t.replicaId,n,s):new qs(t.replicaId,n,s)}requireProfile(){let e=this.settingsHost.getMirrorProfile();if(!e)throw new T("mirror_not_configured","This vault is not connected to a collection authority.");return e}accessSecretId(e){return`${ET}${e.toLowerCase()}`}refreshSecretId(e){return`${AT}${e.toLowerCase()}`}adoptionSecretId(e){return`${kT}${e.toLowerCase()}`}async storeAdoptionSecret(e){this.app.secretStorage.setSecret(this.adoptionSecretId(e.adoptionId),e.credential)}async persistEnrollment(e){this.app.secretStorage.setSecret(this.accessSecretId(e.collectionId),e.accessToken),this.app.secretStorage.setSecret(this.refreshSecretId(e.collectionId),e.refreshCredential),await this.settingsHost.saveMirrorProfile({version:1,syncUrl:e.syncUrl,controlUrl:e.controlUrl,collectionId:e.collectionId,replicaId:e.replicaId,mode:e.mode,name:e.name,enrollmentId:e.enrollmentId,accessTokenExpiresAt:e.accessTokenExpiresAt})}async freshAccessToken(e){let t=this.accessSecretId(e.collectionId),i=this.app.secretStorage.getSecret(t),n=Date.parse(e.accessTokenExpiresAt);if(i&&Number.isFinite(n)&&n-Date.now()>PT)return i;let s=this.app.secretStorage.getSecret(this.refreshSecretId(e.collectionId));if(!s)throw new T("mirror_credentials_missing","The mirror refresh credential is missing. Re-enroll this vault.");let o=await this.enrollmentClient.renew({controlUrl:e.controlUrl,syncUrl:e.syncUrl,collectionId:e.collectionId,replicaId:e.replicaId,mode:e.mode,name:e.name,enrollmentId:e.enrollmentId,accessToken:i!=null?i:"",refreshCredential:s,accessTokenExpiresAt:e.accessTokenExpiresAt});return await this.persistEnrollment(o),o.accessToken}async assertCanBecomeMirror(e){var o;let t=await this.readMarker(),i=await this.readPortableCollectionId();if(i&&!t)throw new T("local_authority_requires_transfer","This vault has a local Connect identity. Transfer authority explicitly before using it as a mirror.");if(i&&(t==null?void 0:t.collection_id)!==i)throw new T("mirror_identity_conflict","The vault identity and mirror role marker identify different collections.");let n=this.settingsHost.getMirrorProfile(),s=(o=n==null?void 0:n.collectionId)!=null?o:e;if(t&&s&&t.collection_id!==s)throw new T("mirror_identity_conflict","This vault is already marked as a different mirror.");if(!t&&!n&&await this.app.vault.adapter.exists("mdbase.yaml"))throw new T("existing_collection_requires_transfer","This vault already contains an mdbase collection. Connect an empty vault, or transfer collection authority explicitly.");return s!=null?s:t==null?void 0:t.collection_id}async readPortableCollectionId(){if(!await this.app.vault.adapter.exists("mdbase.yaml"))return null;let e;try{e=(0,le.parseYaml)(await this.app.vault.adapter.read("mdbase.yaml"))}catch(n){throw new T("invalid_collection_configuration","mdbase.yaml must contain valid YAML.")}if(!st(e))throw new T("invalid_collection_configuration","mdbase.yaml must contain a YAML mapping.");let t=e["x-mdbase-connect"];if(t===void 0)return null;if(!st(t))throw new T("invalid_collection_configuration","x-mdbase-connect must be a YAML mapping.");let i=t.collection_id;if(i===void 0)return null;if(typeof i!="string"||!Fs.test(i))throw new T("invalid_collection_configuration","x-mdbase-connect.collection_id must be a UUID string.");return i}async markMirror(e){let t=await this.readMarker();if(t){if(t.collection_id!==e)throw new T("mirror_identity_conflict","This vault already mirrors a different collection authority.");return!1}return await Ya(this.app.vault,".mdbase"),await this.app.vault.adapter.write(Ls,`${JSON.stringify({version:1,role:"mirror",collection_id:e},null,2)} -`),!0}async assertMirror(e){let t=await this.readMarker();if(!t||t.collection_id!==e)throw new T("mirror_marker_missing","The vault's mirror role marker is missing or does not match this connection.")}async readMarker(){if(!await this.app.vault.adapter.exists(Ls))return null;let e;try{e=JSON.parse(await this.app.vault.adapter.read(Ls))}catch(t){throw new T("invalid_mirror_marker","The mirror role marker is corrupt.")}if(!st(e)||e.version!==1||e.role!=="mirror"||typeof e.collection_id!="string"||!Fs.test(e.collection_id))throw new T("invalid_mirror_marker","The mirror role marker is invalid.");return e}requireAdoptionMarker(e){if(!this.adoptionMarker||this.adoptionMarker.session.adoptionId!==e)throw new T("authority_adoption_state_conflict","The collection-adoption checkpoint does not match this approval.");return this.adoptionMarker}async updateAdoptionPhase(e,t){if(!this.adoptionMarker)throw new T("authority_adoption_not_found","Collection-adoption checkpoint is missing.");await this.writeAdoptionMarker({...this.adoptionMarker,phase:e,...t?{manifest_digest:t.manifest_digest,source_revision:t.source_revision,source_head:t.source_head}:{}})}async writeAdoptionMarker(e){await Ya(this.app.vault,".mdbase"),await this.app.vault.adapter.write(js,`${JSON.stringify(e,null,2)} -`),this.adoptionMarker=e}async readAdoptionMarker(){if(!await this.app.vault.adapter.exists(js))return null;let e;try{e=JSON.parse(await this.app.vault.adapter.read(js))}catch(t){throw new T("invalid_authority_adoption_checkpoint","The collection-adoption checkpoint is corrupt.")}if(!CT(e))throw new T("invalid_authority_adoption_checkpoint","The collection-adoption checkpoint is invalid.");return e}async writeAdoptionSnapshot(e){await Ya(this.app.vault,".mdbase"),await this.app.vault.adapter.write(Ds,JSON.stringify(e))}async readAdoptionSnapshot(e){if(!await this.app.vault.adapter.exists(Ds))throw new T("authority_adoption_snapshot_missing","The fenced authority snapshot is missing; hosted activation cannot be resumed safely.");let t;try{t=JSON.parse(await this.app.vault.adapter.read(Ds))}catch(i){throw new T("invalid_authority_adoption_snapshot","The fenced authority snapshot is corrupt.")}if(t.collection_id!==e.session.requested.collectionId||t.manifest_digest!==e.manifest_digest||t.source_revision!==e.source_revision||t.source_head!==e.source_head)throw new T("authority_adoption_snapshot_mismatch","The fenced authority snapshot does not match its durable checkpoint.");return t}async clearAdoptionCheckpoint(e){await this.app.vault.adapter.exists(js)&&await this.app.vault.adapter.remove(js),await this.app.vault.adapter.exists(Ds)&&await this.app.vault.adapter.remove(Ds),this.app.secretStorage.setSecret(this.adoptionSecretId(e),""),this.adoptionMarker=null}};function hf(r){let{credential:e,...t}=r;return t}function RT(r){return r instanceof we&&["authority_adoption_expired","authority_adoption_cancelled"].includes(r.code)}function TT(r){if(!st(r))return[];let e=r["x-obsidian"];return!st(e)||!st(e.bases)||!Array.isArray(e.bases.include)?[]:e.bases.include.filter(t=>typeof t=="string")}function OT(r){var n;let e=(n=r.getFiles)==null?void 0:n.call(r);if(e)return e;let t=[],i=s=>{for(let o of s.children)o instanceof le.TFile?t.push(o):o instanceof le.TFolder&&i(o)};return i(r.getRoot()),t}function CT(r){if(!st(r)||r.version!==1||!["waiting_for_approval","uploading","fenced","activating","adopted"].includes(String(r.phase))||!st(r.session))return!1;let e=r.session;return typeof e.controlUrl=="string"&&typeof e.adoptionId=="string"&&Fs.test(e.adoptionId)&&typeof e.verificationUri=="string"&&typeof e.expiresAt=="string"&&st(e.requested)&&typeof e.requested.collectionId=="string"&&Fs.test(e.requested.collectionId)&&typeof e.requested.displayName=="string"&&typeof e.requested.sourceName=="string"&&e.requested.retainMirror===!0&&(r.manifest_digest===null||typeof r.manifest_digest=="string")&&(r.source_revision===null||typeof r.source_revision=="string")&&(r.source_head===null||Number.isSafeInteger(r.source_head))}var Xe=require("obsidian");var Bs="0.3.0",NT=new Set(["name","description","display_name_key","strict","path_pattern","filename_pattern","match","fields","extends"]),MT=new Set(["type","required","default","description","values","items","fields","min","max","min_length","max_length","pattern","unique","deprecated","generated","computed","target","validate_exists","tn_role","tn_completed_values"]);function _e(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function Oe(r){return r===void 0?r:JSON.parse(JSON.stringify(r))}function vr(r){return of.digest(r)}function bi(r){return Array.isArray(r)?`[${r.map(bi).join(",")}]`:_e(r)?`{${Object.keys(r).sort().map(e=>`${JSON.stringify(e)}:${bi(r[e])}`).join(",")}}`:JSON.stringify(r)}function vf(r){if(Array.isArray(r))return r.map(vf);if(!_e(r))return r;let e={};for(let[t,i]of Object.entries(r)){let n=vf(i);n!=null&&(Array.isArray(n)&&n.length===0||_e(n)&&Object.keys(n).length===0||(e[t]=n))}return e}function hn(r){return[...new Set(r)]}function qT(r){return _e(r.fields)?Object.values(r.fields).some(e=>_e(e)&&(typeof e.tn_role=="string"||Array.isArray(e.tn_completed_values))):!1}function wf(r,e,t){let i=_e(e)?e:{},n={},s={},o=[],a;switch(i.type){case"any":a={};break;case"string":case"integer":case"number":case"boolean":a={type:i.type};break;case"date":case"datetime":case"time":a={type:"string",format:i.type==="datetime"?"date-time":i.type};break;case"enum":a={enum:Array.isArray(i.values)?Oe(i.values):[]};break;case"link":a={type:"string"},n[r]={target_type:typeof i.target=="string"?i.target:r.endsWith("Parent")||r.endsWith("uid")?"task":"any",validate_exists:i.validate_exists===!0};break;case"list":{let c=wf(`${r}[]`,i.items,t);a={type:"array",items:c.schema},Object.assign(n,c.links),Object.assign(s,c.legacy),o.push(...c.unsupported);break}case"object":{let c={},l=[];for(let[u,d]of Object.entries(_e(i.fields)?i.fields:{})){let f=wf(`${r}.${u}`,d,t);c[u]=f.schema,Object.assign(n,f.links),Object.assign(s,f.legacy),o.push(...f.unsupported),_e(d)&&d.required===!0&&l.push(u)}t&&r==="blockedBy[]"&&l.push("uid"),a={type:"object",additionalProperties:Object.keys(c).length===0,properties:c,...l.length?{required:hn(l)}:{}};break}default:a={},o.push(`${r}.type`);break}t&&r==="title"&&(a.minLength=1,a.description="Short summary of the task."),typeof i.description=="string"&&(a.description=i.description),typeof i.min=="number"&&(i.type==="string"?a.minLength=i.min:i.type==="list"?a.minItems=i.min:a.minimum=i.min),typeof i.max=="number"&&(i.type==="string"?a.maxLength=i.max:i.type==="list"?a.maxItems=i.max:a.maximum=i.max),typeof i.min_length=="number"&&(a.minLength=i.min_length),typeof i.max_length=="number"&&(a.maxLength=i.max_length),typeof i.pattern=="string"&&(a.pattern=i.pattern),i.deprecated===!0&&(a.deprecated=!0),i.default!==void 0&&(a.default=Oe(i.default)),i.computed!==void 0&&o.push(`${r}.computed`);for(let[c,l]of Object.entries(i)){let u=t&&(c==="tn_role"||c==="tn_completed_values");(!MT.has(c)||(c==="tn_role"||c==="tn_completed_values")&&!u)&&(s[`${r}.${c}`]=Oe(l))}return{schema:a,links:n,legacy:s,unsupported:o}}function Vs(r,e,t,i){let n=_e(r[e])?r[e]:{},s=_e(n.set)?n.set:{};s[t]=i,n.set=s,r[e]=n}function LT(r,e,t){if(t==="now")Vs(r,"on_create",e,{now:!0});else if(t==="now_on_write")Vs(r,"on_update",e,{now:!0});else if(t==="uuid")Vs(r,"on_create",e,{uuid:!0});else if(t==="ulid")Vs(r,"on_create",e,{ulid:!0});else if(_e(t)&&t.transform==="slugify"&&typeof t.from=="string")Vs(r,"on_create",e,{slugify:t.from});else return!1;return!0}function jT(r){var t;let e=r.match(/^(.*\/)?\{title\}\.md$/);return e?{runtime:"tasknotes",template:"{{title}}",folder:((t=e[1])!=null?t:"").replace(/\/$/,""),generated_by:"tasknotes.filename.create"}:{runtime:"tasknotes",template:r,generated_by:"tasknotes.filename.create"}}function DT(r,e,t){var P;if(t.kind==="mdbase.type"||t.schema!==void 0)throw new Error(`${r} already looks like a v0.3 type.`);if(typeof t.name!="string"||!_e(t.fields))throw new Error(`${r} is not a v0.2 type with a name and fields.`);let i=qT(t),n=t.name.trim().toLowerCase(),s={type:{const:n}},o=[],a={},c={},l=[],u={},d={},f=[],p=[],m={},h={},y={};for(let[x,E]of Object.entries(t.fields)){let R=_e(E)?E:{},w=wf(x,R,i);s[x]=w.schema,Object.assign(c,w.links),Object.assign(d,w.legacy),f.push(...w.unsupported),R.required===!0&&o.push(x),R.default!==void 0&&(a[x]=Oe(R.default)),R.unique===!0&&l.push({field:x,scope:"collection"}),R.generated!==void 0&<(u,x,R.generated)&&p.push(x),typeof R.tn_role=="string"&&(m[R.tn_role]=x),Array.isArray(R.tn_completed_values)&&(h.completed_values=Oe(R.tn_completed_values))}a.status!==void 0&&(h.default=Oe(a.status)),a.priority!==void 0&&(y.default=Oe(a.priority));let b=typeof t.display_name_key=="string"&&Object.prototype.hasOwnProperty.call(t.fields,t.display_name_key)?t.display_name_key:void 0,g={...b?{display:{name_field:b}}:{},read_defaults:a,links:c,unique:l};typeof t.path_pattern=="string"&&(g.path=i?jT(t.path_pattern):{pattern:t.path_pattern});let _={};for(let[x,E]of Object.entries(t))NT.has(x)||(_[x]=Oe(E));Object.keys(d).length&&(_.fields=d);let S=vf({kind:"mdbase.type",name:n,version:1,description:typeof t.description=="string"?t.description:void 0,match:_e(t.match)?Oe(t.match):void 0,schema:{dialect:"json-schema-2020-12",value:{$schema:"https://json-schema.org/draft/2020-12/schema",type:"object",additionalProperties:t.strict!==!0,properties:s,...o.length?{required:hn(o)}:{}}},collection:g,lifecycle:u,...i?{"x-tasknotes":{contract:"tasknotes.task",version:1,field_roles:m,status:h,priority:y,archive:{tags_field:(P=m.tags)!=null?P:"tags",archived_tag:"archived"}}}:{},...Object.keys(_).length?{"x-legacy-v0.2":_}:{}}),v=[];t.extends!==void 0&&f.push("extends");for(let x of hn(f).sort())v.push({path:r,code:"migration_lossy",message:`${x} cannot be expressed as canonical v0.3 write behavior and was retained as legacy metadata where possible.`,severity:"lossy"});return i&&v.push({path:r,code:"path_policy_runtime_owned",message:"TaskNotes filename behavior is recorded as TaskNotes runtime metadata.",severity:"warning"}),t.strict!==!0&&v.push({path:r,code:"additional_properties_true",message:"The migrated schema allows additional properties because the source type was not strict.",severity:"warning"}),typeof t.display_name_key=="string"&&!b&&v.push({path:r,code:"display_field_missing",message:`The display field '${t.display_name_key}' is not declared, so collection.display was omitted.`,severity:"warning"}),{target:S,summary:{path:r,name:n,fieldsConverted:Object.keys(t.fields).length,requiredFields:hn(o),defaultsMoved:Object.keys(a),generatedFieldsMoved:hn(p),linksMoved:Object.keys(c),taskNotes:i},diagnostics:v}}function FT(r){let e=Oe(r);e.spec_version=Bs;let t=_e(e.settings)?e.settings:{};if(e.settings=t,!Array.isArray(t.record_extensions)){let i=Array.isArray(t.extensions)?t.extensions.map(String).map(n=>n.replace(/^\./,"")):[];t.record_extensions=hn(["md",...i])}return Array.isArray(t.explicit_type_keys)||(t.explicit_type_keys=["type","types"]),typeof t.include_subfolders!="boolean"&&(t.include_subfolders=!0),t.validation===void 0&&typeof t.default_validation=="string"&&(t.validation=t.default_validation),t.validation===void 0&&typeof e.default_validation=="string"&&(t.validation=e.default_validation),delete t.default_validation,delete t.extensions,delete e.default_validation,e}function o_(r,e){let t=_e(r.settings)?r.settings:{};return{spec_version:e,name:typeof r.name=="string"?r.name:void 0,description:typeof r.description=="string"?r.description:void 0,settings:{types_folder:typeof t.types_folder=="string"?t.types_folder:"_types",explicit_type_keys:Array.isArray(t.explicit_type_keys)?t.explicit_type_keys.filter(i=>typeof i=="string"):["type","types"],default_strict:t.default_strict===!0,include_subfolders:t.include_subfolders!==!1,exclude:Array.isArray(t.exclude)?t.exclude.filter(i=>typeof i=="string"):["_types",".obsidian",".git",".mdbase"]}}}function VT(r,e){var i,n;let t={};for(let[s,o]of Object.entries(_e(e.fields)?e.fields:{}))_e(o)&&(t[s]=Oe(o));return{name:typeof e.name=="string"?e.name:(n=(i=r.split("/").pop())==null?void 0:i.replace(/\.md$/,""))!=null?n:"type",fields:t,match:_e(e.match)?Oe(e.match):void 0,filePath:r,specProfile:"v0.2"}}function UT(r,e){var n,s;let t=_e(e.schema)?e.schema:{},i=_e(t.value)?t.value:{};return{name:typeof e.name=="string"?e.name:(s=(n=r.split("/").pop())==null?void 0:n.replace(/\.md$/,""))!=null?s:"type",fields:ci(i),match:_e(e.match)?Oe(e.match):void 0,collection:_e(e.collection)?Oe(e.collection):void 0,schema:Oe(i),filePath:r,specProfile:"v0.3"}}function zT(r,e,t){let i=Oe(r);for(let n of e){let s=t.get(n);if(s)for(let[o,a]of Object.entries(s.fields))!(o in i)&&a.default!==void 0&&(i[o]=Oe(a.default))}return i}function BT(r,e,t){var n,s;let i=Oe(r);for(let o of e){let a=t.get(o);if(a)for(let[c,l]of Object.entries((s=(n=a.collection)==null?void 0:n.read_defaults)!=null?s:{}))c in i||(i[c]=Oe(l))}return i}async function HT(r,e){let t=(0,Xe.normalizePath)(e).replace(/\/+$/,"");if(!t)return;let i="";for(let n of t.split("/")){i=i?`${i}/${n}`:n;let s=r.getAbstractFileByPath(i);if(!(s instanceof Xe.TFolder)){if(s)throw new Error(`A file blocks folder ${i}.`);await r.adapter.exists(i)||await r.createFolder(i)}}}async function Za(r,e,t){let i=(0,Xe.normalizePath)(e),n=i.lastIndexOf("/");if(n>=0&&await HT(r,i.slice(0,n)),i.startsWith(".mdbase/")){await r.adapter.write(i,t);return}let s=r.getAbstractFileByPath(i);if(s instanceof Xe.TFolder)throw new Error(`A folder blocks file ${i}.`);s instanceof Xe.TFile?await r.modify(s,t):await r.create(i,t)}async function zs(r,e){let t=(0,Xe.normalizePath)(e),i=r.getAbstractFileByPath(t);if(i instanceof Xe.TFile)return r.cachedRead(i);if(await r.adapter.exists(t))return r.adapter.read(t);throw new Error(`File not found: ${e}`)}async function a_(r){var S;let e=await zs(r,"mdbase.yaml"),t=(0,Xe.parseYaml)(e);if(!_e(t))throw new Error("mdbase.yaml must contain a YAML mapping.");let i=typeof t.spec_version=="string"?t.spec_version:"";if(!/^0\.2(?:\.\d+)?$/.test(i))throw new Error(i===Bs?"This collection is already mdbase v0.3.":`Expected an mdbase v0.2.x collection, found ${JSON.stringify(i)}.`);let n=_e(t.settings)?t.settings:{},s=typeof n.types_folder=="string"?(0,Xe.normalizePath)(n.types_folder):"_types",o=`${s}/`,a=[],c=[],l=[],u=FT(t),d=`${(0,Xe.stringifyYaml)(u).trimEnd()} -`;a.push({path:"mdbase.yaml",sourceDigest:vr(e),targetDigest:vr(d),source:e,target:d});let f=new Map,p=new Map;for(let v of r.getMarkdownFiles().filter(P=>P.path.startsWith(o)).sort((P,x)=>P.path.localeCompare(x.path))){let P=await r.cachedRead(v),x=Ue(P);if(!x.hasFrontmatter||x.error)throw new Error(`Cannot migrate ${v.path}: ${(S=x.error)!=null?S:"frontmatter is missing"}.`);let E=DT(v.path,i,x.frontmatter),R=VT(v.path,x.frontmatter),w=UT(v.path,E.target);f.set(R.name,R),p.set(w.name,w);let F=`${at(E.target,x.body)} -`;a.push({path:v.path,sourceDigest:vr(P),targetDigest:vr(F),source:P,target:F}),c.push(E.summary),l.push(...E.diagnostics)}if(!c.length)throw new Error(`No v0.2 type files were found in ${s}.`);let m=0,h=0,y=o_(t,i),b=o_(u,Bs),g=r.getMarkdownFiles().filter(v=>!v.path.startsWith(o)).filter(v=>!v.path.startsWith(".mdbase/")).sort((v,P)=>v.path.localeCompare(P.path));for(let[v,P]of g.entries()){let x=Ue(await r.cachedRead(P));if(x.error){h+=1;continue}let E=Ji(P.path,x.frontmatter,y,f),R=Ji(P.path,x.frontmatter,b,p),w=zT(x.frontmatter,E,f),F=BT(x.frontmatter,R,p);(bi(E.slice().sort())!==bi(R.slice().sort())||bi(w)!==bi(F))&&l.push({path:P.path,code:"effective_read_changed",message:"The proposed v0.3 types would change this record's resolved types or effective default values.",severity:"lossy"}),m+=1,v>0&&v%250===0&&await new Promise(V=>setTimeout(V,0))}let _=vr(bi({sourceVersion:i,operations:a.map(({path:v,sourceDigest:P,targetDigest:x})=>({path:v,sourceDigest:P,targetDigest:x})),diagnostics:l}));return{planVersion:1,analysisId:_,sourceVersion:i,targetVersion:Bs,createdAt:new Date().toISOString(),backupLocation:`.mdbase/migrations/v02-to-v03-${_.slice(0,12)}`,operations:a,typeSummaries:c,diagnostics:l,applicable:!l.some(v=>v.severity==="lossy"),recordFilesRewritten:0,recordsVerified:m,recordsSkipped:h}}async function Us(r,e,t){await Za(r,e,`${JSON.stringify(t,null,2)} -`)}async function c_(r,e,t={}){if(e.planVersion!==1||e.targetVersion!==Bs)throw new Error("Unsupported migration plan.");if(!e.applicable&&!t.allowLossy)throw new Error("This migration has lossy diagnostics. Review them and explicitly allow lossy migration.");for(let s of e.operations){let o=await zs(r,s.path);if(vr(o)!==s.sourceDigest)throw new Error(`${s.path} changed after migration analysis. Run the review again.`)}let i=`${e.backupLocation}/manifest.json`,n={manifest_version:1,analysis_id:e.analysisId,source_version:e.sourceVersion,target_version:e.targetVersion,status:"prepared",created_at:new Date().toISOString(),written:[],files:e.operations.map(s=>({path:s.path,source_digest:s.sourceDigest,target_digest:s.targetDigest,backup_path:`${e.backupLocation}/files/${s.path}`}))};for(let s of e.operations)await Za(r,`${e.backupLocation}/files/${s.path}`,s.source);await Us(r,i,n),n.status="applying",await Us(r,i,n);try{for(let s of e.operations){let o=await zs(r,s.path);if(vr(o)!==s.sourceDigest)throw new Error(`${s.path} changed during migration.`);n.written.push(s.path),await Us(r,i,n),await Za(r,s.path,s.target);let a=await zs(r,s.path);if(vr(a)!==s.targetDigest)throw new Error(`${s.path} did not verify after write.`)}return n.status="applied",n.completed_at=new Date().toISOString(),await Us(r,i,n),{applied:!0,restored:!1,manifestPath:i,written:[...n.written]}}catch(s){let o=[];for(let a of[...n.written].reverse()){let c=e.operations.find(l=>l.path===a);if(!c){o.push(a);continue}try{await Za(r,a,c.source),vr(await zs(r,a))!==c.sourceDigest&&o.push(a)}catch(l){o.push(a)}}n.status=o.length?"recovery_required":"rolled_back",n.error=s instanceof Error?s.message:String(s),n.manual_recovery_paths=o.length?o:void 0,n.completed_at=new Date().toISOString();try{await Us(r,i,n)}catch(a){}return{applied:!1,restored:o.length===0,manifestPath:i,written:[...n.written],error:n.error}}}var Qa=require("obsidian");function Pe(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function rr(r){return JSON.parse(JSON.stringify(r))}var KT=new Set(["file","formula","this"]);function GT(r){let e=r.trim();if(!e)throw new Error("Type name is required.");if(!/^[A-Za-z]/.test(e))throw new Error("Type name must start with a letter.");if(e.length>=64)throw new Error("Type name must be shorter than 64 characters.");if(!/^[A-Za-z][A-Za-z0-9_-]*$/.test(e))throw new Error("Type name may contain only letters, numbers, hyphens, and underscores.");if(KT.has(e.toLowerCase()))throw new Error(`Type name '${e}' is reserved.`);return e}function $f(){return{specProfile:"v0.3",originalFrontmatter:{},name:"",description:"",extendsType:"",displayNameKey:"",strictMode:!1,pathPattern:"",filenamePattern:"",matchPathGlob:"",matchFieldsPresent:"",matchWhere:"",fields:[{name:"title",definition:{type:"string",required:!0}}],body:`# Type +${t}`}function Lu(r,e){var s;let t=r.match(/^---[ \t]*\r?\n([\s\S]*?)^---[ \t]*(?:\r?\n|$)([\s\S]*)$/m);if(!t)return{frontmatter:{},body:r};let n;try{n=Nu(t[1])}catch(i){throw new O("invalid_frontmatter",`Writable mirror file ${e} has invalid YAML frontmatter.`)}if(n===null&&t[1].trim()===""&&(n={}),!n||typeof n!="object"||Array.isArray(n))throw new O("invalid_frontmatter",`Writable mirror file ${e} requires object frontmatter.`);return{frontmatter:n,body:(s=t[2])!=null?s:""}}function u0(r,e){return!(r instanceof O)||r.code!=="invalid_frontmatter"?null:{path:e,code:"invalid_frontmatter",message:r.message}}function f0(r,e){let t={...e};for(let n of Object.keys(r))n in e||(t[n]=null);return t}function Fu(r){let e=sn.create().update(dn.encode(`mdbase-authority-manifest-v1 +`));for(let t of[...r].sort((n,s)=>n.kind!==s.kind?n.kindHu)throw nt("Connect returned an invalid collection adoption request.");let d=k0(n,lt(u.verification_uri),lt(u.adoption_id));return{controlUrl:n,adoptionId:lt(u.adoption_id),credential:lt(u.adoption_secret),verificationUri:d,expiresAt:new Date(this.now()+Number(u.expires_in)*1e3).toISOString(),requested:{collectionId:s,displayName:i,sourceName:o,retainMirror:a,...c?{mirrorName:c}:{}}}}async start(e,t){let n=await this.begin(e,t),{credential:s,...i}=n;return await t.onVerification(i),{session:n,prepared:await this.waitForApproval(n,t)}}async waitForApproval(e,t={}){var o,a;os(e,this.now());let n=_0(t.pollIntervalMs),s=Date.parse(e.expiresAt),i=0;for(;this.now()=500){let l=un(c);if(!await this.retry(s,(a=c.retryAfterMs)!=null?a:n,i,t,{code:l.code,message:l.message}))break;continue}throw un(c)}throw new _e("authority_adoption_expired","Collection adoption approval expired before upload began.")}async exchange(e,t={}){os(e,this.now(),!0);let n=await this.controlRequest(e,"exchange","POST",{},t.signal);if(n.status===202)throw new _e("authority_adoption_pending","Collection adoption is still awaiting approval.",202);if(n.status!==200)throw un(n);return g0(e,n.body)}async uploadSnapshot(e,t,n,s={}){os(e,this.now(),!0),E0(e,t),y0(e,n);let i={protocol_version:1,collection_id:n.collection_id,source_head:n.source_head,source_revision:n.source_revision,manifest_digest:n.manifest_digest,resources:n.resources,record_count:n.records.length};await this.importRequest(t.import.manifest_url,"PUT",t.import.access_token,i,s.signal);let o=0,a=[],c=0;for(let l of n.records){let u=Br.encode(JSON.stringify(l)).length;if(u>p0)throw new _e("authority_adoption_record_too_large",`Record ${l.path} is too large to adopt.`);a.length>0&&(a.length===TP||c+u>p0)&&(await this.uploadPage(t.import,o,a,s.signal),o+=1,a=[],c=0),a.push(l),c+=u}a.length>0&&await this.uploadPage(t.import,o,a,s.signal),await this.importRequest(t.import.finalize_url,"POST",t.import.access_token,void 0,s.signal)}async complete(e,t,n={}){os(e,this.now(),!0),y0(e,t);let s;try{s=await this.controlRequest(e,"complete","POST",{manifest_digest:t.manifest_digest,source_revision:t.source_revision,source_head:t.source_head},n.signal)}catch(a){throw fn(n.signal),new pn("Connect could not confirm whether hosted authority activated.",{cause:a})}if(s.status>=500)throw new pn("Connect could not confirm whether hosted authority activated.");if(s.status!==200)throw un(s);let i=s.body;if(!gr(i)||i.status!=="completed")throw nt("Connect returned an invalid adoption completion.");let o=A0(e,i.adoption);if(o.state!=="completed"||o.manifest_digest!==t.manifest_digest||o.source_revision!==t.source_revision||o.final_head!==t.source_head)throw nt("Connect completed a different adoption snapshot.");return{status:"completed",adoption:o}}async cancel(e,t={}){os(e,this.now(),!0);let n=await this.controlRequest(e,void 0,"DELETE",void 0,t.signal);if(n.status!==200)throw un(n)}mirrorEnrollmentSession(e,t){var n;if(os(e,this.now(),!0),t.status!=="completed"||t.adoption.collection_id!==e.requested.collectionId)throw nt("Completed adoption does not belong to this session.");return e.requested.retainMirror?{controlUrl:e.controlUrl,pairingId:e.adoptionId,refreshCredential:e.credential,verificationUri:`${e.controlUrl}/mirror/${e.adoptionId}`,expiresAt:new Date(this.now()+Hu).toISOString(),requested:{mirrorName:(n=e.requested.mirrorName)!=null?n:e.requested.sourceName,mode:"read_write",collectionId:e.requested.collectionId}}:null}async uploadPage(e,t,n,s){let i={protocol_version:1,page:t,records:n};await this.importRequest(e.records_url,"PUT",e.access_token,i,s)}async importRequest(e,t,n,s,i){let o;try{o=await this.request({url:e,method:t,headers:{authorization:`Bearer ${n}`,...s===void 0?{}:{"content-type":"application/json"}},...s===void 0?{}:{body:s},...i?{signal:i}:{}})}catch(a){throw fn(i),w0()}if(o.status<200||o.status>=300)throw un(o)}controlRequest(e,t,n,s,i){return this.request({url:b0(e,t),method:n,headers:{authorization:`Bearer ${e.credential}`,...s===void 0?{}:{"content-type":"application/json"}},...s===void 0?{}:{body:s},...i?{signal:i}:{}})}async retry(e,t,n,s,i){var l;let o=e-this.now();if(o<=0)return!1;let a=Math.min(_0(t),o),c=new Date(this.now()+a).toISOString();return(l=s.onStatus)==null||l.call(s,{state:i?"retrying":"waiting_for_approval",attempt:n,expiresAt:new Date(e).toISOString(),retryAt:c,...i?{error:i}:{}}),await this.wait(a,s.signal),!0}},_e=class extends O{constructor(t,n,s,i){super(t,n);P(this,"status");this.status=s,this.name="AuthorityAdoptionError",(i==null?void 0:i.cause)!==void 0&&(this.cause=i.cause)}},pn=class extends _e{constructor(t,n){super("authority_adoption_outcome_unknown",t,void 0,n);P(this,"sourceMustRemainFenced",!0);this.name="AuthorityAdoptionOutcomeUnknownError"}};function $0(r){var l,u,d,f;let e=Na(r.collectionId,"Collection ID"),t=(l=r.sourceHead)!=null?l:0;if(!Number.isSafeInteger(t)||t<0)throw new _e("invalid_authority_snapshot","Source head must be a non-negative integer.");let n=new Set,s=r.resources.map(p=>{let m=zu(p.path);if(n.add(m)||m0(m),!["configuration","contract","schema","type","view"].includes(p.kind))throw new _e("invalid_authority_snapshot",`Unsupported collection resource kind for ${m}.`);return{path:m,kind:p.kind,revision:Vu(p.document),document:p.document}}).sort(OP);if(((u=s[0])==null?void 0:u.path)!=="mdbase.yaml"||s[0].kind!=="configuration"||s.filter(({kind:p})=>p==="configuration").length!==1)throw new _e("invalid_authority_snapshot","A portable snapshot requires one mdbase.yaml configuration resource.");let i=r.records.map(p=>{let m=zu(p.path);return n.add(m)||m0(m),{record_id:p.recordId?Na(p.recordId,`Record ID for ${m}`):PP(e,m),path:m,document:p.document}}).sort((p,m)=>S0(p.path,m.path)),o=h0(s.flatMap(({path:p,revision:m})=>[p,m])),a=h0([...s.flatMap(({path:p,revision:m})=>["resource",p,m]),...i.flatMap(p=>["record",p.path,Vu(p.document)])]),c=Fu([...s.map(({path:p,document:m})=>({kind:"resource",path:p,document_hash:Nr(sn(Br.encode(m)))})),...i.map(p=>({kind:"record",path:p.path,document_hash:Vu(p.document)}))]);return{protocol_version:1,collection_id:e,source_head:t,source_revision:a,manifest_digest:c,resources:{revision:o,spec_version:r.specVersion,types:(d=r.types)!=null?d:[],contracts:(f=r.contracts)!=null?f:[],documents:s},records:i}}function PP(r,e){let t=RP(Na(r,"Collection ID")),s=lb(new Uint8Array([...t,...Br.encode(zu(e))])).slice(0,16);s[6]=s[6]&15|80,s[8]=s[8]&63|128;let i=Nr(s);return`${i.slice(0,8)}-${i.slice(8,12)}-${i.slice(12,16)}-${i.slice(16,20)}-${i.slice(20)}`}function Vu(r){return`sha256:${Nr(sn(Br.encode(r)))}`}function h0(r){let e=sn.create();for(let t of r){let n=BigInt(Br.encode(t).length),s=new Uint8Array(8);new DataView(s.buffer).setBigUint64(0,n),e.update(s),e.update(Br.encode(t))}return`sha256:${Nr(e.digest())}`}function OP(r,e){return r.kind==="configuration"&&e.kind!=="configuration"?-1:e.kind==="configuration"&&r.kind!=="configuration"?1:S0(r.path,e.path)}function S0(r,e){let t=Br.encode(r),n=Br.encode(e),s=Math.min(t.length,n.length);for(let i=0;i!t||t==="."||t===".."))throw new _e("invalid_authority_snapshot",`Collection path is unsafe: ${r}`);return e}function m0(r){throw new _e("invalid_authority_snapshot",`Collection snapshot contains the path more than once: ${r}`)}function RP(r){return Uint8Array.from(r.replaceAll("-","").match(/../g).map(e=>Number.parseInt(e,16)))}function os(r,e,t=!1){dr(r.controlUrl);let n=Date.parse(r.expiresAt);if(!Ra.test(r.adoptionId)||!I0(r.credential)||!Number.isFinite(n)||n-e>Hu||!t&&n<=e||!Ra.test(r.requested.collectionId)||!r.requested.displayName.trim()||!r.requested.sourceName.trim())throw new _e("invalid_authority_adoption_session","Stored collection adoption state is invalid.");k0(r.controlUrl,r.verificationUri,r.adoptionId)}function E0(r,e){if(e.status!=="ready"||e.adoption.id!==r.adoptionId||e.adoption.collection_id!==r.requested.collectionId)throw nt("Prepared adoption does not belong to this session.");for(let[t,n]of Object.entries(e.import))if(!n||t!=="access_token"&&!CP(n))throw nt("Connect returned an invalid authority import capability.")}function y0(r,e){var t;if(e.protocol_version!==1||e.collection_id!==r.requested.collectionId||!Number.isSafeInteger(e.source_head)||e.source_head<0||!xP.test(e.source_revision)||!IP.test(e.manifest_digest)||((t=e.resources.documents)==null?void 0:t.length)===0)throw new _e("invalid_authority_snapshot","Authority snapshot does not belong to this adoption.")}function g0(r,e){if(!gr(e)||!["ready","activating","completed"].includes(lt(e.status)))throw nt("Connect returned an invalid adoption exchange.");let t=A0(r,e.adoption);if(e.status==="completed")return{status:"completed",adoption:t};if(e.status==="activating")return{status:"activating",adoption:t};if(!gr(e.import)||!gr(e.staged))throw nt("Connect omitted the authority import capability.");let n=e.import,s=e.staged,i={status:"ready",adoption:t,import:{manifest_url:lt(n.manifest_url),records_url:lt(n.records_url),finalize_url:lt(n.finalize_url),access_token:lt(n.access_token)},staged:{state:s.state,manifest_digest:v0(s.manifest_digest),source_revision:v0(s.source_revision),source_head:jP(s.source_head)}};if(E0(r,i),!["receiving","uploaded"].includes(i.staged.state))throw nt("Connect returned an invalid staged import state.");return i}function A0(r,e){if(!gr(e))throw nt("Connect omitted collection adoption state.");let t=e;if(t.id!==r.adoptionId||t.collection_id!==r.requested.collectionId||!["requested","approved","prepared","activating","completed","cancelled","expired"].includes(t.state)||!Number.isSafeInteger(t.authority_epoch)||t.authority_epoch<2||!DP(t.expires_at))throw nt("Connect returned invalid collection adoption state.");return t}function CP(r){try{let e=new URL(r);return(e.protocol==="https:"||e.protocol==="http:"&&["localhost","127.0.0.1","[::1]","::1"].includes(e.hostname))&&!e.username&&!e.password&&!e.search&&!e.hash&&/^\/v1\/authority-imports\/[0-9a-f-]+\/(manifest|records|finalize)$/i.test(e.pathname)}catch(e){return!1}}function k0(r,e,t){let n;try{n=new URL(e)}catch(i){throw nt("Connect returned an invalid adoption verification URI.")}let s=new URL(`/adopt/${encodeURIComponent(t)}`,r);if(n.origin!==s.origin||n.pathname!==s.pathname||n.search||n.hash||n.username||n.password)throw nt("Connect returned an untrusted adoption verification URI.");return n.href}function b0(r,e){let t=e?`/${e}`:"";return`${dr(r.controlUrl)}/v1/authority-adoptions/${encodeURIComponent(r.adoptionId)}${t}`}function Na(r,e){if(!Ra.test(r))throw new _e("invalid_authority_adoption",`${e} must be a UUID.`);return r.toLowerCase()}function Uu(r,e){let t=r.trim();if(!t||t.length>200)throw new _e("invalid_authority_adoption",`${e} must contain between 1 and 200 characters.`);return t}function NP(r,e){if(r.status!==e)throw un(r);return r.body}function un(r){let e=gr(r.body)&&gr(r.body.error)?r.body.error:{};return new _e(lt(e.code)||"authority_adoption_request_failed",lt(e.message)||`Collection adoption request failed with status ${r.status}.`,r.status)}function nt(r){return new _e("invalid_authority_adoption_response",r)}function x0(r){return{code:"authority_adoption_unreachable",message:"Connect could not be reached for collection adoption."}}function w0(){let r=x0(void 0);return new _e(r.code,r.message)}function _0(r=Bu){return Number.isFinite(r)?Math.min(3e4,Math.max(250,Math.round(r))):Bu}function MP(r,e){return fn(e),new Promise((t,n)=>{let s=setTimeout(o,r),i=()=>{clearTimeout(s),e==null||e.removeEventListener("abort",i),n(new _e("authority_adoption_cancelled","Collection adoption was cancelled."))};function o(){e==null||e.removeEventListener("abort",i),t()}e==null||e.addEventListener("abort",i,{once:!0})})}function fn(r){if(r!=null&&r.aborted)throw new _e("authority_adoption_cancelled","Collection adoption was cancelled.")}async function LP(r){let e=await fetch(r.url,{method:r.method,headers:r.headers,...r.body===void 0?{}:{body:JSON.stringify(r.body)},...r.signal?{signal:r.signal}:{}}),t=await e.json().catch(()=>({})),n=e.headers.get("retry-after");return{status:e.status,body:t,...n?{retryAfterMs:qP(n)}:{}}}function qP(r){let e=Number(r);if(Number.isFinite(e)&&e>=0)return e*1e3;let t=Date.parse(r);return Number.isFinite(t)?Math.max(0,t-Date.now()):Bu}function DP(r){return Number.isFinite(Date.parse(r))}function v0(r){return r===null?null:lt(r)}function jP(r){return r===null?null:typeof r=="number"&&Number.isSafeInteger(r)&&r>=0?r:Number.NaN}function FP(r){return typeof r=="number"&&Number.isSafeInteger(r)&&r>0}function I0(r){return typeof r=="string"&&r.length>=16}function lt(r){return typeof r=="string"?r:""}function gr(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}var xi=".mdbase/connect-role.json",Ii=".mdbase/authority-adoption.json",Ti=".mdbase/authority-adoption-snapshot.json",VP="mdbase-obsidian-connect",as="mirrors",UP="mdbase-connect-access-",BP="mdbase-connect-refresh-",HP="mdbase-connect-adoption-",zP=300*1e3,P0=[".git/",".obsidian/",".trash/",".mdbase/"],Pi=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function st(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function Qu(r,e){if(e!=null)return e;if(!r.trim())return{};try{return JSON.parse(r)}catch(t){return{}}}function O0(r){var s;let e=(s=r["retry-after"])!=null?s:r["Retry-After"];if(!e)return;let t=Number(e);if(Number.isFinite(t)&&t>=0)return t*1e3;let n=Date.parse(e);if(Number.isFinite(n))return Math.max(0,n-Date.now())}function KP(){return async r=>{var t,n;if((t=r.signal)!=null&&t.aborted)throw new DOMException("Enrollment cancelled.","AbortError");let e=await(0,le.requestUrl)({url:r.url,method:r.method,headers:r.headers,body:r.body===void 0?void 0:JSON.stringify(r.body),contentType:r.body===void 0?void 0:"application/json",throw:!1});if((n=r.signal)!=null&&n.aborted)throw new DOMException("Enrollment cancelled.","AbortError");return{status:e.status,body:Qu(e.text,e.json),retryAfterMs:O0(e.headers)}}}function GP(){return async r=>{var t,n;if((t=r.signal)!=null&&t.aborted)throw new DOMException("Collection adoption cancelled.","AbortError");let e=await(0,le.requestUrl)({url:r.url,method:r.method,headers:r.headers,body:r.body===void 0?void 0:JSON.stringify(r.body),contentType:r.body===void 0?void 0:"application/json",throw:!1});if((n=r.signal)!=null&&n.aborted)throw new DOMException("Collection adoption cancelled.","AbortError");return{status:e.status,body:Qu(e.text,e.json),retryAfterMs:O0(e.headers)}}}var Wu=class{constructor(e,t){this.accessToken=t;let n;try{n=new URL(e)}catch(s){throw new O("invalid_sync_url","Sync URL must be an absolute authority endpoint.")}if(!(n.protocol==="https:"||n.protocol==="http:"&&["localhost","127.0.0.1","[::1]","::1"].includes(n.hostname))||n.username||n.password||n.search||n.hash||!/^\/v1\/authorities\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\/sync\/?$/i.test(n.pathname))throw new O("invalid_sync_url","Sync URL must identify one authority sync endpoint.");this.syncUrl=n.href.replace(/\/$/,"")}openSession(){return this.request("POST","sessions")}snapshot(e,t){let n=new URLSearchParams({snapshot_id:e});return t&&n.set("page",t),this.request("GET",`snapshot?${n.toString()}`)}changes(e,t=200){let n=new URLSearchParams({after:String(e),limit:String(t)});return this.request("GET",`changes?${n.toString()}`)}mutate(e){return this.request("POST","mutations",e)}async request(e,t,n){let s=await(0,le.requestUrl)({url:`${this.syncUrl}/${t}`,method:e,headers:{authorization:`Bearer ${this.accessToken}`},body:n===void 0?void 0:JSON.stringify(n),contentType:n===void 0?void 0:"application/json",throw:!1}),i=Qu(s.text,s.json);if(s.status<200||s.status>=300){let o=st(i)&&st(i.error)?i.error:{};throw new O(typeof o.code=="string"?o.code:"sync_failed",typeof o.message=="string"?o.message:`Sync request failed (${s.status}).`)}return i}};function Ku(r){let e=ri(r);if(e===".mdbase"||P0.some(t=>e.startsWith(t)))throw new O("unsafe_mirror_path",`The collection authority attempted to write a reserved path: ${e}`);return e}async function Ma(r,e){let t=(0,le.normalizePath)(e).replace(/\/+$/,"");if(!t)return;let n="";for(let s of t.split("/")){n=n?`${n}/${s}`:s;let i=r.getAbstractFileByPath(n);if(!(i instanceof le.TFolder)){if(i)throw new O("mirror_path_collision",`A file blocks the mirror folder ${n}.`);await r.adapter.exists(n)||await r.createFolder(n)}}}var Ju=class{constructor(e){this.vault=e}async read(e){let t=Ku(e),n=this.vault.getAbstractFileByPath(t);if(n==null)return null;if(!(n instanceof le.TFile))throw new O("mirror_path_collision",`Expected a file at ${t}.`);return this.vault.cachedRead(n)}async write(e,t){let n=Ku(e),s=n.lastIndexOf("/");s>=0&&await Ma(this.vault,n.slice(0,s));let i=this.vault.getAbstractFileByPath(n);if(i instanceof le.TFolder)throw new O("mirror_path_collision",`A folder blocks the mirror file ${n}.`);i instanceof le.TFile?await this.vault.modify(i,t):await this.vault.create(n,t)}async remove(e){let t=Ku(e),n=this.vault.getAbstractFileByPath(t);if(n!=null){if(!(n instanceof le.TFile))throw new O("mirror_path_collision",`Expected a file at ${t}.`);await this.vault.delete(n,!0)}}async listMarkdown(e){return this.vault.getMarkdownFiles().map(t=>(0,le.normalizePath)(t.path)).filter(t=>!e.has(t)).filter(t=>!P0.some(n=>t.startsWith(n))).sort()}},Yu=class{constructor(e){this.key=e;this.database=null}async read(){let e=await this.open();return new Promise((t,n)=>{let s=e.transaction(as,"readonly").objectStore(as).get(this.key);s.onsuccess=()=>{var i;return t((i=s.result)!=null?i:null)},s.onerror=()=>n(s.error)})}async write(e){let t=await this.open();await new Promise((n,s)=>{let i=t.transaction(as,"readwrite");i.objectStore(as).put(e,this.key),i.oncomplete=()=>n(),i.onerror=()=>s(i.error),i.onabort=()=>s(i.error)})}open(){var e;if(typeof indexedDB=="undefined")throw new O("storage_unavailable","IndexedDB is required for persistent mirror state.");return(e=this.database)!=null||(this.database=new Promise((t,n)=>{let s=indexedDB.open(VP,1);s.onupgradeneeded=()=>{s.result.objectStoreNames.contains(as)||s.result.createObjectStore(as)},s.onerror=()=>n(s.error),s.onsuccess=()=>t(s.result)})),this.database}},cs=class cs{constructor(e){this.key=e}async runExclusive(e){if(cs.active.has(this.key))throw new O("mirror_busy","A mirror operation is already running for this vault.");cs.active.add(this.key);try{return await e()}finally{cs.active.delete(this.key)}}};cs.active=new Set;var Xu=cs,La=class{constructor(e,t,n={}){this.app=e;this.settingsHost=t;this.options=n;this.progress=null;this.adoptionMarker=null;var s,i,o;this.fileSystem=(s=n.fileSystem)!=null?s:new Ju(e.vault),this.enrollmentClient=(i=n.enrollmentClient)!=null?i:new Wo({request:KP()}),this.adoptionClient=(o=n.adoptionClient)!=null?o:new Ca({request:GP()})}async initialize(){if(this.adoptionMarker=await this.readAdoptionMarker(),this.adoptionMarker&&this.settingsHost.getMirrorProfile())throw new O("authority_adoption_state_conflict","This vault contains both an authority-adoption checkpoint and a mirror profile.")}getProgress(){return this.progress?{...this.progress}:null}getAdoptionMarker(){return this.adoptionMarker?JSON.parse(JSON.stringify(this.adoptionMarker)):null}assertLocalAuthorityWritable(){if(this.adoptionMarker&&["fenced","activating","adopted"].includes(this.adoptionMarker.phase))throw new O("local_authority_fenced",this.adoptionMarker.phase==="adopted"?"Hosted mdbase is now authoritative. Finish reconnecting this vault as its mirror before editing.":"This local authority is frozen while its exact snapshot is adopted by hosted mdbase.")}async adoptLocalCollection(e,t){if(this.settingsHost.getMirrorProfile())throw new O("mirror_already_configured","This vault already mirrors a collection authority.");if(this.adoptionMarker)return this.resumeAdoption(t);let n=await this.ensurePortableCollectionIdentity(),s=await this.adoptionClient.begin({controlUrl:e.controlUrl,collectionId:n.collectionId,displayName:n.displayName,sourceName:e.mirrorName,retainMirror:!0,mirrorName:e.mirrorName},t);return await this.storeAdoptionSecret(s),await this.writeAdoptionMarker({version:1,phase:"waiting_for_approval",session:Gu(s),manifest_digest:null,source_revision:null,source_head:null}),await t.onVerification(Gu(s)),this.runAdoptionWithRecovery(s,t)}async resumeAdoption(e={}){var i,o,a;let t=(i=this.adoptionMarker)!=null?i:await this.readAdoptionMarker();if(!t)throw new O("authority_adoption_not_found","This vault has no collection-adoption checkpoint.");this.adoptionMarker=t;let n=this.app.secretStorage.getSecret(this.adoptionSecretId(t.session.adoptionId));if(!n)throw new O("authority_adoption_credentials_missing","The collection-adoption credential is missing from Obsidian's secret store.");let s={...t.session,credential:n};return t.phase==="waiting_for_approval"&&await((o=e.onVerification)==null?void 0:o.call(e,Gu(s))),this.runAdoptionWithRecovery(s,{...e,onVerification:(a=e.onVerification)!=null?a:(()=>{})})}async cancelAdoption(e){var s;let t=(s=this.adoptionMarker)!=null?s:await this.readAdoptionMarker();if(!t)return;if(["activating","adopted"].includes(t.phase))throw new O("authority_adoption_activation_started","Hosted activation has started and must be resumed; it can no longer be cancelled.");let n=this.app.secretStorage.getSecret(this.adoptionSecretId(t.session.adoptionId));if(!n)throw new O("authority_adoption_credentials_missing","The collection-adoption credential is missing from Obsidian's secret store.");await this.adoptionClient.cancel({...t.session,credential:n},{signal:e}),await this.clearAdoptionCheckpoint(t.session.adoptionId)}async enroll(e,t){let n=await this.assertCanBecomeMirror(e.collectionId),s=await this.enrollmentClient.enroll({...e,...n?{collectionId:n}:{}},t),i=await this.markMirror(s.collectionId);try{await this.persistEnrollment(s)}catch(o){if(i)try{await this.app.vault.adapter.remove(xi)}catch(a){throw new O("enrollment_recovery_required",`Enrollment settings could not be saved and the temporary role marker could not be removed: ${o instanceof Error?o.message:String(o)}`)}throw o}return this.requireProfile()}async preview(){return(await this.createMirror()).previewInitialization()}async status(){let e=this.settingsHost.getMirrorProfile();return e?(await this.assertMirror(e.collectionId),(await this.createMirror()).status()):null}async sync(e){let t=await this.createMirror(n=>{this.progress=n,e==null||e({...n})});try{return await t.sync(),t.status()}finally{this.progress=null}}async resolveConflict(e,t){let n=await this.createMirror();return await n.resolveConflict(e,t),n.status()}async runAdoption(e,t){let n=this.requireAdoptionMarker(e.adoptionId),s=null;if(n.phase==="adopted"){let i=await this.adoptionClient.exchange(e,t);if(i.status!=="completed")throw new O("authority_adoption_state_conflict","The local checkpoint says adoption completed, but Connect does not.");s=i}else if(n.phase==="activating"){let i=await this.readAdoptionSnapshot(n),o=await this.adoptionClient.exchange(e,t);s=o.status==="completed"?o:await this.adoptionClient.complete(e,i,t)}else if(n.phase==="fenced"){let i=await this.readAdoptionSnapshot(n),o=await this.adoptionClient.exchange(e,t);o.status==="completed"?s=o:(o.status==="ready"&&await this.adoptionClient.uploadSnapshot(e,o,i,t),await this.updateAdoptionPhase("activating",i),s=await this.adoptionClient.complete(e,i,t))}else{let i=n.phase==="waiting_for_approval"?await this.adoptionClient.waitForApproval(e,t):await this.requirePreparedAdoption(e,t);await this.updateAdoptionPhase("uploading");let o=await this.captureAuthoritySnapshot(e.requested.collectionId);await this.adoptionClient.uploadSnapshot(e,i,o,t);let a=await this.captureAuthoritySnapshot(e.requested.collectionId);await this.writeAdoptionSnapshot(a),await this.updateAdoptionPhase("fenced",a);let c=await this.requirePreparedAdoption(e,t);await this.adoptionClient.uploadSnapshot(e,c,a,t),await this.updateAdoptionPhase("activating",a),s=await this.adoptionClient.complete(e,a,t)}return await this.updateAdoptionPhase("adopted"),this.finishRetainedMirror(e,s,t)}async runAdoptionWithRecovery(e,t){try{return await this.runAdoption(e,t)}catch(n){throw WP(n)?(await this.adoptionClient.cancel(e,{signal:t.signal}).catch(()=>{}),await this.clearAdoptionCheckpoint(e.adoptionId),new O(n.code,"This adoption ended before hosted activation. The vault remains the writable local authority; start a new adoption to try again.")):n}}async requirePreparedAdoption(e,t){let n=await this.adoptionClient.exchange(e,t);if(n.status==="ready")return n;throw n.status==="activating"?new pn("Hosted authority activation has already started. Resume using the saved fenced snapshot."):new O("authority_adoption_already_completed","Hosted authority has already adopted this collection.")}async finishRetainedMirror(e,t,n){var a,c;let s,i=this.adoptionClient.mirrorEnrollmentSession(e,t);if(!i)throw new O("authority_adoption_mirror_missing","Hosted authority activated without retaining this vault as a mirror.");try{s=await this.enrollmentClient.waitForApproval(i,{signal:n.signal,onStatus:l=>{var u;return(u=n.onStatus)==null?void 0:u.call(n,{...l,state:l.state})}})}catch(l){if((a=n.signal)!=null&&a.aborted)throw l;s=await this.enrollmentClient.enroll({controlUrl:e.controlUrl,collectionId:e.requested.collectionId,mirrorName:(c=e.requested.mirrorName)!=null?c:e.requested.sourceName,mode:"read_write"},{signal:n.signal,onVerification:n.onVerification})}let o=await this.markMirror(s.collectionId);try{await this.persistEnrollment(s)}catch(l){throw o&&await this.app.vault.adapter.remove(xi),l}return await this.clearAdoptionCheckpoint(e.adoptionId),this.requireProfile()}async captureAuthoritySnapshot(e){let t=await zn(this.app.vault);if(!t)throw new O("invalid_collection_configuration","A valid mdbase.yaml is required.");let n=await this.app.vault.adapter.read("mdbase.yaml"),s=(0,le.parseYaml)(n),i=[{path:"mdbase.yaml",kind:"configuration",document:n}],o=`${(0,le.normalizePath)(t.settings.types_folder)}/`,a=this.app.vault.getMarkdownFiles().filter(u=>(0,le.normalizePath)(u.path).startsWith(o)).sort((u,d)=>u.path.localeCompare(d.path));for(let u of a)i.push({path:(0,le.normalizePath)(u.path),kind:"type",document:await this.app.vault.cachedRead(u)});let c=JP(s);if(c.length){let u=c.map(f=>(0,T0.default)(f,{dot:!0})),d=YP(this.app.vault).filter(f=>f.extension==="base").filter(f=>u.some(p=>p((0,le.normalizePath)(f.path)))).sort((f,p)=>f.path.localeCompare(p.path));for(let f of d)i.push({path:(0,le.normalizePath)(f.path),kind:"view",document:await this.app.vault.cachedRead(f)})}let l=[];for(let u of this.app.vault.getMarkdownFiles().sort((d,f)=>d.path.localeCompare(f.path))){let d=(0,le.normalizePath)(u.path);if(ni(d,t))continue;let f=await this.app.vault.cachedRead(u),p=tt(f);if(p.error)throw new O("invalid_authority_record",`${d} has invalid frontmatter: ${p.error}`);l.push({path:d,document:f})}return $0({collectionId:e,sourceHead:0,specVersion:t.spec_version,resources:i,records:l})}async ensurePortableCollectionIdentity(){if(!await this.app.vault.adapter.exists("mdbase.yaml"))throw new O("collection_not_initialized","Initialize an mdbase collection before hosting it.");let e=await this.app.vault.adapter.read("mdbase.yaml"),t;try{t=(0,le.parseYaml)(e)}catch(o){throw new O("invalid_collection_configuration","mdbase.yaml must contain valid YAML.")}if(!st(t))throw new O("invalid_collection_configuration","mdbase.yaml must contain a YAML mapping.");let n=st(t["x-mdbase-connect"])?t["x-mdbase-connect"].collection_id:void 0,s;if(n===void 0){s=crypto.randomUUID();let o=st(t["x-mdbase-connect"])?t["x-mdbase-connect"]:{};t["x-mdbase-connect"]={...o,collection_id:s},await this.app.vault.adapter.write("mdbase.yaml",(0,le.stringifyYaml)(t))}else if(typeof n=="string"&&Pi.test(n))s=n;else throw new O("invalid_collection_configuration","x-mdbase-connect.collection_id must be a UUID string.");let i=typeof t.name=="string"&&t.name.trim()?t.name.trim():this.app.vault.getName();return{collectionId:s,displayName:i}}async createMirror(e){var o,a,c,l,u,d,f,p,m;let t=this.requireProfile();await this.assertMirror(t.collectionId);let n=await this.freshAccessToken(t),s=(c=(a=(o=this.options).transportFactory)==null?void 0:a.call(o,t,n))!=null?c:new Wu(t.syncUrl,n),i={stateStore:(d=(u=(l=this.options).stateStoreFactory)==null?void 0:u.call(l,t))!=null?d:new Yu(`${t.collectionId}:${t.replicaId}`),fileSystem:this.fileSystem,lease:(m=(p=(f=this.options).leaseFactory)==null?void 0:p.call(f,t))!=null?m:new Xu(`${t.collectionId}:${t.replicaId}`),onProgress:e};return t.mode==="read_write"?new Oa(t.replicaId,s,i):new ki(t.replicaId,s,i)}requireProfile(){let e=this.settingsHost.getMirrorProfile();if(!e)throw new O("mirror_not_configured","This vault is not connected to a collection authority.");return e}accessSecretId(e){return`${UP}${e.toLowerCase()}`}refreshSecretId(e){return`${BP}${e.toLowerCase()}`}adoptionSecretId(e){return`${HP}${e.toLowerCase()}`}async storeAdoptionSecret(e){this.app.secretStorage.setSecret(this.adoptionSecretId(e.adoptionId),e.credential)}async persistEnrollment(e){this.app.secretStorage.setSecret(this.accessSecretId(e.collectionId),e.accessToken),this.app.secretStorage.setSecret(this.refreshSecretId(e.collectionId),e.refreshCredential),await this.settingsHost.saveMirrorProfile({version:1,syncUrl:e.syncUrl,controlUrl:e.controlUrl,collectionId:e.collectionId,replicaId:e.replicaId,mode:e.mode,name:e.name,enrollmentId:e.enrollmentId,accessTokenExpiresAt:e.accessTokenExpiresAt})}async freshAccessToken(e){let t=this.accessSecretId(e.collectionId),n=this.app.secretStorage.getSecret(t),s=Date.parse(e.accessTokenExpiresAt);if(n&&Number.isFinite(s)&&s-Date.now()>zP)return n;let i=this.app.secretStorage.getSecret(this.refreshSecretId(e.collectionId));if(!i)throw new O("mirror_credentials_missing","The mirror refresh credential is missing. Re-enroll this vault.");let o=await this.enrollmentClient.renew({controlUrl:e.controlUrl,syncUrl:e.syncUrl,collectionId:e.collectionId,replicaId:e.replicaId,mode:e.mode,name:e.name,enrollmentId:e.enrollmentId,accessToken:n!=null?n:"",refreshCredential:i,accessTokenExpiresAt:e.accessTokenExpiresAt});return await this.persistEnrollment(o),o.accessToken}async assertCanBecomeMirror(e){var o;let t=await this.readMarker(),n=await this.readPortableCollectionId();if(n&&!t)throw new O("local_authority_requires_transfer","This vault has a local Connect identity. Transfer authority explicitly before using it as a mirror.");if(n&&(t==null?void 0:t.collection_id)!==n)throw new O("mirror_identity_conflict","The vault identity and mirror role marker identify different collections.");let s=this.settingsHost.getMirrorProfile(),i=(o=s==null?void 0:s.collectionId)!=null?o:e;if(t&&i&&t.collection_id!==i)throw new O("mirror_identity_conflict","This vault is already marked as a different mirror.");if(!t&&!s&&await this.app.vault.adapter.exists("mdbase.yaml"))throw new O("existing_collection_requires_transfer","This vault already contains an mdbase collection. Connect an empty vault, or transfer collection authority explicitly.");return i!=null?i:t==null?void 0:t.collection_id}async readPortableCollectionId(){if(!await this.app.vault.adapter.exists("mdbase.yaml"))return null;let e;try{e=(0,le.parseYaml)(await this.app.vault.adapter.read("mdbase.yaml"))}catch(s){throw new O("invalid_collection_configuration","mdbase.yaml must contain valid YAML.")}if(!st(e))throw new O("invalid_collection_configuration","mdbase.yaml must contain a YAML mapping.");let t=e["x-mdbase-connect"];if(t===void 0)return null;if(!st(t))throw new O("invalid_collection_configuration","x-mdbase-connect must be a YAML mapping.");let n=t.collection_id;if(n===void 0)return null;if(typeof n!="string"||!Pi.test(n))throw new O("invalid_collection_configuration","x-mdbase-connect.collection_id must be a UUID string.");return n}async markMirror(e){let t=await this.readMarker();if(t){if(t.collection_id!==e)throw new O("mirror_identity_conflict","This vault already mirrors a different collection authority.");return!1}return await Ma(this.app.vault,".mdbase"),await this.app.vault.adapter.write(xi,`${JSON.stringify({version:1,role:"mirror",collection_id:e},null,2)} +`),!0}async assertMirror(e){let t=await this.readMarker();if(!t||t.collection_id!==e)throw new O("mirror_marker_missing","The vault's mirror role marker is missing or does not match this connection.")}async readMarker(){if(!await this.app.vault.adapter.exists(xi))return null;let e;try{e=JSON.parse(await this.app.vault.adapter.read(xi))}catch(t){throw new O("invalid_mirror_marker","The mirror role marker is corrupt.")}if(!st(e)||e.version!==1||e.role!=="mirror"||typeof e.collection_id!="string"||!Pi.test(e.collection_id))throw new O("invalid_mirror_marker","The mirror role marker is invalid.");return e}requireAdoptionMarker(e){if(!this.adoptionMarker||this.adoptionMarker.session.adoptionId!==e)throw new O("authority_adoption_state_conflict","The collection-adoption checkpoint does not match this approval.");return this.adoptionMarker}async updateAdoptionPhase(e,t){if(!this.adoptionMarker)throw new O("authority_adoption_not_found","Collection-adoption checkpoint is missing.");await this.writeAdoptionMarker({...this.adoptionMarker,phase:e,...t?{manifest_digest:t.manifest_digest,source_revision:t.source_revision,source_head:t.source_head}:{}})}async writeAdoptionMarker(e){await Ma(this.app.vault,".mdbase"),await this.app.vault.adapter.write(Ii,`${JSON.stringify(e,null,2)} +`),this.adoptionMarker=e}async readAdoptionMarker(){if(!await this.app.vault.adapter.exists(Ii))return null;let e;try{e=JSON.parse(await this.app.vault.adapter.read(Ii))}catch(t){throw new O("invalid_authority_adoption_checkpoint","The collection-adoption checkpoint is corrupt.")}if(!XP(e))throw new O("invalid_authority_adoption_checkpoint","The collection-adoption checkpoint is invalid.");return e}async writeAdoptionSnapshot(e){await Ma(this.app.vault,".mdbase"),await this.app.vault.adapter.write(Ti,JSON.stringify(e))}async readAdoptionSnapshot(e){if(!await this.app.vault.adapter.exists(Ti))throw new O("authority_adoption_snapshot_missing","The fenced authority snapshot is missing; hosted activation cannot be resumed safely.");let t;try{t=JSON.parse(await this.app.vault.adapter.read(Ti))}catch(n){throw new O("invalid_authority_adoption_snapshot","The fenced authority snapshot is corrupt.")}if(t.collection_id!==e.session.requested.collectionId||t.manifest_digest!==e.manifest_digest||t.source_revision!==e.source_revision||t.source_head!==e.source_head)throw new O("authority_adoption_snapshot_mismatch","The fenced authority snapshot does not match its durable checkpoint.");return t}async clearAdoptionCheckpoint(e){await this.app.vault.adapter.exists(Ii)&&await this.app.vault.adapter.remove(Ii),await this.app.vault.adapter.exists(Ti)&&await this.app.vault.adapter.remove(Ti),this.app.secretStorage.setSecret(this.adoptionSecretId(e),""),this.adoptionMarker=null}};function Gu(r){let{credential:e,...t}=r;return t}function WP(r){return r instanceof _e&&["authority_adoption_expired","authority_adoption_cancelled"].includes(r.code)}function JP(r){if(!st(r))return[];let e=r["x-obsidian"];return!st(e)||!st(e.bases)||!Array.isArray(e.bases.include)?[]:e.bases.include.filter(t=>typeof t=="string")}function YP(r){var s;let e=(s=r.getFiles)==null?void 0:s.call(r);if(e)return e;let t=[],n=i=>{for(let o of i.children)o instanceof le.TFile?t.push(o):o instanceof le.TFolder&&n(o)};return n(r.getRoot()),t}function XP(r){if(!st(r)||r.version!==1||!["waiting_for_approval","uploading","fenced","activating","adopted"].includes(String(r.phase))||!st(r.session))return!1;let e=r.session;return typeof e.controlUrl=="string"&&typeof e.adoptionId=="string"&&Pi.test(e.adoptionId)&&typeof e.verificationUri=="string"&&typeof e.expiresAt=="string"&&st(e.requested)&&typeof e.requested.collectionId=="string"&&Pi.test(e.requested.collectionId)&&typeof e.requested.displayName=="string"&&typeof e.requested.sourceName=="string"&&e.requested.retainMirror===!0&&(r.manifest_digest===null||typeof r.manifest_digest=="string")&&(r.source_revision===null||typeof r.source_revision=="string")&&(r.source_head===null||Number.isSafeInteger(r.source_head))}var Je=require("obsidian");var Ni="0.3.0",QP=new Set(["name","description","display_name_key","strict","path_pattern","filename_pattern","match","fields","extends"]),ZP=new Set(["type","required","default","description","values","items","fields","min","max","min_length","max_length","pattern","unique","deprecated","generated","computed","target","validate_exists","tn_role","tn_completed_values"]);function be(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function Oe(r){return r===void 0?r:JSON.parse(JSON.stringify(r))}function br(r){return ju.digest(r)}function hn(r){return Array.isArray(r)?`[${r.map(hn).join(",")}]`:be(r)?`{${Object.keys(r).sort().map(e=>`${JSON.stringify(e)}:${hn(r[e])}`).join(",")}}`:JSON.stringify(r)}function Zu(r){if(Array.isArray(r))return r.map(Zu);if(!be(r))return r;let e={};for(let[t,n]of Object.entries(r)){let s=Zu(n);s!=null&&(Array.isArray(s)&&s.length===0||be(s)&&Object.keys(s).length===0||(e[t]=s))}return e}function ls(r){return[...new Set(r)]}function eO(r){return be(r.fields)?Object.values(r.fields).some(e=>be(e)&&(typeof e.tn_role=="string"||Array.isArray(e.tn_completed_values))):!1}function ef(r,e,t){let n=be(e)?e:{},s={},i={},o=[],a;switch(n.type){case"any":a={};break;case"string":case"integer":case"number":case"boolean":a={type:n.type};break;case"date":case"datetime":case"time":a={type:"string",format:n.type==="datetime"?"date-time":n.type};break;case"enum":a={enum:Array.isArray(n.values)?Oe(n.values):[]};break;case"link":a={type:"string"},s[r]={target_type:typeof n.target=="string"?n.target:r.endsWith("Parent")||r.endsWith("uid")?"task":"any",validate_exists:n.validate_exists===!0};break;case"list":{let c=ef(`${r}[]`,n.items,t);a={type:"array",items:c.schema},Object.assign(s,c.links),Object.assign(i,c.legacy),o.push(...c.unsupported);break}case"object":{let c={},l=[];for(let[u,d]of Object.entries(be(n.fields)?n.fields:{})){let f=ef(`${r}.${u}`,d,t);c[u]=f.schema,Object.assign(s,f.links),Object.assign(i,f.legacy),o.push(...f.unsupported),be(d)&&d.required===!0&&l.push(u)}t&&r==="blockedBy[]"&&l.push("uid"),a={type:"object",additionalProperties:Object.keys(c).length===0,properties:c,...l.length?{required:ls(l)}:{}};break}default:a={},o.push(`${r}.type`);break}t&&r==="title"&&(a.minLength=1,a.description="Short summary of the task."),typeof n.description=="string"&&(a.description=n.description),typeof n.min=="number"&&(n.type==="string"?a.minLength=n.min:n.type==="list"?a.minItems=n.min:a.minimum=n.min),typeof n.max=="number"&&(n.type==="string"?a.maxLength=n.max:n.type==="list"?a.maxItems=n.max:a.maximum=n.max),typeof n.min_length=="number"&&(a.minLength=n.min_length),typeof n.max_length=="number"&&(a.maxLength=n.max_length),typeof n.pattern=="string"&&(a.pattern=n.pattern),n.deprecated===!0&&(a.deprecated=!0),n.default!==void 0&&(a.default=Oe(n.default)),n.computed!==void 0&&o.push(`${r}.computed`);for(let[c,l]of Object.entries(n)){let u=t&&(c==="tn_role"||c==="tn_completed_values");(!ZP.has(c)||(c==="tn_role"||c==="tn_completed_values")&&!u)&&(i[`${r}.${c}`]=Oe(l))}return{schema:a,links:s,legacy:i,unsupported:o}}function Oi(r,e,t,n){let s=be(r[e])?r[e]:{},i=be(s.set)?s.set:{};i[t]=n,s.set=i,r[e]=s}function tO(r,e,t){if(t==="now")Oi(r,"on_create",e,{now:!0});else if(t==="now_on_write")Oi(r,"on_update",e,{now:!0});else if(t==="uuid")Oi(r,"on_create",e,{uuid:!0});else if(t==="ulid")Oi(r,"on_create",e,{ulid:!0});else if(be(t)&&t.transform==="slugify"&&typeof t.from=="string")Oi(r,"on_create",e,{slugify:t.from});else return!1;return!0}function rO(r){var t;let e=r.match(/^(.*\/)?\{title\}\.md$/);return e?{runtime:"tasknotes",template:"{{title}}",folder:((t=e[1])!=null?t:"").replace(/\/$/,""),generated_by:"tasknotes.filename.create"}:{runtime:"tasknotes",template:r,generated_by:"tasknotes.filename.create"}}function nO(r,e,t){var x;if(t.kind==="mdbase.type"||t.schema!==void 0)throw new Error(`${r} already looks like a v0.3 type.`);if(typeof t.name!="string"||!be(t.fields))throw new Error(`${r} is not a v0.2 type with a name and fields.`);let n=eO(t),s=t.name.trim().toLowerCase(),i={type:{const:s}},o=[],a={},c={},l=[],u={},d={},f=[],p=[],m={},h={},y={};for(let[I,E]of Object.entries(t.fields)){let T=be(E)?E:{},v=ef(I,T,n);i[I]=v.schema,Object.assign(c,v.links),Object.assign(d,v.legacy),f.push(...v.unsupported),T.required===!0&&o.push(I),T.default!==void 0&&(a[I]=Oe(T.default)),T.unique===!0&&l.push({field:I,scope:"collection"}),T.generated!==void 0&&tO(u,I,T.generated)&&p.push(I),typeof T.tn_role=="string"&&(m[T.tn_role]=I),Array.isArray(T.tn_completed_values)&&(h.completed_values=Oe(T.tn_completed_values))}a.status!==void 0&&(h.default=Oe(a.status)),a.priority!==void 0&&(y.default=Oe(a.priority));let b=typeof t.display_name_key=="string"&&Object.prototype.hasOwnProperty.call(t.fields,t.display_name_key)?t.display_name_key:void 0,g={...b?{display:{name_field:b}}:{},read_defaults:a,links:c,unique:l};typeof t.path_pattern=="string"&&(g.path=n?rO(t.path_pattern):{pattern:t.path_pattern});let w={};for(let[I,E]of Object.entries(t))QP.has(I)||(w[I]=Oe(E));Object.keys(d).length&&(w.fields=d);let S=Zu({kind:"mdbase.type",name:s,version:1,description:typeof t.description=="string"?t.description:void 0,match:be(t.match)?Oe(t.match):void 0,schema:{dialect:"json-schema-2020-12",value:{$schema:"https://json-schema.org/draft/2020-12/schema",type:"object",additionalProperties:t.strict!==!0,properties:i,...o.length?{required:ls(o)}:{}}},collection:g,lifecycle:u,...n?{"x-tasknotes":{contract:"tasknotes.task",version:1,field_roles:m,status:h,priority:y,archive:{tags_field:(x=m.tags)!=null?x:"tags",archived_tag:"archived"}}}:{},...Object.keys(w).length?{"x-legacy-v0.2":w}:{}}),_=[];t.extends!==void 0&&f.push("extends");for(let I of ls(f).sort())_.push({path:r,code:"migration_lossy",message:`${I} cannot be expressed as canonical v0.3 write behavior and was retained as legacy metadata where possible.`,severity:"lossy"});return n&&_.push({path:r,code:"path_policy_runtime_owned",message:"TaskNotes filename behavior is recorded as TaskNotes runtime metadata.",severity:"warning"}),t.strict!==!0&&_.push({path:r,code:"additional_properties_true",message:"The migrated schema allows additional properties because the source type was not strict.",severity:"warning"}),typeof t.display_name_key=="string"&&!b&&_.push({path:r,code:"display_field_missing",message:`The display field '${t.display_name_key}' is not declared, so collection.display was omitted.`,severity:"warning"}),{target:S,summary:{path:r,name:s,fieldsConverted:Object.keys(t.fields).length,requiredFields:ls(o),defaultsMoved:Object.keys(a),generatedFieldsMoved:ls(p),linksMoved:Object.keys(c),taskNotes:n},diagnostics:_}}function sO(r){let e=Oe(r);e.spec_version=Ni;let t=be(e.settings)?e.settings:{};if(e.settings=t,!Array.isArray(t.record_extensions)){let n=Array.isArray(t.extensions)?t.extensions.map(String).map(s=>s.replace(/^\./,"")):[];t.record_extensions=ls(["md",...n])}return Array.isArray(t.explicit_type_keys)||(t.explicit_type_keys=["type","types"]),typeof t.include_subfolders!="boolean"&&(t.include_subfolders=!0),t.validation===void 0&&typeof t.default_validation=="string"&&(t.validation=t.default_validation),t.validation===void 0&&typeof e.default_validation=="string"&&(t.validation=e.default_validation),delete t.default_validation,delete t.extensions,delete e.default_validation,e}function R0(r,e){let t=be(r.settings)?r.settings:{};return{spec_version:e,name:typeof r.name=="string"?r.name:void 0,description:typeof r.description=="string"?r.description:void 0,settings:{types_folder:typeof t.types_folder=="string"?t.types_folder:"_types",explicit_type_keys:Array.isArray(t.explicit_type_keys)?t.explicit_type_keys.filter(n=>typeof n=="string"):["type","types"],default_strict:t.default_strict===!0,include_subfolders:t.include_subfolders!==!1,exclude:Array.isArray(t.exclude)?t.exclude.filter(n=>typeof n=="string"):["_types",".obsidian",".git",".mdbase"]}}}function iO(r,e){var n,s;let t={};for(let[i,o]of Object.entries(be(e.fields)?e.fields:{}))be(o)&&(t[i]=Oe(o));return{name:typeof e.name=="string"?e.name:(s=(n=r.split("/").pop())==null?void 0:n.replace(/\.md$/,""))!=null?s:"type",fields:t,match:be(e.match)?Oe(e.match):void 0,filePath:r,specProfile:"v0.2"}}function oO(r,e){var s,i;let t=be(e.schema)?e.schema:{},n=be(t.value)?t.value:{};return{name:typeof e.name=="string"?e.name:(i=(s=r.split("/").pop())==null?void 0:s.replace(/\.md$/,""))!=null?i:"type",fields:nn(n),match:be(e.match)?Oe(e.match):void 0,collection:be(e.collection)?Oe(e.collection):void 0,schema:Oe(n),filePath:r,specProfile:"v0.3"}}function aO(r,e,t){let n=Oe(r);for(let s of e){let i=t.get(s);if(i)for(let[o,a]of Object.entries(i.fields))!(o in n)&&a.default!==void 0&&(n[o]=Oe(a.default))}return n}function cO(r,e,t){var s,i;let n=Oe(r);for(let o of e){let a=t.get(o);if(a)for(let[c,l]of Object.entries((i=(s=a.collection)==null?void 0:s.read_defaults)!=null?i:{}))c in n||(n[c]=Oe(l))}return n}async function lO(r,e){let t=(0,Je.normalizePath)(e).replace(/\/+$/,"");if(!t)return;let n="";for(let s of t.split("/")){n=n?`${n}/${s}`:s;let i=r.getAbstractFileByPath(n);if(!(i instanceof Je.TFolder)){if(i)throw new Error(`A file blocks folder ${n}.`);await r.adapter.exists(n)||await r.createFolder(n)}}}async function qa(r,e,t){let n=(0,Je.normalizePath)(e),s=n.lastIndexOf("/");if(s>=0&&await lO(r,n.slice(0,s)),n.startsWith(".mdbase/")){await r.adapter.write(n,t);return}let i=r.getAbstractFileByPath(n);if(i instanceof Je.TFolder)throw new Error(`A folder blocks file ${n}.`);i instanceof Je.TFile?await r.modify(i,t):await r.create(n,t)}async function Ci(r,e){let t=(0,Je.normalizePath)(e),n=r.getAbstractFileByPath(t);if(n instanceof Je.TFile)return r.cachedRead(n);if(await r.adapter.exists(t))return r.adapter.read(t);throw new Error(`File not found: ${e}`)}async function C0(r){var S;let e=await Ci(r,"mdbase.yaml"),t=(0,Je.parseYaml)(e);if(!be(t))throw new Error("mdbase.yaml must contain a YAML mapping.");let n=typeof t.spec_version=="string"?t.spec_version:"";if(!/^0\.2(?:\.\d+)?$/.test(n))throw new Error(n===Ni?"This collection is already mdbase v0.3.":`Expected an mdbase v0.2.x collection, found ${JSON.stringify(n)}.`);let s=be(t.settings)?t.settings:{},i=typeof s.types_folder=="string"?(0,Je.normalizePath)(s.types_folder):"_types",o=`${i}/`,a=[],c=[],l=[],u=sO(t),d=`${(0,Je.stringifyYaml)(u).trimEnd()} +`;a.push({path:"mdbase.yaml",sourceDigest:br(e),targetDigest:br(d),source:e,target:d});let f=new Map,p=new Map;for(let _ of r.getMarkdownFiles().filter(x=>x.path.startsWith(o)).sort((x,I)=>x.path.localeCompare(I.path))){let x=await r.cachedRead(_),I=tt(x);if(!I.hasFrontmatter||I.error)throw new Error(`Cannot migrate ${_.path}: ${(S=I.error)!=null?S:"frontmatter is missing"}.`);let E=nO(_.path,n,I.frontmatter),T=iO(_.path,I.frontmatter),v=oO(_.path,E.target);f.set(T.name,T),p.set(v.name,v);let F=`${ot(E.target,I.body)} +`;a.push({path:_.path,sourceDigest:br(x),targetDigest:br(F),source:x,target:F}),c.push(E.summary),l.push(...E.diagnostics)}if(!c.length)throw new Error(`No v0.2 type files were found in ${i}.`);let m=0,h=0,y=R0(t,n),b=R0(u,Ni),g=r.getMarkdownFiles().filter(_=>!_.path.startsWith(o)).filter(_=>!_.path.startsWith(".mdbase/")).sort((_,x)=>_.path.localeCompare(x.path));for(let[_,x]of g.entries()){let I=tt(await r.cachedRead(x));if(I.error){h+=1;continue}let E=Kn(x.path,I.frontmatter,y,f),T=Kn(x.path,I.frontmatter,b,p),v=aO(I.frontmatter,E,f),F=cO(I.frontmatter,T,p);(hn(E.slice().sort())!==hn(T.slice().sort())||hn(v)!==hn(F))&&l.push({path:x.path,code:"effective_read_changed",message:"The proposed v0.3 types would change this record's resolved types or effective default values.",severity:"lossy"}),m+=1,_>0&&_%250===0&&await new Promise(V=>setTimeout(V,0))}let w=br(hn({sourceVersion:n,operations:a.map(({path:_,sourceDigest:x,targetDigest:I})=>({path:_,sourceDigest:x,targetDigest:I})),diagnostics:l}));return{planVersion:1,analysisId:w,sourceVersion:n,targetVersion:Ni,createdAt:new Date().toISOString(),backupLocation:`.mdbase/migrations/v02-to-v03-${w.slice(0,12)}`,operations:a,typeSummaries:c,diagnostics:l,applicable:!l.some(_=>_.severity==="lossy"),recordFilesRewritten:0,recordsVerified:m,recordsSkipped:h}}async function Ri(r,e,t){await qa(r,e,`${JSON.stringify(t,null,2)} +`)}async function N0(r,e,t={}){if(e.planVersion!==1||e.targetVersion!==Ni)throw new Error("Unsupported migration plan.");if(!e.applicable&&!t.allowLossy)throw new Error("This migration has lossy diagnostics. Review them and explicitly allow lossy migration.");for(let i of e.operations){let o=await Ci(r,i.path);if(br(o)!==i.sourceDigest)throw new Error(`${i.path} changed after migration analysis. Run the review again.`)}let n=`${e.backupLocation}/manifest.json`,s={manifest_version:1,analysis_id:e.analysisId,source_version:e.sourceVersion,target_version:e.targetVersion,status:"prepared",created_at:new Date().toISOString(),written:[],files:e.operations.map(i=>({path:i.path,source_digest:i.sourceDigest,target_digest:i.targetDigest,backup_path:`${e.backupLocation}/files/${i.path}`}))};for(let i of e.operations)await qa(r,`${e.backupLocation}/files/${i.path}`,i.source);await Ri(r,n,s),s.status="applying",await Ri(r,n,s);try{for(let i of e.operations){let o=await Ci(r,i.path);if(br(o)!==i.sourceDigest)throw new Error(`${i.path} changed during migration.`);s.written.push(i.path),await Ri(r,n,s),await qa(r,i.path,i.target);let a=await Ci(r,i.path);if(br(a)!==i.targetDigest)throw new Error(`${i.path} did not verify after write.`)}return s.status="applied",s.completed_at=new Date().toISOString(),await Ri(r,n,s),{applied:!0,restored:!1,manifestPath:n,written:[...s.written]}}catch(i){let o=[];for(let a of[...s.written].reverse()){let c=e.operations.find(l=>l.path===a);if(!c){o.push(a);continue}try{await qa(r,a,c.source),br(await Ci(r,a))!==c.sourceDigest&&o.push(a)}catch(l){o.push(a)}}s.status=o.length?"recovery_required":"rolled_back",s.error=i instanceof Error?i.message:String(i),s.manual_recovery_paths=o.length?o:void 0,s.completed_at=new Date().toISOString();try{await Ri(r,n,s)}catch(a){}return{applied:!1,restored:o.length===0,manifestPath:n,written:[...s.written],error:s.error}}}var Da=require("obsidian");function ke(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function er(r){return JSON.parse(JSON.stringify(r))}var dO=new Set(["file","formula","this"]);function uO(r){let e=r.trim();if(!e)throw new Error("Type name is required.");if(!/^[A-Za-z]/.test(e))throw new Error("Type name must start with a letter.");if(e.length>=64)throw new Error("Type name must be shorter than 64 characters.");if(!/^[A-Za-z][A-Za-z0-9_-]*$/.test(e))throw new Error("Type name may contain only letters, numbers, hyphens, and underscores.");if(dO.has(e.toLowerCase()))throw new Error(`Type name '${e}' is reserved.`);return e}function tf(){return{specProfile:"v0.3",originalFrontmatter:{},name:"",description:"",extendsType:"",displayNameKey:"",strictMode:!1,pathPattern:"",filenamePattern:"",matchPathGlob:"",matchFieldsPresent:"",matchWhere:"",fields:[{name:"title",definition:{type:"string",required:!0}}],body:`# Type -Describe the type and intended usage.`,extraFrontmatter:{}}}function WT(r){return Pe(r)?Object.entries(r).filter(e=>Pe(e[1])).map(([e,t])=>({name:e,definition:rr(t)})):[]}function JT(r){return Object.fromEntries(r.map(e=>[e.name,e.definition]))}function YT(r,e){let t=e.split("."),i=r,n;for(let[s,o]of t.entries()){let a=o.match(/^([^\[\]]+)((?:\[\])*)$/);if(!a||(n=i[a[1]],!n))return null;let c=a[2].length/2;for(let l=0;l{if(e.selectors.add(n),i.type==="link"&&e.links.set(n,{target_type:typeof i.target=="string"&&i.target.trim()?i.target.trim():"any",validate_exists:i.validate_exists===!0}),i.type==="list"&&i.items&&t(i.items,`${n}[]`),i.type==="object"&&i.fields)for(let[s,o]of Object.entries(i.fields))t(o,`${n}.${s}`)};for(let[i,n]of Object.entries(r))t(n,i);return e}function ec(r,e,t){let i=r.kind==="mdbase.type",n=i&&Pe(r.schema)?r.schema:{},s=Pe(n.value)?n.value:{},o=typeof n.ref=="string"?n.ref:"",a=i&&Pe(r.collection)?r.collection:{},c=Pe(a.display)?a.display:{},l=Pe(a.path)?a.path:{},u=WT(i?ci(s):r.fields);i&&XT(u,a.links);let d=Pe(r.match)?r.match:{},f=i?s.additionalProperties===!1:r.strict,p=new Set(["name","description","extends","display_name_key","strict","path_pattern","filename_pattern","match","fields"]),m={};for(let[y,b]of Object.entries(r))p.has(y)||(m[y]=rr(b));let h="";if(d.where!==void 0)try{h=(0,Qa.stringifyYaml)(d.where).trim()}catch(y){h=""}return{specProfile:i?"v0.3":"v0.2",originalFrontmatter:rr(r),name:typeof r.name=="string"&&r.name.trim()?r.name:t,description:typeof r.description=="string"?r.description:"",extendsType:typeof r.extends=="string"?r.extends:"",displayNameKey:i?typeof c.name_field=="string"?c.name_field:"":typeof r.display_name_key=="string"?r.display_name_key:"",strictMode:f==="warn"?"warn":f===!0,pathPattern:i?typeof l.pattern=="string"?l.pattern:"":typeof r.path_pattern=="string"?r.path_pattern:"",filenamePattern:i?"":typeof r.filename_pattern=="string"?r.filename_pattern:"",matchPathGlob:typeof d.path_glob=="string"?d.path_glob:"",matchFieldsPresent:Array.isArray(d.fields_present)?d.fields_present.map(String).join(", "):"",matchWhere:h,fields:u.length||o?u:$f().fields,body:e.trim()||`# ${t} +Describe the type and intended usage.`,extraFrontmatter:{}}}function fO(r){return ke(r)?Object.entries(r).filter(e=>ke(e[1])).map(([e,t])=>({name:e,definition:er(t)})):[]}function pO(r){return Object.fromEntries(r.map(e=>[e.name,e.definition]))}function hO(r,e){let t=e.split("."),n=r,s;for(let[i,o]of t.entries()){let a=o.match(/^([^\[\]]+)((?:\[\])*)$/);if(!a||(s=n[a[1]],!s))return null;let c=a[2].length/2;for(let l=0;l{if(e.selectors.add(s),n.type==="link"&&e.links.set(s,{target_type:typeof n.target=="string"&&n.target.trim()?n.target.trim():"any",validate_exists:n.validate_exists===!0}),n.type==="list"&&n.items&&t(n.items,`${s}[]`),n.type==="object"&&n.fields)for(let[i,o]of Object.entries(n.fields))t(o,`${s}.${i}`)};for(let[n,s]of Object.entries(r))t(s,n);return e}function ja(r,e,t){let n=r.kind==="mdbase.type",s=n&&ke(r.schema)?r.schema:{},i=ke(s.value)?s.value:{},o=typeof s.ref=="string"?s.ref:"",a=n&&ke(r.collection)?r.collection:{},c=ke(a.display)?a.display:{},l=ke(a.path)?a.path:{},u=fO(n?nn(i):r.fields);n&&mO(u,a.links);let d=ke(r.match)?r.match:{},f=n?i.additionalProperties===!1:r.strict,p=new Set(["name","description","extends","display_name_key","strict","path_pattern","filename_pattern","match","fields"]),m={};for(let[y,b]of Object.entries(r))p.has(y)||(m[y]=er(b));let h="";if(d.where!==void 0)try{h=(0,Da.stringifyYaml)(d.where).trim()}catch(y){h=""}return{specProfile:n?"v0.3":"v0.2",originalFrontmatter:er(r),name:typeof r.name=="string"&&r.name.trim()?r.name:t,description:typeof r.description=="string"?r.description:"",extendsType:typeof r.extends=="string"?r.extends:"",displayNameKey:n?typeof c.name_field=="string"?c.name_field:"":typeof r.display_name_key=="string"?r.display_name_key:"",strictMode:f==="warn"?"warn":f===!0,pathPattern:n?typeof l.pattern=="string"?l.pattern:"":typeof r.path_pattern=="string"?r.path_pattern:"",filenamePattern:n?"":typeof r.filename_pattern=="string"?r.filename_pattern:"",matchPathGlob:typeof d.path_glob=="string"?d.path_glob:"",matchFieldsPresent:Array.isArray(d.fields_present)?d.fields_present.map(String).join(", "):"",matchWhere:h,fields:u.length||o?u:tf().fields,body:e.trim()||`# ${t} -Type definition for ${t}.`,extraFrontmatter:m,...o?{readOnlyReason:`This type uses schema.ref (${o}). Edit the referenced JSON Schema file directly.`}:{}}}function Hs(r){if(r.specProfile!=="v0.3")throw new Error("mdbase v0.2 type definitions are read-only. Migrate the collection before editing.");if(r.readOnlyReason)throw new Error(r.readOnlyReason);let e=r.originalFrontmatter?rr(r.originalFrontmatter):{},t=Pe(e.schema)?e.schema:{},i=Pe(t.value)?t.value:{},n=Object.create(null);for(let h of r.fields){let y=h.name.trim();if(!y)throw new Error("Every field needs a name.");if(Object.prototype.hasOwnProperty.call(n,y))throw new Error(`Duplicate field name: ${y}`);n[y]=rr(h.definition)}let s=GT(r.name),o={...e,kind:"mdbase.type",name:s,version:typeof e.version=="number"?e.version:1,schema:{...t,dialect:"json-schema-2020-12",value:hu(n,i,r.strictMode===!0)}};delete o.schema.ref,r.description.trim()?o.description=r.description.trim():delete o.description;let a=Pe(o.match)?rr(o.match):{};r.matchPathGlob.trim()?a.path_glob=r.matchPathGlob.trim():delete a.path_glob;let c=r.matchFieldsPresent.split(",").map(h=>h.trim()).filter(Boolean);if(c.length?a.fields_present=c:delete a.fields_present,r.matchWhere.trim()){let h=(0,Qa.parseYaml)(r.matchWhere);if(!Pe(h))throw new Error("Match where must be a YAML mapping.");a.where=h}else delete a.where;Object.keys(a).length?o.match=a:delete o.match;let l=Pe(o.collection)?rr(o.collection):{},u=Pe(l.display)?rr(l.display):{};if(r.displayNameKey.trim()?u.name_field=r.displayNameKey.trim():delete u.name_field,Object.keys(u).length?l.display=u:delete l.display,r.pathPattern.trim()){let h=Pe(l.path)?l.path:{};l.path={...h,pattern:r.pathPattern.trim()}}else if(Pe(l.path)&&typeof l.path.pattern=="string"){let h={...l.path};delete h.pattern,Object.keys(h).length?l.path=h:delete l.path}let d=Pe(l.links)?rr(l.links):{},f=rr(d),p=l_(n),m=l_(ci(i));for(let h of new Set([...m.selectors,...p.selectors]))delete f[h];for(let[h,y]of p.links)f[h]={...Pe(d[h])?d[h]:{},target_type:y.target_type,validate_exists:y.validate_exists};Object.keys(f).length?l.links=f:delete l.links,Object.keys(l).length?o.collection=l:delete o.collection;for(let h of["fields","strict","extends","display_name_key","path_pattern","filename_pattern"])delete o[h];return o}var Se=require("obsidian");var mn="mdbase-frontmatter",d_=` +Type definition for ${t}.`,extraFrontmatter:m,...o?{readOnlyReason:`This type uses schema.ref (${o}). Edit the referenced JSON Schema file directly.`}:{}}}function Mi(r){if(r.specProfile!=="v0.3")throw new Error("mdbase v0.2 type definitions are read-only. Migrate the collection before editing.");if(r.readOnlyReason)throw new Error(r.readOnlyReason);let e=r.originalFrontmatter?er(r.originalFrontmatter):{},t=ke(e.schema)?e.schema:{},n=ke(t.value)?t.value:{},s=Object.create(null);for(let h of r.fields){let y=h.name.trim();if(!y)throw new Error("Every field needs a name.");if(Object.prototype.hasOwnProperty.call(s,y))throw new Error(`Duplicate field name: ${y}`);s[y]=er(h.definition)}let i=uO(r.name),o={...e,kind:"mdbase.type",name:i,version:typeof e.version=="number"?e.version:1,schema:{...t,dialect:"json-schema-2020-12",value:Jd(s,n,r.strictMode===!0)}};delete o.schema.ref,r.description.trim()?o.description=r.description.trim():delete o.description;let a=ke(o.match)?er(o.match):{};r.matchPathGlob.trim()?a.path_glob=r.matchPathGlob.trim():delete a.path_glob;let c=r.matchFieldsPresent.split(",").map(h=>h.trim()).filter(Boolean);if(c.length?a.fields_present=c:delete a.fields_present,r.matchWhere.trim()){let h=(0,Da.parseYaml)(r.matchWhere);if(!ke(h))throw new Error("Match where must be a YAML mapping.");a.where=h}else delete a.where;Object.keys(a).length?o.match=a:delete o.match;let l=ke(o.collection)?er(o.collection):{},u=ke(l.display)?er(l.display):{};if(r.displayNameKey.trim()?u.name_field=r.displayNameKey.trim():delete u.name_field,Object.keys(u).length?l.display=u:delete l.display,r.pathPattern.trim()){let h=ke(l.path)?l.path:{};l.path={...h,pattern:r.pathPattern.trim()}}else if(ke(l.path)&&typeof l.path.pattern=="string"){let h={...l.path};delete h.pattern,Object.keys(h).length?l.path=h:delete l.path}let d=ke(l.links)?er(l.links):{},f=er(d),p=M0(s),m=M0(nn(n));for(let h of new Set([...m.selectors,...p.selectors]))delete f[h];for(let[h,y]of p.links)f[h]={...ke(d[h])?d[h]:{},target_type:y.target_type,validate_exists:y.validate_exists};Object.keys(f).length?l.links=f:delete l.links,Object.keys(l).length?o.collection=l:delete o.collection;for(let h of["fields","strict","extends","display_name_key","path_pattern","filename_pattern"])delete o[h];return o}var $e=require("obsidian");var ds="mdbase-frontmatter",L0=` @@ -179,13 +179,13 @@ Type definition for ${t}.`,extraFrontmatter:m,...o?{readOnlyReason:`This type us -`;var vi="mdbase-workspace-view",ZT=["string","integer","number","boolean","date","datetime","time","enum","link","list","object","any"];function _i(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function Sf(r){return JSON.parse(JSON.stringify(r))}function u_(r){return typeof r.type=="string"?r.type:"any"}function QT(r){if(!Object.prototype.hasOwnProperty.call(r,"field"))return"field";let e=2;for(;Object.prototype.hasOwnProperty.call(r,`field${e}`);)e+=1;return`field${e}`}function f_(r,e,t){Object.defineProperty(r,e,{configurable:!0,enumerable:!0,writable:!0,value:t})}function eO(r,e){if(!r)return["A new type definition will be created."];let t=[];r.name!==e.name&&t.push(`Rename type from ${r.name} to ${e.name}.`),(r.matchPathGlob!==e.matchPathGlob||r.matchFieldsPresent!==e.matchFieldsPresent||r.matchWhere!==e.matchWhere)&&t.push("Membership rules changed; different records may match this type.");let i=new Map(r.fields.map(c=>[c.name,c])),n=new Map(e.fields.map(c=>[c.name,c])),s=[...i.keys()].filter(c=>!n.has(c)),o=[...n.keys()].filter(c=>!i.has(c));o.length&&t.push(`Add ${o.length} field${o.length===1?"":"s"}: ${o.join(", ")}.`),s.length&&t.push(`Remove ${s.length} field${s.length===1?"":"s"}: ${s.join(", ")}.`);let a=[...n.entries()].filter(([c,l])=>{var u;return l.definition.required===!0&&((u=i.get(c))==null?void 0:u.definition.required)!==!0}).map(([c])=>c);return a.length&&t.push(`New required fields may invalidate records: ${a.join(", ")}.`),t.length||t.push("Metadata, schema details, or documentation changed."),t}function $t(r,e,t,i,n={}){var l;let s=r.createDiv({cls:"mdbase-form-row"}),o=s.createEl("label",{text:e}),a=`mdbase-${Math.random().toString(36).slice(2)}`;o.htmlFor=a,n.description&&s.createDiv({cls:"mdbase-form-description",text:n.description});let c=n.multiline?s.createEl("textarea"):s.createEl("input",{type:"text"});return c.id=a,c.value=t,c.placeholder=(l=n.placeholder)!=null?l:"",c.addEventListener("input",()=>i(c.value)),c}function Ne(r,e,t){let i=r.createDiv({cls:"mdbase-status-row"});i.createSpan({cls:"mdbase-status-label",text:e}),i.createSpan({cls:"mdbase-status-value",text:t})}function tO(r){if(r<1e3)return String(r);let e=r<1e4?1:0;return`${(r/1e3).toFixed(e)}k`}var tc=class extends Se.ItemView{constructor(t,i){super(t);this.host=i;this.destination="types";this.editorMode="design";this.schema=null;this.query="";this.selectedPath=null;this.model=null;this.originalModel=null;this.yamlDraft="";this.dirty=!1;this.busy=!1;this.migrationPlan=null;this.allowLossy=!1;this.mirrorStatus=null;this.mirrorPreview=null;this.mirrorProgress=null;this.transientMessage="";this.issueQuery="";this.issueSeverity="all";this.issueLimit=250;this.enrollmentVerification="";this.enrollmentAbort=null}getViewType(){return vi}getDisplayText(){return"mdbase"}getIcon(){return mn}async onOpen(){this.containerEl.addClass("mdbase-workspace"),await this.refresh(!0)}async onClose(){var t;(t=this.enrollmentAbort)==null||t.abort(),this.enrollmentAbort=null}async refresh(t=!1){try{this.schema=await this.host.loadWorkspaceSchema(t),this.selectedPath&&!this.typeEntries().some(i=>i.filePath===this.selectedPath)&&(this.selectedPath=null,this.model=null,this.originalModel=null),!this.selectedPath&&this.typeEntries().length&&!Se.Platform.isMobile&&(this.selectedPath=this.typeEntries()[0].filePath),this.selectedPath&&(!this.model||t)&&await this.selectType(this.selectedPath,!1),this.destination==="sync"&&await this.refreshMirrorStatus(),this.render()}catch(i){this.transientMessage=i instanceof Error?i.message:String(i),this.render()}}showDestination(t){this.destination=t,t==="sync"?this.refreshMirrorStatus().then(()=>this.render()):this.render()}typeEntries(){return this.schema?[...this.schema.types.values()].sort((t,i)=>t.name.localeCompare(i.name)):[]}render(){let t=this.containerEl;t.empty(),t.addClass("mdbase-workspace");let i=t.createDiv({cls:"mdbase-shell"});this.renderTopbar(i),this.transientMessage&&i.createDiv({cls:"mdbase-inline-message",text:this.transientMessage}).setAttr("role","status");let n=i.createDiv({cls:"mdbase-workspace-content"});this.destination==="types"?this.renderTypes(n):this.destination==="sync"?this.renderSync(n):this.renderIssues(n)}renderTopbar(t){let i=t.createDiv({cls:"mdbase-topbar"}),n=i.createDiv({cls:"mdbase-identity"}),s=n.createSpan({cls:"mdbase-mark"});s.setAttr("aria-hidden","true"),(0,Se.setIcon)(s,mn),n.createSpan({cls:"mdbase-title",text:"mdbase"});let o=i.createDiv({cls:"mdbase-nav"});o.setAttr("role","tablist");for(let[a,c]of[["types","Types"],["sync","Sync"],["issues","Issues"]]){let l=o.createEl("button",{text:c});if(l.addClass("mdbase-nav-button"),l.setAttr("role","tab"),l.setAttr("aria-selected",String(this.destination===a)),this.destination===a&&l.addClass("is-active"),a==="issues"&&this.host.getIssues().length){let u=this.host.getIssues().length;l.createSpan({cls:"mdbase-count",text:tO(u)}).setAttr("title",`${u} issues`)}l.onclick=()=>this.showDestination(a)}}renderTypes(t){if(!this.schema){let n=t.createDiv({cls:"mdbase-empty-state"});n.createEl("h2",{text:"Start an mdbase collection"}),n.createEl("p",{text:"Initialize this vault as a local v0.3 collection, or use Sync to connect an empty vault to a collection authority."});let s=n.createDiv({cls:"mdbase-actions"}),o=s.createEl("button",{text:"Initialize local collection"});o.addClass("mod-cta"),o.disabled=this.busy||this.host.getMirrorProfile()!==null,o.onclick=()=>void this.perform(async()=>{await this.host.initializeCollection(),await this.refresh(!0)});let a=s.createEl("button",{text:"Connect collection authority"});a.onclick=()=>this.showDestination("sync");return}this.schema.config.spec_version.startsWith("0.2.")&&this.renderLegacyBanner(t);let i=t.createDiv({cls:"mdbase-types-layout"});this.model&&i.addClass("has-selection"),this.renderTypeList(i),this.renderTypeEditor(i)}renderLegacyBanner(t){var o;let i=t.createDiv({cls:"mdbase-legacy-banner"}),n=i.createDiv();n.createEl("strong",{text:`mdbase ${(o=this.schema)==null?void 0:o.config.spec_version} compatibility mode`}),n.createEl("p",{text:"Types are readable and validation remains available, but authoring is disabled until a reviewed v0.3 migration."});let s=i.createEl("button",{text:this.migrationPlan?"Review migration":"Analyze migration"});s.disabled=this.busy||this.host.getMirrorProfile()!==null,s.onclick=()=>void this.perform(async()=>{this.migrationPlan=await this.host.analyzeMigration(),this.render()}),this.host.getMirrorProfile()&&i.createDiv({cls:"mdbase-form-description",text:"Hosted resources must be migrated at the collection authority."}),this.migrationPlan&&this.renderMigrationReview(t,this.migrationPlan)}renderMigrationReview(t,i){let n=t.createDiv({cls:"mdbase-migration-review"}),s=n.createDiv({cls:"mdbase-section-header"});s.createEl("h3",{text:"Migration review"}),s.createSpan({cls:"mdbase-spec-badge",text:`${i.sourceVersion} \u2192 ${i.targetVersion}`});let o=n.createDiv({cls:"mdbase-status-list"});Ne(o,"Files replaced",String(i.operations.length)),Ne(o,"Type definitions",String(i.typeSummaries.length)),Ne(o,"Record reads verified",String(i.recordsVerified)),i.recordsSkipped&&Ne(o,"Records skipped",String(i.recordsSkipped)),Ne(o,"Record files rewritten","0"),Ne(o,"Recovery backup",i.backupLocation);let a=n.createDiv({cls:"mdbase-review-list"});i.diagnostics.length||a.createDiv({cls:"mdbase-review-ok",text:"No migration diagnostics."});for(let d of i.diagnostics.slice(0,250)){let f=a.createDiv({cls:"mdbase-review-item"});f.setAttr("data-severity",d.severity),f.createDiv({cls:"mdbase-review-code",text:`${d.severity} \xB7 ${d.path}`}),f.createDiv({text:d.message})}if(i.diagnostics.length>250&&a.createDiv({cls:"mdbase-form-description",text:`Showing 250 of ${i.diagnostics.length} diagnostics.`}),!i.applicable){let d=n.createEl("label",{cls:"mdbase-consent"}),f=d.createEl("input",{type:"checkbox"});f.checked=this.allowLossy,f.onchange=()=>{this.allowLossy=f.checked,this.render()},d.createSpan({text:"I reviewed the lossy diagnostics and want to apply this migration."})}let c=n.createDiv({cls:"mdbase-actions"}),l=c.createEl("button",{text:"Apply migration"});l.addClass("mod-warning"),l.disabled=this.busy||!i.applicable&&!this.allowLossy,l.onclick=()=>void this.perform(async()=>{await this.host.applyMigration(i,this.allowLossy),this.migrationPlan=null,this.allowLossy=!1,this.model=null,this.originalModel=null,await this.refresh(!0)});let u=c.createEl("button",{text:"Close review"});u.onclick=()=>{this.migrationPlan=null,this.render()}}renderTypeList(t){var u,d,f,p;let i=t.createDiv({cls:"mdbase-type-list-pane"}),n=i.createDiv({cls:"mdbase-pane-header"});n.createEl("h2",{text:"Types"});let s=n.createEl("button");s.setAttr("aria-label","Create type"),(0,Se.setIcon)(s,"plus"),s.disabled=((d=(u=this.schema)==null?void 0:u.config.spec_version.startsWith("0.2."))!=null?d:!0)||((f=this.host.getMirrorProfile())==null?void 0:f.mode)==="read_only",s.onclick=()=>this.createType();let o=i.createEl("input",{type:"search"});o.addClass("mdbase-type-search"),o.placeholder="Search types",o.setAttr("aria-label","Search types"),o.value=this.query,o.oninput=()=>{this.query=o.value,this.render();let m=this.containerEl.querySelector(".mdbase-type-search");m==null||m.focus(),m==null||m.setSelectionRange(m.value.length,m.value.length)};let a=i.createDiv({cls:"mdbase-type-list"}),c=this.query.trim().toLowerCase(),l=this.typeEntries().filter(m=>{var h;return`${m.name} ${(h=m.description)!=null?h:""} ${m.filePath}`.toLowerCase().includes(c)});if(!l.length){a.createDiv({cls:"mdbase-empty-list",text:c?"No matching types.":"No type definitions."});return}for(let m of l){let h=a.createEl("button",{cls:"mdbase-type-row"});m.filePath===this.selectedPath&&h.addClass("is-active"),h.setAttr("aria-current",m.filePath===this.selectedPath?"true":"false"),h.createSpan({cls:"mdbase-type-name",text:m.name}),h.createSpan({cls:"mdbase-type-meta",text:`${Object.keys(m.fields).length} fields \xB7 ${(p=m.specProfile)!=null?p:"v0.2"}`}),h.onclick=()=>void this.selectType(m.filePath)}}renderTypeEditor(t){var h,y,b,g;let i=t.createDiv({cls:"mdbase-type-editor-pane"});if(!this.model){let _=i.createDiv({cls:"mdbase-empty-state"});_.createEl("h2",{text:"Choose a type"}),_.createEl("p",{text:"Select a type definition from the list to inspect or edit it."});return}let n=((h=this.host.getMirrorProfile())==null?void 0:h.mode)==="read_only",s=this.model.specProfile==="v0.2"||n||!!this.model.readOnlyReason,o=(y=this.model.readOnlyReason)!=null?y:n?"This mirror has read-only access. Re-enroll it with write access before editing types.":"This v0.2 type is read-only. Review and apply a collection migration before editing.",a=i.createDiv({cls:"mdbase-editor-header"}),c=a.createEl("button",{cls:"mdbase-mobile-back"});c.setAttr("aria-label","Back to type list"),(0,Se.setIcon)(c,"arrow-left"),c.onclick=()=>{if(this.dirty){new Se.Notice("Save or discard the current type changes before going back.");return}this.selectedPath=null,this.model=null,this.originalModel=null,this.render()};let l=a.createDiv(),u=l.createDiv({cls:"mdbase-editor-title-line"});u.createEl("h2",{text:this.model.name||"Untitled type"}),u.createSpan({cls:"mdbase-spec-badge",text:(b=this.model.specProfile)!=null?b:"v0.2"}),this.dirty&&u.createSpan({cls:"mdbase-dirty",text:"Unsaved"}),l.createDiv({cls:"mdbase-editor-path",text:(g=this.selectedPath)!=null?g:"New type"});let d=a.createDiv({cls:"mdbase-editor-actions"});if(this.selectedPath){let _=d.createEl("button",{text:"Open source"});_.onclick=()=>void this.host.openFileByPath(this.selectedPath)}let f=d.createEl("button",{text:"Save"});f.addClass("mod-cta"),f.disabled=s||!this.dirty||this.busy,f.onclick=()=>void this.saveCurrentType(),s&&i.createDiv({cls:"mdbase-readonly-note",text:o});let p=i.createDiv({cls:"mdbase-mode-switch"});p.setAttr("role","tablist");for(let[_,S]of[["design","Design"],["yaml","YAML"]]){let v=p.createEl("button",{text:S});v.setAttr("role","tab"),v.setAttr("aria-selected",String(this.editorMode===_)),this.editorMode===_&&v.addClass("is-active"),v.onclick=()=>this.switchEditorMode(_)}let m=i.createDiv({cls:"mdbase-editor-document"});this.editorMode==="design"?this.renderDesignEditor(m,this.model,s):this.renderYamlEditor(m,s)}renderDesignEditor(t,i,n){let s=t.createEl("section",{cls:"mdbase-editor-section"});s.createEl("h3",{text:"Identity"});let o=$t(s,"Name",i.name,P=>{i.name=P,this.markDirty()},{description:"Stable type name used by collection records."});o.disabled=n;let a=$t(s,"Description",i.description,P=>{i.description=P,this.markDirty()},{multiline:!0});a.disabled=n;let c=$t(s,"Display field",i.displayNameKey,P=>{i.displayNameKey=P,this.markDirty()},{placeholder:"title"});c.disabled=n;let l=s.createEl("label",{cls:"mdbase-checkbox-row"}),u=l.createEl("input",{type:"checkbox"});u.checked=i.strictMode===!0,u.disabled=n,u.onchange=()=>{i.strictMode=u.checked,this.markDirty()},l.createSpan({text:"Reject undeclared fields"});let d=t.createEl("section",{cls:"mdbase-editor-section"});d.createEl("h3",{text:"Membership"});let f=$t(d,"Path glob",i.matchPathGlob,P=>{i.matchPathGlob=P,this.markDirty()},{placeholder:"Projects/**/*.md"});f.disabled=n;let p=$t(d,"Fields present",i.matchFieldsPresent,P=>{i.matchFieldsPresent=P,this.markDirty()},{description:"Comma-separated frontmatter keys."});p.disabled=n;let m=$t(d,"Where",i.matchWhere,P=>{i.matchWhere=P,this.markDirty()},{multiline:!0,description:"YAML predicate, including contains and nested equality conditions.",placeholder:`tags: - contains: task`});m.disabled=n;let h=t.createEl("section",{cls:"mdbase-editor-section"}),y=h.createDiv({cls:"mdbase-section-header"});y.createEl("h3",{text:"Fields"});let b=y.createEl("button",{text:"Add field"});b.disabled=n,b.onclick=()=>{i.fields.push({name:"",definition:{type:"string"}}),this.markDirty(!0)};let g=h.createDiv({cls:"mdbase-fields"});for(let[P,x]of i.fields.entries())this.renderFieldRow(g,x,P,n);i.fields.length||g.createDiv({cls:"mdbase-empty-list",text:"No fields declared."});let _=t.createEl("section",{cls:"mdbase-editor-section"});_.createEl("h3",{text:"Placement"});let S=$t(_,"Path pattern",i.pathPattern,P=>{i.pathPattern=P,this.markDirty()},{placeholder:"Notes/{title}.md"});S.disabled=n;let v=t.createEl("section",{cls:"mdbase-editor-section mdbase-change-review"});if(v.createEl("h3",{text:"Change review"}),!this.dirty)v.createEl("p",{text:"No pending changes."});else{let P=v.createEl("ul");for(let x of eO(this.originalModel,i))P.createEl("li",{text:x})}}renderFieldRow(t,i,n,s){this.renderFieldDefinition(t,i.definition,{name:i.name,nameLabel:`Field ${n+1} name`,onNameInput:o=>{i.name=o,this.markDirty()},required:i.definition.required===!0,onRequiredChange:o=>{i.definition.required=o,this.markDirty()},onRemove:()=>{var o;(o=this.model)==null||o.fields.splice(n,1),this.markDirty(!0)},readOnly:s,depth:0})}renderFieldDefinition(t,i,n){var u;let s=t.createDiv({cls:"mdbase-field-node"});s.setAttr("data-depth",String(n.depth));let o=s.createDiv({cls:"mdbase-field-row"});if(n.staticLabel)o.createDiv({cls:"mdbase-field-role",text:n.staticLabel});else{let d=o.createEl("input",{type:"text",cls:"mdbase-field-name-control"});d.setAttr("aria-label",n.nameLabel),d.placeholder="fieldName",d.value=(u=n.name)!=null?u:"",d.disabled=n.readOnly,n.onNameInput&&(d.oninput=()=>{var f;return(f=n.onNameInput)==null?void 0:f.call(n,d.value)}),n.onNameCommit&&(d.onchange=()=>{var f;return(f=n.onNameCommit)==null?void 0:f.call(n,d.value,d)})}let a=o.createEl("select",{cls:"mdbase-field-type-control"});a.setAttr("aria-label",`${n.name||n.staticLabel||"Field"} type`);for(let d of ZT){let f=d==="any"?"Any value":d[0].toUpperCase()+d.slice(1);a.createEl("option",{value:d,text:f})}a.value=u_(i),a.disabled=n.readOnly,a.onchange=()=>{i.type=a.value,a.value==="list"&&!_i(i.items)&&(i.items={type:"string"}),a.value==="object"&&!_i(i.fields)&&(i.fields={}),a.value==="enum"&&!Array.isArray(i.values)&&(i.values=[]),this.markDirty(!0)};let c=o.createEl("input",{type:"text",cls:"mdbase-field-description-control"});if(c.setAttr("aria-label",`${n.name||n.staticLabel||"Field"} description`),c.placeholder="Description",c.value=typeof i.description=="string"?i.description:"",c.disabled=n.readOnly,c.oninput=()=>{c.value?i.description=c.value:delete i.description,this.markDirty()},n.onRequiredChange){let d=o.createEl("label",{cls:"mdbase-field-required"}),f=d.createEl("input",{type:"checkbox"});f.checked=n.required===!0,f.disabled=n.readOnly,f.onchange=()=>{var p;return(p=n.onRequiredChange)==null?void 0:p.call(n,f.checked)},d.createSpan({text:"Required"})}if(n.onRemove){let d=o.createEl("button",{cls:"mdbase-field-remove"});d.setAttr("aria-label",`Remove ${n.name||n.staticLabel||"field"}`),(0,Se.setIcon)(d,"trash-2"),d.disabled=n.readOnly,d.onclick=n.onRemove}let l=u_(i);l==="enum"&&this.renderEnumFieldDetails(s,i,n),l==="link"&&this.renderLinkFieldDetails(s,i,n),l==="list"&&this.renderListFieldDetails(s,i,n),l==="object"&&this.renderObjectFieldDetails(s,i,n)}renderEnumFieldDetails(t,i,n){let s=t.createDiv({cls:"mdbase-field-details mdbase-field-options"}),o=s.createEl("label",{text:"Allowed values"}),a=s.createEl("input",{type:"text"});a.setAttr("aria-label",`${n.name||n.staticLabel||"Enum"} allowed values`),a.placeholder="draft, published, archived",a.value=Array.isArray(i.values)?i.values.map(String).join(", "):"",a.disabled=n.readOnly,a.oninput=()=>{i.values=a.value.split(",").map(c=>c.trim()).filter(Boolean),this.markDirty()},o.htmlFor=a.id=`mdbase-${Math.random().toString(36).slice(2)}`}renderLinkFieldDetails(t,i,n){let s=t.createDiv({cls:"mdbase-field-details mdbase-field-options"}),o=s.createEl("label",{text:"Target type"}),a=s.createEl("input",{type:"text"});a.setAttr("aria-label",`${n.name||n.staticLabel||"Link"} target type`),a.placeholder="Any type",a.value=typeof i.target=="string"?i.target:"",a.disabled=n.readOnly,a.oninput=()=>{a.value.trim()?i.target=a.value.trim():delete i.target,this.markDirty()},o.htmlFor=a.id=`mdbase-${Math.random().toString(36).slice(2)}`;let c=s.createEl("label",{cls:"mdbase-field-required"}),l=c.createEl("input",{type:"checkbox"});l.checked=i.validate_exists===!0,l.disabled=n.readOnly,l.onchange=()=>{i.validate_exists=l.checked,this.markDirty()},c.createSpan({text:"Validate target exists"})}renderListFieldDetails(t,i,n){let s=t.createDiv({cls:"mdbase-field-children"});s.createDiv({cls:"mdbase-field-children-label",text:"List items"});let o=_i(i.items)?i.items:{type:"any"};!_i(i.items)&&!n.readOnly&&(i.items=o),this.renderFieldDefinition(s,o,{staticLabel:"Item",nameLabel:"List item",readOnly:n.readOnly,depth:n.depth+1})}renderObjectFieldDetails(t,i,n){let s=t.createDiv({cls:"mdbase-field-children"}),o=s.createDiv({cls:"mdbase-field-children-header"});o.createDiv({cls:"mdbase-field-children-label",text:"Object fields"});let a=o.createEl("button",{text:"Add nested field"});a.disabled=n.readOnly;let c=_i(i.fields)?i.fields:{};!_i(i.fields)&&!n.readOnly&&(i.fields=c),a.onclick=()=>{let d=QT(c);f_(c,d,{type:"string"}),this.markDirty(!0)};let l=s.createDiv({cls:"mdbase-nested-fields"}),u=Object.entries(c).filter(d=>_i(d[1]));if(!u.length){l.createDiv({cls:"mdbase-empty-list",text:"No nested fields."});return}for(let[d,f]of u){let p=d;this.renderFieldDefinition(l,f,{name:p,nameLabel:`${p} nested field name`,onNameCommit:(m,h)=>{let y=m.trim();if(!y){new Se.Notice("Nested field name is required."),h.value=p;return}if(y!==p&&Object.prototype.hasOwnProperty.call(c,y)){new Se.Notice(`Nested field already exists: ${y}`),h.value=p;return}y!==p&&(delete c[p],f_(c,y,f),p=y,this.markDirty())},required:f.required===!0,onRequiredChange:m=>{f.required=m,this.markDirty()},onRemove:()=>{delete c[p],this.markDirty(!0)},readOnly:n.readOnly,depth:n.depth+1})}}renderYamlEditor(t,i){let n=t.createEl("section",{cls:"mdbase-editor-section mdbase-yaml-section"});n.createEl("h3",{text:"Canonical type document"}),n.createEl("p",{cls:"mdbase-form-description",text:"Unknown v0.3 extensions are preserved. Invalid YAML is never normalized or saved."});let s=n.createEl("textarea",{cls:"mdbase-yaml-editor"});s.setAttr("aria-label","Type definition YAML"),s.value=this.yamlDraft,s.disabled=i,s.spellcheck=!1,s.oninput=()=>{this.yamlDraft=s.value,this.markDirty(!1)}}renderSync(t){var f,p,m,h,y,b;let i=t.createDiv({cls:"mdbase-sync-document"}),n=i.createDiv({cls:"mdbase-document-header"});n.createEl("h2",{text:"Sync"}),n.createEl("p",{text:"Connect this vault to a collection authority and keep ordinary Markdown mirrored locally."});let s=this.host.getMirrorProfile();if(!s){this.renderEnrollment(i);return}let o=i.createEl("section",{cls:"mdbase-editor-section"});o.createEl("h3",{text:"Collection authority"});let a=o.createDiv({cls:"mdbase-status-list"});if(Ne(a,"Name",s.name),Ne(a,"Collection",s.collectionId),Ne(a,"Access",s.mode==="read_write"?"Read and write":"Read only"),Ne(a,"Provider",s.syncUrl),Ne(a,"State",(p=(f=this.mirrorStatus)==null?void 0:f.state.replace(/_/g," "))!=null?p:"Checking"),Ne(a,"Last synced",(h=(m=this.mirrorStatus)==null?void 0:m.last_synced_at)!=null?h:"Never"),this.mirrorProgress){let g=this.mirrorProgress.total,_=o.createEl("progress");_.max=g!=null?g:1,_.value=g==null?0:this.mirrorProgress.completed,g==null&&_.removeAttribute("value"),o.createDiv({cls:"mdbase-progress-label",text:`${this.mirrorProgress.phase}: ${this.mirrorProgress.completed}${g==null?"":` of ${g}`}`})}let c=o.createDiv({cls:"mdbase-actions"}),l=c.createEl("button",{text:"Preview"});l.disabled=this.busy,l.onclick=()=>void this.perform(async()=>{this.mirrorPreview=await this.host.connectSync.preview(),this.render()});let u=c.createEl("button",{text:"Sync now"});u.addClass("mod-cta"),u.disabled=this.busy,u.onclick=()=>void this.perform(async()=>{this.mirrorStatus=await this.host.connectSync.sync(g=>{this.mirrorProgress=g,this.render()}),this.mirrorProgress=null,this.transientMessage="Sync completed and the local checkpoint was verified.",await this.refresh(!0)}),this.mirrorPreview&&this.renderMirrorPreview(i,this.mirrorPreview),(y=this.mirrorStatus)!=null&&y.conflicts.length&&this.renderConflicts(i,this.mirrorStatus),(b=this.mirrorStatus)!=null&&b.local_issues.length&&this.renderLocalMirrorIssues(i,this.mirrorStatus);let d=i.createEl("section",{cls:"mdbase-editor-section"});d.createEl("h3",{text:"Mirror ownership"}),d.createEl("p",{text:"Use this plugin as the only sync owner for this vault. Obsidian protects concurrent operations inside the app; a separate desktop mirror process cannot share that mobile-safe lease."})}renderEnrollment(t){if(this.schema||this.host.connectSync.getAdoptionMarker()){this.renderLocalAdoption(t);return}let i=t.createEl("section",{cls:"mdbase-editor-section mdbase-enrollment"});if(i.createEl("h3",{text:"Connect collection authority"}),i.createEl("p",{text:"Connect will open an approval page. Credentials are stored in Obsidian's secret store and never written into this vault."}),this.enrollmentVerification){let d=i.createDiv({cls:"mdbase-approval-link"});d.createSpan({text:"Approval page: "});let f=d.createEl("a",{text:"Open Connect",href:this.enrollmentVerification});f.setAttr("target","_blank"),f.setAttr("rel","noopener noreferrer")}let n="https://connect.mdbase.dev",s="Obsidian",o="",a="read_write";$t(i,"Connect URL",n,d=>{n=d},{placeholder:"https://connect.mdbase.dev"}),$t(i,"Mirror name",s,d=>{s=d}),$t(i,"Collection ID",o,d=>{o=d},{description:"Optional. Leave blank to choose during approval."});let c=i.createDiv({cls:"mdbase-form-row"});c.createEl("label",{text:"Access"});let l=c.createEl("select");l.createEl("option",{value:"read_write",text:"Read and write"}),l.createEl("option",{value:"read_only",text:"Read only"}),l.value=a,l.onchange=()=>{a=l.value==="read_only"?"read_only":"read_write"};let u=i.createEl("button",{text:"Open Connect approval"});u.addClass("mod-cta"),u.disabled=this.busy,u.onclick=()=>void this.perform(async()=>{var f;(f=this.enrollmentAbort)==null||f.abort();let d=new AbortController;this.enrollmentAbort=d;try{await this.host.connectSync.enroll({controlUrl:n,mirrorName:s,mode:a,...o.trim()?{collectionId:o.trim()}:{}},{signal:d.signal,onVerification:p=>{this.enrollmentVerification=p.verificationUri,this.transientMessage="Approve the mirror in the Connect page. This view will keep waiting securely.",window.open(p.verificationUri,"_blank","noopener,noreferrer"),this.render()},onStatus:p=>{this.transientMessage=p.state==="waiting_for_approval"?"Waiting for approval in Connect\u2026":`Connect is retrying enrollment (attempt ${p.attempt}).`,this.render()}}),this.enrollmentVerification="",this.transientMessage="Mirror enrolled. Preview before the first sync.",await this.refreshMirrorStatus(),this.render()}finally{this.enrollmentAbort===d&&(this.enrollmentAbort=null)}})}renderLocalAdoption(t){var u,d;let i=this.host.connectSync.getAdoptionMarker(),n=t.createEl("section",{cls:"mdbase-editor-section mdbase-enrollment"});n.createEl("h3",{text:"Host this local collection"}),n.createEl("p",{text:i?"This vault has a durable adoption checkpoint. Resume it without creating another hosted collection.":"Hosted mdbase will adopt an exact snapshot and become the collection authority. This vault will then continue as a read-write mirror."});let s=this.enrollmentVerification||(i==null?void 0:i.session.verificationUri);if(s){let f=n.createDiv({cls:"mdbase-approval-link"});f.createSpan({text:"Approval page: "});let p=f.createEl("a",{text:"Open Connect",href:s});p.setAttr("target","_blank"),p.setAttr("rel","noopener noreferrer")}let o=(u=i==null?void 0:i.session.controlUrl)!=null?u:"https://connect.mdbase.dev",a=(d=i==null?void 0:i.session.requested.mirrorName)!=null?d:"Obsidian";if(!i)$t(n,"Connect URL",o,f=>{o=f},{placeholder:"https://connect.mdbase.dev"}),$t(n,"Mirror name",a,f=>{a=f});else{let f=n.createDiv({cls:"mdbase-status-list"});Ne(f,"Collection",i.session.requested.collectionId),Ne(f,"Phase",i.phase.replace(/_/g," ")),Ne(f,"Connect",i.session.controlUrl)}let c=n.createDiv({cls:"mdbase-inline-message"});c.createEl("strong",{text:"Authority cut-over: "}),c.appendText("once final staging begins, plugin-managed local edits pause until hosted activation is confirmed. The checkpoint survives app restarts and uncertain network responses.");let l=n.createEl("button",{text:i?"Resume adoption":"Approve and host collection"});if(l.addClass("mod-cta"),l.disabled=this.busy,l.onclick=()=>void this.perform(async()=>{var h;(h=this.enrollmentAbort)==null||h.abort();let f=new AbortController;this.enrollmentAbort=f;let p=y=>{this.enrollmentVerification=y.verificationUri,this.transientMessage="Approve the authority move in Connect, then return here. This checkpoint is safe to resume.",this.render()},m=y=>{this.transientMessage=y.state==="waiting_for_approval"?"Waiting for authority-move approval in Connect\u2026":`Connect is retrying (attempt ${y.attempt}).`,this.render()};try{i?await this.host.connectSync.resumeAdoption({signal:f.signal,onVerification:p,onStatus:m}):await this.host.connectSync.adoptLocalCollection({controlUrl:o,mirrorName:a},{signal:f.signal,onVerification:p,onStatus:m}),this.enrollmentVerification="",this.transientMessage="Hosted mdbase is authoritative and this vault is now its read-write mirror.",await this.refresh(!0)}finally{this.enrollmentAbort===f&&(this.enrollmentAbort=null)}}),i&&!["activating","adopted"].includes(i.phase)){let f=n.createEl("button",{text:"Cancel adoption"});f.disabled=this.busy,f.onclick=()=>void this.perform(async()=>{await this.host.connectSync.cancelAdoption(),this.enrollmentVerification="",this.transientMessage="Collection adoption cancelled. This vault remains the local authority.",await this.refresh(!0)})}}renderMirrorPreview(t,i){let n=t.createEl("section",{cls:"mdbase-editor-section"});n.createEl("h3",{text:"Sync preview"});let s=n.createDiv({cls:"mdbase-status-list"});if(Ne(s,"Download documents",String(i.download_documents)),Ne(s,"Upload documents",String(i.upload_documents)),Ne(s,"Unchanged documents",String(i.unchanged_documents)),i.collisions.length){n.createDiv({cls:"mdbase-inline-error",text:`${i.collisions.length} path collision${i.collisions.length===1?"":"s"} must be resolved before sync.`});let o=n.createEl("ul");for(let a of i.collisions.slice(0,100))o.createEl("li",{text:a})}if(i.local_issues.length){n.createDiv({cls:"mdbase-inline-error",text:`${i.local_issues.length} local file${i.local_issues.length===1?"":"s"} cannot be uploaded until its frontmatter is fixed.`});let o=n.createEl("ul");for(let a of i.local_issues.slice(0,100))o.createEl("li",{text:`${a.path}: ${a.message}`})}}renderConflicts(t,i){var s;let n=t.createEl("section",{cls:"mdbase-editor-section"});n.createEl("h3",{text:"Conflicts"});for(let o of i.conflicts){let a=n.createDiv({cls:"mdbase-conflict-row"}),c=a.createDiv();c.createEl("strong",{text:(s=o.path)!=null?s:o.record_id}),c.createDiv({text:o.message});let l=a.createDiv({cls:"mdbase-actions"});for(let u of["local","remote"]){let d=l.createEl("button",{text:u==="local"?"Keep local":"Use remote"});d.disabled=this.busy,d.onclick=()=>void this.perform(async()=>{this.mirrorStatus=await this.host.connectSync.resolveConflict(o.record_id,u),this.render()})}}}renderLocalMirrorIssues(t,i){let n=t.createEl("section",{cls:"mdbase-editor-section"});n.createEl("h3",{text:"Local files needing attention"}),n.createEl("p",{text:"These files remain untouched and unsynced. Other valid Markdown continues to synchronize."});for(let s of i.local_issues){let o=n.createDiv({cls:"mdbase-conflict-row"}),a=o.createDiv();a.createEl("strong",{text:s.path}),a.createDiv({text:s.message});let l=o.createDiv({cls:"mdbase-actions"}).createEl("button",{text:"Open file"});l.disabled=this.busy,l.onclick=()=>void this.host.openFileByPath(s.path)}}renderIssues(t){var b;let i=t.createDiv({cls:"mdbase-issues-document"}),n=this.host.getIssues(),s=new Set(n.map(g=>g.path)).size,o=i.createDiv({cls:"mdbase-document-header"}),a=o.createDiv();a.createEl("h2",{text:"Issues"}),a.createEl("p",{text:n.length?`${n.length.toLocaleString()} validation issues in ${s.toLocaleString()} files.`:"The collection has no current validation issues."});let c=o.createEl("button",{text:"Validate collection"});c.disabled=this.busy,c.onclick=()=>void this.perform(async()=>{await this.host.validateCollection(),this.render()});let l=i.createDiv({cls:"mdbase-issue-controls"}),u=l.createEl("select");u.setAttr("aria-label","Issue severity"),u.createEl("option",{value:"all",text:"All severities"}),u.createEl("option",{value:"error",text:"Errors"}),u.createEl("option",{value:"warn",text:"Warnings"}),u.value=this.issueSeverity,u.onchange=()=>{this.issueSeverity=u.value==="error"||u.value==="warn"?u.value:"all",this.issueLimit=250,this.render()};let d=l.createEl("input",{type:"search"});d.setAttr("aria-label","Filter issues"),d.placeholder="Filter by path, code, field, or message",d.value=this.issueQuery,d.oninput=()=>{this.issueQuery=d.value,this.issueLimit=250,this.render();let g=this.containerEl.querySelector(".mdbase-issue-controls input[type='search']");g==null||g.focus(),g==null||g.setSelectionRange(g.value.length,g.value.length)};let f=this.issueQuery.trim().toLowerCase(),p=n.filter(g=>{var _;return this.issueSeverity!=="all"&&g.severity!==this.issueSeverity?!1:f?`${g.path} ${g.code} ${(_=g.field)!=null?_:""} ${g.message}`.toLowerCase().includes(f):!0}),m=new Set(p.map(g=>g.path)).size;if(i.createDiv({cls:"mdbase-issues-summary",text:p.length===n.length?`Showing ${Math.min(p.length,this.issueLimit).toLocaleString()} of ${p.length.toLocaleString()} issues`:`${p.length.toLocaleString()} matching issues in ${m.toLocaleString()} files`}),!p.length){i.createDiv({cls:"mdbase-empty-state",text:"No validation issues."});return}let h=p.slice(0,this.issueLimit),y=new Map;for(let g of h)y.set(g.path,[...(b=y.get(g.path))!=null?b:[],g]);for(let[g,_]of y){let S=i.createEl("section",{cls:"mdbase-issue-group"}),v=S.createDiv({cls:"mdbase-issue-group-header"}),P=v.createEl("button",{cls:"mdbase-issue-file-button"});(0,Se.setIcon)(P.createSpan({cls:"mdbase-issue-file-icon"}),"file-text"),P.createSpan({cls:"mdbase-issue-file-path",text:g}),P.onclick=()=>void this.host.openFileByPath(g),v.createSpan({cls:"mdbase-issue-file-count",text:`${_.length} ${_.length===1?"issue":"issues"}`});for(let x of _){let E=S.createEl("button",{cls:"mdbase-issue-row"});E.setAttr("data-severity",x.severity),E.setAttr("aria-label",`${x.severity==="warn"?"Warning":"Error"}: ${x.message}`),E.createSpan({cls:"mdbase-issue-indicator"}).setAttr("aria-hidden","true");let R=E.createDiv({cls:"mdbase-issue-metadata"});R.createEl("code",{text:x.code}),R.createDiv({cls:"mdbase-issue-context",text:`${x.severity==="warn"?"Warning":"Error"}${x.field?` \xB7 ${x.field}`:""}`}),E.createDiv({cls:"mdbase-issue-row-message",text:x.message}),E.onclick=()=>void this.host.openFileByPath(x.path,x.field)}}if(p.length>h.length){let g=i.createEl("button",{cls:"mdbase-load-more",text:`Load ${Math.min(250,p.length-h.length)} more`});g.onclick=()=>{this.issueLimit+=250,this.render()}}}async selectType(t,i=!0){if(i&&this.dirty&&t!==this.selectedPath){new Se.Notice("Save or discard the current type changes before switching.");return}let n=await this.host.loadTypeModel(t);this.selectedPath=t,this.model=n,this.originalModel=Sf(n),this.yamlDraft=`${at(p_(n),n.body)} -`,this.dirty=!1,this.editorMode="design",this.render()}createType(){if(this.dirty){new Se.Notice("Save or discard the current type changes before creating another type.");return}let t=$f();this.selectedPath=null,this.model=t,this.originalModel=null,this.yamlDraft=`${at(Hs(t),t.body)} -`,this.dirty=!0,this.editorMode="design",this.render()}switchEditorMode(t){if(!(!this.model||t===this.editorMode)){if(t==="yaml")try{this.yamlDraft=`${at(p_(this.model),this.model.body)} -`}catch(i){new Se.Notice(i instanceof Error?i.message:String(i));return}else if(!this.readYamlDraftIntoModel())return;this.editorMode=t,this.render()}}readYamlDraftIntoModel(){var i,n;let t=Ue(this.yamlDraft);if(!t.hasFrontmatter||t.error)return new Se.Notice(`Invalid type YAML: ${(i=t.error)!=null?i:"frontmatter is missing"}`),!1;if(t.frontmatter.kind!=="mdbase.type")return new Se.Notice("Canonical v0.3 type YAML requires kind: mdbase.type."),!1;try{return this.model=ec(t.frontmatter,t.body,((n=this.model)==null?void 0:n.name)||"type"),!0}catch(s){return new Se.Notice(s instanceof Error?s.message:String(s)),!1}}async saveCurrentType(){if(!(!this.model||this.model.specProfile!=="v0.3"||this.model.readOnlyReason)&&!(this.editorMode==="yaml"&&!this.readYamlDraftIntoModel())){if(!this.model.name.trim()){new Se.Notice("Type name is required.");return}await this.perform(async()=>{let t=await this.host.saveTypeModel(this.model,this.selectedPath);this.selectedPath=t.path,this.originalModel=Sf(this.model),this.dirty=!1,this.transientMessage=`Saved ${t.path}.`,await this.refresh(!0)})}}markDirty(t=!1){var o,a;if(this.dirty=!0,t){this.render();return}let i=this.containerEl.querySelector(".mdbase-editor-title-line");i&&!i.querySelector(".mdbase-dirty")&&i.createSpan({cls:"mdbase-dirty",text:"Unsaved"});let n=this.containerEl.querySelector(".mdbase-editor-actions .mod-cta");n&&((o=this.model)==null?void 0:o.specProfile)==="v0.3"&&!this.model.readOnlyReason&&((a=this.host.getMirrorProfile())==null?void 0:a.mode)!=="read_only"&&(n.disabled=!1);let s=this.containerEl.querySelector(".mdbase-change-review");if(s){let c=s.querySelector("p");c&&c.setText("Pending changes. Review details after leaving the current field.")}}async refreshMirrorStatus(){try{this.mirrorStatus=await this.host.connectSync.status()}catch(t){this.mirrorStatus=null,this.transientMessage=t instanceof Error?t.message:String(t)}}async perform(t){if(!this.busy){this.busy=!0,this.transientMessage="",this.render();try{await t()}catch(i){let n=i instanceof Error?i.message:String(i);this.transientMessage=n,new Se.Notice(n)}finally{this.busy=!1,this.render()}}}};function p_(r){var e;return r.specProfile==="v0.3"&&!r.readOnlyReason?Hs(r):Sf((e=r.originalFrontmatter)!=null?e:{name:r.name,fields:Object.fromEntries(r.fields.map(t=>[t.name,t.definition]))})}var yn="mdbase-issues-view",rO={validateOnSave:!0,validateOnOpen:!0,showNoticeOnSave:!1,interopEnabled:!1,mirrorProfile:null};function iO(r){if(!r||typeof r!="object"||Array.isArray(r))return!1;let e=r;return e.version===1&&typeof e.syncUrl=="string"&&typeof e.controlUrl=="string"&&typeof e.collectionId=="string"&&typeof e.replicaId=="string"&&(e.mode==="read_only"||e.mode==="read_write")&&typeof e.name=="string"&&typeof e.enrollmentId=="string"&&typeof e.accessTokenExpiresAt=="string"}function nO(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var Ks=class extends M.Modal{constructor(t,i,n="",s=""){super(t);this.resolvePromise=null;this.settled=!1;this.title=i,this.placeholder=n,this.defaultValue=s}openAndGetValue(){return new Promise(t=>{this.settled=!1,this.resolvePromise=t,this.open()})}onOpen(){let{contentEl:t}=this;t.empty(),t.createEl("h3",{text:this.title});let i=t.createEl("input",{type:"text"});i.placeholder=this.placeholder,i.value=this.defaultValue,i.addClass("prompt-input");let n=t.createDiv({cls:"modal-button-container"}),s=n.createEl("button",{text:"Cancel"}),o=n.createEl("button",{text:"OK"});o.addClass("mod-cta"),s.onclick=()=>{this.finish(null),this.close()},o.onclick=()=>{this.finish(i.value.trim()),this.close()},i.addEventListener("keydown",a=>{a.key==="Enter"&&(a.preventDefault(),this.finish(i.value.trim()),this.close()),a.key==="Escape"&&(a.preventDefault(),this.finish(null),this.close())}),window.setTimeout(()=>i.focus(),0)}onClose(){this.settled||this.finish(null),this.contentEl.empty()}finish(t){var i;this.settled||(this.settled=!0,(i=this.resolvePromise)==null||i.call(this,t),this.resolvePromise=null)}},Ef=class extends M.SuggestModal{constructor(t,i,n){super(t);this.resultHandled=!1;this.typeDefs=[...i].sort((s,o)=>s.name.localeCompare(o.name)),this.onResult=n,this.setPlaceholder("Type to search..."),this.setInstructions([{command:"\u2191\u2193",purpose:"navigate"},{command:"\u21B5",purpose:"select"},{command:"esc",purpose:"cancel"}]),this.containerEl.addClass("mdbase-type-picker-modal"),this.titleEl.setText("Select type definition")}getSuggestions(t){let i=t.trim().toLowerCase();return i?this.typeDefs.filter(n=>{var a,c,l;let s=(c=(a=n.match)==null?void 0:a.path_glob)!=null?c:"";return`${n.name} ${(l=n.display_name_key)!=null?l:""} ${n.filePath} ${s}`.toLowerCase().includes(i)}).slice(0,100):this.typeDefs.slice(0,100)}renderSuggestion(t,i){var o,a;let n=i.createDiv({cls:"mdbase-type-picker-suggestion"});n.createDiv({cls:"mdbase-type-picker-name",text:t.name});let s=n.createDiv({cls:"mdbase-type-picker-meta"});s.createSpan({cls:"mdbase-type-picker-path",text:t.filePath}),s.createSpan({cls:"mdbase-type-picker-count",text:`${Object.keys((o=t.fields)!=null?o:{}).length} fields`}),(a=t.match)!=null&&a.path_glob&&n.createDiv({cls:"mdbase-type-picker-match",text:`match: ${t.match.path_glob}`})}onChooseSuggestion(t){this.resultHandled=!0,this.onResult({type:"selected",typeDef:t})}onClose(){window.setTimeout(()=>{this.resultHandled||this.onResult({type:"cancelled"})},0),super.onClose()}};function sO(r,e){return new Promise(t=>{new Ef(r,e,n=>{if(n.type==="selected"){t(n.typeDef);return}t(null)}).open()})}var Af=class extends M.ItemView{constructor(t,i){super(t);this.severityFilter="all";this.query="";this.plugin=i}getViewType(){return yn}getDisplayText(){return"mdbase issues"}getIcon(){return"shield-alert"}async onOpen(){this.containerEl.empty(),this.containerEl.addClass("mdbase-issues-view"),this.render()}render(){var m;let t=this.containerEl;t.empty(),t.addClass("mdbase-issues-view");let i=t.createDiv({cls:"mdbase-issues-header"});i.createEl("h3",{text:"mdbase Issues"});let s=i.createDiv({cls:"mdbase-issues-header-actions"}).createEl("button",{text:"Refresh"});s.addClass("mod-cta"),s.onclick=()=>{this.plugin.runCollectionValidation(!1)};let o=t.createDiv({cls:"mdbase-issues-controls"}),a=o.createEl("select");a.addClass("mdbase-issues-severity"),a.createEl("option",{value:"all",text:"All severities"}),a.createEl("option",{value:"error",text:"Errors only"}),a.createEl("option",{value:"warn",text:"Warnings only"}),a.value=this.severityFilter,a.onchange=()=>{let h=a.value;(h==="error"||h==="warn"||h==="all")&&(this.severityFilter=h),this.render()};let c=o.createEl("input",{type:"search"});c.addClass("mdbase-issues-query"),c.placeholder="Filter by path, code, message, field",c.value=this.query,c.oninput=()=>{this.query=c.value,this.render()};let l=this.plugin.getIssues(),u=this.query.trim().toLowerCase(),d=l.filter(h=>{var b;return this.severityFilter!=="all"&&h.severity!==this.severityFilter?!1:u?`${h.path} ${h.code} ${h.message} ${(b=h.field)!=null?b:""}`.toLowerCase().includes(u):!0}),f=d.slice(0,500);if(t.createDiv({cls:"mdbase-issues-count",text:d.length>f.length?`Showing ${f.length} of ${d.length} matching issues`:d.length===l.length?`${d.length} issue${d.length===1?"":"s"}`:`${d.length} of ${l.length} issue${l.length===1?"":"s"}`}),d.length===0){t.createDiv({cls:"mdbase-empty",text:l.length===0?"No validation issues.":"No issues match current filters."});return}let p=new Map;for(let h of f){let y=(m=p.get(h.path))!=null?m:[];y.push(h),p.set(h.path,y)}for(let[h,y]of p.entries()){t.createDiv({cls:"mdbase-issue-file",text:h});for(let b of y){let g=t.createDiv({cls:"mdbase-issue-item"});g.setAttr("data-severity",b.severity),g.createDiv({cls:"mdbase-issue-code",text:`${b.severity.toUpperCase()} \xB7 ${b.code}${b.field?` \xB7 ${b.field}`:""}`}),g.createDiv({cls:"mdbase-issue-message",text:b.message});let _=g.createDiv({cls:"mdbase-issue-actions"}),S=_.createEl("button",{text:b.field?"Open field":"Open file"});S.onclick=P=>{P.stopPropagation(),this.plugin.openIssue(b)};let v=this.plugin.getQuickFixLabel(b);if(v){let P=_.createEl("button",{text:v});P.onclick=x=>{x.stopPropagation(),this.plugin.applyQuickFix(b)}}g.onclick=()=>{this.plugin.openIssue(b)}}}}},kf=class extends M.PluginSettingTab{constructor(e,t){super(e,t),this.plugin=t}display(){let{containerEl:e}=this;e.empty(),e.createEl("h2",{text:"mdbase settings"}),new M.Setting(e).setName("Validate on save").setDesc("Run mdbase validation when a markdown file is modified.").addToggle(t=>t.setValue(this.plugin.settings.validateOnSave).onChange(async i=>{this.plugin.settings.validateOnSave=i,await this.plugin.saveSettings()})),new M.Setting(e).setName("Validate on file open").setDesc("Validate the active note when opened.").addToggle(t=>t.setValue(this.plugin.settings.validateOnOpen).onChange(async i=>{this.plugin.settings.validateOnOpen=i,await this.plugin.saveSettings()})),new M.Setting(e).setName("Show notices on save").setDesc("Display a notice when save-time validation finds issues.").addToggle(t=>t.setValue(this.plugin.settings.showNoticeOnSave).onChange(async i=>{this.plugin.settings.showNoticeOnSave=i,await this.plugin.saveSettings()})),new M.Setting(e).setName("Allow local application interoperability").setDesc("Allow installed Obsidian plugins to exchange validated mdbase events and actions in this vault. Contracts establish compatibility; this switch is the separate user grant.").addToggle(t=>t.setValue(this.plugin.settings.interopEnabled).onChange(async i=>{this.plugin.settings.interopEnabled=i,await this.plugin.saveSettings()}))}},rc=class extends M.Plugin{constructor(t,i){super(t,i);this.issueMap=new Map;this.sortedIssuesCache=null;this.schemaCache=null;this.schemaLoadPromise=null;this.pendingSaveValidations=new Map;this.saveValidationDebounceMs=250;this.runtimePolicy={...Nr,capabilities:{...Nr.capabilities}};this.runtimePolicyDiagnostics=[];this.runtimePolicyRefreshGeneration=0;this.connectSync=new Xa(t,{getMirrorProfile:()=>this.getMirrorProfile(),saveMirrorProfile:async n=>{this.settings.mirrorProfile=n,await this.saveSettings()}}),this.interopBridge=new Yo(t,()=>{var n;return((n=this.settings)==null?void 0:n.interopEnabled)===!0}),this.api={apiVersion:1,runtime:new ns({policyResolver:()=>this.runtimePolicy}),interop:this.interopBridge,getRuntimeStatus:()=>({policyId:this.runtimePolicy.id,policyPath:this.runtimePolicyPath,diagnostics:this.runtimePolicyDiagnostics.map(n=>({...n}))}),getInteropStatus:()=>{var n;return{enabled:((n=this.settings)==null?void 0:n.interopEnabled)===!0,profileVersion:"0.1"}}}}async onload(){await this.loadSettings(),await this.connectSync.initialize(),await this.refreshRuntimePolicy(),(0,M.addIcon)(mn,d_),this.statusBarEl=this.addStatusBarItem(),this.updateStatusBar(),this.registerView(vi,i=>new tc(i,this)),this.registerView(yn,i=>new Af(i,this)),this.addSettingTab(new kf(this.app,this)),this.addRibbonIcon(mn,"Open mdbase",()=>void this.openWorkspace()),this.addCommand({id:"mdbase-open",name:"mdbase: Open workspace",callback:()=>void this.openWorkspace()}),this.addCommand({id:"mdbase-initialize-collection",name:"mdbase: Initialize collection",callback:()=>void this.initializeCollectionCommand()}),this.addCommand({id:"mdbase-create-type",name:"mdbase: Create type definition",callback:()=>void this.openWorkspace("types")}),this.addCommand({id:"mdbase-edit-type",name:"mdbase: Edit type definition",callback:()=>void this.openWorkspace("types")}),this.addCommand({id:"mdbase-edit-current-type",name:"mdbase: Edit current type definition",callback:()=>void this.openWorkspace("types")}),this.addCommand({id:"mdbase-create-note-from-type",name:"mdbase: Create note from type",callback:()=>void this.createNoteFromTypeCommand()}),this.addCommand({id:"mdbase-validate-current-note",name:"mdbase: Validate current note",callback:()=>void this.validateCurrentNoteCommand()}),this.addCommand({id:"mdbase-validate-collection",name:"mdbase: Validate collection",callback:()=>void this.runCollectionValidation(!0)}),this.addCommand({id:"mdbase-open-issues-view",name:"mdbase: Open issues view",callback:()=>void this.openWorkspace("issues")}),this.addCommand({id:"mdbase-sync",name:"mdbase: Sync collection authority",callback:()=>void this.syncHostedCollectionCommand()}),this.addCommand({id:"mdbase-open-sync",name:"mdbase: Open sync",callback:()=>void this.openWorkspace("sync")}),this.registerEvent(this.app.vault.on("modify",i=>{i instanceof M.TFile&&this.onVaultModify(i)})),this.registerEvent(this.app.vault.on("rename",(i,n)=>{i instanceof M.TFile&&this.onVaultRename(i,n)})),this.registerEvent(this.app.vault.on("delete",i=>{i instanceof M.TFile&&this.onVaultDelete(i)})),this.registerEvent(this.app.vault.on("create",i=>{i instanceof M.TFile&&this.onVaultCreate(i)})),this.registerEvent(this.app.workspace.on("file-open",i=>{this.settings.validateOnOpen&&(!(i instanceof M.TFile)||i.extension!=="md"||this.validateFileAndStore(i,"open"))}));let t=this.app.workspace.getActiveFile();t&&this.settings.validateOnOpen&&this.validateFileAndStore(t,"open")}async onunload(){await this.interopBridge.dispose(),await this.api.runtime.dispose(),this.app.workspace.getLeavesOfType(vi).forEach(t=>t.detach()),this.app.workspace.getLeavesOfType(yn).forEach(t=>t.detach()),this.clearAllPendingSaveValidations()}async loadSettings(){this.settings=Object.assign({},rO,await this.loadData()),iO(this.settings.mirrorProfile)||(this.settings.mirrorProfile=null)}async saveSettings(){await this.saveData(this.settings)}getIssues(){var t;return(t=this.sortedIssuesCache)!=null||(this.sortedIssuesCache=Array.from(this.issueMap.values()).flat().sort((i,n)=>i.path.localeCompare(n.path)||i.severity.localeCompare(n.severity)||i.code.localeCompare(n.code))),this.sortedIssuesCache}getMirrorProfile(){return this.settings.mirrorProfile?{...this.settings.mirrorProfile}:null}async loadWorkspaceSchema(t=!1){return this.getConfigAndTypes(t)}async loadTypeModel(t){var s;let i=this.app.vault.getAbstractFileByPath((0,M.normalizePath)(t));if(!(i instanceof M.TFile))throw new Error(`Type file not found: ${t}`);let n=Ue(await this.app.vault.cachedRead(i));if(!n.hasFrontmatter||n.error)throw new Error(`Invalid type frontmatter: ${(s=n.error)!=null?s:"frontmatter is missing"}`);return ec(n.frontmatter,n.body,i.basename)}async saveTypeModel(t,i){var a;if(this.connectSync.assertLocalAuthorityWritable(),((a=this.getMirrorProfile())==null?void 0:a.mode)==="read_only")throw new Error("This mirror has read-only access. Re-enroll it with write access before editing types.");let n=await ai(this.app.vault);if(!n)throw new Error("No mdbase.yaml found.");if(!n.spec_version.startsWith("0.3."))throw new Error("mdbase v0.2 type definitions are read-only. Migrate the collection first.");let s=i?this.app.vault.getAbstractFileByPath((0,M.normalizePath)(i)):null;if(s!=null&&!(s instanceof M.TFile))throw new Error(`Type file not found: ${i}`);let o=await this.writeTypeDefinition(n,t,s);return this.refreshWorkspaceViews(!0),o}async initializeCollection(){this.connectSync.assertLocalAuthorityWritable(),await this.initializeCollectionCommand(),this.refreshWorkspaceViews(!0)}async validateCollection(){await this.runCollectionValidation(!1)}analyzeMigration(){if(this.getMirrorProfile())throw new Error("Collection authority resources must be migrated at the collection authority.");return a_(this.app.vault)}async applyMigration(t,i){var s,o;if(this.connectSync.assertLocalAuthorityWritable(),this.getMirrorProfile())throw new Error("Collection authority resources must be migrated at the collection authority.");let n=await c_(this.app.vault,t,{allowLossy:i});if(!n.applied)throw new Error(n.restored?`Migration failed and all writes were rolled back. ${(s=n.error)!=null?s:""}`.trim():`Migration needs manual recovery. See ${n.manifestPath}. ${(o=n.error)!=null?o:""}`.trim());this.invalidateSchemaCache(),await this.refreshRuntimePolicy(),new M.Notice(`Migrated to mdbase v0.3. Recovery manifest: ${n.manifestPath}`),this.refreshWorkspaceViews(!0)}async openIssue(t){await this.openFileByPath(t.path,t.field)}getQuickFixLabel(t){return["unknown_field","schema_additional_properties"].includes(t.code)&&t.field?"Remove field":["missing_required","schema_required"].includes(t.code)&&t.field?"Add placeholder":null}async applyQuickFix(t){this.connectSync.assertLocalAuthorityWritable();let i=this.app.vault.getAbstractFileByPath(t.path);if(!(i instanceof M.TFile)){new M.Notice(`File not found: ${t.path}`);return}let n=await this.app.vault.cachedRead(i),s=Ue(n);if(s.error){new M.Notice(`Cannot apply quick fix: invalid frontmatter (${s.error})`);return}if(["unknown_field","schema_additional_properties"].includes(t.code)&&t.field){let o=ta(t.field);if(!(o in s.frontmatter)){new M.Notice(`Field '${o}' not found in frontmatter.`);return}delete s.frontmatter[o],await this.app.vault.modify(i,`${at(s.frontmatter,s.body)} -`),new M.Notice(`Removed '${o}' from ${i.basename}`),await this.validateFileAndStore(i,"manual");return}if(["missing_required","schema_required"].includes(t.code)&&t.field){let o=ta(t.field);s.frontmatter[o]===void 0&&(s.frontmatter[o]="TODO");let a=s.hasFrontmatter?s.body:n;await this.app.vault.modify(i,`${at(s.frontmatter,a)} -`),new M.Notice(`Added placeholder '${o}' to ${i.basename}`),await this.validateFileAndStore(i,"manual");return}new M.Notice("No quick fix available for this issue.")}async openFileByPath(t,i){let n=this.app.vault.getAbstractFileByPath(t);if(!(n instanceof M.TFile)){new M.Notice(`File not found: ${t}`);return}await this.app.workspace.getLeaf(!0).openFile(n),i&&this.revealFrontmatterField(n,i)}revealFrontmatterField(t,i){let n=this.app.workspace.getMostRecentLeaf();if(!n||!(n.view instanceof M.MarkdownView))return;let s=n.view;if(!(s.file instanceof M.TFile)||s.file.path!==t.path)return;let o=s.editor,a=o.lineCount();if(a<3)return;let c=ta(i),l=new RegExp(`^\\s*${nO(c)}\\s*:`);if(o.getLine(0).trim()==="---")for(let u=1;us.severity==="error").length,n=t.length-i;if(t.length===0){this.statusBarEl.setText("mdbase: no issues");return}this.statusBarEl.setText(`mdbase: ${i} error${i===1?"":"s"}, ${n} warning${n===1?"":"s"}`)}async openIssuesView(){var n;let t=this.app.workspace.getLeavesOfType(yn)[0];if(t){this.app.workspace.revealLeaf(t),t.view.render();return}let i=(n=this.app.workspace.getRightLeaf(!1))!=null?n:this.app.workspace.getLeaf(!0);await i.setViewState({type:yn,active:!0}),this.app.workspace.revealLeaf(i)}async openWorkspace(t="types"){let i=this.app.workspace.getLeavesOfType(vi)[0];if(i){this.app.workspace.revealLeaf(i);let o=i.view;o.showDestination(t),await o.refresh();return}let n=this.app.workspace.getLeaf(!0);await n.setViewState({type:vi,active:!0}),this.app.workspace.revealLeaf(n),n.view.showDestination(t)}refreshWorkspaceViews(t=!1){for(let i of this.app.workspace.getLeavesOfType(vi))i.view.refresh(t)}refreshIssueViews(){this.updateStatusBar();for(let t of this.app.workspace.getLeavesOfType(yn))t.view.render();this.refreshWorkspaceViews()}setFileIssues(t,i){i.length===0?this.issueMap.delete(t):this.issueMap.set(t,i),this.sortedIssuesCache=null,this.refreshIssueViews()}clearFileIssues(t){this.issueMap.has(t)&&(this.issueMap.delete(t),this.sortedIssuesCache=null,this.refreshIssueViews())}moveFileIssues(t,i){let n=this.issueMap.get(t);n&&(this.issueMap.delete(t),this.issueMap.set(i,n.map(s=>({...s,path:i}))),this.sortedIssuesCache=null,this.refreshIssueViews())}clearAllPendingSaveValidations(){for(let t of this.pendingSaveValidations.values())window.clearTimeout(t);this.pendingSaveValidations.clear()}clearPendingSaveValidation(t){let i=this.pendingSaveValidations.get(t);i!=null&&(window.clearTimeout(i),this.pendingSaveValidations.delete(t))}scheduleSaveValidation(t){this.clearPendingSaveValidation(t.path);let i=window.setTimeout(()=>{this.pendingSaveValidations.delete(t.path),this.validateFileAndStore(t,"save")},this.saveValidationDebounceMs);this.pendingSaveValidations.set(t.path,i)}isSchemaRelevantPath(t){let i=(0,M.normalizePath)(t);if(i==="mdbase.yaml")return!0;let n=new Set(["_types"]);this.schemaCache&&n.add((0,M.normalizePath)(this.schemaCache.config.settings.types_folder));for(let s of n)if(i===s||i.startsWith(`${s}/`))return!0;return!1}invalidateSchemaCache(){this.schemaCache=null,this.schemaLoadPromise=null}async getConfigAndTypes(t=!1){if(t&&this.invalidateSchemaCache(),this.schemaCache)return this.schemaCache;if(this.schemaLoadPromise)return this.schemaLoadPromise;this.schemaLoadPromise=(async()=>{let i=await ai(this.app.vault);if(!i)return null;let n=await Eb(this.app.vault,i);return{config:i,types:n}})();try{let i=await this.schemaLoadPromise;return i&&(this.schemaCache=i),i}finally{this.schemaLoadPromise=null}}async requireConfigAndTypes(t={}){var s,o;let i=(s=t.background)!=null?s:!1,n=await this.getConfigAndTypes((o=t.forceReload)!=null?o:!1);return n?(n.types.size===0&&!i&&new M.Notice(`No types found in ${n.config.settings.types_folder}`),n):(i||new M.Notice("No mdbase.yaml found. Run 'mdbase: Initialize collection' first."),null)}onVaultModify(t){this.isRuntimePolicyRelevantPath(t.path)&&this.refreshRuntimePolicy(),this.isSchemaRelevantPath(t.path)&&(this.invalidateSchemaCache(),this.refreshWorkspaceViews()),this.settings.validateOnSave&&t.extension==="md"&&this.scheduleSaveValidation(t)}onVaultRename(t,i){(this.isRuntimePolicyRelevantPath(i)||this.isRuntimePolicyRelevantPath(t.path))&&this.refreshRuntimePolicy(),(this.isSchemaRelevantPath(i)||this.isSchemaRelevantPath(t.path))&&(this.invalidateSchemaCache(),this.refreshWorkspaceViews()),t.extension==="md"&&(this.clearPendingSaveValidation(i),this.moveFileIssues(i,t.path),this.settings.validateOnSave&&this.scheduleSaveValidation(t))}onVaultDelete(t){this.isRuntimePolicyRelevantPath(t.path)&&this.refreshRuntimePolicy(),this.isSchemaRelevantPath(t.path)&&(this.invalidateSchemaCache(),this.refreshWorkspaceViews()),t.extension==="md"&&(this.clearPendingSaveValidation(t.path),this.clearFileIssues(t.path))}onVaultCreate(t){this.isRuntimePolicyRelevantPath(t.path)&&this.refreshRuntimePolicy(),this.isSchemaRelevantPath(t.path)&&(this.invalidateSchemaCache(),this.refreshWorkspaceViews())}isRuntimePolicyRelevantPath(t){let i=(0,M.normalizePath)(t);return i==="mdbase.yaml"||i===this.runtimePolicyPath}async refreshRuntimePolicy(){let t=++this.runtimePolicyRefreshGeneration,i=await ai(this.app.vault),n=await Cb(this.app.vault,i);if(t===this.runtimePolicyRefreshGeneration){this.runtimePolicy=n.policy,this.runtimePolicyPath=n.path,this.runtimePolicyDiagnostics=n.diagnostics;for(let s of n.diagnostics)console.warn(`[mdbase/runtime] ${s.code}: ${s.message}`)}}async validateFileAndStore(t,i){let n=await this.requireConfigAndTypes({background:i!=="manual"});if(!n)return i!=="manual"&&this.clearFileIssues(t.path),[];let s=await yu(this.app.vault,t,n.config,n.types);return this.setFileIssues(t.path,s),i==="save"&&this.settings.showNoticeOnSave&&s.length>0&&new M.Notice(`mdbase: ${s.length} issue${s.length===1?"":"s"} in ${t.basename}`),s}async initializeCollectionCommand(){if(this.connectSync.assertLocalAuthorityWritable(),this.getMirrorProfile()){new M.Notice("This vault is configured as a mirror. Sync it instead of initializing a local collection.");return}let{created:t}=await wb(this.app.vault);if(this.invalidateSchemaCache(),t.length===0){new M.Notice("mdbase collection already initialized.");return}new M.Notice(`Initialized mdbase collection: ${t.join(", ")}`)}async syncHostedCollectionCommand(){if(!this.getMirrorProfile()){await this.openWorkspace("sync");return}try{let t=await this.connectSync.sync();this.invalidateSchemaCache(),this.refreshWorkspaceViews(!0);let i=t.conflicts.length+t.local_issues.length;new M.Notice(i?`Sync completed with ${i} item${i===1?"":"s"} needing attention.`:"mdbase sync completed.")}catch(t){new M.Notice(`mdbase sync failed: ${t instanceof Error?t.message:String(t)}`),await this.openWorkspace("sync")}}async createNoteFromTypeCommand(){var u,d;this.connectSync.assertLocalAuthorityWritable();let t=await this.requireConfigAndTypes();if(!t)return;if(t.types.size===0){new M.Notice("No type definitions found.");return}let i=await sO(this.app,Array.from(t.types.values()));if(!i)return;let n=Pb(i,t.config),s=xb(i,n);for(let[f,p]of s){let m=`Required field: ${f}`,h=await new Ks(this.app,m,(u=p.type)!=null?u:"string").openAndGetValue();if(h==null)return;if(h.trim().length===0){new M.Notice(`Field '${f}' is required.`);return}try{n[f]=gu(h,p)}catch(y){new M.Notice(`Invalid value for ${f}: ${y instanceof Error?y.message:String(y)}`);return}}let o=(d=i.display_name_key)!=null?d:"title";if(n[o]==null){let f=await new Ks(this.app,`Optional ${o} (used for filename)`,"").openAndGetValue();f&&f.trim().length>0&&(n[o]=f.trim())}let a=await Rb(this.app.vault,i,n),c=await new Ks(this.app,"Note path","Relative path in vault",a).openAndGetValue();if(c==null)return;let l=(0,M.normalizePath)(c.trim().length>0?c.trim():a);l.endsWith(".md")||(l=`${l}.md`);try{let f=await Tb(this.app.vault,l,n);await this.app.workspace.getLeaf(!0).openFile(f),new M.Notice(`Created note: ${f.path}`),await this.validateFileAndStore(f,"manual")}catch(f){new M.Notice(f instanceof Error?f.message:String(f))}}async validateCurrentNoteCommand(){let t=this.app.workspace.getActiveFile();if(!(t instanceof M.TFile)||t.extension!=="md"){new M.Notice("Open a markdown note first.");return}let i=await this.validateFileAndStore(t,"manual");i.length===0?new M.Notice("No issues in current note."):(new M.Notice(`Found ${i.length} issue${i.length===1?"":"s"} in current note.`),await this.openIssuesView())}async runCollectionValidation(t){var o;let i=await this.requireConfigAndTypes({background:!1});if(!i)return;let n=await kb(this.app.vault,i.config,i.types),s=new Map;for(let a of n){let c=(o=s.get(a.path))!=null?o:[];c.push(a),s.set(a.path,c)}if(this.issueMap=s,this.sortedIssuesCache=null,this.refreshIssueViews(),t)if(n.length===0)new M.Notice("Collection validation passed with no issues.");else{let a=n.filter(l=>l.severity==="error").length,c=n.length-a;new M.Notice(`Collection validation: ${a} error(s), ${c} warning(s)`),await this.openIssuesView()}}async ensureFolderExists(t){let i=(0,M.normalizePath)(t).replace(/\/+$/,"");if(!i)return;let n=i.split("/"),s="";for(let o of n)s=s?`${s}/${o}`:o,await this.app.vault.adapter.exists(s)||await this.app.vault.createFolder(s)}async writeTypeDefinition(t,i,n){let s=i.name.trim();if(!s)throw new Error("Type name is required.");if(!t.spec_version.startsWith("0.3.")||i.specProfile!=="v0.3")throw new Error("mdbase v0.2 type definitions are read-only. Migrate the collection first.");let o=Hs(i),a=i.body.trim()||`# ${s} +`;var yn="mdbase-workspace-view",yO=["string","integer","number","boolean","date","datetime","time","enum","link","list","object","any"];function mn(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function rf(r){return JSON.parse(JSON.stringify(r))}function q0(r){return typeof r.type=="string"?r.type:"any"}function gO(r){if(!Object.prototype.hasOwnProperty.call(r,"field"))return"field";let e=2;for(;Object.prototype.hasOwnProperty.call(r,`field${e}`);)e+=1;return`field${e}`}function D0(r,e,t){Object.defineProperty(r,e,{configurable:!0,enumerable:!0,writable:!0,value:t})}function bO(r,e){if(!r)return["A new type definition will be created."];let t=[];r.name!==e.name&&t.push(`Rename type from ${r.name} to ${e.name}.`),(r.matchPathGlob!==e.matchPathGlob||r.matchFieldsPresent!==e.matchFieldsPresent||r.matchWhere!==e.matchWhere)&&t.push("Membership rules changed; different records may match this type.");let n=new Map(r.fields.map(c=>[c.name,c])),s=new Map(e.fields.map(c=>[c.name,c])),i=[...n.keys()].filter(c=>!s.has(c)),o=[...s.keys()].filter(c=>!n.has(c));o.length&&t.push(`Add ${o.length} field${o.length===1?"":"s"}: ${o.join(", ")}.`),i.length&&t.push(`Remove ${i.length} field${i.length===1?"":"s"}: ${i.join(", ")}.`);let a=[...s.entries()].filter(([c,l])=>{var u;return l.definition.required===!0&&((u=n.get(c))==null?void 0:u.definition.required)!==!0}).map(([c])=>c);return a.length&&t.push(`New required fields may invalidate records: ${a.join(", ")}.`),t.length||t.push("Metadata, schema details, or documentation changed."),t}function _t(r,e,t,n,s={}){var l;let i=r.createDiv({cls:"mdbase-form-row"}),o=i.createEl("label",{text:e}),a=`mdbase-${Math.random().toString(36).slice(2)}`;o.htmlFor=a,s.description&&i.createDiv({cls:"mdbase-form-description",text:s.description});let c=s.multiline?i.createEl("textarea"):i.createEl("input",{type:"text"});return c.id=a,c.value=t,c.placeholder=(l=s.placeholder)!=null?l:"",c.addEventListener("input",()=>n(c.value)),c}function Ce(r,e,t){let n=r.createDiv({cls:"mdbase-status-row"});n.createSpan({cls:"mdbase-status-label",text:e}),n.createSpan({cls:"mdbase-status-value",text:t})}function wO(r){if(r<1e3)return String(r);let e=r<1e4?1:0;return`${(r/1e3).toFixed(e)}k`}var Fa=class extends $e.ItemView{constructor(t,n){super(t);this.host=n;this.destination="types";this.editorMode="design";this.schema=null;this.query="";this.selectedPath=null;this.model=null;this.originalModel=null;this.yamlDraft="";this.dirty=!1;this.busy=!1;this.migrationPlan=null;this.allowLossy=!1;this.mirrorStatus=null;this.mirrorPreview=null;this.mirrorProgress=null;this.transientMessage="";this.issueQuery="";this.issueSeverity="all";this.issueLimit=250;this.enrollmentVerification="";this.enrollmentAbort=null}getViewType(){return yn}getDisplayText(){return"mdbase"}getIcon(){return ds}async onOpen(){this.containerEl.addClass("mdbase-workspace"),await this.refresh(!0)}async onClose(){var t;(t=this.enrollmentAbort)==null||t.abort(),this.enrollmentAbort=null}async refresh(t=!1){try{this.schema=await this.host.loadWorkspaceSchema(t),this.selectedPath&&!this.typeEntries().some(n=>n.filePath===this.selectedPath)&&(this.selectedPath=null,this.model=null,this.originalModel=null),!this.selectedPath&&this.typeEntries().length&&!$e.Platform.isMobile&&(this.selectedPath=this.typeEntries()[0].filePath),this.selectedPath&&(!this.model||t)&&await this.selectType(this.selectedPath,!1),this.destination==="sync"&&await this.refreshMirrorStatus(),this.render()}catch(n){this.transientMessage=n instanceof Error?n.message:String(n),this.render()}}showDestination(t){this.destination=t,t==="sync"?this.refreshMirrorStatus().then(()=>this.render()):this.render()}typeEntries(){return this.schema?[...this.schema.types.values()].sort((t,n)=>t.name.localeCompare(n.name)):[]}render(){let t=this.containerEl;t.empty(),t.addClass("mdbase-workspace");let n=t.createDiv({cls:"mdbase-shell"});this.renderTopbar(n),this.transientMessage&&n.createDiv({cls:"mdbase-inline-message",text:this.transientMessage}).setAttr("role","status");let s=n.createDiv({cls:"mdbase-workspace-content"});this.destination==="types"?this.renderTypes(s):this.destination==="sync"?this.renderSync(s):this.renderIssues(s)}renderTopbar(t){let n=t.createDiv({cls:"mdbase-topbar"}),s=n.createDiv({cls:"mdbase-identity"}),i=s.createSpan({cls:"mdbase-mark"});i.setAttr("aria-hidden","true"),(0,$e.setIcon)(i,ds),s.createSpan({cls:"mdbase-title",text:"mdbase"});let o=n.createDiv({cls:"mdbase-nav"});o.setAttr("role","tablist");for(let[a,c]of[["types","Types"],["sync","Sync"],["issues","Issues"]]){let l=o.createEl("button",{text:c});if(l.addClass("mdbase-nav-button"),l.setAttr("role","tab"),l.setAttr("aria-selected",String(this.destination===a)),this.destination===a&&l.addClass("is-active"),a==="issues"&&this.host.getIssues().length){let u=this.host.getIssues().length;l.createSpan({cls:"mdbase-count",text:wO(u)}).setAttr("title",`${u} issues`)}l.onclick=()=>this.showDestination(a)}}renderTypes(t){if(!this.schema){let s=t.createDiv({cls:"mdbase-empty-state"});s.createEl("h2",{text:"Start an mdbase collection"}),s.createEl("p",{text:"Initialize this vault as a local v0.3 collection, or use Sync to connect an empty vault to a collection authority."});let i=s.createDiv({cls:"mdbase-actions"}),o=i.createEl("button",{text:"Initialize local collection"});o.addClass("mod-cta"),o.disabled=this.busy||this.host.getMirrorProfile()!==null,o.onclick=()=>void this.perform(async()=>{await this.host.initializeCollection(),await this.refresh(!0)});let a=i.createEl("button",{text:"Connect collection authority"});a.onclick=()=>this.showDestination("sync");return}this.schema.config.spec_version.startsWith("0.2.")&&this.renderLegacyBanner(t);let n=t.createDiv({cls:"mdbase-types-layout"});this.model&&n.addClass("has-selection"),this.renderTypeList(n),this.renderTypeEditor(n)}renderLegacyBanner(t){var o;let n=t.createDiv({cls:"mdbase-legacy-banner"}),s=n.createDiv();s.createEl("strong",{text:`mdbase ${(o=this.schema)==null?void 0:o.config.spec_version} compatibility mode`}),s.createEl("p",{text:"Types are readable and validation remains available, but authoring is disabled until a reviewed v0.3 migration."});let i=n.createEl("button",{text:this.migrationPlan?"Review migration":"Analyze migration"});i.disabled=this.busy||this.host.getMirrorProfile()!==null,i.onclick=()=>void this.perform(async()=>{this.migrationPlan=await this.host.analyzeMigration(),this.render()}),this.host.getMirrorProfile()&&n.createDiv({cls:"mdbase-form-description",text:"Hosted resources must be migrated at the collection authority."}),this.migrationPlan&&this.renderMigrationReview(t,this.migrationPlan)}renderMigrationReview(t,n){let s=t.createDiv({cls:"mdbase-migration-review"}),i=s.createDiv({cls:"mdbase-section-header"});i.createEl("h3",{text:"Migration review"}),i.createSpan({cls:"mdbase-spec-badge",text:`${n.sourceVersion} \u2192 ${n.targetVersion}`});let o=s.createDiv({cls:"mdbase-status-list"});Ce(o,"Files replaced",String(n.operations.length)),Ce(o,"Type definitions",String(n.typeSummaries.length)),Ce(o,"Record reads verified",String(n.recordsVerified)),n.recordsSkipped&&Ce(o,"Records skipped",String(n.recordsSkipped)),Ce(o,"Record files rewritten","0"),Ce(o,"Recovery backup",n.backupLocation);let a=s.createDiv({cls:"mdbase-review-list"});n.diagnostics.length||a.createDiv({cls:"mdbase-review-ok",text:"No migration diagnostics."});for(let d of n.diagnostics.slice(0,250)){let f=a.createDiv({cls:"mdbase-review-item"});f.setAttr("data-severity",d.severity),f.createDiv({cls:"mdbase-review-code",text:`${d.severity} \xB7 ${d.path}`}),f.createDiv({text:d.message})}if(n.diagnostics.length>250&&a.createDiv({cls:"mdbase-form-description",text:`Showing 250 of ${n.diagnostics.length} diagnostics.`}),!n.applicable){let d=s.createEl("label",{cls:"mdbase-consent"}),f=d.createEl("input",{type:"checkbox"});f.checked=this.allowLossy,f.onchange=()=>{this.allowLossy=f.checked,this.render()},d.createSpan({text:"I reviewed the lossy diagnostics and want to apply this migration."})}let c=s.createDiv({cls:"mdbase-actions"}),l=c.createEl("button",{text:"Apply migration"});l.addClass("mod-warning"),l.disabled=this.busy||!n.applicable&&!this.allowLossy,l.onclick=()=>void this.perform(async()=>{await this.host.applyMigration(n,this.allowLossy),this.migrationPlan=null,this.allowLossy=!1,this.model=null,this.originalModel=null,await this.refresh(!0)});let u=c.createEl("button",{text:"Close review"});u.onclick=()=>{this.migrationPlan=null,this.render()}}renderTypeList(t){var u,d,f,p;let n=t.createDiv({cls:"mdbase-type-list-pane"}),s=n.createDiv({cls:"mdbase-pane-header"});s.createEl("h2",{text:"Types"});let i=s.createEl("button");i.setAttr("aria-label","Create type"),(0,$e.setIcon)(i,"plus"),i.disabled=((d=(u=this.schema)==null?void 0:u.config.spec_version.startsWith("0.2."))!=null?d:!0)||((f=this.host.getMirrorProfile())==null?void 0:f.mode)==="read_only",i.onclick=()=>this.createType();let o=n.createEl("input",{type:"search"});o.addClass("mdbase-type-search"),o.placeholder="Search types",o.setAttr("aria-label","Search types"),o.value=this.query,o.oninput=()=>{this.query=o.value,this.render();let m=this.containerEl.querySelector(".mdbase-type-search");m==null||m.focus(),m==null||m.setSelectionRange(m.value.length,m.value.length)};let a=n.createDiv({cls:"mdbase-type-list"}),c=this.query.trim().toLowerCase(),l=this.typeEntries().filter(m=>{var h;return`${m.name} ${(h=m.description)!=null?h:""} ${m.filePath}`.toLowerCase().includes(c)});if(!l.length){a.createDiv({cls:"mdbase-empty-list",text:c?"No matching types.":"No type definitions."});return}for(let m of l){let h=a.createEl("button",{cls:"mdbase-type-row"});m.filePath===this.selectedPath&&h.addClass("is-active"),h.setAttr("aria-current",m.filePath===this.selectedPath?"true":"false"),h.createSpan({cls:"mdbase-type-name",text:m.name}),h.createSpan({cls:"mdbase-type-meta",text:`${Object.keys(m.fields).length} fields \xB7 ${(p=m.specProfile)!=null?p:"v0.2"}`}),h.onclick=()=>void this.selectType(m.filePath)}}renderTypeEditor(t){var h,y,b,g;let n=t.createDiv({cls:"mdbase-type-editor-pane"});if(!this.model){let w=n.createDiv({cls:"mdbase-empty-state"});w.createEl("h2",{text:"Choose a type"}),w.createEl("p",{text:"Select a type definition from the list to inspect or edit it."});return}let s=((h=this.host.getMirrorProfile())==null?void 0:h.mode)==="read_only",i=this.model.specProfile==="v0.2"||s||!!this.model.readOnlyReason,o=(y=this.model.readOnlyReason)!=null?y:s?"This mirror has read-only access. Re-enroll it with write access before editing types.":"This v0.2 type is read-only. Review and apply a collection migration before editing.",a=n.createDiv({cls:"mdbase-editor-header"}),c=a.createEl("button",{cls:"mdbase-mobile-back"});c.setAttr("aria-label","Back to type list"),(0,$e.setIcon)(c,"arrow-left"),c.onclick=()=>{if(this.dirty){new $e.Notice("Save or discard the current type changes before going back.");return}this.selectedPath=null,this.model=null,this.originalModel=null,this.render()};let l=a.createDiv(),u=l.createDiv({cls:"mdbase-editor-title-line"});u.createEl("h2",{text:this.model.name||"Untitled type"}),u.createSpan({cls:"mdbase-spec-badge",text:(b=this.model.specProfile)!=null?b:"v0.2"}),this.dirty&&u.createSpan({cls:"mdbase-dirty",text:"Unsaved"}),l.createDiv({cls:"mdbase-editor-path",text:(g=this.selectedPath)!=null?g:"New type"});let d=a.createDiv({cls:"mdbase-editor-actions"});if(this.selectedPath){let w=d.createEl("button",{text:"Open source"});w.onclick=()=>void this.host.openFileByPath(this.selectedPath)}let f=d.createEl("button",{text:"Save"});f.addClass("mod-cta"),f.disabled=i||!this.dirty||this.busy,f.onclick=()=>void this.saveCurrentType(),i&&n.createDiv({cls:"mdbase-readonly-note",text:o});let p=n.createDiv({cls:"mdbase-mode-switch"});p.setAttr("role","tablist");for(let[w,S]of[["design","Design"],["yaml","YAML"]]){let _=p.createEl("button",{text:S});_.setAttr("role","tab"),_.setAttr("aria-selected",String(this.editorMode===w)),this.editorMode===w&&_.addClass("is-active"),_.onclick=()=>this.switchEditorMode(w)}let m=n.createDiv({cls:"mdbase-editor-document"});this.editorMode==="design"?this.renderDesignEditor(m,this.model,i):this.renderYamlEditor(m,i)}renderDesignEditor(t,n,s){let i=t.createEl("section",{cls:"mdbase-editor-section"});i.createEl("h3",{text:"Identity"});let o=_t(i,"Name",n.name,x=>{n.name=x,this.markDirty()},{description:"Stable type name used by collection records."});o.disabled=s;let a=_t(i,"Description",n.description,x=>{n.description=x,this.markDirty()},{multiline:!0});a.disabled=s;let c=_t(i,"Display field",n.displayNameKey,x=>{n.displayNameKey=x,this.markDirty()},{placeholder:"title"});c.disabled=s;let l=i.createEl("label",{cls:"mdbase-checkbox-row"}),u=l.createEl("input",{type:"checkbox"});u.checked=n.strictMode===!0,u.disabled=s,u.onchange=()=>{n.strictMode=u.checked,this.markDirty()},l.createSpan({text:"Reject undeclared fields"});let d=t.createEl("section",{cls:"mdbase-editor-section"});d.createEl("h3",{text:"Membership"});let f=_t(d,"Path glob",n.matchPathGlob,x=>{n.matchPathGlob=x,this.markDirty()},{placeholder:"Projects/**/*.md"});f.disabled=s;let p=_t(d,"Fields present",n.matchFieldsPresent,x=>{n.matchFieldsPresent=x,this.markDirty()},{description:"Comma-separated frontmatter keys."});p.disabled=s;let m=_t(d,"Where",n.matchWhere,x=>{n.matchWhere=x,this.markDirty()},{multiline:!0,description:"YAML predicate, including contains and nested equality conditions.",placeholder:`tags: + contains: task`});m.disabled=s;let h=t.createEl("section",{cls:"mdbase-editor-section"}),y=h.createDiv({cls:"mdbase-section-header"});y.createEl("h3",{text:"Fields"});let b=y.createEl("button",{text:"Add field"});b.disabled=s,b.onclick=()=>{n.fields.push({name:"",definition:{type:"string"}}),this.markDirty(!0)};let g=h.createDiv({cls:"mdbase-fields"});for(let[x,I]of n.fields.entries())this.renderFieldRow(g,I,x,s);n.fields.length||g.createDiv({cls:"mdbase-empty-list",text:"No fields declared."});let w=t.createEl("section",{cls:"mdbase-editor-section"});w.createEl("h3",{text:"Placement"});let S=_t(w,"Path pattern",n.pathPattern,x=>{n.pathPattern=x,this.markDirty()},{placeholder:"Notes/{title}.md"});S.disabled=s;let _=t.createEl("section",{cls:"mdbase-editor-section mdbase-change-review"});if(_.createEl("h3",{text:"Change review"}),!this.dirty)_.createEl("p",{text:"No pending changes."});else{let x=_.createEl("ul");for(let I of bO(this.originalModel,n))x.createEl("li",{text:I})}}renderFieldRow(t,n,s,i){this.renderFieldDefinition(t,n.definition,{name:n.name,nameLabel:`Field ${s+1} name`,onNameInput:o=>{n.name=o,this.markDirty()},required:n.definition.required===!0,onRequiredChange:o=>{n.definition.required=o,this.markDirty()},onRemove:()=>{var o;(o=this.model)==null||o.fields.splice(s,1),this.markDirty(!0)},readOnly:i,depth:0})}renderFieldDefinition(t,n,s){var u;let i=t.createDiv({cls:"mdbase-field-node"});i.setAttr("data-depth",String(s.depth));let o=i.createDiv({cls:"mdbase-field-row"});if(s.staticLabel)o.createDiv({cls:"mdbase-field-role",text:s.staticLabel});else{let d=o.createEl("input",{type:"text",cls:"mdbase-field-name-control"});d.setAttr("aria-label",s.nameLabel),d.placeholder="fieldName",d.value=(u=s.name)!=null?u:"",d.disabled=s.readOnly,s.onNameInput&&(d.oninput=()=>{var f;return(f=s.onNameInput)==null?void 0:f.call(s,d.value)}),s.onNameCommit&&(d.onchange=()=>{var f;return(f=s.onNameCommit)==null?void 0:f.call(s,d.value,d)})}let a=o.createEl("select",{cls:"mdbase-field-type-control"});a.setAttr("aria-label",`${s.name||s.staticLabel||"Field"} type`);for(let d of yO){let f=d==="any"?"Any value":d[0].toUpperCase()+d.slice(1);a.createEl("option",{value:d,text:f})}a.value=q0(n),a.disabled=s.readOnly,a.onchange=()=>{n.type=a.value,a.value==="list"&&!mn(n.items)&&(n.items={type:"string"}),a.value==="object"&&!mn(n.fields)&&(n.fields={}),a.value==="enum"&&!Array.isArray(n.values)&&(n.values=[]),this.markDirty(!0)};let c=o.createEl("input",{type:"text",cls:"mdbase-field-description-control"});if(c.setAttr("aria-label",`${s.name||s.staticLabel||"Field"} description`),c.placeholder="Description",c.value=typeof n.description=="string"?n.description:"",c.disabled=s.readOnly,c.oninput=()=>{c.value?n.description=c.value:delete n.description,this.markDirty()},s.onRequiredChange){let d=o.createEl("label",{cls:"mdbase-field-required"}),f=d.createEl("input",{type:"checkbox"});f.checked=s.required===!0,f.disabled=s.readOnly,f.onchange=()=>{var p;return(p=s.onRequiredChange)==null?void 0:p.call(s,f.checked)},d.createSpan({text:"Required"})}if(s.onRemove){let d=o.createEl("button",{cls:"mdbase-field-remove"});d.setAttr("aria-label",`Remove ${s.name||s.staticLabel||"field"}`),(0,$e.setIcon)(d,"trash-2"),d.disabled=s.readOnly,d.onclick=s.onRemove}let l=q0(n);l==="enum"&&this.renderEnumFieldDetails(i,n,s),l==="link"&&this.renderLinkFieldDetails(i,n,s),l==="list"&&this.renderListFieldDetails(i,n,s),l==="object"&&this.renderObjectFieldDetails(i,n,s)}renderEnumFieldDetails(t,n,s){let i=t.createDiv({cls:"mdbase-field-details mdbase-field-options"}),o=i.createEl("label",{text:"Allowed values"}),a=i.createEl("input",{type:"text"});a.setAttr("aria-label",`${s.name||s.staticLabel||"Enum"} allowed values`),a.placeholder="draft, published, archived",a.value=Array.isArray(n.values)?n.values.map(String).join(", "):"",a.disabled=s.readOnly,a.oninput=()=>{n.values=a.value.split(",").map(c=>c.trim()).filter(Boolean),this.markDirty()},o.htmlFor=a.id=`mdbase-${Math.random().toString(36).slice(2)}`}renderLinkFieldDetails(t,n,s){let i=t.createDiv({cls:"mdbase-field-details mdbase-field-options"}),o=i.createEl("label",{text:"Target type"}),a=i.createEl("input",{type:"text"});a.setAttr("aria-label",`${s.name||s.staticLabel||"Link"} target type`),a.placeholder="Any type",a.value=typeof n.target=="string"?n.target:"",a.disabled=s.readOnly,a.oninput=()=>{a.value.trim()?n.target=a.value.trim():delete n.target,this.markDirty()},o.htmlFor=a.id=`mdbase-${Math.random().toString(36).slice(2)}`;let c=i.createEl("label",{cls:"mdbase-field-required"}),l=c.createEl("input",{type:"checkbox"});l.checked=n.validate_exists===!0,l.disabled=s.readOnly,l.onchange=()=>{n.validate_exists=l.checked,this.markDirty()},c.createSpan({text:"Validate target exists"})}renderListFieldDetails(t,n,s){let i=t.createDiv({cls:"mdbase-field-children"});i.createDiv({cls:"mdbase-field-children-label",text:"List items"});let o=mn(n.items)?n.items:{type:"any"};!mn(n.items)&&!s.readOnly&&(n.items=o),this.renderFieldDefinition(i,o,{staticLabel:"Item",nameLabel:"List item",readOnly:s.readOnly,depth:s.depth+1})}renderObjectFieldDetails(t,n,s){let i=t.createDiv({cls:"mdbase-field-children"}),o=i.createDiv({cls:"mdbase-field-children-header"});o.createDiv({cls:"mdbase-field-children-label",text:"Object fields"});let a=o.createEl("button",{text:"Add nested field"});a.disabled=s.readOnly;let c=mn(n.fields)?n.fields:{};!mn(n.fields)&&!s.readOnly&&(n.fields=c),a.onclick=()=>{let d=gO(c);D0(c,d,{type:"string"}),this.markDirty(!0)};let l=i.createDiv({cls:"mdbase-nested-fields"}),u=Object.entries(c).filter(d=>mn(d[1]));if(!u.length){l.createDiv({cls:"mdbase-empty-list",text:"No nested fields."});return}for(let[d,f]of u){let p=d;this.renderFieldDefinition(l,f,{name:p,nameLabel:`${p} nested field name`,onNameCommit:(m,h)=>{let y=m.trim();if(!y){new $e.Notice("Nested field name is required."),h.value=p;return}if(y!==p&&Object.prototype.hasOwnProperty.call(c,y)){new $e.Notice(`Nested field already exists: ${y}`),h.value=p;return}y!==p&&(delete c[p],D0(c,y,f),p=y,this.markDirty())},required:f.required===!0,onRequiredChange:m=>{f.required=m,this.markDirty()},onRemove:()=>{delete c[p],this.markDirty(!0)},readOnly:s.readOnly,depth:s.depth+1})}}renderYamlEditor(t,n){let s=t.createEl("section",{cls:"mdbase-editor-section mdbase-yaml-section"});s.createEl("h3",{text:"Canonical type document"}),s.createEl("p",{cls:"mdbase-form-description",text:"Unknown v0.3 extensions are preserved. Invalid YAML is never normalized or saved."});let i=s.createEl("textarea",{cls:"mdbase-yaml-editor"});i.setAttr("aria-label","Type definition YAML"),i.value=this.yamlDraft,i.disabled=n,i.spellcheck=!1,i.oninput=()=>{this.yamlDraft=i.value,this.markDirty(!1)}}renderSync(t){var f,p,m,h,y,b;let n=t.createDiv({cls:"mdbase-sync-document"}),s=n.createDiv({cls:"mdbase-document-header"});s.createEl("h2",{text:"Sync"}),s.createEl("p",{text:"Connect this vault to a collection authority and keep ordinary Markdown mirrored locally."});let i=this.host.getMirrorProfile();if(!i){this.renderEnrollment(n);return}let o=n.createEl("section",{cls:"mdbase-editor-section"});o.createEl("h3",{text:"Collection authority"});let a=o.createDiv({cls:"mdbase-status-list"});if(Ce(a,"Name",i.name),Ce(a,"Collection",i.collectionId),Ce(a,"Access",i.mode==="read_write"?"Read and write":"Read only"),Ce(a,"Provider",i.syncUrl),Ce(a,"State",(p=(f=this.mirrorStatus)==null?void 0:f.state.replace(/_/g," "))!=null?p:"Checking"),Ce(a,"Last synced",(h=(m=this.mirrorStatus)==null?void 0:m.last_synced_at)!=null?h:"Never"),this.mirrorProgress){let g=this.mirrorProgress.total,w=o.createEl("progress");w.max=g!=null?g:1,w.value=g==null?0:this.mirrorProgress.completed,g==null&&w.removeAttribute("value"),o.createDiv({cls:"mdbase-progress-label",text:`${this.mirrorProgress.phase}: ${this.mirrorProgress.completed}${g==null?"":` of ${g}`}`})}let c=o.createDiv({cls:"mdbase-actions"}),l=c.createEl("button",{text:"Preview"});l.disabled=this.busy,l.onclick=()=>void this.perform(async()=>{this.mirrorPreview=await this.host.connectSync.preview(),this.render()});let u=c.createEl("button",{text:"Sync now"});u.addClass("mod-cta"),u.disabled=this.busy,u.onclick=()=>void this.perform(async()=>{this.mirrorStatus=await this.host.connectSync.sync(g=>{this.mirrorProgress=g,this.render()}),this.mirrorProgress=null,this.transientMessage="Sync completed and the local checkpoint was verified.",await this.refresh(!0)}),this.mirrorPreview&&this.renderMirrorPreview(n,this.mirrorPreview),(y=this.mirrorStatus)!=null&&y.conflicts.length&&this.renderConflicts(n,this.mirrorStatus),(b=this.mirrorStatus)!=null&&b.local_issues.length&&this.renderLocalMirrorIssues(n,this.mirrorStatus);let d=n.createEl("section",{cls:"mdbase-editor-section"});d.createEl("h3",{text:"Mirror ownership"}),d.createEl("p",{text:"Use this plugin as the only sync owner for this vault. Obsidian protects concurrent operations inside the app; a separate desktop mirror process cannot share that mobile-safe lease."})}renderEnrollment(t){if(this.schema||this.host.connectSync.getAdoptionMarker()){this.renderLocalAdoption(t);return}let n=t.createEl("section",{cls:"mdbase-editor-section mdbase-enrollment"});if(n.createEl("h3",{text:"Connect collection authority"}),n.createEl("p",{text:"Connect will open an approval page. Credentials are stored in Obsidian's secret store and never written into this vault."}),this.enrollmentVerification){let d=n.createDiv({cls:"mdbase-approval-link"});d.createSpan({text:"Approval page: "});let f=d.createEl("a",{text:"Open Connect",href:this.enrollmentVerification});f.setAttr("target","_blank"),f.setAttr("rel","noopener noreferrer")}let s="https://connect.mdbase.dev",i="Obsidian",o="",a="read_write";_t(n,"Connect URL",s,d=>{s=d},{placeholder:"https://connect.mdbase.dev"}),_t(n,"Mirror name",i,d=>{i=d}),_t(n,"Collection ID",o,d=>{o=d},{description:"Optional. Leave blank to choose during approval."});let c=n.createDiv({cls:"mdbase-form-row"});c.createEl("label",{text:"Access"});let l=c.createEl("select");l.createEl("option",{value:"read_write",text:"Read and write"}),l.createEl("option",{value:"read_only",text:"Read only"}),l.value=a,l.onchange=()=>{a=l.value==="read_only"?"read_only":"read_write"};let u=n.createEl("button",{text:"Open Connect approval"});u.addClass("mod-cta"),u.disabled=this.busy,u.onclick=()=>void this.perform(async()=>{var f;(f=this.enrollmentAbort)==null||f.abort();let d=new AbortController;this.enrollmentAbort=d;try{await this.host.connectSync.enroll({controlUrl:s,mirrorName:i,mode:a,...o.trim()?{collectionId:o.trim()}:{}},{signal:d.signal,onVerification:p=>{this.enrollmentVerification=p.verificationUri,this.transientMessage="Approve the mirror in the Connect page. This view will keep waiting securely.",window.open(p.verificationUri,"_blank","noopener,noreferrer"),this.render()},onStatus:p=>{this.transientMessage=p.state==="waiting_for_approval"?"Waiting for approval in Connect\u2026":`Connect is retrying enrollment (attempt ${p.attempt}).`,this.render()}}),this.enrollmentVerification="",this.transientMessage="Mirror enrolled. Preview before the first sync.",await this.refreshMirrorStatus(),this.render()}finally{this.enrollmentAbort===d&&(this.enrollmentAbort=null)}})}renderLocalAdoption(t){var u,d;let n=this.host.connectSync.getAdoptionMarker(),s=t.createEl("section",{cls:"mdbase-editor-section mdbase-enrollment"});s.createEl("h3",{text:"Host this local collection"}),s.createEl("p",{text:n?"This vault has a durable adoption checkpoint. Resume it without creating another hosted collection.":"Hosted mdbase will adopt an exact snapshot and become the collection authority. This vault will then continue as a read-write mirror."});let i=this.enrollmentVerification||(n==null?void 0:n.session.verificationUri);if(i){let f=s.createDiv({cls:"mdbase-approval-link"});f.createSpan({text:"Approval page: "});let p=f.createEl("a",{text:"Open Connect",href:i});p.setAttr("target","_blank"),p.setAttr("rel","noopener noreferrer")}let o=(u=n==null?void 0:n.session.controlUrl)!=null?u:"https://connect.mdbase.dev",a=(d=n==null?void 0:n.session.requested.mirrorName)!=null?d:"Obsidian";if(!n)_t(s,"Connect URL",o,f=>{o=f},{placeholder:"https://connect.mdbase.dev"}),_t(s,"Mirror name",a,f=>{a=f});else{let f=s.createDiv({cls:"mdbase-status-list"});Ce(f,"Collection",n.session.requested.collectionId),Ce(f,"Phase",n.phase.replace(/_/g," ")),Ce(f,"Connect",n.session.controlUrl)}let c=s.createDiv({cls:"mdbase-inline-message"});c.createEl("strong",{text:"Authority cut-over: "}),c.appendText("once final staging begins, plugin-managed local edits pause until hosted activation is confirmed. The checkpoint survives app restarts and uncertain network responses.");let l=s.createEl("button",{text:n?"Resume adoption":"Approve and host collection"});if(l.addClass("mod-cta"),l.disabled=this.busy,l.onclick=()=>void this.perform(async()=>{var h;(h=this.enrollmentAbort)==null||h.abort();let f=new AbortController;this.enrollmentAbort=f;let p=y=>{this.enrollmentVerification=y.verificationUri,this.transientMessage="Approve the authority move in Connect, then return here. This checkpoint is safe to resume.",this.render()},m=y=>{this.transientMessage=y.state==="waiting_for_approval"?"Waiting for authority-move approval in Connect\u2026":`Connect is retrying (attempt ${y.attempt}).`,this.render()};try{n?await this.host.connectSync.resumeAdoption({signal:f.signal,onVerification:p,onStatus:m}):await this.host.connectSync.adoptLocalCollection({controlUrl:o,mirrorName:a},{signal:f.signal,onVerification:p,onStatus:m}),this.enrollmentVerification="",this.transientMessage="Hosted mdbase is authoritative and this vault is now its read-write mirror.",await this.refresh(!0)}finally{this.enrollmentAbort===f&&(this.enrollmentAbort=null)}}),n&&!["activating","adopted"].includes(n.phase)){let f=s.createEl("button",{text:"Cancel adoption"});f.disabled=this.busy,f.onclick=()=>void this.perform(async()=>{await this.host.connectSync.cancelAdoption(),this.enrollmentVerification="",this.transientMessage="Collection adoption cancelled. This vault remains the local authority.",await this.refresh(!0)})}}renderMirrorPreview(t,n){let s=t.createEl("section",{cls:"mdbase-editor-section"});s.createEl("h3",{text:"Sync preview"});let i=s.createDiv({cls:"mdbase-status-list"});if(Ce(i,"Download documents",String(n.download_documents)),Ce(i,"Upload documents",String(n.upload_documents)),Ce(i,"Unchanged documents",String(n.unchanged_documents)),n.collisions.length){s.createDiv({cls:"mdbase-inline-error",text:`${n.collisions.length} path collision${n.collisions.length===1?"":"s"} must be resolved before sync.`});let o=s.createEl("ul");for(let a of n.collisions.slice(0,100))o.createEl("li",{text:a})}if(n.local_issues.length){s.createDiv({cls:"mdbase-inline-error",text:`${n.local_issues.length} local file${n.local_issues.length===1?"":"s"} cannot be uploaded until its frontmatter is fixed.`});let o=s.createEl("ul");for(let a of n.local_issues.slice(0,100))o.createEl("li",{text:`${a.path}: ${a.message}`})}}renderConflicts(t,n){var i;let s=t.createEl("section",{cls:"mdbase-editor-section"});s.createEl("h3",{text:"Conflicts"});for(let o of n.conflicts){let a=s.createDiv({cls:"mdbase-conflict-row"}),c=a.createDiv();c.createEl("strong",{text:(i=o.path)!=null?i:o.record_id}),c.createDiv({text:o.message});let l=a.createDiv({cls:"mdbase-actions"});for(let u of["local","remote"]){let d=l.createEl("button",{text:u==="local"?"Keep local":"Use remote"});d.disabled=this.busy,d.onclick=()=>void this.perform(async()=>{this.mirrorStatus=await this.host.connectSync.resolveConflict(o.record_id,u),this.render()})}}}renderLocalMirrorIssues(t,n){let s=t.createEl("section",{cls:"mdbase-editor-section"});s.createEl("h3",{text:"Local files needing attention"}),s.createEl("p",{text:"These files remain untouched and unsynced. Other valid Markdown continues to synchronize."});for(let i of n.local_issues){let o=s.createDiv({cls:"mdbase-conflict-row"}),a=o.createDiv();a.createEl("strong",{text:i.path}),a.createDiv({text:i.message});let l=o.createDiv({cls:"mdbase-actions"}).createEl("button",{text:"Open file"});l.disabled=this.busy,l.onclick=()=>void this.host.openFileByPath(i.path)}}renderIssues(t){var b;let n=t.createDiv({cls:"mdbase-issues-document"}),s=this.host.getIssues(),i=new Set(s.map(g=>g.path)).size,o=n.createDiv({cls:"mdbase-document-header"}),a=o.createDiv();a.createEl("h2",{text:"Issues"}),a.createEl("p",{text:s.length?`${s.length.toLocaleString()} validation issues in ${i.toLocaleString()} files.`:"The collection has no current validation issues."});let c=o.createEl("button",{text:"Validate collection"});c.disabled=this.busy,c.onclick=()=>void this.perform(async()=>{await this.host.validateCollection(),this.render()});let l=n.createDiv({cls:"mdbase-issue-controls"}),u=l.createEl("select");u.setAttr("aria-label","Issue severity"),u.createEl("option",{value:"all",text:"All severities"}),u.createEl("option",{value:"error",text:"Errors"}),u.createEl("option",{value:"warn",text:"Warnings"}),u.value=this.issueSeverity,u.onchange=()=>{this.issueSeverity=u.value==="error"||u.value==="warn"?u.value:"all",this.issueLimit=250,this.render()};let d=l.createEl("input",{type:"search"});d.setAttr("aria-label","Filter issues"),d.placeholder="Filter by path, code, field, or message",d.value=this.issueQuery,d.oninput=()=>{this.issueQuery=d.value,this.issueLimit=250,this.render();let g=this.containerEl.querySelector(".mdbase-issue-controls input[type='search']");g==null||g.focus(),g==null||g.setSelectionRange(g.value.length,g.value.length)};let f=this.issueQuery.trim().toLowerCase(),p=s.filter(g=>{var w;return this.issueSeverity!=="all"&&g.severity!==this.issueSeverity?!1:f?`${g.path} ${g.code} ${(w=g.field)!=null?w:""} ${g.message}`.toLowerCase().includes(f):!0}),m=new Set(p.map(g=>g.path)).size;if(n.createDiv({cls:"mdbase-issues-summary",text:p.length===s.length?`Showing ${Math.min(p.length,this.issueLimit).toLocaleString()} of ${p.length.toLocaleString()} issues`:`${p.length.toLocaleString()} matching issues in ${m.toLocaleString()} files`}),!p.length){n.createDiv({cls:"mdbase-empty-state",text:"No validation issues."});return}let h=p.slice(0,this.issueLimit),y=new Map;for(let g of h)y.set(g.path,[...(b=y.get(g.path))!=null?b:[],g]);for(let[g,w]of y){let S=n.createEl("section",{cls:"mdbase-issue-group"}),_=S.createDiv({cls:"mdbase-issue-group-header"}),x=_.createEl("button",{cls:"mdbase-issue-file-button"});(0,$e.setIcon)(x.createSpan({cls:"mdbase-issue-file-icon"}),"file-text"),x.createSpan({cls:"mdbase-issue-file-path",text:g}),x.onclick=()=>void this.host.openFileByPath(g),_.createSpan({cls:"mdbase-issue-file-count",text:`${w.length} ${w.length===1?"issue":"issues"}`});for(let I of w){let E=S.createEl("button",{cls:"mdbase-issue-row"});E.setAttr("data-severity",I.severity),E.setAttr("aria-label",`${I.severity==="warn"?"Warning":"Error"}: ${I.message}`),E.createSpan({cls:"mdbase-issue-indicator"}).setAttr("aria-hidden","true");let T=E.createDiv({cls:"mdbase-issue-metadata"});T.createEl("code",{text:I.code}),T.createDiv({cls:"mdbase-issue-context",text:`${I.severity==="warn"?"Warning":"Error"}${I.field?` \xB7 ${I.field}`:""}`}),E.createDiv({cls:"mdbase-issue-row-message",text:I.message}),E.onclick=()=>void this.host.openFileByPath(I.path,I.field)}}if(p.length>h.length){let g=n.createEl("button",{cls:"mdbase-load-more",text:`Load ${Math.min(250,p.length-h.length)} more`});g.onclick=()=>{this.issueLimit+=250,this.render()}}}async selectType(t,n=!0){if(n&&this.dirty&&t!==this.selectedPath){new $e.Notice("Save or discard the current type changes before switching.");return}let s=await this.host.loadTypeModel(t);this.selectedPath=t,this.model=s,this.originalModel=rf(s),this.yamlDraft=`${ot(j0(s),s.body)} +`,this.dirty=!1,this.editorMode="design",this.render()}createType(){if(this.dirty){new $e.Notice("Save or discard the current type changes before creating another type.");return}let t=tf();this.selectedPath=null,this.model=t,this.originalModel=null,this.yamlDraft=`${ot(Mi(t),t.body)} +`,this.dirty=!0,this.editorMode="design",this.render()}switchEditorMode(t){if(!(!this.model||t===this.editorMode)){if(t==="yaml")try{this.yamlDraft=`${ot(j0(this.model),this.model.body)} +`}catch(n){new $e.Notice(n instanceof Error?n.message:String(n));return}else if(!this.readYamlDraftIntoModel())return;this.editorMode=t,this.render()}}readYamlDraftIntoModel(){var n,s;let t=tt(this.yamlDraft);if(!t.hasFrontmatter||t.error)return new $e.Notice(`Invalid type YAML: ${(n=t.error)!=null?n:"frontmatter is missing"}`),!1;if(t.frontmatter.kind!=="mdbase.type")return new $e.Notice("Canonical v0.3 type YAML requires kind: mdbase.type."),!1;try{return this.model=ja(t.frontmatter,t.body,((s=this.model)==null?void 0:s.name)||"type"),!0}catch(i){return new $e.Notice(i instanceof Error?i.message:String(i)),!1}}async saveCurrentType(){if(!(!this.model||this.model.specProfile!=="v0.3"||this.model.readOnlyReason)&&!(this.editorMode==="yaml"&&!this.readYamlDraftIntoModel())){if(!this.model.name.trim()){new $e.Notice("Type name is required.");return}await this.perform(async()=>{let t=await this.host.saveTypeModel(this.model,this.selectedPath);this.selectedPath=t.path,this.originalModel=rf(this.model),this.dirty=!1,this.transientMessage=`Saved ${t.path}.`,await this.refresh(!0)})}}markDirty(t=!1){var o,a;if(this.dirty=!0,t){this.render();return}let n=this.containerEl.querySelector(".mdbase-editor-title-line");n&&!n.querySelector(".mdbase-dirty")&&n.createSpan({cls:"mdbase-dirty",text:"Unsaved"});let s=this.containerEl.querySelector(".mdbase-editor-actions .mod-cta");s&&((o=this.model)==null?void 0:o.specProfile)==="v0.3"&&!this.model.readOnlyReason&&((a=this.host.getMirrorProfile())==null?void 0:a.mode)!=="read_only"&&(s.disabled=!1);let i=this.containerEl.querySelector(".mdbase-change-review");if(i){let c=i.querySelector("p");c&&c.setText("Pending changes. Review details after leaving the current field.")}}async refreshMirrorStatus(){try{this.mirrorStatus=await this.host.connectSync.status()}catch(t){this.mirrorStatus=null,this.transientMessage=t instanceof Error?t.message:String(t)}}async perform(t){if(!this.busy){this.busy=!0,this.transientMessage="",this.render();try{await t()}catch(n){let s=n instanceof Error?n.message:String(n);this.transientMessage=s,new $e.Notice(s)}finally{this.busy=!1,this.render()}}}};function j0(r){var e;return r.specProfile==="v0.3"&&!r.readOnlyReason?Mi(r):rf((e=r.originalFrontmatter)!=null?e:{name:r.name,fields:Object.fromEntries(r.fields.map(t=>[t.name,t.definition]))})}var us="mdbase-issues-view",_O={validateOnSave:!0,validateOnOpen:!0,showNoticeOnSave:!1,interopEnabled:!1,mirrorProfile:null};function vO(r){if(!r||typeof r!="object"||Array.isArray(r))return!1;let e=r;return e.version===1&&typeof e.syncUrl=="string"&&typeof e.controlUrl=="string"&&typeof e.collectionId=="string"&&typeof e.replicaId=="string"&&(e.mode==="read_only"||e.mode==="read_write")&&typeof e.name=="string"&&typeof e.enrollmentId=="string"&&typeof e.accessTokenExpiresAt=="string"}function $O(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var Li=class extends M.Modal{constructor(t,n,s="",i=""){super(t);this.resolvePromise=null;this.settled=!1;this.title=n,this.placeholder=s,this.defaultValue=i}openAndGetValue(){return new Promise(t=>{this.settled=!1,this.resolvePromise=t,this.open()})}onOpen(){let{contentEl:t}=this;t.empty(),t.createEl("h3",{text:this.title});let n=t.createEl("input",{type:"text"});n.placeholder=this.placeholder,n.value=this.defaultValue,n.addClass("prompt-input");let s=t.createDiv({cls:"modal-button-container"}),i=s.createEl("button",{text:"Cancel"}),o=s.createEl("button",{text:"OK"});o.addClass("mod-cta"),i.onclick=()=>{this.finish(null),this.close()},o.onclick=()=>{this.finish(n.value.trim()),this.close()},n.addEventListener("keydown",a=>{a.key==="Enter"&&(a.preventDefault(),this.finish(n.value.trim()),this.close()),a.key==="Escape"&&(a.preventDefault(),this.finish(null),this.close())}),window.setTimeout(()=>n.focus(),0)}onClose(){this.settled||this.finish(null),this.contentEl.empty()}finish(t){var n;this.settled||(this.settled=!0,(n=this.resolvePromise)==null||n.call(this,t),this.resolvePromise=null)}},nf=class extends M.SuggestModal{constructor(t,n,s){super(t);this.resultHandled=!1;this.typeDefs=[...n].sort((i,o)=>i.name.localeCompare(o.name)),this.onResult=s,this.setPlaceholder("Type to search..."),this.setInstructions([{command:"\u2191\u2193",purpose:"navigate"},{command:"\u21B5",purpose:"select"},{command:"esc",purpose:"cancel"}]),this.containerEl.addClass("mdbase-type-picker-modal"),this.titleEl.setText("Select type definition")}getSuggestions(t){let n=t.trim().toLowerCase();return n?this.typeDefs.filter(s=>{var a,c,l;let i=(c=(a=s.match)==null?void 0:a.path_glob)!=null?c:"";return`${s.name} ${(l=s.display_name_key)!=null?l:""} ${s.filePath} ${i}`.toLowerCase().includes(n)}).slice(0,100):this.typeDefs.slice(0,100)}renderSuggestion(t,n){var o,a;let s=n.createDiv({cls:"mdbase-type-picker-suggestion"});s.createDiv({cls:"mdbase-type-picker-name",text:t.name});let i=s.createDiv({cls:"mdbase-type-picker-meta"});i.createSpan({cls:"mdbase-type-picker-path",text:t.filePath}),i.createSpan({cls:"mdbase-type-picker-count",text:`${Object.keys((o=t.fields)!=null?o:{}).length} fields`}),(a=t.match)!=null&&a.path_glob&&s.createDiv({cls:"mdbase-type-picker-match",text:`match: ${t.match.path_glob}`})}onChooseSuggestion(t){this.resultHandled=!0,this.onResult({type:"selected",typeDef:t})}onClose(){window.setTimeout(()=>{this.resultHandled||this.onResult({type:"cancelled"})},0),super.onClose()}};function SO(r,e){return new Promise(t=>{new nf(r,e,s=>{if(s.type==="selected"){t(s.typeDef);return}t(null)}).open()})}var sf=class extends M.ItemView{constructor(t,n){super(t);this.severityFilter="all";this.query="";this.plugin=n}getViewType(){return us}getDisplayText(){return"mdbase issues"}getIcon(){return"shield-alert"}async onOpen(){this.containerEl.empty(),this.containerEl.addClass("mdbase-issues-view"),this.render()}render(){var m;let t=this.containerEl;t.empty(),t.addClass("mdbase-issues-view");let n=t.createDiv({cls:"mdbase-issues-header"});n.createEl("h3",{text:"mdbase Issues"});let i=n.createDiv({cls:"mdbase-issues-header-actions"}).createEl("button",{text:"Refresh"});i.addClass("mod-cta"),i.onclick=()=>{this.plugin.runCollectionValidation(!1)};let o=t.createDiv({cls:"mdbase-issues-controls"}),a=o.createEl("select");a.addClass("mdbase-issues-severity"),a.createEl("option",{value:"all",text:"All severities"}),a.createEl("option",{value:"error",text:"Errors only"}),a.createEl("option",{value:"warn",text:"Warnings only"}),a.value=this.severityFilter,a.onchange=()=>{let h=a.value;(h==="error"||h==="warn"||h==="all")&&(this.severityFilter=h),this.render()};let c=o.createEl("input",{type:"search"});c.addClass("mdbase-issues-query"),c.placeholder="Filter by path, code, message, field",c.value=this.query,c.oninput=()=>{this.query=c.value,this.render()};let l=this.plugin.getIssues(),u=this.query.trim().toLowerCase(),d=l.filter(h=>{var b;return this.severityFilter!=="all"&&h.severity!==this.severityFilter?!1:u?`${h.path} ${h.code} ${h.message} ${(b=h.field)!=null?b:""}`.toLowerCase().includes(u):!0}),f=d.slice(0,500);if(t.createDiv({cls:"mdbase-issues-count",text:d.length>f.length?`Showing ${f.length} of ${d.length} matching issues`:d.length===l.length?`${d.length} issue${d.length===1?"":"s"}`:`${d.length} of ${l.length} issue${l.length===1?"":"s"}`}),d.length===0){t.createDiv({cls:"mdbase-empty",text:l.length===0?"No validation issues.":"No issues match current filters."});return}let p=new Map;for(let h of f){let y=(m=p.get(h.path))!=null?m:[];y.push(h),p.set(h.path,y)}for(let[h,y]of p.entries()){t.createDiv({cls:"mdbase-issue-file",text:h});for(let b of y){let g=t.createDiv({cls:"mdbase-issue-item"});g.setAttr("data-severity",b.severity),g.createDiv({cls:"mdbase-issue-code",text:`${b.severity.toUpperCase()} \xB7 ${b.code}${b.field?` \xB7 ${b.field}`:""}`}),g.createDiv({cls:"mdbase-issue-message",text:b.message});let w=g.createDiv({cls:"mdbase-issue-actions"}),S=w.createEl("button",{text:b.field?"Open field":"Open file"});S.onclick=x=>{x.stopPropagation(),this.plugin.openIssue(b)};let _=this.plugin.getQuickFixLabel(b);if(_){let x=w.createEl("button",{text:_});x.onclick=I=>{I.stopPropagation(),this.plugin.applyQuickFix(b)}}g.onclick=()=>{this.plugin.openIssue(b)}}}}},of=class extends M.PluginSettingTab{constructor(e,t){super(e,t),this.plugin=t}display(){let{containerEl:e}=this;e.empty(),e.createEl("h2",{text:"mdbase settings"}),new M.Setting(e).setName("Validate on save").setDesc("Run mdbase validation when a markdown file is modified.").addToggle(t=>t.setValue(this.plugin.settings.validateOnSave).onChange(async n=>{this.plugin.settings.validateOnSave=n,await this.plugin.saveSettings()})),new M.Setting(e).setName("Validate on file open").setDesc("Validate the active note when opened.").addToggle(t=>t.setValue(this.plugin.settings.validateOnOpen).onChange(async n=>{this.plugin.settings.validateOnOpen=n,await this.plugin.saveSettings()})),new M.Setting(e).setName("Show notices on save").setDesc("Display a notice when save-time validation finds issues.").addToggle(t=>t.setValue(this.plugin.settings.showNoticeOnSave).onChange(async n=>{this.plugin.settings.showNoticeOnSave=n,await this.plugin.saveSettings()})),new M.Setting(e).setName("Allow local application interoperability").setDesc("Allow installed Obsidian plugins to exchange validated mdbase events and actions in this vault. Contracts establish compatibility; this switch is the separate user grant.").addToggle(t=>t.setValue(this.plugin.settings.interopEnabled).onChange(async n=>{this.plugin.settings.interopEnabled=n,await this.plugin.saveSettings()}))}},Va=class extends M.Plugin{constructor(t,n){super(t,n);this.issueMap=new Map;this.sortedIssuesCache=null;this.schemaCache=null;this.schemaLoadPromise=null;this.pendingSaveValidations=new Map;this.saveValidationDebounceMs=250;this.connectSync=new La(t,{getMirrorProfile:()=>this.getMirrorProfile(),saveMirrorProfile:async s=>{this.settings.mirrorProfile=s,await this.saveSettings()}}),this.interopBridge=new Lo(t,()=>{var s;return((s=this.settings)==null?void 0:s.interopEnabled)===!0}),this.api={apiVersion:1,interop:this.interopBridge,getInteropStatus:()=>{var s;return{enabled:((s=this.settings)==null?void 0:s.interopEnabled)===!0,profileVersion:"0.1"}}}}async onload(){await this.loadSettings(),await this.connectSync.initialize(),(0,M.addIcon)(ds,L0),this.statusBarEl=this.addStatusBarItem(),this.updateStatusBar(),this.registerView(yn,n=>new Fa(n,this)),this.registerView(us,n=>new sf(n,this)),this.addSettingTab(new of(this.app,this)),this.addRibbonIcon(ds,"Open mdbase",()=>void this.openWorkspace()),this.addCommand({id:"mdbase-open",name:"mdbase: Open workspace",callback:()=>void this.openWorkspace()}),this.addCommand({id:"mdbase-initialize-collection",name:"mdbase: Initialize collection",callback:()=>void this.initializeCollectionCommand()}),this.addCommand({id:"mdbase-create-type",name:"mdbase: Create type definition",callback:()=>void this.openWorkspace("types")}),this.addCommand({id:"mdbase-edit-type",name:"mdbase: Edit type definition",callback:()=>void this.openWorkspace("types")}),this.addCommand({id:"mdbase-edit-current-type",name:"mdbase: Edit current type definition",callback:()=>void this.openWorkspace("types")}),this.addCommand({id:"mdbase-create-note-from-type",name:"mdbase: Create note from type",callback:()=>void this.createNoteFromTypeCommand()}),this.addCommand({id:"mdbase-validate-current-note",name:"mdbase: Validate current note",callback:()=>void this.validateCurrentNoteCommand()}),this.addCommand({id:"mdbase-validate-collection",name:"mdbase: Validate collection",callback:()=>void this.runCollectionValidation(!0)}),this.addCommand({id:"mdbase-open-issues-view",name:"mdbase: Open issues view",callback:()=>void this.openWorkspace("issues")}),this.addCommand({id:"mdbase-sync",name:"mdbase: Sync collection authority",callback:()=>void this.syncHostedCollectionCommand()}),this.addCommand({id:"mdbase-open-sync",name:"mdbase: Open sync",callback:()=>void this.openWorkspace("sync")}),this.registerEvent(this.app.vault.on("modify",n=>{n instanceof M.TFile&&this.onVaultModify(n)})),this.registerEvent(this.app.vault.on("rename",(n,s)=>{n instanceof M.TFile&&this.onVaultRename(n,s)})),this.registerEvent(this.app.vault.on("delete",n=>{n instanceof M.TFile&&this.onVaultDelete(n)})),this.registerEvent(this.app.vault.on("create",n=>{n instanceof M.TFile&&this.onVaultCreate(n)})),this.registerEvent(this.app.workspace.on("file-open",n=>{this.settings.validateOnOpen&&(!(n instanceof M.TFile)||n.extension!=="md"||this.validateFileAndStore(n,"open"))}));let t=this.app.workspace.getActiveFile();t&&this.settings.validateOnOpen&&this.validateFileAndStore(t,"open")}async onunload(){await this.interopBridge.dispose(),this.app.workspace.getLeavesOfType(yn).forEach(t=>t.detach()),this.app.workspace.getLeavesOfType(us).forEach(t=>t.detach()),this.clearAllPendingSaveValidations()}async loadSettings(){this.settings=Object.assign({},_O,await this.loadData()),vO(this.settings.mirrorProfile)||(this.settings.mirrorProfile=null)}async saveSettings(){await this.saveData(this.settings)}getIssues(){var t;return(t=this.sortedIssuesCache)!=null||(this.sortedIssuesCache=Array.from(this.issueMap.values()).flat().sort((n,s)=>n.path.localeCompare(s.path)||n.severity.localeCompare(s.severity)||n.code.localeCompare(s.code))),this.sortedIssuesCache}getMirrorProfile(){return this.settings.mirrorProfile?{...this.settings.mirrorProfile}:null}async loadWorkspaceSchema(t=!1){return this.getConfigAndTypes(t)}async loadTypeModel(t){var i;let n=this.app.vault.getAbstractFileByPath((0,M.normalizePath)(t));if(!(n instanceof M.TFile))throw new Error(`Type file not found: ${t}`);let s=tt(await this.app.vault.cachedRead(n));if(!s.hasFrontmatter||s.error)throw new Error(`Invalid type frontmatter: ${(i=s.error)!=null?i:"frontmatter is missing"}`);return ja(s.frontmatter,s.body,n.basename)}async saveTypeModel(t,n){var a;if(this.connectSync.assertLocalAuthorityWritable(),((a=this.getMirrorProfile())==null?void 0:a.mode)==="read_only")throw new Error("This mirror has read-only access. Re-enroll it with write access before editing types.");let s=await zn(this.app.vault);if(!s)throw new Error("No mdbase.yaml found.");if(!s.spec_version.startsWith("0.3."))throw new Error("mdbase v0.2 type definitions are read-only. Migrate the collection first.");let i=n?this.app.vault.getAbstractFileByPath((0,M.normalizePath)(n)):null;if(i!=null&&!(i instanceof M.TFile))throw new Error(`Type file not found: ${n}`);let o=await this.writeTypeDefinition(s,t,i);return this.refreshWorkspaceViews(!0),o}async initializeCollection(){this.connectSync.assertLocalAuthorityWritable(),await this.initializeCollectionCommand(),this.refreshWorkspaceViews(!0)}async validateCollection(){await this.runCollectionValidation(!1)}analyzeMigration(){if(this.getMirrorProfile())throw new Error("Collection authority resources must be migrated at the collection authority.");return C0(this.app.vault)}async applyMigration(t,n){var i,o;if(this.connectSync.assertLocalAuthorityWritable(),this.getMirrorProfile())throw new Error("Collection authority resources must be migrated at the collection authority.");let s=await N0(this.app.vault,t,{allowLossy:n});if(!s.applied)throw new Error(s.restored?`Migration failed and all writes were rolled back. ${(i=s.error)!=null?i:""}`.trim():`Migration needs manual recovery. See ${s.manifestPath}. ${(o=s.error)!=null?o:""}`.trim());this.invalidateSchemaCache(),new M.Notice(`Migrated to mdbase v0.3. Recovery manifest: ${s.manifestPath}`),this.refreshWorkspaceViews(!0)}async openIssue(t){await this.openFileByPath(t.path,t.field)}getQuickFixLabel(t){return["unknown_field","schema_additional_properties"].includes(t.code)&&t.field?"Remove field":["missing_required","schema_required"].includes(t.code)&&t.field?"Add placeholder":null}async applyQuickFix(t){this.connectSync.assertLocalAuthorityWritable();let n=this.app.vault.getAbstractFileByPath(t.path);if(!(n instanceof M.TFile)){new M.Notice(`File not found: ${t.path}`);return}let s=await this.app.vault.cachedRead(n),i=tt(s);if(i.error){new M.Notice(`Cannot apply quick fix: invalid frontmatter (${i.error})`);return}if(["unknown_field","schema_additional_properties"].includes(t.code)&&t.field){let o=Vo(t.field);if(!(o in i.frontmatter)){new M.Notice(`Field '${o}' not found in frontmatter.`);return}delete i.frontmatter[o],await this.app.vault.modify(n,`${ot(i.frontmatter,i.body)} +`),new M.Notice(`Removed '${o}' from ${n.basename}`),await this.validateFileAndStore(n,"manual");return}if(["missing_required","schema_required"].includes(t.code)&&t.field){let o=Vo(t.field);i.frontmatter[o]===void 0&&(i.frontmatter[o]="TODO");let a=i.hasFrontmatter?i.body:s;await this.app.vault.modify(n,`${ot(i.frontmatter,a)} +`),new M.Notice(`Added placeholder '${o}' to ${n.basename}`),await this.validateFileAndStore(n,"manual");return}new M.Notice("No quick fix available for this issue.")}async openFileByPath(t,n){let s=this.app.vault.getAbstractFileByPath(t);if(!(s instanceof M.TFile)){new M.Notice(`File not found: ${t}`);return}await this.app.workspace.getLeaf(!0).openFile(s),n&&this.revealFrontmatterField(s,n)}revealFrontmatterField(t,n){let s=this.app.workspace.getMostRecentLeaf();if(!s||!(s.view instanceof M.MarkdownView))return;let i=s.view;if(!(i.file instanceof M.TFile)||i.file.path!==t.path)return;let o=i.editor,a=o.lineCount();if(a<3)return;let c=Vo(n),l=new RegExp(`^\\s*${$O(c)}\\s*:`);if(o.getLine(0).trim()==="---")for(let u=1;ui.severity==="error").length,s=t.length-n;if(t.length===0){this.statusBarEl.setText("mdbase: no issues");return}this.statusBarEl.setText(`mdbase: ${n} error${n===1?"":"s"}, ${s} warning${s===1?"":"s"}`)}async openIssuesView(){var s;let t=this.app.workspace.getLeavesOfType(us)[0];if(t){this.app.workspace.revealLeaf(t),t.view.render();return}let n=(s=this.app.workspace.getRightLeaf(!1))!=null?s:this.app.workspace.getLeaf(!0);await n.setViewState({type:us,active:!0}),this.app.workspace.revealLeaf(n)}async openWorkspace(t="types"){let n=this.app.workspace.getLeavesOfType(yn)[0];if(n){this.app.workspace.revealLeaf(n);let o=n.view;o.showDestination(t),await o.refresh();return}let s=this.app.workspace.getLeaf(!0);await s.setViewState({type:yn,active:!0}),this.app.workspace.revealLeaf(s),s.view.showDestination(t)}refreshWorkspaceViews(t=!1){for(let n of this.app.workspace.getLeavesOfType(yn))n.view.refresh(t)}refreshIssueViews(){this.updateStatusBar();for(let t of this.app.workspace.getLeavesOfType(us))t.view.render();this.refreshWorkspaceViews()}setFileIssues(t,n){n.length===0?this.issueMap.delete(t):this.issueMap.set(t,n),this.sortedIssuesCache=null,this.refreshIssueViews()}clearFileIssues(t){this.issueMap.has(t)&&(this.issueMap.delete(t),this.sortedIssuesCache=null,this.refreshIssueViews())}moveFileIssues(t,n){let s=this.issueMap.get(t);s&&(this.issueMap.delete(t),this.issueMap.set(n,s.map(i=>({...i,path:n}))),this.sortedIssuesCache=null,this.refreshIssueViews())}clearAllPendingSaveValidations(){for(let t of this.pendingSaveValidations.values())window.clearTimeout(t);this.pendingSaveValidations.clear()}clearPendingSaveValidation(t){let n=this.pendingSaveValidations.get(t);n!=null&&(window.clearTimeout(n),this.pendingSaveValidations.delete(t))}scheduleSaveValidation(t){this.clearPendingSaveValidation(t.path);let n=window.setTimeout(()=>{this.pendingSaveValidations.delete(t.path),this.validateFileAndStore(t,"save")},this.saveValidationDebounceMs);this.pendingSaveValidations.set(t.path,n)}isSchemaRelevantPath(t){let n=(0,M.normalizePath)(t);if(n==="mdbase.yaml")return!0;let s=new Set(["_types"]);this.schemaCache&&s.add((0,M.normalizePath)(this.schemaCache.config.settings.types_folder));for(let i of s)if(n===i||n.startsWith(`${i}/`))return!0;return!1}invalidateSchemaCache(){this.schemaCache=null,this.schemaLoadPromise=null}async getConfigAndTypes(t=!1){if(t&&this.invalidateSchemaCache(),this.schemaCache)return this.schemaCache;if(this.schemaLoadPromise)return this.schemaLoadPromise;this.schemaLoadPromise=(async()=>{let n=await zn(this.app.vault);if(!n)return null;let s=await Zg(this.app.vault,n);return{config:n,types:s}})();try{let n=await this.schemaLoadPromise;return n&&(this.schemaCache=n),n}finally{this.schemaLoadPromise=null}}async requireConfigAndTypes(t={}){var i,o;let n=(i=t.background)!=null?i:!1,s=await this.getConfigAndTypes((o=t.forceReload)!=null?o:!1);return s?(s.types.size===0&&!n&&new M.Notice(`No types found in ${s.config.settings.types_folder}`),s):(n||new M.Notice("No mdbase.yaml found. Run 'mdbase: Initialize collection' first."),null)}onVaultModify(t){this.isSchemaRelevantPath(t.path)&&(this.invalidateSchemaCache(),this.refreshWorkspaceViews()),this.settings.validateOnSave&&t.extension==="md"&&this.scheduleSaveValidation(t)}onVaultRename(t,n){(this.isSchemaRelevantPath(n)||this.isSchemaRelevantPath(t.path))&&(this.invalidateSchemaCache(),this.refreshWorkspaceViews()),t.extension==="md"&&(this.clearPendingSaveValidation(n),this.moveFileIssues(n,t.path),this.settings.validateOnSave&&this.scheduleSaveValidation(t))}onVaultDelete(t){this.isSchemaRelevantPath(t.path)&&(this.invalidateSchemaCache(),this.refreshWorkspaceViews()),t.extension==="md"&&(this.clearPendingSaveValidation(t.path),this.clearFileIssues(t.path))}onVaultCreate(t){this.isSchemaRelevantPath(t.path)&&(this.invalidateSchemaCache(),this.refreshWorkspaceViews())}async validateFileAndStore(t,n){let s=await this.requireConfigAndTypes({background:n!=="manual"});if(!s)return n!=="manual"&&this.clearFileIssues(t.path),[];let i=await Xd(this.app.vault,t,s.config,s.types);return this.setFileIssues(t.path,i),n==="save"&&this.settings.showNoticeOnSave&&i.length>0&&new M.Notice(`mdbase: ${i.length} issue${i.length===1?"":"s"} in ${t.basename}`),i}async initializeCollectionCommand(){if(this.connectSync.assertLocalAuthorityWritable(),this.getMirrorProfile()){new M.Notice("This vault is configured as a mirror. Sync it instead of initializing a local collection.");return}let{created:t}=await Yg(this.app.vault);if(this.invalidateSchemaCache(),t.length===0){new M.Notice("mdbase collection already initialized.");return}new M.Notice(`Initialized mdbase collection: ${t.join(", ")}`)}async syncHostedCollectionCommand(){if(!this.getMirrorProfile()){await this.openWorkspace("sync");return}try{let t=await this.connectSync.sync();this.invalidateSchemaCache(),this.refreshWorkspaceViews(!0);let n=t.conflicts.length+t.local_issues.length;new M.Notice(n?`Sync completed with ${n} item${n===1?"":"s"} needing attention.`:"mdbase sync completed.")}catch(t){new M.Notice(`mdbase sync failed: ${t instanceof Error?t.message:String(t)}`),await this.openWorkspace("sync")}}async createNoteFromTypeCommand(){var u,d;this.connectSync.assertLocalAuthorityWritable();let t=await this.requireConfigAndTypes();if(!t)return;if(t.types.size===0){new M.Notice("No type definitions found.");return}let n=await SO(this.app,Array.from(t.types.values()));if(!n)return;let s=rb(n,t.config),i=nb(n,s);for(let[f,p]of i){let m=`Required field: ${f}`,h=await new Li(this.app,m,(u=p.type)!=null?u:"string").openAndGetValue();if(h==null)return;if(h.trim().length===0){new M.Notice(`Field '${f}' is required.`);return}try{s[f]=Qd(h,p)}catch(y){new M.Notice(`Invalid value for ${f}: ${y instanceof Error?y.message:String(y)}`);return}}let o=(d=n.display_name_key)!=null?d:"title";if(s[o]==null){let f=await new Li(this.app,`Optional ${o} (used for filename)`,"").openAndGetValue();f&&f.trim().length>0&&(s[o]=f.trim())}let a=await ib(this.app.vault,n,s),c=await new Li(this.app,"Note path","Relative path in vault",a).openAndGetValue();if(c==null)return;let l=(0,M.normalizePath)(c.trim().length>0?c.trim():a);l.endsWith(".md")||(l=`${l}.md`);try{let f=await ob(this.app.vault,l,s);await this.app.workspace.getLeaf(!0).openFile(f),new M.Notice(`Created note: ${f.path}`),await this.validateFileAndStore(f,"manual")}catch(f){new M.Notice(f instanceof Error?f.message:String(f))}}async validateCurrentNoteCommand(){let t=this.app.workspace.getActiveFile();if(!(t instanceof M.TFile)||t.extension!=="md"){new M.Notice("Open a markdown note first.");return}let n=await this.validateFileAndStore(t,"manual");n.length===0?new M.Notice("No issues in current note."):(new M.Notice(`Found ${n.length} issue${n.length===1?"":"s"} in current note.`),await this.openIssuesView())}async runCollectionValidation(t){var o;let n=await this.requireConfigAndTypes({background:!1});if(!n)return;let s=await tb(this.app.vault,n.config,n.types),i=new Map;for(let a of s){let c=(o=i.get(a.path))!=null?o:[];c.push(a),i.set(a.path,c)}if(this.issueMap=i,this.sortedIssuesCache=null,this.refreshIssueViews(),t)if(s.length===0)new M.Notice("Collection validation passed with no issues.");else{let a=s.filter(l=>l.severity==="error").length,c=s.length-a;new M.Notice(`Collection validation: ${a} error(s), ${c} warning(s)`),await this.openIssuesView()}}async ensureFolderExists(t){let n=(0,M.normalizePath)(t).replace(/\/+$/,"");if(!n)return;let s=n.split("/"),i="";for(let o of s)i=i?`${i}/${o}`:o,await this.app.vault.adapter.exists(i)||await this.app.vault.createFolder(i)}async writeTypeDefinition(t,n,s){let i=n.name.trim();if(!i)throw new Error("Type name is required.");if(!t.spec_version.startsWith("0.3.")||n.specProfile!=="v0.3")throw new Error("mdbase v0.2 type definitions are read-only. Migrate the collection first.");let o=Mi(n),a=n.body.trim()||`# ${i} -Type definition for ${s}.`,c=`${at(o,a)} -`,l=(0,M.normalizePath)(t.settings.types_folder),u=(0,M.normalizePath)(`${l}/${s}.md`);if(!n){if(await this.ensureFolderExists(l),await this.app.vault.adapter.exists(u))throw new Error(`Type already exists: ${u}`);let y=await this.app.vault.create(u,c);return this.invalidateSchemaCache(),y}let d=n.path.lastIndexOf("/"),f=d>=0?n.path.slice(0,d):"",m=(0,M.normalizePath)(`${f?`${f}/`:""}${s}.md`)||u;if(m!==n.path&&await this.app.vault.adapter.exists(m))throw new Error(`Cannot rename type file to ${m}; file already exists.`);m!==n.path&&await this.app.fileManager.renameFile(n,m);let h=this.app.vault.getAbstractFileByPath(m);if(!(h instanceof M.TFile))throw new Error(`Unable to access updated type file: ${m}`);return await this.app.vault.modify(h,c),this.invalidateSchemaCache(),h}}; +Type definition for ${i}.`,c=`${ot(o,a)} +`,l=(0,M.normalizePath)(t.settings.types_folder),u=(0,M.normalizePath)(`${l}/${i}.md`);if(!s){if(await this.ensureFolderExists(l),await this.app.vault.adapter.exists(u))throw new Error(`Type already exists: ${u}`);let y=await this.app.vault.create(u,c);return this.invalidateSchemaCache(),y}let d=s.path.lastIndexOf("/"),f=d>=0?s.path.slice(0,d):"",m=(0,M.normalizePath)(`${f?`${f}/`:""}${i}.md`)||u;if(m!==s.path&&await this.app.vault.adapter.exists(m))throw new Error(`Cannot rename type file to ${m}; file already exists.`);m!==s.path&&await this.app.fileManager.renameFile(s,m);let h=this.app.vault.getAbstractFileByPath(m);if(!(h instanceof M.TFile))throw new Error(`Unable to access updated type file: ${m}`);return await this.app.vault.modify(h,c),this.invalidateSchemaCache(),h}}; diff --git a/main.ts b/main.ts index 3f0f4d3..2176315 100644 --- a/main.ts +++ b/main.ts @@ -13,12 +13,6 @@ import { WorkspaceLeaf, normalizePath, } from "obsidian"; -import { - DEFAULT_DENY_RUNTIME_POLICY, - InMemoryRuntimeHost, - type MdbaseRuntimeHostApi, - type MdbaseRuntimePolicyInfo, -} from "@callumalpass/mdbase-runtime"; import { ObsidianInteropBridge, type MdbaseObsidianInteropApi, @@ -42,10 +36,6 @@ import { validateFile, } from "./src/mdbaseCore"; import type { TypeEditorModel } from "./src/typeEditorTypes"; -import { - loadSelectedRuntimePolicy, - type RuntimePolicyDiagnostic, -} from "./src/runtimePolicy"; import { ConnectSyncController, type MirrorProfile, @@ -480,13 +470,7 @@ interface LoadedSchema { export interface MdbaseObsidianApiV1 { readonly apiVersion: 1; - readonly runtime: MdbaseRuntimeHostApi; readonly interop: MdbaseObsidianInteropApi; - getRuntimeStatus(): { - policyId: string; - policyPath?: string; - diagnostics: RuntimePolicyDiagnostic[]; - }; getInteropStatus(): { enabled: boolean; profileVersion: "0.1"; @@ -504,13 +488,6 @@ export default class MdbasePlugin extends Plugin { private schemaLoadPromise: Promise | null = null; private pendingSaveValidations = new Map(); private readonly saveValidationDebounceMs = 250; - private runtimePolicy: MdbaseRuntimePolicyInfo = { - ...DEFAULT_DENY_RUNTIME_POLICY, - capabilities: { ...DEFAULT_DENY_RUNTIME_POLICY.capabilities }, - }; - private runtimePolicyPath: string | undefined; - private runtimePolicyDiagnostics: RuntimePolicyDiagnostic[] = []; - private runtimePolicyRefreshGeneration = 0; private readonly interopBridge: ObsidianInteropBridge; constructor(app: App, manifest: import("obsidian").PluginManifest) { @@ -525,13 +502,7 @@ export default class MdbasePlugin extends Plugin { this.interopBridge = new ObsidianInteropBridge(app, () => this.settings?.interopEnabled === true); this.api = { apiVersion: 1, - runtime: new InMemoryRuntimeHost({ policyResolver: () => this.runtimePolicy }), interop: this.interopBridge, - getRuntimeStatus: () => ({ - policyId: this.runtimePolicy.id, - policyPath: this.runtimePolicyPath, - diagnostics: this.runtimePolicyDiagnostics.map((diagnostic) => ({ ...diagnostic })), - }), getInteropStatus: () => ({ enabled: this.settings?.interopEnabled === true, profileVersion: "0.1", @@ -542,7 +513,6 @@ export default class MdbasePlugin extends Plugin { async onload(): Promise { await this.loadSettings(); await this.connectSync.initialize(); - await this.refreshRuntimePolicy(); addIcon(MDBASE_ICON_ID, MDBASE_ICON_SVG); this.statusBarEl = this.addStatusBarItem(); @@ -663,7 +633,6 @@ export default class MdbasePlugin extends Plugin { async onunload(): Promise { await this.interopBridge.dispose(); - await this.api.runtime.dispose(); this.app.workspace.getLeavesOfType(MDBASE_WORKSPACE_VIEW).forEach((leaf) => leaf.detach()); this.app.workspace.getLeavesOfType(MDBASE_ISSUES_VIEW).forEach((leaf) => leaf.detach()); this.clearAllPendingSaveValidations(); @@ -757,7 +726,6 @@ export default class MdbasePlugin extends Plugin { ); } this.invalidateSchemaCache(); - await this.refreshRuntimePolicy(); new Notice(`Migrated to mdbase v0.3. Recovery manifest: ${result.manifestPath}`); this.refreshWorkspaceViews(true); } @@ -1041,7 +1009,6 @@ export default class MdbasePlugin extends Plugin { } private onVaultModify(file: TFile): void { - if (this.isRuntimePolicyRelevantPath(file.path)) void this.refreshRuntimePolicy(); if (this.isSchemaRelevantPath(file.path)) { this.invalidateSchemaCache(); this.refreshWorkspaceViews(); @@ -1053,9 +1020,6 @@ export default class MdbasePlugin extends Plugin { } private onVaultRename(file: TFile, oldPath: string): void { - if (this.isRuntimePolicyRelevantPath(oldPath) || this.isRuntimePolicyRelevantPath(file.path)) { - void this.refreshRuntimePolicy(); - } if (this.isSchemaRelevantPath(oldPath) || this.isSchemaRelevantPath(file.path)) { this.invalidateSchemaCache(); this.refreshWorkspaceViews(); @@ -1072,7 +1036,6 @@ export default class MdbasePlugin extends Plugin { } private onVaultDelete(file: TFile): void { - if (this.isRuntimePolicyRelevantPath(file.path)) void this.refreshRuntimePolicy(); if (this.isSchemaRelevantPath(file.path)) { this.invalidateSchemaCache(); this.refreshWorkspaceViews(); @@ -1084,31 +1047,12 @@ export default class MdbasePlugin extends Plugin { } private onVaultCreate(file: TFile): void { - if (this.isRuntimePolicyRelevantPath(file.path)) void this.refreshRuntimePolicy(); if (this.isSchemaRelevantPath(file.path)) { this.invalidateSchemaCache(); this.refreshWorkspaceViews(); } } - private isRuntimePolicyRelevantPath(path: string): boolean { - const normalized = normalizePath(path); - return normalized === "mdbase.yaml" || normalized === this.runtimePolicyPath; - } - - private async refreshRuntimePolicy(): Promise { - const generation = ++this.runtimePolicyRefreshGeneration; - const config = await loadMdbaseConfig(this.app.vault); - const selected = await loadSelectedRuntimePolicy(this.app.vault, config); - if (generation !== this.runtimePolicyRefreshGeneration) return; - this.runtimePolicy = selected.policy; - this.runtimePolicyPath = selected.path; - this.runtimePolicyDiagnostics = selected.diagnostics; - for (const diagnostic of selected.diagnostics) { - console.warn(`[mdbase/runtime] ${diagnostic.code}: ${diagnostic.message}`); - } - } - private async validateFileAndStore(file: TFile, reason: "save" | "open" | "manual"): Promise { const loaded = await this.requireConfigAndTypes({ background: reason !== "manual" }); if (!loaded) { diff --git a/package-lock.json b/package-lock.json index 461d8b7..67d0a88 100644 --- a/package-lock.json +++ b/package-lock.json @@ -10,7 +10,6 @@ "license": "MIT", "dependencies": { "@callumalpass/mdbase-interop": "file:vendor/callumalpass-mdbase-interop-0.1.0-rc.2.tgz", - "@callumalpass/mdbase-runtime": "0.1.0-rc.1", "@mdbase/connect-protocol": "file:vendor/mdbase-connect-protocol-0.1.0-beta.11.tgz", "@mdbase/connect-sync": "file:vendor/mdbase-connect-sync-0.1.0-beta.11.tgz", "ajv": "^8.20.0", @@ -38,18 +37,6 @@ "semver": "^7.8.5" } }, - "node_modules/@callumalpass/mdbase-runtime": { - "version": "0.1.0-rc.1", - "resolved": "https://registry.npmjs.org/@callumalpass/mdbase-runtime/-/mdbase-runtime-0.1.0-rc.1.tgz", - "integrity": "sha512-I+sLSUZWvq2F57ehWsfgFM5ZIbDiCkf7ROyE7EzAV/M1lkFqihFjkkH0FSr/2RzleiT84UEadZuQD1D8NdJKFA==", - "license": "MIT", - "dependencies": { - "ajv": "^8.17.1", - "ajv-formats": "^3.0.1", - "semver": "^7.8.5", - "yaml": "^2.8.1" - } - }, "node_modules/@codemirror/state": { "version": "6.5.0", "resolved": "https://registry.npmjs.org/@codemirror/state/-/state-6.5.0.tgz", diff --git a/package.json b/package.json index 767553b..9f47f33 100644 --- a/package.json +++ b/package.json @@ -33,7 +33,6 @@ }, "dependencies": { "@callumalpass/mdbase-interop": "file:vendor/callumalpass-mdbase-interop-0.1.0-rc.2.tgz", - "@callumalpass/mdbase-runtime": "0.1.0-rc.1", "@mdbase/connect-protocol": "file:vendor/mdbase-connect-protocol-0.1.0-beta.11.tgz", "@mdbase/connect-sync": "file:vendor/mdbase-connect-sync-0.1.0-beta.11.tgz", "ajv": "^8.20.0", diff --git a/src/runtimePolicy.ts b/src/runtimePolicy.ts deleted file mode 100644 index b3b8dbf..0000000 --- a/src/runtimePolicy.ts +++ /dev/null @@ -1,109 +0,0 @@ -import { normalizePath, TFile, type Vault } from "obsidian"; -import { - DEFAULT_DENY_RUNTIME_POLICY, - validateCanonicalSchema, - type MdbaseRuntimePolicyInfo, -} from "@callumalpass/mdbase-runtime"; -import { parseFrontmatter, type MdbaseConfig } from "./mdbaseCore"; - -export interface RuntimePolicyDiagnostic { - code: string; - message: string; - path?: string; -} - -export interface SelectedRuntimePolicy { - policy: MdbaseRuntimePolicyInfo; - path?: string; - diagnostics: RuntimePolicyDiagnostic[]; -} - -export async function loadSelectedRuntimePolicy( - vault: Vault, - config: MdbaseConfig | null, -): Promise { - if (!config || !config.spec_version.startsWith("0.3.")) return defaultResult(); - if (!config.runtime || config.runtime.enabled === false) return defaultResult(); - if (config.runtime.profile_version !== "0.1.0") { - return denied("unsupported_profile", `Unsupported runtime profile ${String(config.runtime.profile_version)}.`); - } - if (!config.runtime.policy) return defaultResult(); - - const selectedPath = normalizePolicyPath(config.runtime.policy); - if (!selectedPath) { - return denied("path_traversal", "Runtime policy path must remain inside the vault.", config.runtime.policy); - } - - const file = vault.getAbstractFileByPath(selectedPath); - if (!(file instanceof TFile)) { - return denied("policy_not_selected", `Selected runtime policy was not found: ${selectedPath}.`, selectedPath); - } - - const parsed = parseFrontmatter(await vault.cachedRead(file)); - if (!parsed.hasFrontmatter || parsed.error) { - return denied( - "invalid_runtime_policy", - parsed.error ?? "Runtime policy must be a Markdown record with frontmatter.", - selectedPath, - ); - } - - const validation = validateCanonicalSchema("runtimePolicy", parsed.frontmatter); - if (!validation.valid) { - const detail = validation.errors - .map((error) => `${error.instancePath || "/"} ${error.message ?? error.keyword}`) - .join("; "); - return denied("invalid_runtime_policy", `Runtime policy failed canonical validation: ${detail}`, selectedPath); - } - if (parsed.frontmatter.enabled === false) { - return denied("policy_not_selected", `Selected runtime policy is disabled: ${selectedPath}.`, selectedPath); - } - - const capabilities: Record = {}; - const rawCapabilities = asRecord(parsed.frontmatter.capabilities); - for (const [id, value] of Object.entries(rawCapabilities)) { - const mode = asRecord(value).mode; - capabilities[id] = mode === "allow" ? "allow" : "deny"; - } - - return { - policy: { - id: String(parsed.frontmatter.id), - selected: true, - capabilities, - }, - path: selectedPath, - diagnostics: [], - }; -} - -function normalizePolicyPath(value: string): string | null { - const slashPath = value.replace(/\\/g, "/").replace(/^\.\//, ""); - if (!slashPath || slashPath.startsWith("/") || slashPath.split("/").includes("..")) return null; - const normalized = normalizePath(slashPath); - return normalized.endsWith(".md") ? normalized : null; -} - -function defaultResult(): SelectedRuntimePolicy { - return { policy: cloneDefaultPolicy(), diagnostics: [] }; -} - -function denied(code: string, message: string, path?: string): SelectedRuntimePolicy { - return { - policy: cloneDefaultPolicy(), - diagnostics: [{ code, message, path }], - }; -} - -function cloneDefaultPolicy(): MdbaseRuntimePolicyInfo { - return { - ...DEFAULT_DENY_RUNTIME_POLICY, - capabilities: { ...DEFAULT_DENY_RUNTIME_POLICY.capabilities }, - }; -} - -function asRecord(value: unknown): Record { - return value && typeof value === "object" && !Array.isArray(value) - ? value as Record - : {}; -} diff --git a/test/runtimePolicy.test.ts b/test/runtimePolicy.test.ts deleted file mode 100644 index c751db2..0000000 --- a/test/runtimePolicy.test.ts +++ /dev/null @@ -1,93 +0,0 @@ -import * as assert from "node:assert/strict"; -import { test } from "node:test"; -import { TFile, normalizePath } from "obsidian"; -import type { MdbaseConfig } from "../src/mdbaseCore"; -import { loadSelectedRuntimePolicy } from "../src/runtimePolicy"; - -const TestFileCtor = TFile as unknown as { new (path: string): TFile }; - -class MockVault { - private files = new Map(); - - getAbstractFileByPath(path: string): TFile | null { - return this.files.get(normalizePath(path))?.file ?? null; - } - - async cachedRead(file: TFile): Promise { - return this.files.get(file.path)?.content ?? ""; - } - - write(path: string, content: string): void { - const normalized = normalizePath(path); - this.files.set(normalized, { file: new TestFileCtor(normalized), content }); - } -} - -function config(policy?: string): MdbaseConfig { - return { - spec_version: "0.3.0", - runtime: { - profile_version: "0.1.0", - policy, - }, - settings: { - types_folder: "_types", - explicit_type_keys: ["type", "types"], - default_strict: false, - include_subfolders: true, - exclude: [], - }, - }; -} - -test("loads and normalizes the selected canonical runtime policy", async () => { - const vault = new MockVault(); - vault.write("policies/local.md", `--- -${JSON.stringify({ - type: "runtime_policy", - id: "local.runtime", - version: 1, - name: "Local runtime policy", - capabilities: { - "task.patch": { mode: "allow" }, - "task.read": {}, - }, -})} ---- -`); - - const result = await loadSelectedRuntimePolicy(vault as never, config("policies/local.md")); - - assert.equal(result.policy.id, "local.runtime"); - assert.deepEqual(result.policy.capabilities, { - "task.patch": "allow", - "task.read": "deny", - }); - assert.equal(result.path, "policies/local.md"); - assert.deepEqual(result.diagnostics, []); -}); - -test("missing or invalid selected policies remain default-deny", async () => { - const vault = new MockVault(); - vault.write("policies/invalid.md", `--- -${JSON.stringify({ - type: "runtime_policy", - id: "invalid", - version: 1, - name: "Invalid", - typo: true, -})} ---- -`); - - const missing = await loadSelectedRuntimePolicy(vault as never, config("policies/missing.md")); - const invalid = await loadSelectedRuntimePolicy(vault as never, config("policies/invalid.md")); - const traversal = await loadSelectedRuntimePolicy(vault as never, config("../outside.md")); - - assert.equal(missing.policy.id, "mdbase.default-deny"); - assert.equal(missing.diagnostics[0]?.code, "policy_not_selected"); - assert.equal(invalid.policy.id, "mdbase.default-deny"); - assert.equal(invalid.diagnostics[0]?.code, "invalid_runtime_policy"); - assert.equal(traversal.policy.id, "mdbase.default-deny"); - assert.equal(traversal.diagnostics[0]?.code, "path_traversal"); -});