diff --git a/main.js b/main.js index 2cf3ecb..32d9abb 100644 --- a/main.js +++ b/main.js @@ -3,64 +3,64 @@ THIS IS A GENERATED/BUNDLED FILE BY ESBUILD if you want to view the source, please visit the github repository of this plugin */ -var Qx=Object.create;var Pa=Object.defineProperty;var Zx=Object.getOwnPropertyDescriptor;var eE=Object.getOwnPropertyNames;var tE=Object.getPrototypeOf,rE=Object.prototype.hasOwnProperty;var oy=(r,e)=>()=>(r&&(e=r(r=0)),e);var A=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),ay=(r,e)=>{for(var t in e)Pa(r,t,{get:e[t],enumerable:!0})},cy=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of eE(e))!rE.call(r,i)&&i!==t&&Pa(r,i,{get:()=>e[i],enumerable:!(n=Zx(e,i))||n.enumerable});return r};var Kn=(r,e,t)=>(t=r!=null?Qx(tE(r)):{},cy(e||!r||!r.__esModule?Pa(t,"default",{value:r,enumerable:!0}):t,r)),nE=r=>cy(Pa({},"__esModule",{value:!0}),r);var qs=A(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 Fs=class{};se._CodeOrName=Fs;se.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Gn=class extends Fs{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=Gn;var Ot=class extends Fs{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 Gn&&(t[n.str]=(t[n.str]||0)+1),t),{})}};se._Code=Ot;se.nil=new Ot("");function uy(r,...e){let t=[r[0]],n=0;for(;n{"use strict";Object.defineProperty(dt,"__esModule",{value:!0});dt.ValueScope=dt.ValueScopeName=dt.Scope=dt.varKinds=dt.UsedValueState=void 0;var lt=qs(),qd=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},Ra;(function(r){r[r.Started=0]="Started",r[r.Completed=1]="Completed"})(Ra||(dt.UsedValueState=Ra={}));dt.varKinds={const:new lt.Name("const"),let:new lt.Name("let"),var:new lt.Name("var")};var Ia=class{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t}toName(e){return e instanceof lt.Name?e:this.name(e)}name(e){return new lt.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}}};dt.Scope=Ia;var Oa=class extends lt.Name{constructor(e,t){super(t),this.prefix=e}setValue(e,{property:t,itemIndex:n}){this.value=e,this.scopePath=(0,lt._)`.${new lt.Name(t)}[${n}]`}};dt.ValueScopeName=Oa;var bE=(0,lt._)`\n`,Bd=class extends Ia{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?bE:lt.nil}}get(){return this._scope}name(e){return new Oa(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 i=this.toName(e),{prefix:s}=i,o=(n=t.key)!==null&&n!==void 0?n: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,i);let c=this._scope[s]||(this._scope[s]=[]),l=c.length;return c[l]=t.ref,i.setValue(t,{property:s,itemIndex:l}),i}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,lt._)`${e}${n.scopePath}`})}scopeCode(e=this._values,t,n){return this._reduceValues(e,i=>{if(i.value===void 0)throw new Error(`CodeGen: name "${i}" has no value`);return i.value.code},t,n)}_reduceValues(e,t,n={},i){let s=lt.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,Ra.Started);let u=t(l);if(u){let d=this.opts.es5?dt.varKinds.var:dt.varKinds.const;s=(0,lt._)`${s}${d} ${l} = ${u};${this.opts._n}`}else if(u=i?.(l))s=(0,lt._)`${s}${u}${this.opts._n}`;else throw new qd(l);c.set(l,Ra.Completed)})}return s}};dt.ValueScope=Bd});var U=A(Y=>{"use strict";Object.defineProperty(Y,"__esModule",{value:!0});Y.or=Y.and=Y.not=Y.CodeGen=Y.operators=Y.varKinds=Y.ValueScopeName=Y.ValueScope=Y.Scope=Y.Name=Y.regexpCode=Y.stringify=Y.getProperty=Y.nil=Y.strConcat=Y.str=Y._=void 0;var re=qs(),Gt=Ud(),an=qs();Object.defineProperty(Y,"_",{enumerable:!0,get:function(){return an._}});Object.defineProperty(Y,"str",{enumerable:!0,get:function(){return an.str}});Object.defineProperty(Y,"strConcat",{enumerable:!0,get:function(){return an.strConcat}});Object.defineProperty(Y,"nil",{enumerable:!0,get:function(){return an.nil}});Object.defineProperty(Y,"getProperty",{enumerable:!0,get:function(){return an.getProperty}});Object.defineProperty(Y,"stringify",{enumerable:!0,get:function(){return an.stringify}});Object.defineProperty(Y,"regexpCode",{enumerable:!0,get:function(){return an.regexpCode}});Object.defineProperty(Y,"Name",{enumerable:!0,get:function(){return an.Name}});var Fa=Ud();Object.defineProperty(Y,"Scope",{enumerable:!0,get:function(){return Fa.Scope}});Object.defineProperty(Y,"ValueScope",{enumerable:!0,get:function(){return Fa.ValueScope}});Object.defineProperty(Y,"ValueScopeName",{enumerable:!0,get:function(){return Fa.ValueScopeName}});Object.defineProperty(Y,"varKinds",{enumerable:!0,get:function(){return Fa.varKinds}});Y.operators={GT:new re._Code(">"),GTE:new re._Code(">="),LT:new re._Code("<"),LTE:new re._Code("<="),EQ:new re._Code("==="),NEQ:new re._Code("!=="),NOT:new re._Code("!"),OR:new re._Code("||"),AND:new re._Code("&&"),ADD:new re._Code("+")};var Lr=class{optimizeNodes(){return this}optimizeNames(e,t){return this}},Vd=class extends Lr{constructor(e,t,n){super(),this.varKind=e,this.name=t,this.rhs=n}render({es5:e,_n:t}){let n=e?Gt.varKinds.var:this.varKind,i=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${i};`+t}optimizeNames(e,t){if(e[this.name.str])return this.rhs&&(this.rhs=Mi(this.rhs,e,t)),this}get names(){return this.rhs instanceof re._CodeOrName?this.rhs.names:{}}},Da=class extends Lr{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 re.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Mi(this.rhs,e,t),this}get names(){let e=this.lhs instanceof re.Name?{}:{...this.lhs.names};return La(e,this.rhs)}},Hd=class extends Da{constructor(e,t,n,i){super(e,n,i),this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},zd=class extends Lr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Kd=class extends Lr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Wd=class extends Lr{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Gd=class extends Lr{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=Mi(this.code,e,t),this}get names(){return this.code instanceof re._CodeOrName?this.code.names:{}}},Bs=class extends Lr{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,i=n.length;for(;i--;){let s=n[i];s.optimizeNames(e,t)||(vE(e,s.names),n.splice(i,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>Xn(e,t.names),{})}},Fr=class extends Bs{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Jd=class extends Bs{},Ci=class extends Fr{};Ci.kind="else";var Jn=class r extends Fr{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 Ci(n):n}if(t)return e===!1?t instanceof r?t:t.nodes:this.nodes.length?this:new r(py(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=Mi(this.condition,e,t),this}get names(){let e=super.names;return La(e,this.condition),this.else&&Xn(e,this.else.names),e}};Jn.kind="if";var Yn=class extends Fr{};Yn.kind="for";var Yd=class extends Yn{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=Mi(this.iteration,e,t),this}get names(){return Xn(super.names,this.iteration.names)}},Xd=class extends Yn{constructor(e,t,n,i){super(),this.varKind=e,this.name=t,this.from=n,this.to=i}render(e){let t=e.es5?Gt.varKinds.var:this.varKind,{name:n,from:i,to:s}=this;return`for(${t} ${n}=${i}; ${n}<${s}; ${n}++)`+super.render(e)}get names(){let e=La(super.names,this.from);return La(e,this.to)}},Na=class extends Yn{constructor(e,t,n,i){super(),this.loop=e,this.varKind=t,this.name=n,this.iterable=i}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=Mi(this.iterable,e,t),this}get names(){return Xn(super.names,this.iterable.names)}},Us=class extends Fr{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)}};Us.kind="func";var Vs=class extends Bs{render(e){return"return "+super.render(e)}};Vs.kind="return";var Qd=class extends Fr{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,i;return super.optimizeNames(e,t),(n=this.catch)===null||n===void 0||n.optimizeNames(e,t),(i=this.finally)===null||i===void 0||i.optimizeNames(e,t),this}get names(){let e=super.names;return this.catch&&Xn(e,this.catch.names),this.finally&&Xn(e,this.finally.names),e}},Hs=class extends Fr{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};Hs.kind="catch";var zs=class extends Fr{render(e){return"finally"+super.render(e)}};zs.kind="finally";var Zd=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?` -`:""},this._extScope=e,this._scope=new Gt.Scope({parent:e}),this._nodes=[new Jd]}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,i){let s=this._scope.toName(t);return n!==void 0&&i&&(this._constants[s.str]=n),this._leafNode(new Vd(e,s,n)),s}const(e,t,n){return this._def(Gt.varKinds.const,e,t,n)}let(e,t,n){return this._def(Gt.varKinds.let,e,t,n)}var(e,t,n){return this._def(Gt.varKinds.var,e,t,n)}assign(e,t,n){return this._leafNode(new Da(e,t,n))}add(e,t){return this._leafNode(new Hd(e,Y.operators.ADD,t))}code(e){return typeof e=="function"?e():e!==re.nil&&this._leafNode(new Gd(e)),this}object(...e){let t=["{"];for(let[n,i]of e)t.length>1&&t.push(","),t.push(n),(n!==i||this.opts.es5)&&(t.push(":"),(0,re.addCodeArg)(t,i));return t.push("}"),new re._Code(t)}if(e,t,n){if(this._blockNode(new Jn(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 Jn(e))}else(){return this._elseNode(new Ci)}endIf(){return this._endBlockNode(Jn,Ci)}_for(e,t){return this._blockNode(e),t&&this.code(t).endFor(),this}for(e,t){return this._for(new Yd(e),t)}forRange(e,t,n,i,s=this.opts.es5?Gt.varKinds.var:Gt.varKinds.let){let o=this._scope.toName(e);return this._for(new Xd(s,o,t,n),()=>i(o))}forOf(e,t,n,i=Gt.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let o=t instanceof re.Name?t:this.var("_arr",t);return this.forRange("_i",0,(0,re._)`${o}.length`,a=>{this.var(s,(0,re._)`${o}[${a}]`),n(s)})}return this._for(new Na("of",i,s,t),()=>n(s))}forIn(e,t,n,i=this.opts.es5?Gt.varKinds.var:Gt.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,re._)`Object.keys(${t})`,n);let s=this._scope.toName(e);return this._for(new Na("in",i,s,t),()=>n(s))}endFor(){return this._endBlockNode(Yn)}label(e){return this._leafNode(new zd(e))}break(e){return this._leafNode(new Kd(e))}return(e){let t=new Vs;if(this._blockNode(t),this.code(e),t.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Vs)}try(e,t,n){if(!t&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let i=new Qd;if(this._blockNode(i),this.code(e),t){let s=this.name("e");this._currNode=i.catch=new Hs(s),t(s)}return n&&(this._currNode=i.finally=new zs,this.code(n)),this._endBlockNode(Hs,zs)}throw(e){return this._leafNode(new Wd(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=re.nil,n,i){return this._blockNode(new Us(e,t,n)),i&&this.code(i).endFunc(),this}endFunc(){return this._endBlockNode(Us)}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 Jn))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}};Y.CodeGen=Zd;function Xn(r,e){for(let t in e)r[t]=(r[t]||0)+(e[t]||0);return r}function La(r,e){return e instanceof re._CodeOrName?Xn(r,e.names):r}function Mi(r,e,t){if(r instanceof re.Name)return n(r);if(!i(r))return r;return new re._Code(r._items.reduce((s,o)=>(o instanceof re.Name&&(o=n(o)),o instanceof re._Code?s.push(...o._items):s.push(o),s),[]));function n(s){let o=t[s.str];return o===void 0||e[s.str]!==1?s:(delete e[s.str],o)}function i(s){return s instanceof re._Code&&s._items.some(o=>o instanceof re.Name&&e[o.str]===1&&t[o.str]!==void 0)}}function vE(r,e){for(let t in e)r[t]=(r[t]||0)-(e[t]||0)}function py(r){return typeof r=="boolean"||typeof r=="number"||r===null?!r:(0,re._)`!${eu(r)}`}Y.not=py;var wE=hy(Y.operators.AND);function _E(...r){return r.reduce(wE)}Y.and=_E;var SE=hy(Y.operators.OR);function $E(...r){return r.reduce(SE)}Y.or=$E;function hy(r){return(e,t)=>e===re.nil?t:t===re.nil?e:(0,re._)`${eu(e)} ${r} ${eu(t)}`}function eu(r){return r instanceof re.Name?r:(0,re._)`(${r})`}});var Q=A(X=>{"use strict";Object.defineProperty(X,"__esModule",{value:!0});X.checkStrictMode=X.getErrorPath=X.Type=X.useFunc=X.setEvaluated=X.evaluatedPropsToName=X.mergeEvaluated=X.eachItem=X.unescapeJsonPointer=X.escapeJsonPointer=X.escapeFragment=X.unescapeFragment=X.schemaRefOrVal=X.schemaHasRulesButRef=X.schemaHasRules=X.checkUnknownRules=X.alwaysValidSchema=X.toHash=void 0;var de=U(),xE=qs();function EE(r){let e={};for(let t of r)e[t]=!0;return e}X.toHash=EE;function AE(r,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(gy(r,e),!by(e,r.self.RULES.all))}X.alwaysValidSchema=AE;function gy(r,e=r.schema){let{opts:t,self:n}=r;if(!t.strictSchema||typeof e=="boolean")return;let i=n.RULES.keywords;for(let s in e)i[s]||_y(r,`unknown keyword: "${s}"`)}X.checkUnknownRules=gy;function by(r,e){if(typeof r=="boolean")return!r;for(let t in r)if(e[t])return!0;return!1}X.schemaHasRules=by;function kE(r,e){if(typeof r=="boolean")return!r;for(let t in r)if(t!=="$ref"&&e.all[t])return!0;return!1}X.schemaHasRulesButRef=kE;function PE({topSchemaRef:r,schemaPath:e},t,n,i){if(!i){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)}`}X.schemaRefOrVal=PE;function CE(r){return vy(decodeURIComponent(r))}X.unescapeFragment=CE;function ME(r){return encodeURIComponent(ru(r))}X.escapeFragment=ME;function ru(r){return typeof r=="number"?`${r}`:r.replace(/~/g,"~0").replace(/\//g,"~1")}X.escapeJsonPointer=ru;function vy(r){return r.replace(/~1/g,"/").replace(/~0/g,"~")}X.unescapeJsonPointer=vy;function TE(r,e){if(Array.isArray(r))for(let t of r)e(t);else e(r)}X.eachItem=TE;function my({mergeNames:r,mergeToName:e,mergeValues:t,resultToName:n}){return(i,s,o,a)=>{let c=o===void 0?s:o instanceof de.Name?(s instanceof de.Name?r(i,s,o):e(i,s,o),o):s instanceof de.Name?(e(i,o,s),s):t(s,o);return a===de.Name&&!(c instanceof de.Name)?n(i,c):c}}X.mergeEvaluated={props:my({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} || {}`),nu(r,t,e))}),mergeValues:(r,e)=>r===!0?!0:{...r,...e},resultToName:wy}),items:my({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 wy(r,e){if(e===!0)return r.var("props",!0);let t=r.var("props",(0,de._)`{}`);return e!==void 0&&nu(r,t,e),t}X.evaluatedPropsToName=wy;function nu(r,e,t){Object.keys(t).forEach(n=>r.assign((0,de._)`${e}${(0,de.getProperty)(n)}`,!0))}X.setEvaluated=nu;var yy={};function RE(r,e){return r.scopeValue("func",{ref:e,code:yy[e.code]||(yy[e.code]=new xE._Code(e.code))})}X.useFunc=RE;var tu;(function(r){r[r.Num=0]="Num",r[r.Str=1]="Str"})(tu||(X.Type=tu={}));function IE(r,e,t){if(r instanceof de.Name){let n=e===tu.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():"/"+ru(r)}X.getErrorPath=IE;function _y(r,e,t=r.opts.strictSchema){if(t){if(e=`strict mode: ${e}`,t===!0)throw new Error(e);r.self.logger.warn(e)}}X.checkStrictMode=_y});var Dt=A(iu=>{"use strict";Object.defineProperty(iu,"__esModule",{value:!0});var Ue=U(),OE={data:new Ue.Name("data"),valCxt:new Ue.Name("valCxt"),instancePath:new Ue.Name("instancePath"),parentData:new Ue.Name("parentData"),parentDataProperty:new Ue.Name("parentDataProperty"),rootData:new Ue.Name("rootData"),dynamicAnchors:new Ue.Name("dynamicAnchors"),vErrors:new Ue.Name("vErrors"),errors:new Ue.Name("errors"),this:new Ue.Name("this"),self:new Ue.Name("self"),scope:new Ue.Name("scope"),json:new Ue.Name("json"),jsonPos:new Ue.Name("jsonPos"),jsonLen:new Ue.Name("jsonLen"),jsonPart:new Ue.Name("jsonPart")};iu.default=OE});var Ks=A(Ve=>{"use strict";Object.defineProperty(Ve,"__esModule",{value:!0});Ve.extendErrors=Ve.resetErrorsCount=Ve.reportExtraError=Ve.reportError=Ve.keyword$DataError=Ve.keywordError=void 0;var ie=U(),ja=Q(),Ze=Dt();Ve.keywordError={message:({keyword:r})=>(0,ie.str)`must pass "${r}" keyword validation`};Ve.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 DE(r,e=Ve.keywordError,t,n){let{it:i}=r,{gen:s,compositeRule:o,allErrors:a}=i,c=xy(r,e,t);n??(o||a)?Sy(s,c):$y(i,(0,ie._)`[${c}]`)}Ve.reportError=DE;function NE(r,e=Ve.keywordError,t){let{it:n}=r,{gen:i,compositeRule:s,allErrors:o}=n,a=xy(r,e,t);Sy(i,a),s||o||$y(n,Ze.default.vErrors)}Ve.reportExtraError=NE;function LE(r,e){r.assign(Ze.default.errors,e),r.if((0,ie._)`${Ze.default.vErrors} !== null`,()=>r.if(e,()=>r.assign((0,ie._)`${Ze.default.vErrors}.length`,e),()=>r.assign(Ze.default.vErrors,null)))}Ve.resetErrorsCount=LE;function FE({gen:r,keyword:e,schemaValue:t,data:n,errsCount:i,it:s}){if(i===void 0)throw new Error("ajv implementation error");let o=r.name("err");r.forRange("i",i,Ze.default.errors,a=>{r.const(o,(0,ie._)`${Ze.default.vErrors}[${a}]`),r.if((0,ie._)`${o}.instancePath === undefined`,()=>r.assign((0,ie._)`${o}.instancePath`,(0,ie.strConcat)(Ze.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`,n))})}Ve.extendErrors=FE;function Sy(r,e){let t=r.const("err",e);r.if((0,ie._)`${Ze.default.vErrors} === null`,()=>r.assign(Ze.default.vErrors,(0,ie._)`[${t}]`),(0,ie._)`${Ze.default.vErrors}.push(${t})`),r.code((0,ie._)`${Ze.default.errors}++`)}function $y(r,e){let{gen:t,validateName:n,schemaEnv:i}=r;i.$async?t.throw((0,ie._)`new ${r.ValidationError}(${e})`):(t.assign((0,ie._)`${n}.errors`,e),t.return(!1))}var Qn={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 xy(r,e,t){let{createErrors:n}=r.it;return n===!1?(0,ie._)`{}`:jE(r,e,t)}function jE(r,e,t={}){let{gen:n,it:i}=r,s=[qE(i,t),BE(r,t)];return UE(r,e,s),n.object(...s)}function qE({errorPath:r},{instancePath:e}){let t=e?(0,ie.str)`${r}${(0,ja.getErrorPath)(e,ja.Type.Str)}`:r;return[Ze.default.instancePath,(0,ie.strConcat)(Ze.default.instancePath,t)]}function BE({keyword:r,it:{errSchemaPath:e}},{schemaPath:t,parentSchema:n}){let i=n?e:(0,ie.str)`${e}/${r}`;return t&&(i=(0,ie.str)`${i}${(0,ja.getErrorPath)(t,ja.Type.Str)}`),[Qn.schemaPath,i]}function UE(r,{params:e,message:t},n){let{keyword:i,data:s,schemaValue:o,it:a}=r,{opts:c,propertyName:l,topSchemaRef:u,schemaPath:d}=a;n.push([Qn.keyword,i],[Qn.params,typeof e=="function"?e(r):e||(0,ie._)`{}`]),c.messages&&n.push([Qn.message,typeof t=="function"?t(r):t]),c.verbose&&n.push([Qn.schema,o],[Qn.parentSchema,(0,ie._)`${u}${d}`],[Ze.default.data,s]),l&&n.push([Qn.propertyName,l])}});var Ay=A(Ti=>{"use strict";Object.defineProperty(Ti,"__esModule",{value:!0});Ti.boolOrEmptySchema=Ti.topBoolOrEmptySchema=void 0;var VE=Ks(),HE=U(),zE=Dt(),KE={message:"boolean schema is false"};function WE(r){let{gen:e,schema:t,validateName:n}=r;t===!1?Ey(r,!1):typeof t=="object"&&t.$async===!0?e.return(zE.default.data):(e.assign((0,HE._)`${n}.errors`,null),e.return(!0))}Ti.topBoolOrEmptySchema=WE;function GE(r,e){let{gen:t,schema:n}=r;n===!1?(t.var(e,!1),Ey(r)):t.var(e,!0)}Ti.boolOrEmptySchema=GE;function Ey(r,e){let{gen:t,data:n}=r,i={gen:t,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:r};(0,VE.reportError)(i,KE,void 0,e)}});var su=A(Ri=>{"use strict";Object.defineProperty(Ri,"__esModule",{value:!0});Ri.getRules=Ri.isJSONType=void 0;var JE=["string","number","integer","boolean","null","object","array"],YE=new Set(JE);function XE(r){return typeof r=="string"&&YE.has(r)}Ri.isJSONType=XE;function QE(){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:{}}}Ri.getRules=QE});var ou=A(cn=>{"use strict";Object.defineProperty(cn,"__esModule",{value:!0});cn.shouldUseRule=cn.shouldUseGroup=cn.schemaHasRulesForType=void 0;function ZE({schema:r,self:e},t){let n=e.RULES.types[t];return n&&n!==!0&&ky(r,n)}cn.schemaHasRulesForType=ZE;function ky(r,e){return e.rules.some(t=>Py(r,t))}cn.shouldUseGroup=ky;function Py(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))}cn.shouldUseRule=Py});var Ws=A(He=>{"use strict";Object.defineProperty(He,"__esModule",{value:!0});He.reportTypeError=He.checkDataTypes=He.checkDataType=He.coerceAndCheckDataType=He.getJSONTypes=He.getSchemaTypes=He.DataType=void 0;var eA=su(),tA=ou(),rA=Ks(),K=U(),Cy=Q(),Ii;(function(r){r[r.Correct=0]="Correct",r[r.Wrong=1]="Wrong"})(Ii||(He.DataType=Ii={}));function nA(r){let e=My(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}He.getSchemaTypes=nA;function My(r){let e=Array.isArray(r)?r:r?[r]:[];if(e.every(eA.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}He.getJSONTypes=My;function iA(r,e){let{gen:t,data:n,opts:i}=r,s=sA(e,i.coerceTypes),o=e.length>0&&!(s.length===0&&e.length===1&&(0,tA.schemaHasRulesForType)(r,e[0]));if(o){let a=cu(e,n,i.strictNumbers,Ii.Wrong);t.if(a,()=>{s.length?oA(r,e,s):lu(r)})}return o}He.coerceAndCheckDataType=iA;var Ty=new Set(["string","number","integer","boolean","null"]);function sA(r,e){return e?r.filter(t=>Ty.has(t)||e==="array"&&t==="array"):[]}function oA(r,e,t){let{gen:n,data:i,opts:s}=r,o=n.let("dataType",(0,K._)`typeof ${i}`),a=n.let("coerced",(0,K._)`undefined`);s.coerceTypes==="array"&&n.if((0,K._)`${o} == 'object' && Array.isArray(${i}) && ${i}.length == 1`,()=>n.assign(i,(0,K._)`${i}[0]`).assign(o,(0,K._)`typeof ${i}`).if(cu(e,i,s.strictNumbers),()=>n.assign(a,i))),n.if((0,K._)`${a} !== undefined`);for(let l of t)(Ty.has(l)||l==="array"&&s.coerceTypes==="array")&&c(l);n.else(),lu(r),n.endIf(),n.if((0,K._)`${a} !== undefined`,()=>{n.assign(i,a),aA(r,a)});function c(l){switch(l){case"string":n.elseIf((0,K._)`${o} == "number" || ${o} == "boolean"`).assign(a,(0,K._)`"" + ${i}`).elseIf((0,K._)`${i} === null`).assign(a,(0,K._)`""`);return;case"number":n.elseIf((0,K._)`${o} == "boolean" || ${i} === null +var Zx=Object.create;var Pa=Object.defineProperty;var eE=Object.getOwnPropertyDescriptor;var tE=Object.getOwnPropertyNames;var rE=Object.getPrototypeOf,nE=Object.prototype.hasOwnProperty;var oy=(r,e)=>()=>(r&&(e=r(r=0)),e);var A=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),ay=(r,e)=>{for(var t in e)Pa(r,t,{get:e[t],enumerable:!0})},cy=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of tE(e))!nE.call(r,i)&&i!==t&&Pa(r,i,{get:()=>e[i],enumerable:!(n=eE(e,i))||n.enumerable});return r};var Kn=(r,e,t)=>(t=r!=null?Zx(rE(r)):{},cy(e||!r||!r.__esModule?Pa(t,"default",{value:r,enumerable:!0}):t,r)),iE=r=>cy(Pa({},"__esModule",{value:!0}),r);var qs=A(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 Fs=class{};se._CodeOrName=Fs;se.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Gn=class extends Fs{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=Gn;var Ot=class extends Fs{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 Gn&&(t[n.str]=(t[n.str]||0)+1),t),{})}};se._Code=Ot;se.nil=new Ot("");function uy(r,...e){let t=[r[0]],n=0;for(;n{"use strict";Object.defineProperty(dt,"__esModule",{value:!0});dt.ValueScope=dt.ValueScopeName=dt.Scope=dt.varKinds=dt.UsedValueState=void 0;var lt=qs(),jd=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},Ra;(function(r){r[r.Started=0]="Started",r[r.Completed=1]="Completed"})(Ra||(dt.UsedValueState=Ra={}));dt.varKinds={const:new lt.Name("const"),let:new lt.Name("let"),var:new lt.Name("var")};var Ia=class{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t}toName(e){return e instanceof lt.Name?e:this.name(e)}name(e){return new lt.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}}};dt.Scope=Ia;var Oa=class extends lt.Name{constructor(e,t){super(t),this.prefix=e}setValue(e,{property:t,itemIndex:n}){this.value=e,this.scopePath=(0,lt._)`.${new lt.Name(t)}[${n}]`}};dt.ValueScopeName=Oa;var vE=(0,lt._)`\n`,qd=class extends Ia{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?vE:lt.nil}}get(){return this._scope}name(e){return new Oa(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 i=this.toName(e),{prefix:s}=i,o=(n=t.key)!==null&&n!==void 0?n: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,i);let c=this._scope[s]||(this._scope[s]=[]),l=c.length;return c[l]=t.ref,i.setValue(t,{property:s,itemIndex:l}),i}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,lt._)`${e}${n.scopePath}`})}scopeCode(e=this._values,t,n){return this._reduceValues(e,i=>{if(i.value===void 0)throw new Error(`CodeGen: name "${i}" has no value`);return i.value.code},t,n)}_reduceValues(e,t,n={},i){let s=lt.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,Ra.Started);let u=t(l);if(u){let d=this.opts.es5?dt.varKinds.var:dt.varKinds.const;s=(0,lt._)`${s}${d} ${l} = ${u};${this.opts._n}`}else if(u=i?.(l))s=(0,lt._)`${s}${u}${this.opts._n}`;else throw new jd(l);c.set(l,Ra.Completed)})}return s}};dt.ValueScope=qd});var U=A(Y=>{"use strict";Object.defineProperty(Y,"__esModule",{value:!0});Y.or=Y.and=Y.not=Y.CodeGen=Y.operators=Y.varKinds=Y.ValueScopeName=Y.ValueScope=Y.Scope=Y.Name=Y.regexpCode=Y.stringify=Y.getProperty=Y.nil=Y.strConcat=Y.str=Y._=void 0;var re=qs(),Gt=Bd(),an=qs();Object.defineProperty(Y,"_",{enumerable:!0,get:function(){return an._}});Object.defineProperty(Y,"str",{enumerable:!0,get:function(){return an.str}});Object.defineProperty(Y,"strConcat",{enumerable:!0,get:function(){return an.strConcat}});Object.defineProperty(Y,"nil",{enumerable:!0,get:function(){return an.nil}});Object.defineProperty(Y,"getProperty",{enumerable:!0,get:function(){return an.getProperty}});Object.defineProperty(Y,"stringify",{enumerable:!0,get:function(){return an.stringify}});Object.defineProperty(Y,"regexpCode",{enumerable:!0,get:function(){return an.regexpCode}});Object.defineProperty(Y,"Name",{enumerable:!0,get:function(){return an.Name}});var Fa=Bd();Object.defineProperty(Y,"Scope",{enumerable:!0,get:function(){return Fa.Scope}});Object.defineProperty(Y,"ValueScope",{enumerable:!0,get:function(){return Fa.ValueScope}});Object.defineProperty(Y,"ValueScopeName",{enumerable:!0,get:function(){return Fa.ValueScopeName}});Object.defineProperty(Y,"varKinds",{enumerable:!0,get:function(){return Fa.varKinds}});Y.operators={GT:new re._Code(">"),GTE:new re._Code(">="),LT:new re._Code("<"),LTE:new re._Code("<="),EQ:new re._Code("==="),NEQ:new re._Code("!=="),NOT:new re._Code("!"),OR:new re._Code("||"),AND:new re._Code("&&"),ADD:new re._Code("+")};var Lr=class{optimizeNodes(){return this}optimizeNames(e,t){return this}},Ud=class extends Lr{constructor(e,t,n){super(),this.varKind=e,this.name=t,this.rhs=n}render({es5:e,_n:t}){let n=e?Gt.varKinds.var:this.varKind,i=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${i};`+t}optimizeNames(e,t){if(e[this.name.str])return this.rhs&&(this.rhs=Mi(this.rhs,e,t)),this}get names(){return this.rhs instanceof re._CodeOrName?this.rhs.names:{}}},Da=class extends Lr{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 re.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Mi(this.rhs,e,t),this}get names(){let e=this.lhs instanceof re.Name?{}:{...this.lhs.names};return La(e,this.rhs)}},Vd=class extends Da{constructor(e,t,n,i){super(e,n,i),this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Hd=class extends Lr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},zd=class extends Lr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Kd=class extends Lr{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Wd=class extends Lr{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=Mi(this.code,e,t),this}get names(){return this.code instanceof re._CodeOrName?this.code.names:{}}},Bs=class extends Lr{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,i=n.length;for(;i--;){let s=n[i];s.optimizeNames(e,t)||(wE(e,s.names),n.splice(i,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>Xn(e,t.names),{})}},Fr=class extends Bs{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Gd=class extends Bs{},Ci=class extends Fr{};Ci.kind="else";var Jn=class r extends Fr{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 Ci(n):n}if(t)return e===!1?t instanceof r?t:t.nodes:this.nodes.length?this:new r(py(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=Mi(this.condition,e,t),this}get names(){let e=super.names;return La(e,this.condition),this.else&&Xn(e,this.else.names),e}};Jn.kind="if";var Yn=class extends Fr{};Yn.kind="for";var Jd=class extends Yn{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=Mi(this.iteration,e,t),this}get names(){return Xn(super.names,this.iteration.names)}},Yd=class extends Yn{constructor(e,t,n,i){super(),this.varKind=e,this.name=t,this.from=n,this.to=i}render(e){let t=e.es5?Gt.varKinds.var:this.varKind,{name:n,from:i,to:s}=this;return`for(${t} ${n}=${i}; ${n}<${s}; ${n}++)`+super.render(e)}get names(){let e=La(super.names,this.from);return La(e,this.to)}},Na=class extends Yn{constructor(e,t,n,i){super(),this.loop=e,this.varKind=t,this.name=n,this.iterable=i}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=Mi(this.iterable,e,t),this}get names(){return Xn(super.names,this.iterable.names)}},Us=class extends Fr{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)}};Us.kind="func";var Vs=class extends Bs{render(e){return"return "+super.render(e)}};Vs.kind="return";var Xd=class extends Fr{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,i;return super.optimizeNames(e,t),(n=this.catch)===null||n===void 0||n.optimizeNames(e,t),(i=this.finally)===null||i===void 0||i.optimizeNames(e,t),this}get names(){let e=super.names;return this.catch&&Xn(e,this.catch.names),this.finally&&Xn(e,this.finally.names),e}},Hs=class extends Fr{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};Hs.kind="catch";var zs=class extends Fr{render(e){return"finally"+super.render(e)}};zs.kind="finally";var Qd=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?` +`:""},this._extScope=e,this._scope=new Gt.Scope({parent:e}),this._nodes=[new Gd]}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,i){let s=this._scope.toName(t);return n!==void 0&&i&&(this._constants[s.str]=n),this._leafNode(new Ud(e,s,n)),s}const(e,t,n){return this._def(Gt.varKinds.const,e,t,n)}let(e,t,n){return this._def(Gt.varKinds.let,e,t,n)}var(e,t,n){return this._def(Gt.varKinds.var,e,t,n)}assign(e,t,n){return this._leafNode(new Da(e,t,n))}add(e,t){return this._leafNode(new Vd(e,Y.operators.ADD,t))}code(e){return typeof e=="function"?e():e!==re.nil&&this._leafNode(new Wd(e)),this}object(...e){let t=["{"];for(let[n,i]of e)t.length>1&&t.push(","),t.push(n),(n!==i||this.opts.es5)&&(t.push(":"),(0,re.addCodeArg)(t,i));return t.push("}"),new re._Code(t)}if(e,t,n){if(this._blockNode(new Jn(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 Jn(e))}else(){return this._elseNode(new Ci)}endIf(){return this._endBlockNode(Jn,Ci)}_for(e,t){return this._blockNode(e),t&&this.code(t).endFor(),this}for(e,t){return this._for(new Jd(e),t)}forRange(e,t,n,i,s=this.opts.es5?Gt.varKinds.var:Gt.varKinds.let){let o=this._scope.toName(e);return this._for(new Yd(s,o,t,n),()=>i(o))}forOf(e,t,n,i=Gt.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let o=t instanceof re.Name?t:this.var("_arr",t);return this.forRange("_i",0,(0,re._)`${o}.length`,a=>{this.var(s,(0,re._)`${o}[${a}]`),n(s)})}return this._for(new Na("of",i,s,t),()=>n(s))}forIn(e,t,n,i=this.opts.es5?Gt.varKinds.var:Gt.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,re._)`Object.keys(${t})`,n);let s=this._scope.toName(e);return this._for(new Na("in",i,s,t),()=>n(s))}endFor(){return this._endBlockNode(Yn)}label(e){return this._leafNode(new Hd(e))}break(e){return this._leafNode(new zd(e))}return(e){let t=new Vs;if(this._blockNode(t),this.code(e),t.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Vs)}try(e,t,n){if(!t&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let i=new Xd;if(this._blockNode(i),this.code(e),t){let s=this.name("e");this._currNode=i.catch=new Hs(s),t(s)}return n&&(this._currNode=i.finally=new zs,this.code(n)),this._endBlockNode(Hs,zs)}throw(e){return this._leafNode(new Kd(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=re.nil,n,i){return this._blockNode(new Us(e,t,n)),i&&this.code(i).endFunc(),this}endFunc(){return this._endBlockNode(Us)}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 Jn))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}};Y.CodeGen=Qd;function Xn(r,e){for(let t in e)r[t]=(r[t]||0)+(e[t]||0);return r}function La(r,e){return e instanceof re._CodeOrName?Xn(r,e.names):r}function Mi(r,e,t){if(r instanceof re.Name)return n(r);if(!i(r))return r;return new re._Code(r._items.reduce((s,o)=>(o instanceof re.Name&&(o=n(o)),o instanceof re._Code?s.push(...o._items):s.push(o),s),[]));function n(s){let o=t[s.str];return o===void 0||e[s.str]!==1?s:(delete e[s.str],o)}function i(s){return s instanceof re._Code&&s._items.some(o=>o instanceof re.Name&&e[o.str]===1&&t[o.str]!==void 0)}}function wE(r,e){for(let t in e)r[t]=(r[t]||0)-(e[t]||0)}function py(r){return typeof r=="boolean"||typeof r=="number"||r===null?!r:(0,re._)`!${Zd(r)}`}Y.not=py;var _E=hy(Y.operators.AND);function SE(...r){return r.reduce(_E)}Y.and=SE;var $E=hy(Y.operators.OR);function xE(...r){return r.reduce($E)}Y.or=xE;function hy(r){return(e,t)=>e===re.nil?t:t===re.nil?e:(0,re._)`${Zd(e)} ${r} ${Zd(t)}`}function Zd(r){return r instanceof re.Name?r:(0,re._)`(${r})`}});var Q=A(X=>{"use strict";Object.defineProperty(X,"__esModule",{value:!0});X.checkStrictMode=X.getErrorPath=X.Type=X.useFunc=X.setEvaluated=X.evaluatedPropsToName=X.mergeEvaluated=X.eachItem=X.unescapeJsonPointer=X.escapeJsonPointer=X.escapeFragment=X.unescapeFragment=X.schemaRefOrVal=X.schemaHasRulesButRef=X.schemaHasRules=X.checkUnknownRules=X.alwaysValidSchema=X.toHash=void 0;var de=U(),EE=qs();function AE(r){let e={};for(let t of r)e[t]=!0;return e}X.toHash=AE;function kE(r,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(gy(r,e),!by(e,r.self.RULES.all))}X.alwaysValidSchema=kE;function gy(r,e=r.schema){let{opts:t,self:n}=r;if(!t.strictSchema||typeof e=="boolean")return;let i=n.RULES.keywords;for(let s in e)i[s]||_y(r,`unknown keyword: "${s}"`)}X.checkUnknownRules=gy;function by(r,e){if(typeof r=="boolean")return!r;for(let t in r)if(e[t])return!0;return!1}X.schemaHasRules=by;function PE(r,e){if(typeof r=="boolean")return!r;for(let t in r)if(t!=="$ref"&&e.all[t])return!0;return!1}X.schemaHasRulesButRef=PE;function CE({topSchemaRef:r,schemaPath:e},t,n,i){if(!i){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)}`}X.schemaRefOrVal=CE;function ME(r){return vy(decodeURIComponent(r))}X.unescapeFragment=ME;function TE(r){return encodeURIComponent(tu(r))}X.escapeFragment=TE;function tu(r){return typeof r=="number"?`${r}`:r.replace(/~/g,"~0").replace(/\//g,"~1")}X.escapeJsonPointer=tu;function vy(r){return r.replace(/~1/g,"/").replace(/~0/g,"~")}X.unescapeJsonPointer=vy;function RE(r,e){if(Array.isArray(r))for(let t of r)e(t);else e(r)}X.eachItem=RE;function my({mergeNames:r,mergeToName:e,mergeValues:t,resultToName:n}){return(i,s,o,a)=>{let c=o===void 0?s:o instanceof de.Name?(s instanceof de.Name?r(i,s,o):e(i,s,o),o):s instanceof de.Name?(e(i,o,s),s):t(s,o);return a===de.Name&&!(c instanceof de.Name)?n(i,c):c}}X.mergeEvaluated={props:my({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} || {}`),ru(r,t,e))}),mergeValues:(r,e)=>r===!0?!0:{...r,...e},resultToName:wy}),items:my({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 wy(r,e){if(e===!0)return r.var("props",!0);let t=r.var("props",(0,de._)`{}`);return e!==void 0&&ru(r,t,e),t}X.evaluatedPropsToName=wy;function ru(r,e,t){Object.keys(t).forEach(n=>r.assign((0,de._)`${e}${(0,de.getProperty)(n)}`,!0))}X.setEvaluated=ru;var yy={};function IE(r,e){return r.scopeValue("func",{ref:e,code:yy[e.code]||(yy[e.code]=new EE._Code(e.code))})}X.useFunc=IE;var eu;(function(r){r[r.Num=0]="Num",r[r.Str=1]="Str"})(eu||(X.Type=eu={}));function OE(r,e,t){if(r instanceof de.Name){let n=e===eu.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():"/"+tu(r)}X.getErrorPath=OE;function _y(r,e,t=r.opts.strictSchema){if(t){if(e=`strict mode: ${e}`,t===!0)throw new Error(e);r.self.logger.warn(e)}}X.checkStrictMode=_y});var Dt=A(nu=>{"use strict";Object.defineProperty(nu,"__esModule",{value:!0});var Ue=U(),DE={data:new Ue.Name("data"),valCxt:new Ue.Name("valCxt"),instancePath:new Ue.Name("instancePath"),parentData:new Ue.Name("parentData"),parentDataProperty:new Ue.Name("parentDataProperty"),rootData:new Ue.Name("rootData"),dynamicAnchors:new Ue.Name("dynamicAnchors"),vErrors:new Ue.Name("vErrors"),errors:new Ue.Name("errors"),this:new Ue.Name("this"),self:new Ue.Name("self"),scope:new Ue.Name("scope"),json:new Ue.Name("json"),jsonPos:new Ue.Name("jsonPos"),jsonLen:new Ue.Name("jsonLen"),jsonPart:new Ue.Name("jsonPart")};nu.default=DE});var Ks=A(Ve=>{"use strict";Object.defineProperty(Ve,"__esModule",{value:!0});Ve.extendErrors=Ve.resetErrorsCount=Ve.reportExtraError=Ve.reportError=Ve.keyword$DataError=Ve.keywordError=void 0;var ie=U(),ja=Q(),Ze=Dt();Ve.keywordError={message:({keyword:r})=>(0,ie.str)`must pass "${r}" keyword validation`};Ve.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 NE(r,e=Ve.keywordError,t,n){let{it:i}=r,{gen:s,compositeRule:o,allErrors:a}=i,c=xy(r,e,t);n??(o||a)?Sy(s,c):$y(i,(0,ie._)`[${c}]`)}Ve.reportError=NE;function LE(r,e=Ve.keywordError,t){let{it:n}=r,{gen:i,compositeRule:s,allErrors:o}=n,a=xy(r,e,t);Sy(i,a),s||o||$y(n,Ze.default.vErrors)}Ve.reportExtraError=LE;function FE(r,e){r.assign(Ze.default.errors,e),r.if((0,ie._)`${Ze.default.vErrors} !== null`,()=>r.if(e,()=>r.assign((0,ie._)`${Ze.default.vErrors}.length`,e),()=>r.assign(Ze.default.vErrors,null)))}Ve.resetErrorsCount=FE;function jE({gen:r,keyword:e,schemaValue:t,data:n,errsCount:i,it:s}){if(i===void 0)throw new Error("ajv implementation error");let o=r.name("err");r.forRange("i",i,Ze.default.errors,a=>{r.const(o,(0,ie._)`${Ze.default.vErrors}[${a}]`),r.if((0,ie._)`${o}.instancePath === undefined`,()=>r.assign((0,ie._)`${o}.instancePath`,(0,ie.strConcat)(Ze.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`,n))})}Ve.extendErrors=jE;function Sy(r,e){let t=r.const("err",e);r.if((0,ie._)`${Ze.default.vErrors} === null`,()=>r.assign(Ze.default.vErrors,(0,ie._)`[${t}]`),(0,ie._)`${Ze.default.vErrors}.push(${t})`),r.code((0,ie._)`${Ze.default.errors}++`)}function $y(r,e){let{gen:t,validateName:n,schemaEnv:i}=r;i.$async?t.throw((0,ie._)`new ${r.ValidationError}(${e})`):(t.assign((0,ie._)`${n}.errors`,e),t.return(!1))}var Qn={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 xy(r,e,t){let{createErrors:n}=r.it;return n===!1?(0,ie._)`{}`:qE(r,e,t)}function qE(r,e,t={}){let{gen:n,it:i}=r,s=[BE(i,t),UE(r,t)];return VE(r,e,s),n.object(...s)}function BE({errorPath:r},{instancePath:e}){let t=e?(0,ie.str)`${r}${(0,ja.getErrorPath)(e,ja.Type.Str)}`:r;return[Ze.default.instancePath,(0,ie.strConcat)(Ze.default.instancePath,t)]}function UE({keyword:r,it:{errSchemaPath:e}},{schemaPath:t,parentSchema:n}){let i=n?e:(0,ie.str)`${e}/${r}`;return t&&(i=(0,ie.str)`${i}${(0,ja.getErrorPath)(t,ja.Type.Str)}`),[Qn.schemaPath,i]}function VE(r,{params:e,message:t},n){let{keyword:i,data:s,schemaValue:o,it:a}=r,{opts:c,propertyName:l,topSchemaRef:u,schemaPath:d}=a;n.push([Qn.keyword,i],[Qn.params,typeof e=="function"?e(r):e||(0,ie._)`{}`]),c.messages&&n.push([Qn.message,typeof t=="function"?t(r):t]),c.verbose&&n.push([Qn.schema,o],[Qn.parentSchema,(0,ie._)`${u}${d}`],[Ze.default.data,s]),l&&n.push([Qn.propertyName,l])}});var Ay=A(Ti=>{"use strict";Object.defineProperty(Ti,"__esModule",{value:!0});Ti.boolOrEmptySchema=Ti.topBoolOrEmptySchema=void 0;var HE=Ks(),zE=U(),KE=Dt(),WE={message:"boolean schema is false"};function GE(r){let{gen:e,schema:t,validateName:n}=r;t===!1?Ey(r,!1):typeof t=="object"&&t.$async===!0?e.return(KE.default.data):(e.assign((0,zE._)`${n}.errors`,null),e.return(!0))}Ti.topBoolOrEmptySchema=GE;function JE(r,e){let{gen:t,schema:n}=r;n===!1?(t.var(e,!1),Ey(r)):t.var(e,!0)}Ti.boolOrEmptySchema=JE;function Ey(r,e){let{gen:t,data:n}=r,i={gen:t,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:r};(0,HE.reportError)(i,WE,void 0,e)}});var iu=A(Ri=>{"use strict";Object.defineProperty(Ri,"__esModule",{value:!0});Ri.getRules=Ri.isJSONType=void 0;var YE=["string","number","integer","boolean","null","object","array"],XE=new Set(YE);function QE(r){return typeof r=="string"&&XE.has(r)}Ri.isJSONType=QE;function ZE(){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:{}}}Ri.getRules=ZE});var su=A(cn=>{"use strict";Object.defineProperty(cn,"__esModule",{value:!0});cn.shouldUseRule=cn.shouldUseGroup=cn.schemaHasRulesForType=void 0;function eA({schema:r,self:e},t){let n=e.RULES.types[t];return n&&n!==!0&&ky(r,n)}cn.schemaHasRulesForType=eA;function ky(r,e){return e.rules.some(t=>Py(r,t))}cn.shouldUseGroup=ky;function Py(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))}cn.shouldUseRule=Py});var Ws=A(He=>{"use strict";Object.defineProperty(He,"__esModule",{value:!0});He.reportTypeError=He.checkDataTypes=He.checkDataType=He.coerceAndCheckDataType=He.getJSONTypes=He.getSchemaTypes=He.DataType=void 0;var tA=iu(),rA=su(),nA=Ks(),K=U(),Cy=Q(),Ii;(function(r){r[r.Correct=0]="Correct",r[r.Wrong=1]="Wrong"})(Ii||(He.DataType=Ii={}));function iA(r){let e=My(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}He.getSchemaTypes=iA;function My(r){let e=Array.isArray(r)?r:r?[r]:[];if(e.every(tA.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}He.getJSONTypes=My;function sA(r,e){let{gen:t,data:n,opts:i}=r,s=oA(e,i.coerceTypes),o=e.length>0&&!(s.length===0&&e.length===1&&(0,rA.schemaHasRulesForType)(r,e[0]));if(o){let a=au(e,n,i.strictNumbers,Ii.Wrong);t.if(a,()=>{s.length?aA(r,e,s):cu(r)})}return o}He.coerceAndCheckDataType=sA;var Ty=new Set(["string","number","integer","boolean","null"]);function oA(r,e){return e?r.filter(t=>Ty.has(t)||e==="array"&&t==="array"):[]}function aA(r,e,t){let{gen:n,data:i,opts:s}=r,o=n.let("dataType",(0,K._)`typeof ${i}`),a=n.let("coerced",(0,K._)`undefined`);s.coerceTypes==="array"&&n.if((0,K._)`${o} == 'object' && Array.isArray(${i}) && ${i}.length == 1`,()=>n.assign(i,(0,K._)`${i}[0]`).assign(o,(0,K._)`typeof ${i}`).if(au(e,i,s.strictNumbers),()=>n.assign(a,i))),n.if((0,K._)`${a} !== undefined`);for(let l of t)(Ty.has(l)||l==="array"&&s.coerceTypes==="array")&&c(l);n.else(),cu(r),n.endIf(),n.if((0,K._)`${a} !== undefined`,()=>{n.assign(i,a),cA(r,a)});function c(l){switch(l){case"string":n.elseIf((0,K._)`${o} == "number" || ${o} == "boolean"`).assign(a,(0,K._)`"" + ${i}`).elseIf((0,K._)`${i} === null`).assign(a,(0,K._)`""`);return;case"number":n.elseIf((0,K._)`${o} == "boolean" || ${i} === null || (${o} == "string" && ${i} && ${i} == +${i})`).assign(a,(0,K._)`+${i}`);return;case"integer":n.elseIf((0,K._)`${o} === "boolean" || ${i} === null || (${o} === "string" && ${i} && ${i} == +${i} && !(${i} % 1))`).assign(a,(0,K._)`+${i}`);return;case"boolean":n.elseIf((0,K._)`${i} === "false" || ${i} === 0 || ${i} === null`).assign(a,!1).elseIf((0,K._)`${i} === "true" || ${i} === 1`).assign(a,!0);return;case"null":n.elseIf((0,K._)`${i} === "" || ${i} === 0 || ${i} === false`),n.assign(a,null);return;case"array":n.elseIf((0,K._)`${o} === "string" || ${o} === "number" - || ${o} === "boolean" || ${i} === null`).assign(a,(0,K._)`[${i}]`)}}}function aA({gen:r,parentData:e,parentDataProperty:t},n){r.if((0,K._)`${e} !== undefined`,()=>r.assign((0,K._)`${e}[${t}]`,n))}function au(r,e,t,n=Ii.Correct){let i=n===Ii.Correct?K.operators.EQ:K.operators.NEQ,s;switch(r){case"null":return(0,K._)`${e} ${i} null`;case"array":s=(0,K._)`Array.isArray(${e})`;break;case"object":s=(0,K._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=o((0,K._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=o();break;default:return(0,K._)`typeof ${e} ${i} ${r}`}return n===Ii.Correct?s:(0,K.not)(s);function o(a=K.nil){return(0,K.and)((0,K._)`typeof ${e} == "number"`,a,t?(0,K._)`isFinite(${e})`:K.nil)}}He.checkDataType=au;function cu(r,e,t,n){if(r.length===1)return au(r[0],e,t,n);let i,s=(0,Cy.toHash)(r);if(s.array&&s.object){let o=(0,K._)`typeof ${e} != "object"`;i=s.null?o:(0,K._)`!${e} || ${o}`,delete s.null,delete s.array,delete s.object}else i=K.nil;s.number&&delete s.integer;for(let o in s)i=(0,K.and)(i,au(o,e,t,n));return i}He.checkDataTypes=cu;var cA={message:({schema:r})=>`must be ${r}`,params:({schema:r,schemaValue:e})=>typeof r=="string"?(0,K._)`{type: ${r}}`:(0,K._)`{type: ${e}}`};function lu(r){let e=lA(r);(0,rA.reportError)(e,cA)}He.reportTypeError=lu;function lA(r){let{gen:e,data:t,schema:n}=r,i=(0,Cy.schemaRefOrVal)(r,n,"type");return{gen:e,keyword:"type",data:t,schema:n.type,schemaCode:i,schemaValue:i,parentSchema:n,params:{},it:r}}});var Iy=A(qa=>{"use strict";Object.defineProperty(qa,"__esModule",{value:!0});qa.assignDefaults=void 0;var Oi=U(),dA=Q();function uA(r,e){let{properties:t,items:n}=r.schema;if(e==="object"&&t)for(let i in t)Ry(r,i,t[i].default);else e==="array"&&Array.isArray(n)&&n.forEach((i,s)=>Ry(r,s,i.default))}qa.assignDefaults=uA;function Ry(r,e,t){let{gen:n,compositeRule:i,data:s,opts:o}=r;if(t===void 0)return;let a=(0,Oi._)`${s}${(0,Oi.getProperty)(e)}`;if(i){(0,dA.checkStrictMode)(r,`default is ignored for: ${a}`);return}let c=(0,Oi._)`${a} === undefined`;o.useDefaults==="empty"&&(c=(0,Oi._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,Oi._)`${a} = ${(0,Oi.stringify)(t)}`)}});var Nt=A(le=>{"use strict";Object.defineProperty(le,"__esModule",{value:!0});le.validateUnion=le.validateArray=le.usePattern=le.callValidateCode=le.schemaProperties=le.allSchemaProperties=le.noPropertyInData=le.propertyInData=le.isOwnProperty=le.hasPropFunc=le.reportMissingProp=le.checkMissingProp=le.checkReportMissingProp=void 0;var me=U(),du=Q(),ln=Dt(),fA=Q();function pA(r,e){let{gen:t,data:n,it:i}=r;t.if(fu(t,n,e,i.opts.ownProperties),()=>{r.setParams({missingProperty:(0,me._)`${e}`},!0),r.error()})}le.checkReportMissingProp=pA;function hA({gen:r,data:e,it:{opts:t}},n,i){return(0,me.or)(...n.map(s=>(0,me.and)(fu(r,e,s,t.ownProperties),(0,me._)`${i} = ${s}`)))}le.checkMissingProp=hA;function mA(r,e){r.setParams({missingProperty:e},!0),r.error()}le.reportMissingProp=mA;function Oy(r){return r.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,me._)`Object.prototype.hasOwnProperty`})}le.hasPropFunc=Oy;function uu(r,e,t){return(0,me._)`${Oy(r)}.call(${e}, ${t})`}le.isOwnProperty=uu;function yA(r,e,t,n){let i=(0,me._)`${e}${(0,me.getProperty)(t)} !== undefined`;return n?(0,me._)`${i} && ${uu(r,e,t)}`:i}le.propertyInData=yA;function fu(r,e,t,n){let i=(0,me._)`${e}${(0,me.getProperty)(t)} === undefined`;return n?(0,me.or)(i,(0,me.not)(uu(r,e,t))):i}le.noPropertyInData=fu;function Dy(r){return r?Object.keys(r).filter(e=>e!=="__proto__"):[]}le.allSchemaProperties=Dy;function gA(r,e){return Dy(e).filter(t=>!(0,du.alwaysValidSchema)(r,e[t]))}le.schemaProperties=gA;function bA({schemaCode:r,data:e,it:{gen:t,topSchemaRef:n,schemaPath:i,errorPath:s},it:o},a,c,l){let u=l?(0,me._)`${r}, ${e}, ${n}${i}`:e,d=[[ln.default.instancePath,(0,me.strConcat)(ln.default.instancePath,s)],[ln.default.parentData,o.parentData],[ln.default.parentDataProperty,o.parentDataProperty],[ln.default.rootData,ln.default.rootData]];o.opts.dynamicRef&&d.push([ln.default.dynamicAnchors,ln.default.dynamicAnchors]);let f=(0,me._)`${u}, ${t.object(...d)}`;return c!==me.nil?(0,me._)`${a}.call(${c}, ${f})`:(0,me._)`${a}(${f})`}le.callValidateCode=bA;var vA=(0,me._)`new RegExp`;function wA({gen:r,it:{opts:e}},t){let n=e.unicodeRegExp?"u":"",{regExp:i}=e.code,s=i(t,n);return r.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,me._)`${i.code==="new RegExp"?vA:(0,fA.useFunc)(r,i)}(${t}, ${n})`})}le.usePattern=wA;function _A(r){let{gen:e,data:t,keyword:n,it:i}=r,s=e.name("valid");if(i.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,me._)`${t}.length`);e.forRange("i",0,c,l=>{r.subschema({keyword:n,dataProp:l,dataPropType:du.Type.Num},s),e.if((0,me.not)(s),a)})}}le.validateArray=_A;function SA(r){let{gen:e,schema:t,keyword:n,it:i}=r;if(!Array.isArray(t))throw new Error("ajv implementation error");if(t.some(c=>(0,du.alwaysValidSchema)(i,c))&&!i.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,me._)`${o} || ${a}`),r.mergeValidEvaluated(u,a)||e.if((0,me.not)(o))})),r.result(o,()=>r.reset(),()=>r.error(!0))}le.validateUnion=SA});var Fy=A(yr=>{"use strict";Object.defineProperty(yr,"__esModule",{value:!0});yr.validateKeywordUsage=yr.validSchemaType=yr.funcKeywordCode=yr.macroKeywordCode=void 0;var et=U(),Zn=Dt(),$A=Nt(),xA=Ks();function EA(r,e){let{gen:t,keyword:n,schema:i,parentSchema:s,it:o}=r,a=e.macro.call(o.self,i,s,o),c=Ly(t,n,a);o.opts.validateSchema!==!1&&o.self.validateSchema(a,!0);let l=t.name("valid");r.subschema({schema:a,schemaPath:et.nil,errSchemaPath:`${o.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},l),r.pass(l,()=>r.error(!0))}yr.macroKeywordCode=EA;function AA(r,e){var t;let{gen:n,keyword:i,schema:s,parentSchema:o,$data:a,it:c}=r;PA(c,e);let l=!a&&e.compile?e.compile.call(c.self,s,o,c):e.validate,u=Ly(n,i,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)m(),e.modifying&&Ny(r),y(()=>r.error());else{let g=e.async?p():h();e.modifying&&Ny(r),y(()=>kA(r,g))}}function p(){let g=n.let("ruleErrs",null);return n.try(()=>m((0,et._)`await `),b=>n.assign(d,!1).if((0,et._)`${b} instanceof ${c.ValidationError}`,()=>n.assign(g,(0,et._)`${b}.errors`),()=>n.throw(b))),g}function h(){let g=(0,et._)`${u}.errors`;return n.assign(g,null),m(et.nil),g}function m(g=e.async?(0,et._)`await `:et.nil){let b=c.opts.passContext?Zn.default.this:Zn.default.self,v=!("compile"in e&&!a||e.schema===!1);n.assign(d,(0,et._)`${g}${(0,$A.callValidateCode)(r,u,b,v)}`,e.modifying)}function y(g){var b;n.if((0,et.not)((b=e.valid)!==null&&b!==void 0?b:d),g)}}yr.funcKeywordCode=AA;function Ny(r){let{gen:e,data:t,it:n}=r;e.if(n.parentData,()=>e.assign(t,(0,et._)`${n.parentData}[${n.parentDataProperty}]`))}function kA(r,e){let{gen:t}=r;t.if((0,et._)`Array.isArray(${e})`,()=>{t.assign(Zn.default.vErrors,(0,et._)`${Zn.default.vErrors} === null ? ${e} : ${Zn.default.vErrors}.concat(${e})`).assign(Zn.default.errors,(0,et._)`${Zn.default.vErrors}.length`),(0,xA.extendErrors)(r)},()=>r.error())}function PA({schemaEnv:r},e){if(e.async&&!r.$async)throw new Error("async keyword in sync schema")}function Ly(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,et.stringify)(t)})}function CA(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>"u")}yr.validSchemaType=CA;function MA({schema:r,opts:e,self:t,errSchemaPath:n},i,s){if(Array.isArray(i.keyword)?!i.keyword.includes(s):i.keyword!==s)throw new Error("ajv implementation error");let o=i.dependencies;if(o?.some(a=>!Object.prototype.hasOwnProperty.call(r,a)))throw new Error(`parent schema must have dependencies of ${s}: ${o.join(",")}`);if(i.validateSchema&&!i.validateSchema(r[s])){let c=`keyword "${s}" value is invalid at path "${n}": `+t.errorsText(i.validateSchema.errors);if(e.validateSchema==="log")t.logger.error(c);else throw new Error(c)}}yr.validateKeywordUsage=MA});var qy=A(dn=>{"use strict";Object.defineProperty(dn,"__esModule",{value:!0});dn.extendSubschemaMode=dn.extendSubschemaData=dn.getSubschema=void 0;var gr=U(),jy=Q();function TA(r,{keyword:e,schemaProp:t,schema:n,schemaPath:i,errSchemaPath:s,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,gr._)`${r.schemaPath}${(0,gr.getProperty)(e)}`,errSchemaPath:`${r.errSchemaPath}/${e}`}:{schema:a[t],schemaPath:(0,gr._)`${r.schemaPath}${(0,gr.getProperty)(e)}${(0,gr.getProperty)(t)}`,errSchemaPath:`${r.errSchemaPath}/${e}/${(0,jy.escapeFragment)(t)}`}}if(n!==void 0){if(i===void 0||s===void 0||o===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:i,topSchemaRef:o,errSchemaPath:s}}throw new Error('either "keyword" or "schema" must be passed')}dn.getSubschema=TA;function RA(r,e,{dataProp:t,dataPropType:n,data:i,dataTypes:s,propertyName:o}){if(i!==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,gr._)`${e.data}${(0,gr.getProperty)(t)}`,!0);c(f),r.errorPath=(0,gr.str)`${l}${(0,jy.getErrorPath)(t,n,d.jsPropertySyntax)}`,r.parentDataProperty=(0,gr._)`${t}`,r.dataPathArr=[...u,r.parentDataProperty]}if(i!==void 0){let l=i instanceof gr.Name?i:a.let("data",i,!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]}}dn.extendSubschemaData=RA;function IA(r,{jtdDiscriminator:e,jtdMetadata:t,compositeRule:n,createErrors:i,allErrors:s}){n!==void 0&&(r.compositeRule=n),i!==void 0&&(r.createErrors=i),s!==void 0&&(r.allErrors=s),r.jtdDiscriminator=e,r.jtdMetadata=t}dn.extendSubschemaMode=IA});var pu=A((Mj,By)=>{"use strict";By.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,i,s;if(Array.isArray(e)){if(n=e.length,n!=t.length)return!1;for(i=n;i--!==0;)if(!r(e[i],t[i]))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),n=s.length,n!==Object.keys(t).length)return!1;for(i=n;i--!==0;)if(!Object.prototype.hasOwnProperty.call(t,s[i]))return!1;for(i=n;i--!==0;){var o=s[i];if(!r(e[o],t[o]))return!1}return!0}return e!==e&&t!==t}});var Vy=A((Tj,Uy)=>{"use strict";var un=Uy.exports=function(r,e,t){typeof e=="function"&&(t=e,e={}),t=e.cb||t;var n=typeof t=="function"?t:t.pre||function(){},i=t.post||function(){};Ba(e,n,i,r,"",r)};un.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};un.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};un.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};un.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 Ba(r,e,t,n,i,s,o,a,c,l){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,i,s,o,a,c,l);for(var u in n){var d=n[u];if(Array.isArray(d)){if(u in un.arrayKeywords)for(var f=0;f{"use strict";Object.defineProperty(ut,"__esModule",{value:!0});ut.getSchemaRefs=ut.resolveUrl=ut.normalizeId=ut._getFullPath=ut.getFullPath=ut.inlineRef=void 0;var DA=Q(),NA=pu(),LA=Vy(),FA=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function jA(r,e=!0){return typeof r=="boolean"?!0:e===!0?!hu(r):e?Hy(r)<=e:!1}ut.inlineRef=jA;var qA=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function hu(r){for(let e in r){if(qA.has(e))return!0;let t=r[e];if(Array.isArray(t)&&t.some(hu)||typeof t=="object"&&hu(t))return!0}return!1}function Hy(r){let e=0;for(let t in r){if(t==="$ref")return 1/0;if(e++,!FA.has(t)&&(typeof r[t]=="object"&&(0,DA.eachItem)(r[t],n=>e+=Hy(n)),e===1/0))return 1/0}return e}function zy(r,e="",t){t!==!1&&(e=Di(e));let n=r.parse(e);return Ky(r,n)}ut.getFullPath=zy;function Ky(r,e){return r.serialize(e).split("#")[0]+"#"}ut._getFullPath=Ky;var BA=/#\/?$/;function Di(r){return r?r.replace(BA,""):""}ut.normalizeId=Di;function UA(r,e,t){return t=Di(t),r.resolve(e,t)}ut.resolveUrl=UA;var VA=/^[a-z_][-a-z0-9._]*$/i;function HA(r,e){if(typeof r=="boolean")return{};let{schemaId:t,uriResolver:n}=this.opts,i=Di(r[t]||e),s={"":i},o=zy(n,i,!1),a={},c=new Set;return LA(r,{allKeys:!0},(d,f,p,h)=>{if(h===void 0)return;let m=o+f,y=s[h];typeof d[t]=="string"&&(y=g.call(this,d[t])),b.call(this,d.$anchor),b.call(this,d.$dynamicAnchor),s[f]=y;function g(v){let S=this.opts.uriResolver.resolve;if(v=Di(y?S(y,v):v),c.has(v))throw u(v);c.add(v);let _=this.refs[v];return typeof _=="string"&&(_=this.refs[_]),typeof _=="object"?l(d,_.schema,v):v!==Di(m)&&(v[0]==="#"?(l(d,a[v],v),a[v]=d):this.refs[v]=m),v}function b(v){if(typeof v=="string"){if(!VA.test(v))throw new Error(`invalid anchor "${v}"`);g.call(this,`#${v}`)}}}),a;function l(d,f,p){if(f!==void 0&&!NA(d,f))throw u(p)}function u(d){return new Error(`reference "${d}" resolves to more than one schema`)}}ut.getSchemaRefs=HA});var Ni=A(fn=>{"use strict";Object.defineProperty(fn,"__esModule",{value:!0});fn.getData=fn.KeywordCxt=fn.validateFunctionCode=void 0;var Xy=Ay(),Wy=Ws(),yu=ou(),Ua=Ws(),zA=Iy(),Ys=Fy(),mu=qy(),j=U(),B=Dt(),KA=Gs(),jr=Q(),Js=Ks();function WA(r){if(eg(r)&&(tg(r),Zy(r))){YA(r);return}Qy(r,()=>(0,Xy.topBoolOrEmptySchema)(r))}fn.validateFunctionCode=WA;function Qy({gen:r,validateName:e,schema:t,schemaEnv:n,opts:i},s){i.code.es5?r.func(e,(0,j._)`${B.default.data}, ${B.default.valCxt}`,n.$async,()=>{r.code((0,j._)`"use strict"; ${Gy(t,i)}`),JA(r,i),r.code(s)}):r.func(e,(0,j._)`${B.default.data}, ${GA(i)}`,n.$async,()=>r.code(Gy(t,i)).code(s))}function GA(r){return(0,j._)`{${B.default.instancePath}="", ${B.default.parentData}, ${B.default.parentDataProperty}, ${B.default.rootData}=${B.default.data}${r.dynamicRef?(0,j._)`, ${B.default.dynamicAnchors}={}`:j.nil}}={}`}function JA(r,e){r.if(B.default.valCxt,()=>{r.var(B.default.instancePath,(0,j._)`${B.default.valCxt}.${B.default.instancePath}`),r.var(B.default.parentData,(0,j._)`${B.default.valCxt}.${B.default.parentData}`),r.var(B.default.parentDataProperty,(0,j._)`${B.default.valCxt}.${B.default.parentDataProperty}`),r.var(B.default.rootData,(0,j._)`${B.default.valCxt}.${B.default.rootData}`),e.dynamicRef&&r.var(B.default.dynamicAnchors,(0,j._)`${B.default.valCxt}.${B.default.dynamicAnchors}`)},()=>{r.var(B.default.instancePath,(0,j._)`""`),r.var(B.default.parentData,(0,j._)`undefined`),r.var(B.default.parentDataProperty,(0,j._)`undefined`),r.var(B.default.rootData,B.default.data),e.dynamicRef&&r.var(B.default.dynamicAnchors,(0,j._)`{}`)})}function YA(r){let{schema:e,opts:t,gen:n}=r;Qy(r,()=>{t.$comment&&e.$comment&&ng(r),tk(r),n.let(B.default.vErrors,null),n.let(B.default.errors,0),t.unevaluated&&XA(r),rg(r),ik(r)})}function XA(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 Gy(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 QA(r,e){if(eg(r)&&(tg(r),Zy(r))){ZA(r,e);return}(0,Xy.boolOrEmptySchema)(r,e)}function Zy({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 eg(r){return typeof r.schema!="boolean"}function ZA(r,e){let{schema:t,gen:n,opts:i}=r;i.$comment&&t.$comment&&ng(r),rk(r),nk(r);let s=n.const("_errs",B.default.errors);rg(r,s),n.var(e,(0,j._)`${s} === ${B.default.errors}`)}function tg(r){(0,jr.checkUnknownRules)(r),ek(r)}function rg(r,e){if(r.opts.jtd)return Jy(r,[],!1,e);let t=(0,Wy.getSchemaTypes)(r.schema),n=(0,Wy.coerceAndCheckDataType)(r,t);Jy(r,t,!n,e)}function ek(r){let{schema:e,errSchemaPath:t,opts:n,self:i}=r;e.$ref&&n.ignoreKeywordsWithRef&&(0,jr.schemaHasRulesButRef)(e,i.RULES)&&i.logger.warn(`$ref: keywords ignored in schema at path "${t}"`)}function tk(r){let{schema:e,opts:t}=r;e.default!==void 0&&t.useDefaults&&t.strictSchema&&(0,jr.checkStrictMode)(r,"default is ignored in the schema root")}function rk(r){let e=r.schema[r.opts.schemaId];e&&(r.baseId=(0,KA.resolveUrl)(r.opts.uriResolver,r.baseId,e))}function nk(r){if(r.schema.$async&&!r.schemaEnv.$async)throw new Error("async schema in sync schema")}function ng({gen:r,schemaEnv:e,schema:t,errSchemaPath:n,opts:i}){let s=t.$comment;if(i.$comment===!0)r.code((0,j._)`${B.default.self}.logger.log(${s})`);else if(typeof i.$comment=="function"){let o=(0,j.str)`${n}/$comment`,a=r.scopeValue("root",{ref:e.root});r.code((0,j._)`${B.default.self}.opts.$comment(${s}, ${o}, ${a}.schema)`)}}function ik(r){let{gen:e,schemaEnv:t,validateName:n,ValidationError:i,opts:s}=r;t.$async?e.if((0,j._)`${B.default.errors} === 0`,()=>e.return(B.default.data),()=>e.throw((0,j._)`new ${i}(${B.default.vErrors})`)):(e.assign((0,j._)`${n}.errors`,B.default.vErrors),s.unevaluated&&sk(r),e.return((0,j._)`${B.default.errors} === 0`))}function sk({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 Jy(r,e,t,n){let{gen:i,schema:s,data:o,allErrors:a,opts:c,self:l}=r,{RULES:u}=l;if(s.$ref&&(c.ignoreKeywordsWithRef||!(0,jr.schemaHasRulesButRef)(s,u))){i.block(()=>sg(r,"$ref",u.all.$ref.definition));return}c.jtd||ok(r,e),i.block(()=>{for(let f of u.rules)d(f);d(u.post)});function d(f){(0,yu.shouldUseGroup)(s,f)&&(f.type?(i.if((0,Ua.checkDataType)(f.type,o,c.strictNumbers)),Yy(r,f),e.length===1&&e[0]===f.type&&t&&(i.else(),(0,Ua.reportTypeError)(r)),i.endIf()):Yy(r,f),a||i.if((0,j._)`${B.default.errors} === ${n||0}`))}}function Yy(r,e){let{gen:t,schema:n,opts:{useDefaults:i}}=r;i&&(0,zA.assignDefaults)(r,e.type),t.block(()=>{for(let s of e.rules)(0,yu.shouldUseRule)(n,s)&&sg(r,s.keyword,s.definition,e.type)})}function ok(r,e){r.schemaEnv.meta||!r.opts.strictTypes||(ak(r,e),r.opts.allowUnionTypes||ck(r,e),lk(r,r.dataTypes))}function ak(r,e){if(e.length){if(!r.dataTypes.length){r.dataTypes=e;return}e.forEach(t=>{ig(r.dataTypes,t)||gu(r,`type "${t}" not allowed by context "${r.dataTypes.join(",")}"`)}),uk(r,e)}}function ck(r,e){e.length>1&&!(e.length===2&&e.includes("null"))&&gu(r,"use allowUnionTypes to allow union type keyword")}function lk(r,e){let t=r.self.RULES.all;for(let n in t){let i=t[n];if(typeof i=="object"&&(0,yu.shouldUseRule)(r.schema,i)){let{type:s}=i.definition;s.length&&!s.some(o=>dk(e,o))&&gu(r,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function dk(r,e){return r.includes(e)||e==="number"&&r.includes("integer")}function ig(r,e){return r.includes(e)||e==="integer"&&r.includes("number")}function uk(r,e){let t=[];for(let n of r.dataTypes)ig(e,n)?t.push(n):e.includes("integer")&&n==="number"&&t.push("integer");r.dataTypes=t}function gu(r,e){let t=r.schemaEnv.baseId+r.errSchemaPath;e+=` at "${t}" (strictTypes)`,(0,jr.checkStrictMode)(r,e,r.opts.strictTypes)}var Va=class{constructor(e,t,n){if((0,Ys.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,jr.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",og(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,Ys.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",B.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?Js.reportExtraError:Js.reportError)(this,this.def.error,t)}$dataError(){(0,Js.reportError)(this,this.def.$dataError||Js.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,Js.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:i,schemaType:s,def:o}=this;n.if((0,j.or)((0,j._)`${i} === undefined`,t)),e!==j.nil&&n.assign(e,!0),(s.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:i,it:s}=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,Ua.checkDataTypes)(c,t,s.opts.strictNumbers,Ua.DataType.Wrong)}`}return j.nil}function a(){if(i.validateSchema){let c=e.scopeValue("validate$data",{ref:i.validateSchema});return(0,j._)`!${c}(${t})`}return j.nil}}subschema(e,t){let n=(0,mu.getSubschema)(this.it,e);(0,mu.extendSubschemaData)(n,this.it,e),(0,mu.extendSubschemaMode)(n,e);let i={...this.it,...n,items:void 0,props:void 0};return QA(i,t),i}mergeEvaluated(e,t){let{it:n,gen:i}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=jr.mergeEvaluated.props(i,e.props,n.props,t)),n.items!==!0&&e.items!==void 0&&(n.items=jr.mergeEvaluated.items(i,e.items,n.items,t)))}mergeValidEvaluated(e,t){let{it:n,gen:i}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return i.if(t,()=>this.mergeEvaluated(e,j.Name)),!0}};fn.KeywordCxt=Va;function sg(r,e,t,n){let i=new Va(r,t,e);"code"in t?t.code(i,n):i.$data&&t.validate?(0,Ys.funcKeywordCode)(i,t):"macro"in t?(0,Ys.macroKeywordCode)(i,t):(t.compile||t.validate)&&(0,Ys.funcKeywordCode)(i,t)}var fk=/^\/(?:[^~]|~0|~1)*$/,pk=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function og(r,{dataLevel:e,dataNames:t,dataPathArr:n}){let i,s;if(r==="")return B.default.rootData;if(r[0]==="/"){if(!fk.test(r))throw new Error(`Invalid JSON-pointer: ${r}`);i=r,s=B.default.rootData}else{let l=pk.exec(r);if(!l)throw new Error(`Invalid JSON-pointer: ${r}`);let u=+l[1];if(i=l[2],i==="#"){if(u>=e)throw new Error(c("property/index",u));return n[e-u]}if(u>e)throw new Error(c("data",u));if(s=t[e-u],!i)return s}let o=s,a=i.split("/");for(let l of a)l&&(s=(0,j._)`${s}${(0,j.getProperty)((0,jr.unescapeJsonPointer)(l))}`,o=(0,j._)`${o} && ${s}`);return o;function c(l,u){return`Cannot access ${l} ${u} levels up, current level is ${e}`}}fn.getData=og});var Xs=A(vu=>{"use strict";Object.defineProperty(vu,"__esModule",{value:!0});var bu=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};vu.default=bu});var Li=A(Su=>{"use strict";Object.defineProperty(Su,"__esModule",{value:!0});var wu=Gs(),_u=class extends Error{constructor(e,t,n,i){super(i||`can't resolve reference ${n} from id ${t}`),this.missingRef=(0,wu.resolveUrl)(e,t,n),this.missingSchema=(0,wu.normalizeId)((0,wu.getFullPath)(e,this.missingRef))}};Su.default=_u});var Qs=A(Lt=>{"use strict";Object.defineProperty(Lt,"__esModule",{value:!0});Lt.resolveSchema=Lt.getCompilingSchema=Lt.resolveRef=Lt.compileSchema=Lt.SchemaEnv=void 0;var Jt=U(),hk=Xs(),ei=Dt(),Yt=Gs(),ag=Q(),mk=Ni(),Fi=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,Yt.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};Lt.SchemaEnv=Fi;function xu(r){let e=cg.call(this,r);if(e)return e;let t=(0,Yt.getFullPath)(this.opts.uriResolver,r.root.baseId),{es5:n,lines:i}=this.opts.code,{ownProperties:s}=this.opts,o=new Jt.CodeGen(this.scope,{es5:n,lines:i,ownProperties:s}),a;r.$async&&(a=o.scopeValue("Error",{ref:hk.default,code:(0,Jt._)`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:[Jt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:o.scopeValue("schema",this.opts.code.source===!0?{ref:r.schema,code:(0,Jt.stringify)(r.schema)}:{ref:r.schema}),validateName:c,ValidationError:a,schema:r.schema,schemaEnv:r,rootId:t,baseId:r.baseId||t,schemaPath:Jt.nil,errSchemaPath:r.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Jt._)`""`,opts:this.opts,self:this},u;try{this._compilations.add(r),(0,mk.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:h,items:m}=l;p.evaluated={props:h instanceof Jt.Name?void 0:h,items:m instanceof Jt.Name?void 0:m,dynamicProps:h instanceof Jt.Name,dynamicItems:m instanceof Jt.Name},p.source&&(p.source.evaluated=(0,Jt.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)}}Lt.compileSchema=xu;function yk(r,e,t){var n;t=(0,Yt.resolveUrl)(this.opts.uriResolver,e,t);let i=r.refs[t];if(i)return i;let s=vk.call(this,r,t);if(s===void 0){let o=(n=r.localRefs)===null||n===void 0?void 0:n[t],{schemaId:a}=this.opts;o&&(s=new Fi({schema:o,schemaId:a,root:r,baseId:e}))}if(s!==void 0)return r.refs[t]=gk.call(this,s)}Lt.resolveRef=yk;function gk(r){return(0,Yt.inlineRef)(r.schema,this.opts.inlineRefs)?r.schema:r.validate?r:xu.call(this,r)}function cg(r){for(let e of this._compilations)if(bk(e,r))return e}Lt.getCompilingSchema=cg;function bk(r,e){return r.schema===e.schema&&r.root===e.root&&r.baseId===e.baseId}function vk(r,e){let t;for(;typeof(t=this.refs[e])=="string";)e=t;return t||this.schemas[e]||Ha.call(this,r,e)}function Ha(r,e){let t=this.opts.uriResolver.parse(e),n=(0,Yt._getFullPath)(this.opts.uriResolver,t),i=(0,Yt.getFullPath)(this.opts.uriResolver,r.baseId,void 0);if(Object.keys(r.schema).length>0&&n===i)return $u.call(this,t,r);let s=(0,Yt.normalizeId)(n),o=this.refs[s]||this.schemas[s];if(typeof o=="string"){let a=Ha.call(this,r,o);return typeof a?.schema!="object"?void 0:$u.call(this,t,a)}if(typeof o?.schema=="object"){if(o.validate||xu.call(this,o),s===(0,Yt.normalizeId)(e)){let{schema:a}=o,{schemaId:c}=this.opts,l=a[c];return l&&(i=(0,Yt.resolveUrl)(this.opts.uriResolver,i,l)),new Fi({schema:a,schemaId:c,root:r,baseId:i})}return $u.call(this,t,o)}}Lt.resolveSchema=Ha;var wk=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function $u(r,{baseId:e,schema:t,root:n}){var i;if(((i=r.fragment)===null||i===void 0?void 0:i[0])!=="/")return;for(let a of r.fragment.slice(1).split("/")){if(typeof t=="boolean")return;let c=t[(0,ag.unescapeFragment)(a)];if(c===void 0)return;t=c;let l=typeof t=="object"&&t[this.opts.schemaId];!wk.has(a)&&l&&(e=(0,Yt.resolveUrl)(this.opts.uriResolver,e,l))}let s;if(typeof t!="boolean"&&t.$ref&&!(0,ag.schemaHasRulesButRef)(t,this.RULES)){let a=(0,Yt.resolveUrl)(this.opts.uriResolver,e,t.$ref);s=Ha.call(this,n,a)}let{schemaId:o}=this.opts;if(s=s||new Fi({schema:t,schemaId:o,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var lg=A((Lj,_k)=>{_k.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 Mu=A((Fj,yg)=>{"use strict";var Sk=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Au=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),$k=RegExp.prototype.test.bind(/^\d*$/u),ti=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),ku=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),ug=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u),Pu=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u),xk=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u),ft=new Array(256);{let r="0123456789ABCDEF";for(let e=0;e<256;e++)ft[e]="%"+r[e>>4]+r[e&15]}function ze(r){return r<2048?ft[192|r>>6]+ft[128|r&63]:r<65536?ft[224|r>>12]+ft[128|r>>6&63]+ft[128|r&63]:ft[240|r>>18]+ft[128|r>>12&63]+ft[128|r>>6&63]+ft[128|r&63]}function Ek(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 Ak=RegExp.prototype.test.bind(/^[\dA-Fa-f]{1,4}$/),kk=RegExp.prototype.test.bind(/^[vV][\dA-Fa-f]+\.[A-Za-z\d\-._~!$&'()*+,;=:]+$/),Pk=RegExp.prototype.test.bind(/^[A-Za-z\d\-._~]$/),Ck=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function Mk(r){if(r.length===0)return!1;for(let e=0;et&&(t=i,e=n)):(n=-1,i=0);if(t<2)return r.join(":");let s=r.slice(0,e).join(":"),o=r.slice(e+t).join(":");return s+"::"+o}function Tk(r){let e=r.indexOf("::");if(e!==-1&&r.indexOf("::",e+1)!==-1)return;let t=e===-1?r.split(":"):r.slice(0,e).split(":"),n=e===-1?[]:r.slice(e+2).split(":");e!==-1&&(t.length===1&&t[0]===""&&(t.length=0),n.length===1&&n[0]===""&&(n.length=0));let i=t.concat(n),s=0;for(let a=0;a=8)return;let o=i.slice(0,t.length);for(let a=s;a<8;a++)o.push("0");for(let a=t.length;aOk[n])}function pg(r,e=!1){if(r.indexOf("%")===-1)return r;let t="";for(let n=0;n57343)e+=ze(i);else if(i<=56319&&t+1=56320&&s<=57343?(e+=ze(65536+(i-55296<<10)+(s-56320)),t++):e+=ze(65533)}else e+=ze(65533)}}return e}function Fk(r,e=!1){let t="",n=e&&r[0]!=="/";for(let i=0;i57343)t+=ze(o);else if(o<=56319&&i+1=56320&&a<=57343?(t+=ze(65536+(o-55296<<10)+(a-56320)),i++):t+=ze(65533)}else t+=ze(65533)}}return t}function Cu(r,e){let t="";for(let n=0;n57343)t+=ze(s);else if(s<=56319&&n+1=56320&&o<=57343?(t+=ze(65536+(s-55296<<10)+(o-56320)),n++):t+=ze(65533)}else t+=ze(65533)}}return t}function hg(r){return Cu(r,xk)}function jk(r){return Cu(r,Pu)}function qk(r){return Cu(r,Pu)}function mg(r){return r>=48&&r<=57||r>=65&&r<=90||r>=97&&r<=122||r===42||r===43||r===45||r===46||r===47||r===64||r===95}function Bk(r){let e="";for(let t=0;t57343)e+=ze(i);else if(i<=56319&&t+1=56320&&s<=57343?(e+=ze(65536+(i-55296<<10)+(s-56320)),t++):e+=ze(65533)}else e+=ze(65533)}}return e}function Uk(r){let e="";for(let t=0;t{"use strict";var{isUUID:Hk}=Mu(),zk=/^([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-./:;=@]|%[\da-f]{2})+)$/iu,Kk=["http","https","ws","wss","urn","urn:uuid"];function Wk(r){return Kk.indexOf(r)!==-1}function Tu(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 gg(r){return r.host||(r.error=r.error||"HTTP URIs must have a host."),r}function bg(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 Gk(r){return r.secure=Tu(r),r.resourceName=(r.path||"/")+(r.query?"?"+r.query:""),r.path=void 0,r.query=void 0,r}function Jk(r){if((r.port===(Tu(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=r.resourceName.indexOf("?"),t=e===-1?r.resourceName:r.resourceName.slice(0,e);r.path=t&&t!=="/"?t:void 0,r.query=e===-1?void 0:r.resourceName.slice(e+1),r.resourceName=void 0}return r.fragment=void 0,r}function Yk(r,e){if(!r.path)return r.error="URN can not be parsed",r;let t=r.path.match(zk);if(t&&t[0]===r.path){let n=e.scheme||r.scheme||"urn";r.nid=t[1].toLowerCase(),r.nss=t[2];let i=`${n}:${e.nid||r.nid}`,s=Ru(i);r.path=void 0,s&&(r=s.parse(r,e))}else r.error=r.error||"URN can not be parsed.";return r}function Xk(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(),i=`${t}:${e.nid||n}`,s=Ru(i);s&&(r=s.serialize(r,e));let o=r,a=r.nss;return o.path=`${n||e.nid}:${a}`,e.skipEscape=!0,o}function Qk(r,e){let t=r;return t.uuid=t.nss,t.nss=void 0,!e.tolerant&&(!t.uuid||!Hk(t.uuid))&&(t.error=t.error||"UUID is not valid."),t}function Zk(r){let e=r;return e.nss=(r.uuid||"").toLowerCase(),e}var vg={scheme:"http",domainHost:!0,parse:gg,serialize:bg},eP={scheme:"https",domainHost:vg.domainHost,parse:gg,serialize:bg},za={scheme:"ws",domainHost:!0,parse:Gk,serialize:Jk},tP={scheme:"wss",domainHost:za.domainHost,parse:za.parse,serialize:za.serialize},rP={scheme:"urn",parse:Yk,serialize:Xk,skipNormalize:!0},nP={scheme:"urn:uuid",parse:Qk,serialize:Zk,skipNormalize:!0},Ka={http:vg,https:eP,ws:za,wss:tP,urn:rP,"urn:uuid":nP};Object.setPrototypeOf(Ka,null);function Ru(r){return r&&(Ka[r]||Ka[r.toLowerCase()])||void 0}wg.exports={wsIsSecure:Tu,SCHEMES:Ka,isValidSchemeName:Wk,getSchemeHandler:Ru}});var Dg=A((qj,Ja)=>{"use strict";var{normalizeIPv6:Ag,removeDotSegments:eo,recomposeAuthority:iP,normalizePercentEncoding:kg,normalizePathEncoding:sP,serializePathEncoding:Sg,normalizeQueryFragmentEncoding:$g,encodeQuery:oP,encodeFragment:aP,reescapeHostDelimiters:cP,isIPv4:Pg,nonSimpleDomain:lP}=Mu(),{SCHEMES:Cg,getSchemeHandler:Iu}=_g(),Mg=/^[A-Za-z][A-Za-z0-9+.-]*$/u,Tg="URI scheme is malformed.";function xg(r){let e=unescape(String(r));if(!Mg.test(e))throw new TypeError(Tg);return e}function dP(r,e){return typeof r=="string"?r=bP(r,e):typeof r=="object"&&(r=Ga(ri(r,e),e)),r}function uP(r,e,t){let n=t?Object.assign({scheme:"null"},t):{scheme:"null"},{parsed:i,malformedAuthorityOrPort:s,malformedPercentEncoding:o,malformedSchemeSpecific:a,malformedHost:c,malformedScheme:l}=Wa(r,n),{parsed:u,malformedAuthorityOrPort:d,malformedPercentEncoding:f,malformedSchemeSpecific:p,malformedHost:h,malformedScheme:m}=Wa(e,n);if(s||d||o||f||a||p||c||h||l||m)throw new Error(i.error||u.error||"URI is malformed.");let y=Rg(i,u,n,!0),g=Iu(t&&t.scheme||y.scheme),b=y.host,v=b!==void 0&&b!==""&&(Pg(b)||Ag(b).isIPV6);Ig(y,t||{},g,v);let S=b&&b.indexOf("%")!==-1&&!/\P{ASCII}/u.test(b);if(y.error&&!S)throw new Error(y.error);return n.skipEscape=!0,ri(y,n)}function Rg(r,e,t,n){let i={};return n||(r=Ga(ri(r,t),t),e=Ga(ri(e,t),t)),t=t||{},!t.tolerant&&e.scheme?(i.scheme=e.scheme,i.userinfo=e.userinfo,i.host=e.host,i.port=e.port,i.path=eo(e.path||""),i.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(i.userinfo=e.userinfo,i.host=e.host,i.port=e.port,i.path=eo(e.path||""),i.query=e.query):(e.path?(e.path[0]==="/"?i.path=eo(e.path):((r.userinfo!==void 0||r.host!==void 0||r.port!==void 0)&&!r.path?i.path="/"+e.path:r.path?i.path=r.path.slice(0,r.path.lastIndexOf("/")+1)+e.path:i.path=e.path,i.path=eo(i.path)),i.query=e.query):(i.path=r.path,e.query!==void 0?i.query=e.query:i.query=r.query),i.userinfo=r.userinfo,i.host=r.host,i.port=r.port),i.scheme=r.scheme),i.fragment=e.fragment,i}function fP(r,e,t){let n=Eg(r,t),i=Eg(e,t);return n!==void 0&&i!==void 0&&n===i}function ri(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),i=[];t.scheme&&(t.scheme=xg(t.scheme));let s=Iu(n.scheme||t.scheme);s&&s.serialize&&s.serialize(t,n);let o=t.userinfo!==void 0||t.host!==void 0||t.port!==void 0,a=!n.skipEscape&&t.scheme===void 0&&!o;t.path!==void 0&&(n.skipEscape?t.path=kg(t.path):t.path=Sg(t.path,a)),n.reference!=="suffix"&&t.scheme&&(t.scheme=xg(t.scheme),i.push(t.scheme,":"));let c=iP(t);if(c!==void 0&&(n.reference!=="suffix"&&i.push("//"),i.push(c),t.path&&t.path[0]!=="/"&&i.push("/")),t.path!==void 0){let l=t.path;!n.absolutePath&&(!s||!s.absolutePath)&&(l=eo(l)),a&&(l=Sg(l,!0)),c===void 0&&l[0]==="/"&&l[1]==="/"&&(l="/%2F"+l.slice(2)),i.push(l)}return t.query!==void 0&&i.push("?",oP(t.query)),t.fragment!==void 0&&i.push("#",aP(t.fragment)),i.join("")}var pP=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,hP=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,mP=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function yP(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 Zs(r){if(r===void 0)return!1;let e=r.indexOf("%");for(;e!==-1;){if(e+2>=r.length||!/^[\da-f]{2}$/iu.test(r.slice(e+1,e+3)))return!0;e=r.indexOf("%",e+3)}return!1}function Ou(r){return r[0]==="["&&r[r.length-1]==="]"}function gP(r){let e=r[4];return Zs(r[3])||e!==void 0&&!Ou(e)&&Zs(e)||Zs(r[6])||Zs(r[7])||Zs(r[8])}function Ig(r,e,t,n){if(!e.unicodeSupport&&(!t||!t.unicodeSupport)&&r.host&&!Ou(r.host)&&(e.domainHost||t&&t.domainHost)&&n===!1&&lP(r.host))try{r.host=new URL("http://"+r.host).hostname}catch(i){return r.error=r.error||"Host's domain name can not be converted to ASCII: "+i,!0}return!1}function Wa(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},i=!1,s=!1,o=!1,a=!1,c=!1,l=!1,u=!1;t.reference==="suffix"&&(t.scheme?r=t.scheme+":"+r:r="//"+r);let d=r.match(hP);d!==null&&d[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",i=!0);let f=r.match(mP);if(f!==null){let h=f[1],m=h.replace(/[\t\n\r]/g,"");m.length>=2&&(m.slice(0,2)!=="//"?(n.error=n.error||"URI authority must not contain a literal backslash.",i=!0):h.length!==m.length&&(n.error=n.error||"URI authority introducer must not contain whitespace.",i=!0))}let p=r.match(pP);if(p){if(n.scheme=p[1],n.userinfo=p[3],n.host=p[4],n.port=parseInt(p[5],10),n.path=p[6]||"",n.query=p[7],n.fragment=p[8],n.scheme!==void 0){let y=unescape(n.scheme);Mg.test(y)?n.scheme=y.toLowerCase():(n.error=n.error||Tg,l=!0)}s=gP(p),s&&(n.error=n.error||"URI contains malformed percent-encoding."),isNaN(n.port)&&(n.port=p[5]);let h=yP(n,p);if(h!==void 0&&(n.error=n.error||h,i=!0),n.host)if(Pg(n.host)===!1){let g=Ou(n.host),b=n.host.indexOf("[")!==-1||n.host.indexOf("]")!==-1,v=Ag(n.host);u=v.isIPV6||v.isIPVFuture===!0,c=b&&(!g||v.error===!0),n.host=u?v.host:v.host.toLowerCase(),c&&(n.error=n.error||"URI host is malformed.",i=!0)}else u=!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 m=Iu(t.scheme||n.scheme);if(c||(a=Ig(n,t,m,u)),!m||m&&!m.skipNormalize){if(r.indexOf("%")!==-1&&n.host!==void 0&&!c){let y=u?n.host:kg(n.host,!0);n.host=cP(y,u)}n.path&&(n.path=sP(n.path)),n.query&&(n.query=$g(n.query)),n.fragment&&(n.fragment=$g(n.fragment))}m&&m.parse&&(m.parse(n,t),m===Cg.urn&&n.nid===void 0&&(o=!0))}else n.error=n.error||"URI can not be parsed.";return{parsed:n,malformedAuthorityOrPort:i,malformedPercentEncoding:s,malformedSchemeSpecific:o,malformedHost:a,malformedScheme:l}}function Ga(r,e){return Wa(r,e).parsed}function bP(r,e){return Og(r,e).normalized}function Og(r,e){let{parsed:t,malformedAuthorityOrPort:n,malformedPercentEncoding:i,malformedSchemeSpecific:s,malformedHost:o,malformedScheme:a}=Wa(r,e);return{normalized:n||i||s||o||a?r:ri(t,e),malformedAuthorityOrPort:n,malformedPercentEncoding:i,malformedSchemeSpecific:s,malformedHost:o,malformedScheme:a}}function Eg(r,e){if(typeof r!="string"&&typeof r!="object")return;let t;try{t=typeof r=="string"?r:ri(r,e)}catch{return}let{normalized:n,malformedAuthorityOrPort:i,malformedPercentEncoding:s,malformedSchemeSpecific:o,malformedHost:a,malformedScheme:c}=Og(t,e);return i||s||o||a||c?void 0:n}var Du={SCHEMES:Cg,normalize:dP,resolve:uP,resolveComponent:Rg,equal:fP,serialize:ri,parse:Ga};Ja.exports=Du;Ja.exports.default=Du;Ja.exports.fastUri=Du});var Lg=A(Nu=>{"use strict";Object.defineProperty(Nu,"__esModule",{value:!0});var Ng=Dg();Ng.code='require("ajv/dist/runtime/uri").default';Nu.default=Ng});var ju=A(Le=>{"use strict";Object.defineProperty(Le,"__esModule",{value:!0});Le.CodeGen=Le.Name=Le.nil=Le.stringify=Le.str=Le._=Le.KeywordCxt=void 0;var vP=Ni();Object.defineProperty(Le,"KeywordCxt",{enumerable:!0,get:function(){return vP.KeywordCxt}});var ji=U();Object.defineProperty(Le,"_",{enumerable:!0,get:function(){return ji._}});Object.defineProperty(Le,"str",{enumerable:!0,get:function(){return ji.str}});Object.defineProperty(Le,"stringify",{enumerable:!0,get:function(){return ji.stringify}});Object.defineProperty(Le,"nil",{enumerable:!0,get:function(){return ji.nil}});Object.defineProperty(Le,"Name",{enumerable:!0,get:function(){return ji.Name}});Object.defineProperty(Le,"CodeGen",{enumerable:!0,get:function(){return ji.CodeGen}});var wP=Xs(),Ug=Li(),_P=su(),to=Qs(),SP=U(),ro=Gs(),Ya=Ws(),Fu=Q(),Fg=lg(),$P=Lg(),Vg=(r,e)=>new RegExp(r,e);Vg.code="new RegExp";var xP=["removeAdditional","useDefaults","coerceTypes"],EP=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),AP={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."},kP={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},jg=200;function PP(r){var e,t,n,i,s,o,a,c,l,u,d,f,p,h,m,y,g,b,v,S,_,E,k,$,M;let x=r.strict,q=(e=r.code)===null||e===void 0?void 0:e.optimize,T=q===!0||q===void 0?1:q||0,V=(n=(t=r.code)===null||t===void 0?void 0:t.regExp)!==null&&n!==void 0?n:Vg,P=(i=r.uriResolver)!==null&&i!==void 0?i:$P.default;return{strictSchema:(o=(s=r.strictSchema)!==null&&s!==void 0?s:x)!==null&&o!==void 0?o:!0,strictNumbers:(c=(a=r.strictNumbers)!==null&&a!==void 0?a:x)!==null&&c!==void 0?c:!0,strictTypes:(u=(l=r.strictTypes)!==null&&l!==void 0?l:x)!==null&&u!==void 0?u:"log",strictTuples:(f=(d=r.strictTuples)!==null&&d!==void 0?d:x)!==null&&f!==void 0?f:"log",strictRequired:(h=(p=r.strictRequired)!==null&&p!==void 0?p:x)!==null&&h!==void 0?h:!1,code:r.code?{...r.code,optimize:T,regExp:V}:{optimize:T,regExp:V},loopRequired:(m=r.loopRequired)!==null&&m!==void 0?m:jg,loopEnum:(y=r.loopEnum)!==null&&y!==void 0?y:jg,meta:(g=r.meta)!==null&&g!==void 0?g:!0,messages:(b=r.messages)!==null&&b!==void 0?b:!0,inlineRefs:(v=r.inlineRefs)!==null&&v!==void 0?v:!0,schemaId:(S=r.schemaId)!==null&&S!==void 0?S:"$id",addUsedSchema:(_=r.addUsedSchema)!==null&&_!==void 0?_:!0,validateSchema:(E=r.validateSchema)!==null&&E!==void 0?E:!0,validateFormats:(k=r.validateFormats)!==null&&k!==void 0?k:!0,unicodeRegExp:($=r.unicodeRegExp)!==null&&$!==void 0?$:!0,int32range:(M=r.int32range)!==null&&M!==void 0?M:!0,uriResolver:P}}var no=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,...PP(e)};let{es5:t,lines:n}=this.opts.code;this.scope=new SP.ValueScope({scope:{},prefixes:EP,es5:t,lines:n}),this.logger=OP(e.logger);let i=e.validateFormats;e.validateFormats=!1,this.RULES=(0,_P.getRules)(),qg.call(this,AP,e,"NOT SUPPORTED"),qg.call(this,kP,e,"DEPRECATED","warn"),this._metaOpts=RP.call(this),e.formats&&MP.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&TP.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),CP.call(this),e.validateFormats=i}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:t,schemaId:n}=this.opts,i=Fg;n==="id"&&(i={...Fg},i.id=i.$id,delete i.$id),t&&e&&this.addMetaSchema(i,i[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 i=n(t);return"$async"in n||(this.errors=n.errors),i}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 i.call(this,e,t);async function i(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 i.call(this,{$ref:u},!0)}async function o(u){try{return this._compileSchemaEnv(u)}catch(d){if(!(d instanceof Ug.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]=n(u))}finally{delete this._loading[u]}}}addSchema(e,t,n,i=this.opts.validateSchema){if(Array.isArray(e)){for(let o of e)this.addSchema(o,void 0,n,i);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,ro.normalizeId)(t||s),this._checkUnique(t),this.schemas[t]=this._addSchema(e,n,t,i,!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 i=this.validate(n,e);if(!i&&t){let s="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(s);else throw new Error(s)}return i}getSchema(e){let t;for(;typeof(t=Bg.call(this,e))=="string";)e=t;if(t===void 0){let{schemaId:n}=this.opts,i=new to.SchemaEnv({schema:{},schemaId:n});if(t=to.resolveSchema.call(this,i,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=Bg.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,ro.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(NP.call(this,n,t),!t)return(0,Fu.eachItem)(n,s=>Lu.call(this,s)),this;FP.call(this,t);let i={...t,type:(0,Ya.getJSONTypes)(t.type),schemaType:(0,Ya.getJSONTypes)(t.schemaType)};return(0,Fu.eachItem)(n,i.type.length===0?s=>Lu.call(this,s,i):s=>i.type.forEach(o=>Lu.call(this,s,i,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 i=n.rules.findIndex(s=>s.keyword===e);i>=0&&n.rules.splice(i,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(i=>`${n}${i.instancePath} ${i.message}`).reduce((i,s)=>i+t+s)}$dataMetaSchema(e,t){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let i of t){let s=i.split("/").slice(1),o=e;for(let a of s)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]=Hg(u))}}return e}_removeAllSchemas(e,t){for(let n in e){let i=e[n];(!t||t.test(n))&&(typeof i=="string"?delete e[n]:i&&!i.meta&&(this._cache.delete(i.schema),delete e[n]))}}_addSchema(e,t,n,i=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;n=(0,ro.normalizeId)(o||n);let l=ro.getSchemaRefs.call(this,e,n);return c=new to.SchemaEnv({schema:e,schemaId:a,meta:t,baseId:n,localRefs:l}),this._cache.set(c.schema,c),s&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=c),i&&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):to.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{to.compileSchema.call(this,e)}finally{this.opts=t}}};no.ValidationError=wP.default;no.MissingRefError=Ug.default;Le.default=no;function qg(r,e,t,n="error"){for(let i in r){let s=i;s in e&&this.logger[n](`${t}: option ${i}. ${r[s]}`)}}function Bg(r){return r=(0,ro.normalizeId)(r),this.schemas[r]||this.refs[r]}function CP(){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 MP(){for(let r in this.opts.formats){let e=this.opts.formats[r];e&&this.addFormat(r,e)}}function TP(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 RP(){let r={...this.opts};for(let e of xP)delete r[e];return r}var IP={log(){},warn(){},error(){}};function OP(r){if(r===!1)return IP;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 DP=/^[a-z_$][a-z0-9_$:-]*$/i;function NP(r,e){let{RULES:t}=this;if((0,Fu.eachItem)(r,n=>{if(t.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!DP.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 Lu(r,e,t){var n;let i=e?.post;if(t&&i)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:s}=this,o=i?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,Ya.getJSONTypes)(e.type),schemaType:(0,Ya.getJSONTypes)(e.schemaType)}};e.before?LP.call(this,o,a,e.before):o.rules.push(a),s.all[r]=a,(n=e.implements)===null||n===void 0||n.forEach(c=>this.addKeyword(c))}function LP(r,e,t){let n=r.rules.findIndex(i=>i.keyword===t);n>=0?r.rules.splice(n,0,e):(r.rules.push(e),this.logger.warn(`rule ${t} is not defined`))}function FP(r){let{metaSchema:e}=r;e!==void 0&&(r.$data&&this.opts.$data&&(e=Hg(e)),r.validateSchema=this.compile(e,!0))}var jP={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Hg(r){return{anyOf:[r,jP]}}});var zg=A(qu=>{"use strict";Object.defineProperty(qu,"__esModule",{value:!0});var qP={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};qu.default=qP});var Za=A(ni=>{"use strict";Object.defineProperty(ni,"__esModule",{value:!0});ni.callRef=ni.getValidate=void 0;var BP=Li(),Kg=Nt(),pt=U(),qi=Dt(),Wg=Qs(),Xa=Q(),UP={keyword:"$ref",schemaType:"string",code(r){let{gen:e,schema:t,it:n}=r,{baseId:i,schemaEnv:s,validateName:o,opts:a,self:c}=n,{root:l}=s;if((t==="#"||t==="#/")&&i===l.baseId)return d();let u=Wg.resolveRef.call(c,l,i,t);if(u===void 0)throw new BP.default(n.opts.uriResolver,i,t);if(u instanceof Wg.SchemaEnv)return f(u);return p(u);function d(){if(s===l)return Qa(r,o,s,s.$async);let h=e.scopeValue("root",{ref:l});return Qa(r,(0,pt._)`${h}.validate`,l,l.$async)}function f(h){let m=Gg(r,h);Qa(r,m,h,h.$async)}function p(h){let m=e.scopeValue("schema",a.code.source===!0?{ref:h,code:(0,pt.stringify)(h)}:{ref:h}),y=e.name("valid"),g=r.subschema({schema:h,dataTypes:[],schemaPath:pt.nil,topSchemaRef:m,errSchemaPath:t},y);r.mergeEvaluated(g),r.ok(y)}}};function Gg(r,e){let{gen:t}=r;return e.validate?t.scopeValue("validate",{ref:e.validate}):(0,pt._)`${t.scopeValue("wrapper",{ref:e})}.validate`}ni.getValidate=Gg;function Qa(r,e,t,n){let{gen:i,it:s}=r,{allErrors:o,schemaEnv:a,opts:c}=s,l=c.passContext?qi.default.this:pt.nil;n?u():d();function u(){if(!a.$async)throw new Error("async schema referenced by sync schema");let h=i.let("valid");i.try(()=>{i.code((0,pt._)`await ${(0,Kg.callValidateCode)(r,e,l)}`),p(e),o||i.assign(h,!0)},m=>{i.if((0,pt._)`!(${m} instanceof ${s.ValidationError})`,()=>i.throw(m)),f(m),o||i.assign(h,!1)}),r.ok(h)}function d(){r.result((0,Kg.callValidateCode)(r,e,l),()=>p(e),()=>f(e))}function f(h){let m=(0,pt._)`${h}.errors`;i.assign(qi.default.vErrors,(0,pt._)`${qi.default.vErrors} === null ? ${m} : ${qi.default.vErrors}.concat(${m})`),i.assign(qi.default.errors,(0,pt._)`${qi.default.vErrors}.length`)}function p(h){var m;if(!s.opts.unevaluated)return;let y=(m=t?.validate)===null||m===void 0?void 0:m.evaluated;if(s.props!==!0)if(y&&!y.dynamicProps)y.props!==void 0&&(s.props=Xa.mergeEvaluated.props(i,y.props,s.props));else{let g=i.var("props",(0,pt._)`${h}.evaluated.props`);s.props=Xa.mergeEvaluated.props(i,g,s.props,pt.Name)}if(s.items!==!0)if(y&&!y.dynamicItems)y.items!==void 0&&(s.items=Xa.mergeEvaluated.items(i,y.items,s.items));else{let g=i.var("items",(0,pt._)`${h}.evaluated.items`);s.items=Xa.mergeEvaluated.items(i,g,s.items,pt.Name)}}}ni.callRef=Qa;ni.default=UP});var Uu=A(Bu=>{"use strict";Object.defineProperty(Bu,"__esModule",{value:!0});var VP=zg(),HP=Za(),zP=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",VP.default,HP.default];Bu.default=zP});var Jg=A(Vu=>{"use strict";Object.defineProperty(Vu,"__esModule",{value:!0});var ec=U(),pn=ec.operators,tc={maximum:{okStr:"<=",ok:pn.LTE,fail:pn.GT},minimum:{okStr:">=",ok:pn.GTE,fail:pn.LT},exclusiveMaximum:{okStr:"<",ok:pn.LT,fail:pn.GTE},exclusiveMinimum:{okStr:">",ok:pn.GT,fail:pn.LTE}},KP={message:({keyword:r,schemaCode:e})=>(0,ec.str)`must be ${tc[r].okStr} ${e}`,params:({keyword:r,schemaCode:e})=>(0,ec._)`{comparison: ${tc[r].okStr}, limit: ${e}}`},WP={keyword:Object.keys(tc),type:"number",schemaType:"number",$data:!0,error:KP,code(r){let{keyword:e,data:t,schemaCode:n}=r;r.fail$data((0,ec._)`${t} ${tc[e].fail} ${n} || isNaN(${t})`)}};Vu.default=WP});var Yg=A(Hu=>{"use strict";Object.defineProperty(Hu,"__esModule",{value:!0});var io=U(),GP={message:({schemaCode:r})=>(0,io.str)`must be multiple of ${r}`,params:({schemaCode:r})=>(0,io._)`{multipleOf: ${r}}`},JP={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:GP,code(r){let{gen:e,data:t,schemaCode:n,it:i}=r,s=i.opts.multipleOfPrecision,o=e.let("res"),a=s?(0,io._)`Math.abs(Math.round(${o}) - ${o}) > 1e-${s}`:(0,io._)`${o} !== parseInt(${o})`;r.fail$data((0,io._)`(${n} === 0 || (${o} = ${t}/${n}, ${a}))`)}};Hu.default=JP});var Qg=A(zu=>{"use strict";Object.defineProperty(zu,"__esModule",{value:!0});function Xg(r){let e=r.length,t=0,n=0,i;for(;n=55296&&i<=56319&&n{"use strict";Object.defineProperty(Ku,"__esModule",{value:!0});var ii=U(),YP=Q(),XP=Qg(),QP={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}}`},ZP={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:QP,code(r){let{keyword:e,data:t,schemaCode:n,it:i}=r,s=e==="maxLength"?ii.operators.GT:ii.operators.LT,o=i.opts.unicode===!1?(0,ii._)`${t}.length`:(0,ii._)`${(0,YP.useFunc)(r.gen,XP.default)}(${t})`;r.fail$data((0,ii._)`${o} ${s} ${n}`)}};Ku.default=ZP});var eb=A(Wu=>{"use strict";Object.defineProperty(Wu,"__esModule",{value:!0});var eC=Nt(),tC=Q(),Bi=U(),rC={message:({schemaCode:r})=>(0,Bi.str)`must match pattern "${r}"`,params:({schemaCode:r})=>(0,Bi._)`{pattern: ${r}}`},nC={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:rC,code(r){let{gen:e,data:t,$data:n,schema:i,schemaCode:s,it:o}=r,a=o.opts.unicodeRegExp?"u":"";if(n){let{regExp:c}=o.opts.code,l=c.code==="new RegExp"?(0,Bi._)`new RegExp`:(0,tC.useFunc)(e,c),u=e.let("valid");e.try(()=>e.assign(u,(0,Bi._)`${l}(${s}, ${a}).test(${t})`),()=>e.assign(u,!1)),r.fail$data((0,Bi._)`!${u}`)}else{let c=(0,eC.usePattern)(r,i);r.fail$data((0,Bi._)`!${c}.test(${t})`)}}};Wu.default=nC});var tb=A(Gu=>{"use strict";Object.defineProperty(Gu,"__esModule",{value:!0});var so=U(),iC={message({keyword:r,schemaCode:e}){let t=r==="maxProperties"?"more":"fewer";return(0,so.str)`must NOT have ${t} than ${e} properties`},params:({schemaCode:r})=>(0,so._)`{limit: ${r}}`},sC={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:iC,code(r){let{keyword:e,data:t,schemaCode:n}=r,i=e==="maxProperties"?so.operators.GT:so.operators.LT;r.fail$data((0,so._)`Object.keys(${t}).length ${i} ${n}`)}};Gu.default=sC});var rb=A(Ju=>{"use strict";Object.defineProperty(Ju,"__esModule",{value:!0});var oo=Nt(),ao=U(),oC=Q(),aC={message:({params:{missingProperty:r}})=>(0,ao.str)`must have required property '${r}'`,params:({params:{missingProperty:r}})=>(0,ao._)`{missingProperty: ${r}}`},cC={keyword:"required",type:"object",schemaType:"array",$data:!0,error:aC,code(r){let{gen:e,schema:t,schemaCode:n,data:i,$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:h}=r.it;for(let m of t)if(p?.[m]===void 0&&!h.has(m)){let y=o.schemaEnv.baseId+o.errSchemaPath,g=`required property "${m}" is not defined at "${y}" (strictRequired)`;(0,oC.checkStrictMode)(o,g,o.opts.strictRequired)}}function l(){if(c||s)r.block$data(ao.nil,d);else for(let p of t)(0,oo.checkReportMissingProp)(r,p)}function u(){let p=e.let("missing");if(c||s){let h=e.let("valid",!0);r.block$data(h,()=>f(p,h)),r.ok(h)}else e.if((0,oo.checkMissingProp)(r,t,p)),(0,oo.reportMissingProp)(r,p),e.else()}function d(){e.forOf("prop",n,p=>{r.setParams({missingProperty:p}),e.if((0,oo.noPropertyInData)(e,i,p,a.ownProperties),()=>r.error())})}function f(p,h){r.setParams({missingProperty:p}),e.forOf(p,n,()=>{e.assign(h,(0,oo.propertyInData)(e,i,p,a.ownProperties)),e.if((0,ao.not)(h),()=>{r.error(),e.break()})},ao.nil)}}};Ju.default=cC});var nb=A(Yu=>{"use strict";Object.defineProperty(Yu,"__esModule",{value:!0});var co=U(),lC={message({keyword:r,schemaCode:e}){let t=r==="maxItems"?"more":"fewer";return(0,co.str)`must NOT have ${t} than ${e} items`},params:({schemaCode:r})=>(0,co._)`{limit: ${r}}`},dC={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:lC,code(r){let{keyword:e,data:t,schemaCode:n}=r,i=e==="maxItems"?co.operators.GT:co.operators.LT;r.fail$data((0,co._)`${t}.length ${i} ${n}`)}};Yu.default=dC});var rc=A(Xu=>{"use strict";Object.defineProperty(Xu,"__esModule",{value:!0});var ib=pu();ib.code='require("ajv/dist/runtime/equal").default';Xu.default=ib});var sb=A(Zu=>{"use strict";Object.defineProperty(Zu,"__esModule",{value:!0});var Qu=Ws(),Fe=U(),uC=Q(),fC=rc(),pC={message:({params:{i:r,j:e}})=>(0,Fe.str)`must NOT have duplicate items (items ## ${e} and ${r} are identical)`,params:({params:{i:r,j:e}})=>(0,Fe._)`{i: ${r}, j: ${e}}`},hC={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:pC,code(r){let{gen:e,data:t,$data:n,schema:i,parentSchema:s,schemaCode:o,it:a}=r;if(!n&&!i)return;let c=e.let("valid"),l=s.items?(0,Qu.getSchemaTypes)(s.items):[];r.block$data(c,u,(0,Fe._)`${o} === false`),r.ok(c);function u(){let h=e.let("i",(0,Fe._)`${t}.length`),m=e.let("j");r.setParams({i:h,j:m}),e.assign(c,!0),e.if((0,Fe._)`${h} > 1`,()=>(d()?f:p)(h,m))}function d(){return l.length>0&&!l.some(h=>h==="object"||h==="array")}function f(h,m){let y=e.name("item"),g=(0,Qu.checkDataTypes)(l,y,a.opts.strictNumbers,Qu.DataType.Wrong),b=e.const("indices",(0,Fe._)`{}`);e.for((0,Fe._)`;${h}--;`,()=>{e.let(y,(0,Fe._)`${t}[${h}]`),e.if(g,(0,Fe._)`continue`),l.length>1&&e.if((0,Fe._)`typeof ${y} == "string"`,(0,Fe._)`${y} += "_"`),e.if((0,Fe._)`typeof ${b}[${y}] == "number"`,()=>{e.assign(m,(0,Fe._)`${b}[${y}]`),r.error(),e.assign(c,!1).break()}).code((0,Fe._)`${b}[${y}] = ${h}`)})}function p(h,m){let y=(0,uC.useFunc)(e,fC.default),g=e.name("outer");e.label(g).for((0,Fe._)`;${h}--;`,()=>e.for((0,Fe._)`${m} = ${h}; ${m}--;`,()=>e.if((0,Fe._)`${y}(${t}[${h}], ${t}[${m}])`,()=>{r.error(),e.assign(c,!1).break(g)})))}}};Zu.default=hC});var ob=A(tf=>{"use strict";Object.defineProperty(tf,"__esModule",{value:!0});var ef=U(),mC=Q(),yC=rc(),gC={message:"must be equal to constant",params:({schemaCode:r})=>(0,ef._)`{allowedValue: ${r}}`},bC={keyword:"const",$data:!0,error:gC,code(r){let{gen:e,data:t,$data:n,schemaCode:i,schema:s}=r;n||s&&typeof s=="object"?r.fail$data((0,ef._)`!${(0,mC.useFunc)(e,yC.default)}(${t}, ${i})`):r.fail((0,ef._)`${s} !== ${t}`)}};tf.default=bC});var ab=A(rf=>{"use strict";Object.defineProperty(rf,"__esModule",{value:!0});var lo=U(),vC=Q(),wC=rc(),_C={message:"must be equal to one of the allowed values",params:({schemaCode:r})=>(0,lo._)`{allowedValues: ${r}}`},SC={keyword:"enum",schemaType:"array",$data:!0,error:_C,code(r){let{gen:e,data:t,$data:n,schema:i,schemaCode:s,it:o}=r;if(!n&&i.length===0)throw new Error("enum must have non-empty array");let a=i.length>=o.opts.loopEnum,c,l=()=>c??(c=(0,vC.useFunc)(e,wC.default)),u;if(a||n)u=e.let("valid"),r.block$data(u,d);else{if(!Array.isArray(i))throw new Error("ajv implementation error");let p=e.const("vSchema",s);u=(0,lo.or)(...i.map((h,m)=>f(p,m)))}r.pass(u);function d(){e.assign(u,!1),e.forOf("v",s,p=>e.if((0,lo._)`${l()}(${t}, ${p})`,()=>e.assign(u,!0).break()))}function f(p,h){let m=i[h];return typeof m=="object"&&m!==null?(0,lo._)`${l()}(${t}, ${p}[${h}])`:(0,lo._)`${t} === ${m}`}}};rf.default=SC});var sf=A(nf=>{"use strict";Object.defineProperty(nf,"__esModule",{value:!0});var $C=Jg(),xC=Yg(),EC=Zg(),AC=eb(),kC=tb(),PC=rb(),CC=nb(),MC=sb(),TC=ob(),RC=ab(),IC=[$C.default,xC.default,EC.default,AC.default,kC.default,PC.default,CC.default,MC.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},TC.default,RC.default];nf.default=IC});var af=A(uo=>{"use strict";Object.defineProperty(uo,"__esModule",{value:!0});uo.validateAdditionalItems=void 0;var si=U(),of=Q(),OC={message:({params:{len:r}})=>(0,si.str)`must NOT have more than ${r} items`,params:({params:{len:r}})=>(0,si._)`{limit: ${r}}`},DC={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:OC,code(r){let{parentSchema:e,it:t}=r,{items:n}=e;if(!Array.isArray(n)){(0,of.checkStrictMode)(t,'"additionalItems" is ignored when "items" is not an array of schemas');return}cb(r,n)}};function cb(r,e){let{gen:t,schema:n,data:i,keyword:s,it:o}=r;o.items=!0;let a=t.const("len",(0,si._)`${i}.length`);if(n===!1)r.setParams({len:e.length}),r.pass((0,si._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,of.alwaysValidSchema)(o,n)){let l=t.var("valid",(0,si._)`${a} <= ${e.length}`);t.if((0,si.not)(l),()=>c(l)),r.ok(l)}function c(l){t.forRange("i",e.length,a,u=>{r.subschema({keyword:s,dataProp:u,dataPropType:of.Type.Num},l),o.allErrors||t.if((0,si.not)(l),()=>t.break())})}}uo.validateAdditionalItems=cb;uo.default=DC});var cf=A(fo=>{"use strict";Object.defineProperty(fo,"__esModule",{value:!0});fo.validateTuple=void 0;var lb=U(),nc=Q(),NC=Nt(),LC={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(r){let{schema:e,it:t}=r;if(Array.isArray(e))return db(r,"additionalItems",e);t.items=!0,!(0,nc.alwaysValidSchema)(t,e)&&r.ok((0,NC.validateArray)(r))}};function db(r,e,t=r.schema){let{gen:n,parentSchema:i,data:s,keyword:o,it:a}=r;u(i),a.opts.unevaluated&&t.length&&a.items!==!0&&(a.items=nc.mergeEvaluated.items(n,t.length,a.items));let c=n.name("valid"),l=n.const("len",(0,lb._)`${s}.length`);t.forEach((d,f)=>{(0,nc.alwaysValidSchema)(a,d)||(n.if((0,lb._)`${l} > ${f}`,()=>r.subschema({keyword:o,schemaProp:f,dataProp:f},c)),r.ok(c))});function u(d){let{opts:f,errSchemaPath:p}=a,h=t.length,m=h===d.minItems&&(h===d.maxItems||d[e]===!1);if(f.strictTuples&&!m){let y=`"${o}" is ${h}-tuple, but minItems or maxItems/${e} are not specified or different at path "${p}"`;(0,nc.checkStrictMode)(a,y,f.strictTuples)}}}fo.validateTuple=db;fo.default=LC});var ub=A(lf=>{"use strict";Object.defineProperty(lf,"__esModule",{value:!0});var FC=cf(),jC={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:r=>(0,FC.validateTuple)(r,"items")};lf.default=jC});var pb=A(df=>{"use strict";Object.defineProperty(df,"__esModule",{value:!0});var fb=U(),qC=Q(),BC=Nt(),UC=af(),VC={message:({params:{len:r}})=>(0,fb.str)`must NOT have more than ${r} items`,params:({params:{len:r}})=>(0,fb._)`{limit: ${r}}`},HC={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:VC,code(r){let{schema:e,parentSchema:t,it:n}=r,{prefixItems:i}=t;n.items=!0,!(0,qC.alwaysValidSchema)(n,e)&&(i?(0,UC.validateAdditionalItems)(r,i):r.ok((0,BC.validateArray)(r)))}};df.default=HC});var hb=A(uf=>{"use strict";Object.defineProperty(uf,"__esModule",{value:!0});var Ft=U(),ic=Q(),zC={message:({params:{min:r,max:e}})=>e===void 0?(0,Ft.str)`must contain at least ${r} valid item(s)`:(0,Ft.str)`must contain at least ${r} and no more than ${e} valid item(s)`,params:({params:{min:r,max:e}})=>e===void 0?(0,Ft._)`{minContains: ${r}}`:(0,Ft._)`{minContains: ${r}, maxContains: ${e}}`},KC={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:zC,code(r){let{gen:e,schema:t,parentSchema:n,data:i,it:s}=r,o,a,{minContains:c,maxContains:l}=n;s.opts.next?(o=c===void 0?1:c,a=l):o=1;let u=e.const("len",(0,Ft._)`${i}.length`);if(r.setParams({min:o,max:a}),a===void 0&&o===0){(0,ic.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&o>a){(0,ic.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),r.fail();return}if((0,ic.alwaysValidSchema)(s,t)){let m=(0,Ft._)`${u} >= ${o}`;a!==void 0&&(m=(0,Ft._)`${m} && ${u} <= ${a}`),r.pass(m);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,Ft._)`${i}.length > 0`,f)):(e.let(d,!1),f()),r.result(d,()=>r.reset());function f(){let m=e.name("_valid"),y=e.let("count",0);p(m,()=>e.if(m,()=>h(y)))}function p(m,y){e.forRange("i",0,u,g=>{r.subschema({keyword:"contains",dataProp:g,dataPropType:ic.Type.Num,compositeRule:!0},m),y()})}function h(m){e.code((0,Ft._)`${m}++`),a===void 0?e.if((0,Ft._)`${m} >= ${o}`,()=>e.assign(d,!0).break()):(e.if((0,Ft._)`${m} > ${a}`,()=>e.assign(d,!1).break()),o===1?e.assign(d,!0):e.if((0,Ft._)`${m} >= ${o}`,()=>e.assign(d,!0)))}}};uf.default=KC});var sc=A(br=>{"use strict";Object.defineProperty(br,"__esModule",{value:!0});br.validateSchemaDeps=br.validatePropertyDeps=br.error=void 0;var ff=U(),WC=Q(),po=Nt();br.error={message:({params:{property:r,depsCount:e,deps:t}})=>{let n=e===1?"property":"properties";return(0,ff.str)`must have ${n} ${t} when property ${r} is present`},params:({params:{property:r,depsCount:e,deps:t,missingProperty:n}})=>(0,ff._)`{property: ${r}, + || ${o} === "boolean" || ${i} === null`).assign(a,(0,K._)`[${i}]`)}}}function cA({gen:r,parentData:e,parentDataProperty:t},n){r.if((0,K._)`${e} !== undefined`,()=>r.assign((0,K._)`${e}[${t}]`,n))}function ou(r,e,t,n=Ii.Correct){let i=n===Ii.Correct?K.operators.EQ:K.operators.NEQ,s;switch(r){case"null":return(0,K._)`${e} ${i} null`;case"array":s=(0,K._)`Array.isArray(${e})`;break;case"object":s=(0,K._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=o((0,K._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=o();break;default:return(0,K._)`typeof ${e} ${i} ${r}`}return n===Ii.Correct?s:(0,K.not)(s);function o(a=K.nil){return(0,K.and)((0,K._)`typeof ${e} == "number"`,a,t?(0,K._)`isFinite(${e})`:K.nil)}}He.checkDataType=ou;function au(r,e,t,n){if(r.length===1)return ou(r[0],e,t,n);let i,s=(0,Cy.toHash)(r);if(s.array&&s.object){let o=(0,K._)`typeof ${e} != "object"`;i=s.null?o:(0,K._)`!${e} || ${o}`,delete s.null,delete s.array,delete s.object}else i=K.nil;s.number&&delete s.integer;for(let o in s)i=(0,K.and)(i,ou(o,e,t,n));return i}He.checkDataTypes=au;var lA={message:({schema:r})=>`must be ${r}`,params:({schema:r,schemaValue:e})=>typeof r=="string"?(0,K._)`{type: ${r}}`:(0,K._)`{type: ${e}}`};function cu(r){let e=dA(r);(0,nA.reportError)(e,lA)}He.reportTypeError=cu;function dA(r){let{gen:e,data:t,schema:n}=r,i=(0,Cy.schemaRefOrVal)(r,n,"type");return{gen:e,keyword:"type",data:t,schema:n.type,schemaCode:i,schemaValue:i,parentSchema:n,params:{},it:r}}});var Iy=A(qa=>{"use strict";Object.defineProperty(qa,"__esModule",{value:!0});qa.assignDefaults=void 0;var Oi=U(),uA=Q();function fA(r,e){let{properties:t,items:n}=r.schema;if(e==="object"&&t)for(let i in t)Ry(r,i,t[i].default);else e==="array"&&Array.isArray(n)&&n.forEach((i,s)=>Ry(r,s,i.default))}qa.assignDefaults=fA;function Ry(r,e,t){let{gen:n,compositeRule:i,data:s,opts:o}=r;if(t===void 0)return;let a=(0,Oi._)`${s}${(0,Oi.getProperty)(e)}`;if(i){(0,uA.checkStrictMode)(r,`default is ignored for: ${a}`);return}let c=(0,Oi._)`${a} === undefined`;o.useDefaults==="empty"&&(c=(0,Oi._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,Oi._)`${a} = ${(0,Oi.stringify)(t)}`)}});var Nt=A(le=>{"use strict";Object.defineProperty(le,"__esModule",{value:!0});le.validateUnion=le.validateArray=le.usePattern=le.callValidateCode=le.schemaProperties=le.allSchemaProperties=le.noPropertyInData=le.propertyInData=le.isOwnProperty=le.hasPropFunc=le.reportMissingProp=le.checkMissingProp=le.checkReportMissingProp=void 0;var me=U(),lu=Q(),ln=Dt(),pA=Q();function hA(r,e){let{gen:t,data:n,it:i}=r;t.if(uu(t,n,e,i.opts.ownProperties),()=>{r.setParams({missingProperty:(0,me._)`${e}`},!0),r.error()})}le.checkReportMissingProp=hA;function mA({gen:r,data:e,it:{opts:t}},n,i){return(0,me.or)(...n.map(s=>(0,me.and)(uu(r,e,s,t.ownProperties),(0,me._)`${i} = ${s}`)))}le.checkMissingProp=mA;function yA(r,e){r.setParams({missingProperty:e},!0),r.error()}le.reportMissingProp=yA;function Oy(r){return r.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,me._)`Object.prototype.hasOwnProperty`})}le.hasPropFunc=Oy;function du(r,e,t){return(0,me._)`${Oy(r)}.call(${e}, ${t})`}le.isOwnProperty=du;function gA(r,e,t,n){let i=(0,me._)`${e}${(0,me.getProperty)(t)} !== undefined`;return n?(0,me._)`${i} && ${du(r,e,t)}`:i}le.propertyInData=gA;function uu(r,e,t,n){let i=(0,me._)`${e}${(0,me.getProperty)(t)} === undefined`;return n?(0,me.or)(i,(0,me.not)(du(r,e,t))):i}le.noPropertyInData=uu;function Dy(r){return r?Object.keys(r).filter(e=>e!=="__proto__"):[]}le.allSchemaProperties=Dy;function bA(r,e){return Dy(e).filter(t=>!(0,lu.alwaysValidSchema)(r,e[t]))}le.schemaProperties=bA;function vA({schemaCode:r,data:e,it:{gen:t,topSchemaRef:n,schemaPath:i,errorPath:s},it:o},a,c,l){let u=l?(0,me._)`${r}, ${e}, ${n}${i}`:e,d=[[ln.default.instancePath,(0,me.strConcat)(ln.default.instancePath,s)],[ln.default.parentData,o.parentData],[ln.default.parentDataProperty,o.parentDataProperty],[ln.default.rootData,ln.default.rootData]];o.opts.dynamicRef&&d.push([ln.default.dynamicAnchors,ln.default.dynamicAnchors]);let f=(0,me._)`${u}, ${t.object(...d)}`;return c!==me.nil?(0,me._)`${a}.call(${c}, ${f})`:(0,me._)`${a}(${f})`}le.callValidateCode=vA;var wA=(0,me._)`new RegExp`;function _A({gen:r,it:{opts:e}},t){let n=e.unicodeRegExp?"u":"",{regExp:i}=e.code,s=i(t,n);return r.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,me._)`${i.code==="new RegExp"?wA:(0,pA.useFunc)(r,i)}(${t}, ${n})`})}le.usePattern=_A;function SA(r){let{gen:e,data:t,keyword:n,it:i}=r,s=e.name("valid");if(i.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,me._)`${t}.length`);e.forRange("i",0,c,l=>{r.subschema({keyword:n,dataProp:l,dataPropType:lu.Type.Num},s),e.if((0,me.not)(s),a)})}}le.validateArray=SA;function $A(r){let{gen:e,schema:t,keyword:n,it:i}=r;if(!Array.isArray(t))throw new Error("ajv implementation error");if(t.some(c=>(0,lu.alwaysValidSchema)(i,c))&&!i.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,me._)`${o} || ${a}`),r.mergeValidEvaluated(u,a)||e.if((0,me.not)(o))})),r.result(o,()=>r.reset(),()=>r.error(!0))}le.validateUnion=$A});var Fy=A(yr=>{"use strict";Object.defineProperty(yr,"__esModule",{value:!0});yr.validateKeywordUsage=yr.validSchemaType=yr.funcKeywordCode=yr.macroKeywordCode=void 0;var et=U(),Zn=Dt(),xA=Nt(),EA=Ks();function AA(r,e){let{gen:t,keyword:n,schema:i,parentSchema:s,it:o}=r,a=e.macro.call(o.self,i,s,o),c=Ly(t,n,a);o.opts.validateSchema!==!1&&o.self.validateSchema(a,!0);let l=t.name("valid");r.subschema({schema:a,schemaPath:et.nil,errSchemaPath:`${o.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},l),r.pass(l,()=>r.error(!0))}yr.macroKeywordCode=AA;function kA(r,e){var t;let{gen:n,keyword:i,schema:s,parentSchema:o,$data:a,it:c}=r;CA(c,e);let l=!a&&e.compile?e.compile.call(c.self,s,o,c):e.validate,u=Ly(n,i,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&&Ny(r),y(()=>r.error());else{let g=e.async?p():m();e.modifying&&Ny(r),y(()=>PA(r,g))}}function p(){let g=n.let("ruleErrs",null);return n.try(()=>h((0,et._)`await `),b=>n.assign(d,!1).if((0,et._)`${b} instanceof ${c.ValidationError}`,()=>n.assign(g,(0,et._)`${b}.errors`),()=>n.throw(b))),g}function m(){let g=(0,et._)`${u}.errors`;return n.assign(g,null),h(et.nil),g}function h(g=e.async?(0,et._)`await `:et.nil){let b=c.opts.passContext?Zn.default.this:Zn.default.self,v=!("compile"in e&&!a||e.schema===!1);n.assign(d,(0,et._)`${g}${(0,xA.callValidateCode)(r,u,b,v)}`,e.modifying)}function y(g){var b;n.if((0,et.not)((b=e.valid)!==null&&b!==void 0?b:d),g)}}yr.funcKeywordCode=kA;function Ny(r){let{gen:e,data:t,it:n}=r;e.if(n.parentData,()=>e.assign(t,(0,et._)`${n.parentData}[${n.parentDataProperty}]`))}function PA(r,e){let{gen:t}=r;t.if((0,et._)`Array.isArray(${e})`,()=>{t.assign(Zn.default.vErrors,(0,et._)`${Zn.default.vErrors} === null ? ${e} : ${Zn.default.vErrors}.concat(${e})`).assign(Zn.default.errors,(0,et._)`${Zn.default.vErrors}.length`),(0,EA.extendErrors)(r)},()=>r.error())}function CA({schemaEnv:r},e){if(e.async&&!r.$async)throw new Error("async keyword in sync schema")}function Ly(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,et.stringify)(t)})}function MA(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>"u")}yr.validSchemaType=MA;function TA({schema:r,opts:e,self:t,errSchemaPath:n},i,s){if(Array.isArray(i.keyword)?!i.keyword.includes(s):i.keyword!==s)throw new Error("ajv implementation error");let o=i.dependencies;if(o?.some(a=>!Object.prototype.hasOwnProperty.call(r,a)))throw new Error(`parent schema must have dependencies of ${s}: ${o.join(",")}`);if(i.validateSchema&&!i.validateSchema(r[s])){let c=`keyword "${s}" value is invalid at path "${n}": `+t.errorsText(i.validateSchema.errors);if(e.validateSchema==="log")t.logger.error(c);else throw new Error(c)}}yr.validateKeywordUsage=TA});var qy=A(dn=>{"use strict";Object.defineProperty(dn,"__esModule",{value:!0});dn.extendSubschemaMode=dn.extendSubschemaData=dn.getSubschema=void 0;var gr=U(),jy=Q();function RA(r,{keyword:e,schemaProp:t,schema:n,schemaPath:i,errSchemaPath:s,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,gr._)`${r.schemaPath}${(0,gr.getProperty)(e)}`,errSchemaPath:`${r.errSchemaPath}/${e}`}:{schema:a[t],schemaPath:(0,gr._)`${r.schemaPath}${(0,gr.getProperty)(e)}${(0,gr.getProperty)(t)}`,errSchemaPath:`${r.errSchemaPath}/${e}/${(0,jy.escapeFragment)(t)}`}}if(n!==void 0){if(i===void 0||s===void 0||o===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:i,topSchemaRef:o,errSchemaPath:s}}throw new Error('either "keyword" or "schema" must be passed')}dn.getSubschema=RA;function IA(r,e,{dataProp:t,dataPropType:n,data:i,dataTypes:s,propertyName:o}){if(i!==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,gr._)`${e.data}${(0,gr.getProperty)(t)}`,!0);c(f),r.errorPath=(0,gr.str)`${l}${(0,jy.getErrorPath)(t,n,d.jsPropertySyntax)}`,r.parentDataProperty=(0,gr._)`${t}`,r.dataPathArr=[...u,r.parentDataProperty]}if(i!==void 0){let l=i instanceof gr.Name?i:a.let("data",i,!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]}}dn.extendSubschemaData=IA;function OA(r,{jtdDiscriminator:e,jtdMetadata:t,compositeRule:n,createErrors:i,allErrors:s}){n!==void 0&&(r.compositeRule=n),i!==void 0&&(r.createErrors=i),s!==void 0&&(r.allErrors=s),r.jtdDiscriminator=e,r.jtdMetadata=t}dn.extendSubschemaMode=OA});var fu=A((Mj,By)=>{"use strict";By.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,i,s;if(Array.isArray(e)){if(n=e.length,n!=t.length)return!1;for(i=n;i--!==0;)if(!r(e[i],t[i]))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),n=s.length,n!==Object.keys(t).length)return!1;for(i=n;i--!==0;)if(!Object.prototype.hasOwnProperty.call(t,s[i]))return!1;for(i=n;i--!==0;){var o=s[i];if(!r(e[o],t[o]))return!1}return!0}return e!==e&&t!==t}});var Vy=A((Tj,Uy)=>{"use strict";var un=Uy.exports=function(r,e,t){typeof e=="function"&&(t=e,e={}),t=e.cb||t;var n=typeof t=="function"?t:t.pre||function(){},i=t.post||function(){};Ba(e,n,i,r,"",r)};un.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};un.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};un.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};un.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 Ba(r,e,t,n,i,s,o,a,c,l){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,i,s,o,a,c,l);for(var u in n){var d=n[u];if(Array.isArray(d)){if(u in un.arrayKeywords)for(var f=0;f{"use strict";Object.defineProperty(ut,"__esModule",{value:!0});ut.getSchemaRefs=ut.resolveUrl=ut.normalizeId=ut._getFullPath=ut.getFullPath=ut.inlineRef=void 0;var NA=Q(),LA=fu(),FA=Vy(),jA=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function qA(r,e=!0){return typeof r=="boolean"?!0:e===!0?!pu(r):e?Hy(r)<=e:!1}ut.inlineRef=qA;var BA=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function pu(r){for(let e in r){if(BA.has(e))return!0;let t=r[e];if(Array.isArray(t)&&t.some(pu)||typeof t=="object"&&pu(t))return!0}return!1}function Hy(r){let e=0;for(let t in r){if(t==="$ref")return 1/0;if(e++,!jA.has(t)&&(typeof r[t]=="object"&&(0,NA.eachItem)(r[t],n=>e+=Hy(n)),e===1/0))return 1/0}return e}function zy(r,e="",t){t!==!1&&(e=Di(e));let n=r.parse(e);return Ky(r,n)}ut.getFullPath=zy;function Ky(r,e){return r.serialize(e).split("#")[0]+"#"}ut._getFullPath=Ky;var UA=/#\/?$/;function Di(r){return r?r.replace(UA,""):""}ut.normalizeId=Di;function VA(r,e,t){return t=Di(t),r.resolve(e,t)}ut.resolveUrl=VA;var HA=/^[a-z_][-a-z0-9._]*$/i;function zA(r,e){if(typeof r=="boolean")return{};let{schemaId:t,uriResolver:n}=this.opts,i=Di(r[t]||e),s={"":i},o=zy(n,i,!1),a={},c=new Set;return FA(r,{allKeys:!0},(d,f,p,m)=>{if(m===void 0)return;let h=o+f,y=s[m];typeof d[t]=="string"&&(y=g.call(this,d[t])),b.call(this,d.$anchor),b.call(this,d.$dynamicAnchor),s[f]=y;function g(v){let S=this.opts.uriResolver.resolve;if(v=Di(y?S(y,v):v),c.has(v))throw u(v);c.add(v);let _=this.refs[v];return typeof _=="string"&&(_=this.refs[_]),typeof _=="object"?l(d,_.schema,v):v!==Di(h)&&(v[0]==="#"?(l(d,a[v],v),a[v]=d):this.refs[v]=h),v}function b(v){if(typeof v=="string"){if(!HA.test(v))throw new Error(`invalid anchor "${v}"`);g.call(this,`#${v}`)}}}),a;function l(d,f,p){if(f!==void 0&&!LA(d,f))throw u(p)}function u(d){return new Error(`reference "${d}" resolves to more than one schema`)}}ut.getSchemaRefs=zA});var Ni=A(fn=>{"use strict";Object.defineProperty(fn,"__esModule",{value:!0});fn.getData=fn.KeywordCxt=fn.validateFunctionCode=void 0;var Xy=Ay(),Wy=Ws(),mu=su(),Ua=Ws(),KA=Iy(),Ys=Fy(),hu=qy(),j=U(),B=Dt(),WA=Gs(),jr=Q(),Js=Ks();function GA(r){if(eg(r)&&(tg(r),Zy(r))){XA(r);return}Qy(r,()=>(0,Xy.topBoolOrEmptySchema)(r))}fn.validateFunctionCode=GA;function Qy({gen:r,validateName:e,schema:t,schemaEnv:n,opts:i},s){i.code.es5?r.func(e,(0,j._)`${B.default.data}, ${B.default.valCxt}`,n.$async,()=>{r.code((0,j._)`"use strict"; ${Gy(t,i)}`),YA(r,i),r.code(s)}):r.func(e,(0,j._)`${B.default.data}, ${JA(i)}`,n.$async,()=>r.code(Gy(t,i)).code(s))}function JA(r){return(0,j._)`{${B.default.instancePath}="", ${B.default.parentData}, ${B.default.parentDataProperty}, ${B.default.rootData}=${B.default.data}${r.dynamicRef?(0,j._)`, ${B.default.dynamicAnchors}={}`:j.nil}}={}`}function YA(r,e){r.if(B.default.valCxt,()=>{r.var(B.default.instancePath,(0,j._)`${B.default.valCxt}.${B.default.instancePath}`),r.var(B.default.parentData,(0,j._)`${B.default.valCxt}.${B.default.parentData}`),r.var(B.default.parentDataProperty,(0,j._)`${B.default.valCxt}.${B.default.parentDataProperty}`),r.var(B.default.rootData,(0,j._)`${B.default.valCxt}.${B.default.rootData}`),e.dynamicRef&&r.var(B.default.dynamicAnchors,(0,j._)`${B.default.valCxt}.${B.default.dynamicAnchors}`)},()=>{r.var(B.default.instancePath,(0,j._)`""`),r.var(B.default.parentData,(0,j._)`undefined`),r.var(B.default.parentDataProperty,(0,j._)`undefined`),r.var(B.default.rootData,B.default.data),e.dynamicRef&&r.var(B.default.dynamicAnchors,(0,j._)`{}`)})}function XA(r){let{schema:e,opts:t,gen:n}=r;Qy(r,()=>{t.$comment&&e.$comment&&ng(r),rk(r),n.let(B.default.vErrors,null),n.let(B.default.errors,0),t.unevaluated&&QA(r),rg(r),sk(r)})}function QA(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 Gy(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 ZA(r,e){if(eg(r)&&(tg(r),Zy(r))){ek(r,e);return}(0,Xy.boolOrEmptySchema)(r,e)}function Zy({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 eg(r){return typeof r.schema!="boolean"}function ek(r,e){let{schema:t,gen:n,opts:i}=r;i.$comment&&t.$comment&&ng(r),nk(r),ik(r);let s=n.const("_errs",B.default.errors);rg(r,s),n.var(e,(0,j._)`${s} === ${B.default.errors}`)}function tg(r){(0,jr.checkUnknownRules)(r),tk(r)}function rg(r,e){if(r.opts.jtd)return Jy(r,[],!1,e);let t=(0,Wy.getSchemaTypes)(r.schema),n=(0,Wy.coerceAndCheckDataType)(r,t);Jy(r,t,!n,e)}function tk(r){let{schema:e,errSchemaPath:t,opts:n,self:i}=r;e.$ref&&n.ignoreKeywordsWithRef&&(0,jr.schemaHasRulesButRef)(e,i.RULES)&&i.logger.warn(`$ref: keywords ignored in schema at path "${t}"`)}function rk(r){let{schema:e,opts:t}=r;e.default!==void 0&&t.useDefaults&&t.strictSchema&&(0,jr.checkStrictMode)(r,"default is ignored in the schema root")}function nk(r){let e=r.schema[r.opts.schemaId];e&&(r.baseId=(0,WA.resolveUrl)(r.opts.uriResolver,r.baseId,e))}function ik(r){if(r.schema.$async&&!r.schemaEnv.$async)throw new Error("async schema in sync schema")}function ng({gen:r,schemaEnv:e,schema:t,errSchemaPath:n,opts:i}){let s=t.$comment;if(i.$comment===!0)r.code((0,j._)`${B.default.self}.logger.log(${s})`);else if(typeof i.$comment=="function"){let o=(0,j.str)`${n}/$comment`,a=r.scopeValue("root",{ref:e.root});r.code((0,j._)`${B.default.self}.opts.$comment(${s}, ${o}, ${a}.schema)`)}}function sk(r){let{gen:e,schemaEnv:t,validateName:n,ValidationError:i,opts:s}=r;t.$async?e.if((0,j._)`${B.default.errors} === 0`,()=>e.return(B.default.data),()=>e.throw((0,j._)`new ${i}(${B.default.vErrors})`)):(e.assign((0,j._)`${n}.errors`,B.default.vErrors),s.unevaluated&&ok(r),e.return((0,j._)`${B.default.errors} === 0`))}function ok({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 Jy(r,e,t,n){let{gen:i,schema:s,data:o,allErrors:a,opts:c,self:l}=r,{RULES:u}=l;if(s.$ref&&(c.ignoreKeywordsWithRef||!(0,jr.schemaHasRulesButRef)(s,u))){i.block(()=>sg(r,"$ref",u.all.$ref.definition));return}c.jtd||ak(r,e),i.block(()=>{for(let f of u.rules)d(f);d(u.post)});function d(f){(0,mu.shouldUseGroup)(s,f)&&(f.type?(i.if((0,Ua.checkDataType)(f.type,o,c.strictNumbers)),Yy(r,f),e.length===1&&e[0]===f.type&&t&&(i.else(),(0,Ua.reportTypeError)(r)),i.endIf()):Yy(r,f),a||i.if((0,j._)`${B.default.errors} === ${n||0}`))}}function Yy(r,e){let{gen:t,schema:n,opts:{useDefaults:i}}=r;i&&(0,KA.assignDefaults)(r,e.type),t.block(()=>{for(let s of e.rules)(0,mu.shouldUseRule)(n,s)&&sg(r,s.keyword,s.definition,e.type)})}function ak(r,e){r.schemaEnv.meta||!r.opts.strictTypes||(ck(r,e),r.opts.allowUnionTypes||lk(r,e),dk(r,r.dataTypes))}function ck(r,e){if(e.length){if(!r.dataTypes.length){r.dataTypes=e;return}e.forEach(t=>{ig(r.dataTypes,t)||yu(r,`type "${t}" not allowed by context "${r.dataTypes.join(",")}"`)}),fk(r,e)}}function lk(r,e){e.length>1&&!(e.length===2&&e.includes("null"))&&yu(r,"use allowUnionTypes to allow union type keyword")}function dk(r,e){let t=r.self.RULES.all;for(let n in t){let i=t[n];if(typeof i=="object"&&(0,mu.shouldUseRule)(r.schema,i)){let{type:s}=i.definition;s.length&&!s.some(o=>uk(e,o))&&yu(r,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function uk(r,e){return r.includes(e)||e==="number"&&r.includes("integer")}function ig(r,e){return r.includes(e)||e==="integer"&&r.includes("number")}function fk(r,e){let t=[];for(let n of r.dataTypes)ig(e,n)?t.push(n):e.includes("integer")&&n==="number"&&t.push("integer");r.dataTypes=t}function yu(r,e){let t=r.schemaEnv.baseId+r.errSchemaPath;e+=` at "${t}" (strictTypes)`,(0,jr.checkStrictMode)(r,e,r.opts.strictTypes)}var Va=class{constructor(e,t,n){if((0,Ys.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,jr.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",og(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,Ys.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",B.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?Js.reportExtraError:Js.reportError)(this,this.def.error,t)}$dataError(){(0,Js.reportError)(this,this.def.$dataError||Js.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,Js.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:i,schemaType:s,def:o}=this;n.if((0,j.or)((0,j._)`${i} === undefined`,t)),e!==j.nil&&n.assign(e,!0),(s.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:i,it:s}=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,Ua.checkDataTypes)(c,t,s.opts.strictNumbers,Ua.DataType.Wrong)}`}return j.nil}function a(){if(i.validateSchema){let c=e.scopeValue("validate$data",{ref:i.validateSchema});return(0,j._)`!${c}(${t})`}return j.nil}}subschema(e,t){let n=(0,hu.getSubschema)(this.it,e);(0,hu.extendSubschemaData)(n,this.it,e),(0,hu.extendSubschemaMode)(n,e);let i={...this.it,...n,items:void 0,props:void 0};return ZA(i,t),i}mergeEvaluated(e,t){let{it:n,gen:i}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=jr.mergeEvaluated.props(i,e.props,n.props,t)),n.items!==!0&&e.items!==void 0&&(n.items=jr.mergeEvaluated.items(i,e.items,n.items,t)))}mergeValidEvaluated(e,t){let{it:n,gen:i}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return i.if(t,()=>this.mergeEvaluated(e,j.Name)),!0}};fn.KeywordCxt=Va;function sg(r,e,t,n){let i=new Va(r,t,e);"code"in t?t.code(i,n):i.$data&&t.validate?(0,Ys.funcKeywordCode)(i,t):"macro"in t?(0,Ys.macroKeywordCode)(i,t):(t.compile||t.validate)&&(0,Ys.funcKeywordCode)(i,t)}var pk=/^\/(?:[^~]|~0|~1)*$/,hk=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function og(r,{dataLevel:e,dataNames:t,dataPathArr:n}){let i,s;if(r==="")return B.default.rootData;if(r[0]==="/"){if(!pk.test(r))throw new Error(`Invalid JSON-pointer: ${r}`);i=r,s=B.default.rootData}else{let l=hk.exec(r);if(!l)throw new Error(`Invalid JSON-pointer: ${r}`);let u=+l[1];if(i=l[2],i==="#"){if(u>=e)throw new Error(c("property/index",u));return n[e-u]}if(u>e)throw new Error(c("data",u));if(s=t[e-u],!i)return s}let o=s,a=i.split("/");for(let l of a)l&&(s=(0,j._)`${s}${(0,j.getProperty)((0,jr.unescapeJsonPointer)(l))}`,o=(0,j._)`${o} && ${s}`);return o;function c(l,u){return`Cannot access ${l} ${u} levels up, current level is ${e}`}}fn.getData=og});var Xs=A(bu=>{"use strict";Object.defineProperty(bu,"__esModule",{value:!0});var gu=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};bu.default=gu});var Li=A(_u=>{"use strict";Object.defineProperty(_u,"__esModule",{value:!0});var vu=Gs(),wu=class extends Error{constructor(e,t,n,i){super(i||`can't resolve reference ${n} from id ${t}`),this.missingRef=(0,vu.resolveUrl)(e,t,n),this.missingSchema=(0,vu.normalizeId)((0,vu.getFullPath)(e,this.missingRef))}};_u.default=wu});var Qs=A(Lt=>{"use strict";Object.defineProperty(Lt,"__esModule",{value:!0});Lt.resolveSchema=Lt.getCompilingSchema=Lt.resolveRef=Lt.compileSchema=Lt.SchemaEnv=void 0;var Jt=U(),mk=Xs(),ei=Dt(),Yt=Gs(),ag=Q(),yk=Ni(),Fi=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,Yt.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};Lt.SchemaEnv=Fi;function $u(r){let e=cg.call(this,r);if(e)return e;let t=(0,Yt.getFullPath)(this.opts.uriResolver,r.root.baseId),{es5:n,lines:i}=this.opts.code,{ownProperties:s}=this.opts,o=new Jt.CodeGen(this.scope,{es5:n,lines:i,ownProperties:s}),a;r.$async&&(a=o.scopeValue("Error",{ref:mk.default,code:(0,Jt._)`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:[Jt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:o.scopeValue("schema",this.opts.code.source===!0?{ref:r.schema,code:(0,Jt.stringify)(r.schema)}:{ref:r.schema}),validateName:c,ValidationError:a,schema:r.schema,schemaEnv:r,rootId:t,baseId:r.baseId||t,schemaPath:Jt.nil,errSchemaPath:r.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Jt._)`""`,opts:this.opts,self:this},u;try{this._compilations.add(r),(0,yk.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 Jt.Name?void 0:m,items:h instanceof Jt.Name?void 0:h,dynamicProps:m instanceof Jt.Name,dynamicItems:h instanceof Jt.Name},p.source&&(p.source.evaluated=(0,Jt.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)}}Lt.compileSchema=$u;function gk(r,e,t){var n;t=(0,Yt.resolveUrl)(this.opts.uriResolver,e,t);let i=r.refs[t];if(i)return i;let s=wk.call(this,r,t);if(s===void 0){let o=(n=r.localRefs)===null||n===void 0?void 0:n[t],{schemaId:a}=this.opts;o&&(s=new Fi({schema:o,schemaId:a,root:r,baseId:e}))}if(s!==void 0)return r.refs[t]=bk.call(this,s)}Lt.resolveRef=gk;function bk(r){return(0,Yt.inlineRef)(r.schema,this.opts.inlineRefs)?r.schema:r.validate?r:$u.call(this,r)}function cg(r){for(let e of this._compilations)if(vk(e,r))return e}Lt.getCompilingSchema=cg;function vk(r,e){return r.schema===e.schema&&r.root===e.root&&r.baseId===e.baseId}function wk(r,e){let t;for(;typeof(t=this.refs[e])=="string";)e=t;return t||this.schemas[e]||Ha.call(this,r,e)}function Ha(r,e){let t=this.opts.uriResolver.parse(e),n=(0,Yt._getFullPath)(this.opts.uriResolver,t),i=(0,Yt.getFullPath)(this.opts.uriResolver,r.baseId,void 0);if(Object.keys(r.schema).length>0&&n===i)return Su.call(this,t,r);let s=(0,Yt.normalizeId)(n),o=this.refs[s]||this.schemas[s];if(typeof o=="string"){let a=Ha.call(this,r,o);return typeof a?.schema!="object"?void 0:Su.call(this,t,a)}if(typeof o?.schema=="object"){if(o.validate||$u.call(this,o),s===(0,Yt.normalizeId)(e)){let{schema:a}=o,{schemaId:c}=this.opts,l=a[c];return l&&(i=(0,Yt.resolveUrl)(this.opts.uriResolver,i,l)),new Fi({schema:a,schemaId:c,root:r,baseId:i})}return Su.call(this,t,o)}}Lt.resolveSchema=Ha;var _k=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Su(r,{baseId:e,schema:t,root:n}){var i;if(((i=r.fragment)===null||i===void 0?void 0:i[0])!=="/")return;for(let a of r.fragment.slice(1).split("/")){if(typeof t=="boolean")return;let c=t[(0,ag.unescapeFragment)(a)];if(c===void 0)return;t=c;let l=typeof t=="object"&&t[this.opts.schemaId];!_k.has(a)&&l&&(e=(0,Yt.resolveUrl)(this.opts.uriResolver,e,l))}let s;if(typeof t!="boolean"&&t.$ref&&!(0,ag.schemaHasRulesButRef)(t,this.RULES)){let a=(0,Yt.resolveUrl)(this.opts.uriResolver,e,t.$ref);s=Ha.call(this,n,a)}let{schemaId:o}=this.opts;if(s=s||new Fi({schema:t,schemaId:o,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var lg=A((Lj,Sk)=>{Sk.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 Cu=A((Fj,yg)=>{"use strict";var $k=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Eu=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),xk=RegExp.prototype.test.bind(/^\d*$/u),ti=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),Au=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),ug=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u),ku=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u),Ek=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u),ft=new Array(256);{let r="0123456789ABCDEF";for(let e=0;e<256;e++)ft[e]="%"+r[e>>4]+r[e&15]}function ze(r){return r<2048?ft[192|r>>6]+ft[128|r&63]:r<65536?ft[224|r>>12]+ft[128|r>>6&63]+ft[128|r&63]:ft[240|r>>18]+ft[128|r>>12&63]+ft[128|r>>6&63]+ft[128|r&63]}function Ak(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 kk=RegExp.prototype.test.bind(/^[\dA-Fa-f]{1,4}$/),Pk=RegExp.prototype.test.bind(/^[vV][\dA-Fa-f]+\.[A-Za-z\d\-._~!$&'()*+,;=:]+$/),Ck=RegExp.prototype.test.bind(/^[A-Za-z\d\-._~]$/),Mk=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function Tk(r){if(r.length===0)return!1;for(let e=0;et&&(t=i,e=n)):(n=-1,i=0);if(t<2)return r.join(":");let s=r.slice(0,e).join(":"),o=r.slice(e+t).join(":");return s+"::"+o}function Rk(r){let e=r.indexOf("::");if(e!==-1&&r.indexOf("::",e+1)!==-1)return;let t=e===-1?r.split(":"):r.slice(0,e).split(":"),n=e===-1?[]:r.slice(e+2).split(":");e!==-1&&(t.length===1&&t[0]===""&&(t.length=0),n.length===1&&n[0]===""&&(n.length=0));let i=t.concat(n),s=0;for(let a=0;a=8)return;let o=i.slice(0,t.length);for(let a=s;a<8;a++)o.push("0");for(let a=t.length;aDk[n])}function pg(r,e=!1){if(r.indexOf("%")===-1)return r;let t="";for(let n=0;n57343)e+=ze(i);else if(i<=56319&&t+1=56320&&s<=57343?(e+=ze(65536+(i-55296<<10)+(s-56320)),t++):e+=ze(65533)}else e+=ze(65533)}}return e}function jk(r,e=!1){let t="",n=e&&r[0]!=="/";for(let i=0;i57343)t+=ze(o);else if(o<=56319&&i+1=56320&&a<=57343?(t+=ze(65536+(o-55296<<10)+(a-56320)),i++):t+=ze(65533)}else t+=ze(65533)}}return t}function Pu(r,e){let t="";for(let n=0;n57343)t+=ze(s);else if(s<=56319&&n+1=56320&&o<=57343?(t+=ze(65536+(s-55296<<10)+(o-56320)),n++):t+=ze(65533)}else t+=ze(65533)}}return t}function hg(r){return Pu(r,Ek)}function qk(r){return Pu(r,ku)}function Bk(r){return Pu(r,ku)}function mg(r){return r>=48&&r<=57||r>=65&&r<=90||r>=97&&r<=122||r===42||r===43||r===45||r===46||r===47||r===64||r===95}function Uk(r){let e="";for(let t=0;t57343)e+=ze(i);else if(i<=56319&&t+1=56320&&s<=57343?(e+=ze(65536+(i-55296<<10)+(s-56320)),t++):e+=ze(65533)}else e+=ze(65533)}}return e}function Vk(r){let e="";for(let t=0;t{"use strict";var{isUUID:zk}=Cu(),Kk=/^([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-./:;=@]|%[\da-f]{2})+)$/iu,Wk=["http","https","ws","wss","urn","urn:uuid"];function Gk(r){return Wk.indexOf(r)!==-1}function Mu(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 gg(r){return r.host||(r.error=r.error||"HTTP URIs must have a host."),r}function bg(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 Jk(r){return r.secure=Mu(r),r.resourceName=(r.path||"/")+(r.query?"?"+r.query:""),r.path=void 0,r.query=void 0,r}function Yk(r){if((r.port===(Mu(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=r.resourceName.indexOf("?"),t=e===-1?r.resourceName:r.resourceName.slice(0,e);r.path=t&&t!=="/"?t:void 0,r.query=e===-1?void 0:r.resourceName.slice(e+1),r.resourceName=void 0}return r.fragment=void 0,r}function Xk(r,e){if(!r.path)return r.error="URN can not be parsed",r;let t=r.path.match(Kk);if(t&&t[0]===r.path){let n=e.scheme||r.scheme||"urn";r.nid=t[1].toLowerCase(),r.nss=t[2];let i=`${n}:${e.nid||r.nid}`,s=Tu(i);r.path=void 0,s&&(r=s.parse(r,e))}else r.error=r.error||"URN can not be parsed.";return r}function Qk(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(),i=`${t}:${e.nid||n}`,s=Tu(i);s&&(r=s.serialize(r,e));let o=r,a=r.nss;return o.path=`${n||e.nid}:${a}`,e.skipEscape=!0,o}function Zk(r,e){let t=r;return t.uuid=t.nss,t.nss=void 0,!e.tolerant&&(!t.uuid||!zk(t.uuid))&&(t.error=t.error||"UUID is not valid."),t}function eP(r){let e=r;return e.nss=(r.uuid||"").toLowerCase(),e}var vg={scheme:"http",domainHost:!0,parse:gg,serialize:bg},tP={scheme:"https",domainHost:vg.domainHost,parse:gg,serialize:bg},za={scheme:"ws",domainHost:!0,parse:Jk,serialize:Yk},rP={scheme:"wss",domainHost:za.domainHost,parse:za.parse,serialize:za.serialize},nP={scheme:"urn",parse:Xk,serialize:Qk,skipNormalize:!0},iP={scheme:"urn:uuid",parse:Zk,serialize:eP,skipNormalize:!0},Ka={http:vg,https:tP,ws:za,wss:rP,urn:nP,"urn:uuid":iP};Object.setPrototypeOf(Ka,null);function Tu(r){return r&&(Ka[r]||Ka[r.toLowerCase()])||void 0}wg.exports={wsIsSecure:Mu,SCHEMES:Ka,isValidSchemeName:Gk,getSchemeHandler:Tu}});var Dg=A((qj,Ja)=>{"use strict";var{normalizeIPv6:Ag,removeDotSegments:eo,recomposeAuthority:sP,normalizePercentEncoding:kg,normalizePathEncoding:oP,serializePathEncoding:Sg,normalizeQueryFragmentEncoding:$g,encodeQuery:aP,encodeFragment:cP,reescapeHostDelimiters:lP,isIPv4:Pg,nonSimpleDomain:dP}=Cu(),{SCHEMES:Cg,getSchemeHandler:Ru}=_g(),Mg=/^[A-Za-z][A-Za-z0-9+.-]*$/u,Tg="URI scheme is malformed.";function xg(r){let e=unescape(String(r));if(!Mg.test(e))throw new TypeError(Tg);return e}function uP(r,e){return typeof r=="string"?r=vP(r,e):typeof r=="object"&&(r=Ga(ri(r,e),e)),r}function fP(r,e,t){let n=t?Object.assign({scheme:"null"},t):{scheme:"null"},{parsed:i,malformedAuthorityOrPort:s,malformedPercentEncoding:o,malformedSchemeSpecific:a,malformedHost:c,malformedScheme:l}=Wa(r,n),{parsed:u,malformedAuthorityOrPort:d,malformedPercentEncoding:f,malformedSchemeSpecific:p,malformedHost:m,malformedScheme:h}=Wa(e,n);if(s||d||o||f||a||p||c||m||l||h)throw new Error(i.error||u.error||"URI is malformed.");let y=Rg(i,u,n,!0),g=Ru(t&&t.scheme||y.scheme),b=y.host,v=b!==void 0&&b!==""&&(Pg(b)||Ag(b).isIPV6);Ig(y,t||{},g,v);let S=b&&b.indexOf("%")!==-1&&!/\P{ASCII}/u.test(b);if(y.error&&!S)throw new Error(y.error);return n.skipEscape=!0,ri(y,n)}function Rg(r,e,t,n){let i={};return n||(r=Ga(ri(r,t),t),e=Ga(ri(e,t),t)),t=t||{},!t.tolerant&&e.scheme?(i.scheme=e.scheme,i.userinfo=e.userinfo,i.host=e.host,i.port=e.port,i.path=eo(e.path||""),i.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(i.userinfo=e.userinfo,i.host=e.host,i.port=e.port,i.path=eo(e.path||""),i.query=e.query):(e.path?(e.path[0]==="/"?i.path=eo(e.path):((r.userinfo!==void 0||r.host!==void 0||r.port!==void 0)&&!r.path?i.path="/"+e.path:r.path?i.path=r.path.slice(0,r.path.lastIndexOf("/")+1)+e.path:i.path=e.path,i.path=eo(i.path)),i.query=e.query):(i.path=r.path,e.query!==void 0?i.query=e.query:i.query=r.query),i.userinfo=r.userinfo,i.host=r.host,i.port=r.port),i.scheme=r.scheme),i.fragment=e.fragment,i}function pP(r,e,t){let n=Eg(r,t),i=Eg(e,t);return n!==void 0&&i!==void 0&&n===i}function ri(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),i=[];t.scheme&&(t.scheme=xg(t.scheme));let s=Ru(n.scheme||t.scheme);s&&s.serialize&&s.serialize(t,n);let o=t.userinfo!==void 0||t.host!==void 0||t.port!==void 0,a=!n.skipEscape&&t.scheme===void 0&&!o;t.path!==void 0&&(n.skipEscape?t.path=kg(t.path):t.path=Sg(t.path,a)),n.reference!=="suffix"&&t.scheme&&(t.scheme=xg(t.scheme),i.push(t.scheme,":"));let c=sP(t);if(c!==void 0&&(n.reference!=="suffix"&&i.push("//"),i.push(c),t.path&&t.path[0]!=="/"&&i.push("/")),t.path!==void 0){let l=t.path;!n.absolutePath&&(!s||!s.absolutePath)&&(l=eo(l)),a&&(l=Sg(l,!0)),c===void 0&&l[0]==="/"&&l[1]==="/"&&(l="/%2F"+l.slice(2)),i.push(l)}return t.query!==void 0&&i.push("?",aP(t.query)),t.fragment!==void 0&&i.push("#",cP(t.fragment)),i.join("")}var hP=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,mP=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,yP=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function gP(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 Zs(r){if(r===void 0)return!1;let e=r.indexOf("%");for(;e!==-1;){if(e+2>=r.length||!/^[\da-f]{2}$/iu.test(r.slice(e+1,e+3)))return!0;e=r.indexOf("%",e+3)}return!1}function Iu(r){return r[0]==="["&&r[r.length-1]==="]"}function bP(r){let e=r[4];return Zs(r[3])||e!==void 0&&!Iu(e)&&Zs(e)||Zs(r[6])||Zs(r[7])||Zs(r[8])}function Ig(r,e,t,n){if(!e.unicodeSupport&&(!t||!t.unicodeSupport)&&r.host&&!Iu(r.host)&&(e.domainHost||t&&t.domainHost)&&n===!1&&dP(r.host))try{r.host=new URL("http://"+r.host).hostname}catch(i){return r.error=r.error||"Host's domain name can not be converted to ASCII: "+i,!0}return!1}function Wa(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},i=!1,s=!1,o=!1,a=!1,c=!1,l=!1,u=!1;t.reference==="suffix"&&(t.scheme?r=t.scheme+":"+r:r="//"+r);let d=r.match(mP);d!==null&&d[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",i=!0);let f=r.match(yP);if(f!==null){let m=f[1],h=m.replace(/[\t\n\r]/g,"");h.length>=2&&(h.slice(0,2)!=="//"?(n.error=n.error||"URI authority must not contain a literal backslash.",i=!0):m.length!==h.length&&(n.error=n.error||"URI authority introducer must not contain whitespace.",i=!0))}let p=r.match(hP);if(p){if(n.scheme=p[1],n.userinfo=p[3],n.host=p[4],n.port=parseInt(p[5],10),n.path=p[6]||"",n.query=p[7],n.fragment=p[8],n.scheme!==void 0){let y=unescape(n.scheme);Mg.test(y)?n.scheme=y.toLowerCase():(n.error=n.error||Tg,l=!0)}s=bP(p),s&&(n.error=n.error||"URI contains malformed percent-encoding."),isNaN(n.port)&&(n.port=p[5]);let m=gP(n,p);if(m!==void 0&&(n.error=n.error||m,i=!0),n.host)if(Pg(n.host)===!1){let g=Iu(n.host),b=n.host.indexOf("[")!==-1||n.host.indexOf("]")!==-1,v=Ag(n.host);u=v.isIPV6||v.isIPVFuture===!0,c=b&&(!g||v.error===!0),n.host=u?v.host:v.host.toLowerCase(),c&&(n.error=n.error||"URI host is malformed.",i=!0)}else u=!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 h=Ru(t.scheme||n.scheme);if(c||(a=Ig(n,t,h,u)),!h||h&&!h.skipNormalize){if(r.indexOf("%")!==-1&&n.host!==void 0&&!c){let y=u?n.host:kg(n.host,!0);n.host=lP(y,u)}n.path&&(n.path=oP(n.path)),n.query&&(n.query=$g(n.query)),n.fragment&&(n.fragment=$g(n.fragment))}h&&h.parse&&(h.parse(n,t),h===Cg.urn&&n.nid===void 0&&(o=!0))}else n.error=n.error||"URI can not be parsed.";return{parsed:n,malformedAuthorityOrPort:i,malformedPercentEncoding:s,malformedSchemeSpecific:o,malformedHost:a,malformedScheme:l}}function Ga(r,e){return Wa(r,e).parsed}function vP(r,e){return Og(r,e).normalized}function Og(r,e){let{parsed:t,malformedAuthorityOrPort:n,malformedPercentEncoding:i,malformedSchemeSpecific:s,malformedHost:o,malformedScheme:a}=Wa(r,e);return{normalized:n||i||s||o||a?r:ri(t,e),malformedAuthorityOrPort:n,malformedPercentEncoding:i,malformedSchemeSpecific:s,malformedHost:o,malformedScheme:a}}function Eg(r,e){if(typeof r!="string"&&typeof r!="object")return;let t;try{t=typeof r=="string"?r:ri(r,e)}catch{return}let{normalized:n,malformedAuthorityOrPort:i,malformedPercentEncoding:s,malformedSchemeSpecific:o,malformedHost:a,malformedScheme:c}=Og(t,e);return i||s||o||a||c?void 0:n}var Ou={SCHEMES:Cg,normalize:uP,resolve:fP,resolveComponent:Rg,equal:pP,serialize:ri,parse:Ga};Ja.exports=Ou;Ja.exports.default=Ou;Ja.exports.fastUri=Ou});var Lg=A(Du=>{"use strict";Object.defineProperty(Du,"__esModule",{value:!0});var Ng=Dg();Ng.code='require("ajv/dist/runtime/uri").default';Du.default=Ng});var Fu=A(Le=>{"use strict";Object.defineProperty(Le,"__esModule",{value:!0});Le.CodeGen=Le.Name=Le.nil=Le.stringify=Le.str=Le._=Le.KeywordCxt=void 0;var wP=Ni();Object.defineProperty(Le,"KeywordCxt",{enumerable:!0,get:function(){return wP.KeywordCxt}});var ji=U();Object.defineProperty(Le,"_",{enumerable:!0,get:function(){return ji._}});Object.defineProperty(Le,"str",{enumerable:!0,get:function(){return ji.str}});Object.defineProperty(Le,"stringify",{enumerable:!0,get:function(){return ji.stringify}});Object.defineProperty(Le,"nil",{enumerable:!0,get:function(){return ji.nil}});Object.defineProperty(Le,"Name",{enumerable:!0,get:function(){return ji.Name}});Object.defineProperty(Le,"CodeGen",{enumerable:!0,get:function(){return ji.CodeGen}});var _P=Xs(),Ug=Li(),SP=iu(),to=Qs(),$P=U(),ro=Gs(),Ya=Ws(),Lu=Q(),Fg=lg(),xP=Lg(),Vg=(r,e)=>new RegExp(r,e);Vg.code="new RegExp";var EP=["removeAdditional","useDefaults","coerceTypes"],AP=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),kP={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."},PP={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},jg=200;function CP(r){var e,t,n,i,s,o,a,c,l,u,d,f,p,m,h,y,g,b,v,S,_,E,k,$,M;let x=r.strict,q=(e=r.code)===null||e===void 0?void 0:e.optimize,T=q===!0||q===void 0?1:q||0,V=(n=(t=r.code)===null||t===void 0?void 0:t.regExp)!==null&&n!==void 0?n:Vg,P=(i=r.uriResolver)!==null&&i!==void 0?i:xP.default;return{strictSchema:(o=(s=r.strictSchema)!==null&&s!==void 0?s:x)!==null&&o!==void 0?o:!0,strictNumbers:(c=(a=r.strictNumbers)!==null&&a!==void 0?a:x)!==null&&c!==void 0?c:!0,strictTypes:(u=(l=r.strictTypes)!==null&&l!==void 0?l:x)!==null&&u!==void 0?u:"log",strictTuples:(f=(d=r.strictTuples)!==null&&d!==void 0?d:x)!==null&&f!==void 0?f:"log",strictRequired:(m=(p=r.strictRequired)!==null&&p!==void 0?p:x)!==null&&m!==void 0?m:!1,code:r.code?{...r.code,optimize:T,regExp:V}:{optimize:T,regExp:V},loopRequired:(h=r.loopRequired)!==null&&h!==void 0?h:jg,loopEnum:(y=r.loopEnum)!==null&&y!==void 0?y:jg,meta:(g=r.meta)!==null&&g!==void 0?g:!0,messages:(b=r.messages)!==null&&b!==void 0?b:!0,inlineRefs:(v=r.inlineRefs)!==null&&v!==void 0?v:!0,schemaId:(S=r.schemaId)!==null&&S!==void 0?S:"$id",addUsedSchema:(_=r.addUsedSchema)!==null&&_!==void 0?_:!0,validateSchema:(E=r.validateSchema)!==null&&E!==void 0?E:!0,validateFormats:(k=r.validateFormats)!==null&&k!==void 0?k:!0,unicodeRegExp:($=r.unicodeRegExp)!==null&&$!==void 0?$:!0,int32range:(M=r.int32range)!==null&&M!==void 0?M:!0,uriResolver:P}}var no=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,...CP(e)};let{es5:t,lines:n}=this.opts.code;this.scope=new $P.ValueScope({scope:{},prefixes:AP,es5:t,lines:n}),this.logger=DP(e.logger);let i=e.validateFormats;e.validateFormats=!1,this.RULES=(0,SP.getRules)(),qg.call(this,kP,e,"NOT SUPPORTED"),qg.call(this,PP,e,"DEPRECATED","warn"),this._metaOpts=IP.call(this),e.formats&&TP.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&RP.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),MP.call(this),e.validateFormats=i}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:t,schemaId:n}=this.opts,i=Fg;n==="id"&&(i={...Fg},i.id=i.$id,delete i.$id),t&&e&&this.addMetaSchema(i,i[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 i=n(t);return"$async"in n||(this.errors=n.errors),i}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 i.call(this,e,t);async function i(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 i.call(this,{$ref:u},!0)}async function o(u){try{return this._compileSchemaEnv(u)}catch(d){if(!(d instanceof Ug.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]=n(u))}finally{delete this._loading[u]}}}addSchema(e,t,n,i=this.opts.validateSchema){if(Array.isArray(e)){for(let o of e)this.addSchema(o,void 0,n,i);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,ro.normalizeId)(t||s),this._checkUnique(t),this.schemas[t]=this._addSchema(e,n,t,i,!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 i=this.validate(n,e);if(!i&&t){let s="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(s);else throw new Error(s)}return i}getSchema(e){let t;for(;typeof(t=Bg.call(this,e))=="string";)e=t;if(t===void 0){let{schemaId:n}=this.opts,i=new to.SchemaEnv({schema:{},schemaId:n});if(t=to.resolveSchema.call(this,i,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=Bg.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,ro.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(LP.call(this,n,t),!t)return(0,Lu.eachItem)(n,s=>Nu.call(this,s)),this;jP.call(this,t);let i={...t,type:(0,Ya.getJSONTypes)(t.type),schemaType:(0,Ya.getJSONTypes)(t.schemaType)};return(0,Lu.eachItem)(n,i.type.length===0?s=>Nu.call(this,s,i):s=>i.type.forEach(o=>Nu.call(this,s,i,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 i=n.rules.findIndex(s=>s.keyword===e);i>=0&&n.rules.splice(i,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(i=>`${n}${i.instancePath} ${i.message}`).reduce((i,s)=>i+t+s)}$dataMetaSchema(e,t){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let i of t){let s=i.split("/").slice(1),o=e;for(let a of s)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]=Hg(u))}}return e}_removeAllSchemas(e,t){for(let n in e){let i=e[n];(!t||t.test(n))&&(typeof i=="string"?delete e[n]:i&&!i.meta&&(this._cache.delete(i.schema),delete e[n]))}}_addSchema(e,t,n,i=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;n=(0,ro.normalizeId)(o||n);let l=ro.getSchemaRefs.call(this,e,n);return c=new to.SchemaEnv({schema:e,schemaId:a,meta:t,baseId:n,localRefs:l}),this._cache.set(c.schema,c),s&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=c),i&&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):to.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{to.compileSchema.call(this,e)}finally{this.opts=t}}};no.ValidationError=_P.default;no.MissingRefError=Ug.default;Le.default=no;function qg(r,e,t,n="error"){for(let i in r){let s=i;s in e&&this.logger[n](`${t}: option ${i}. ${r[s]}`)}}function Bg(r){return r=(0,ro.normalizeId)(r),this.schemas[r]||this.refs[r]}function MP(){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 TP(){for(let r in this.opts.formats){let e=this.opts.formats[r];e&&this.addFormat(r,e)}}function RP(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 IP(){let r={...this.opts};for(let e of EP)delete r[e];return r}var OP={log(){},warn(){},error(){}};function DP(r){if(r===!1)return OP;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 NP=/^[a-z_$][a-z0-9_$:-]*$/i;function LP(r,e){let{RULES:t}=this;if((0,Lu.eachItem)(r,n=>{if(t.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!NP.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 Nu(r,e,t){var n;let i=e?.post;if(t&&i)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:s}=this,o=i?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,Ya.getJSONTypes)(e.type),schemaType:(0,Ya.getJSONTypes)(e.schemaType)}};e.before?FP.call(this,o,a,e.before):o.rules.push(a),s.all[r]=a,(n=e.implements)===null||n===void 0||n.forEach(c=>this.addKeyword(c))}function FP(r,e,t){let n=r.rules.findIndex(i=>i.keyword===t);n>=0?r.rules.splice(n,0,e):(r.rules.push(e),this.logger.warn(`rule ${t} is not defined`))}function jP(r){let{metaSchema:e}=r;e!==void 0&&(r.$data&&this.opts.$data&&(e=Hg(e)),r.validateSchema=this.compile(e,!0))}var qP={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Hg(r){return{anyOf:[r,qP]}}});var zg=A(ju=>{"use strict";Object.defineProperty(ju,"__esModule",{value:!0});var BP={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};ju.default=BP});var Za=A(ni=>{"use strict";Object.defineProperty(ni,"__esModule",{value:!0});ni.callRef=ni.getValidate=void 0;var UP=Li(),Kg=Nt(),pt=U(),qi=Dt(),Wg=Qs(),Xa=Q(),VP={keyword:"$ref",schemaType:"string",code(r){let{gen:e,schema:t,it:n}=r,{baseId:i,schemaEnv:s,validateName:o,opts:a,self:c}=n,{root:l}=s;if((t==="#"||t==="#/")&&i===l.baseId)return d();let u=Wg.resolveRef.call(c,l,i,t);if(u===void 0)throw new UP.default(n.opts.uriResolver,i,t);if(u instanceof Wg.SchemaEnv)return f(u);return p(u);function d(){if(s===l)return Qa(r,o,s,s.$async);let m=e.scopeValue("root",{ref:l});return Qa(r,(0,pt._)`${m}.validate`,l,l.$async)}function f(m){let h=Gg(r,m);Qa(r,h,m,m.$async)}function p(m){let h=e.scopeValue("schema",a.code.source===!0?{ref:m,code:(0,pt.stringify)(m)}:{ref:m}),y=e.name("valid"),g=r.subschema({schema:m,dataTypes:[],schemaPath:pt.nil,topSchemaRef:h,errSchemaPath:t},y);r.mergeEvaluated(g),r.ok(y)}}};function Gg(r,e){let{gen:t}=r;return e.validate?t.scopeValue("validate",{ref:e.validate}):(0,pt._)`${t.scopeValue("wrapper",{ref:e})}.validate`}ni.getValidate=Gg;function Qa(r,e,t,n){let{gen:i,it:s}=r,{allErrors:o,schemaEnv:a,opts:c}=s,l=c.passContext?qi.default.this:pt.nil;n?u():d();function u(){if(!a.$async)throw new Error("async schema referenced by sync schema");let m=i.let("valid");i.try(()=>{i.code((0,pt._)`await ${(0,Kg.callValidateCode)(r,e,l)}`),p(e),o||i.assign(m,!0)},h=>{i.if((0,pt._)`!(${h} instanceof ${s.ValidationError})`,()=>i.throw(h)),f(h),o||i.assign(m,!1)}),r.ok(m)}function d(){r.result((0,Kg.callValidateCode)(r,e,l),()=>p(e),()=>f(e))}function f(m){let h=(0,pt._)`${m}.errors`;i.assign(qi.default.vErrors,(0,pt._)`${qi.default.vErrors} === null ? ${h} : ${qi.default.vErrors}.concat(${h})`),i.assign(qi.default.errors,(0,pt._)`${qi.default.vErrors}.length`)}function p(m){var h;if(!s.opts.unevaluated)return;let y=(h=t?.validate)===null||h===void 0?void 0:h.evaluated;if(s.props!==!0)if(y&&!y.dynamicProps)y.props!==void 0&&(s.props=Xa.mergeEvaluated.props(i,y.props,s.props));else{let g=i.var("props",(0,pt._)`${m}.evaluated.props`);s.props=Xa.mergeEvaluated.props(i,g,s.props,pt.Name)}if(s.items!==!0)if(y&&!y.dynamicItems)y.items!==void 0&&(s.items=Xa.mergeEvaluated.items(i,y.items,s.items));else{let g=i.var("items",(0,pt._)`${m}.evaluated.items`);s.items=Xa.mergeEvaluated.items(i,g,s.items,pt.Name)}}}ni.callRef=Qa;ni.default=VP});var Bu=A(qu=>{"use strict";Object.defineProperty(qu,"__esModule",{value:!0});var HP=zg(),zP=Za(),KP=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",HP.default,zP.default];qu.default=KP});var Jg=A(Uu=>{"use strict";Object.defineProperty(Uu,"__esModule",{value:!0});var ec=U(),pn=ec.operators,tc={maximum:{okStr:"<=",ok:pn.LTE,fail:pn.GT},minimum:{okStr:">=",ok:pn.GTE,fail:pn.LT},exclusiveMaximum:{okStr:"<",ok:pn.LT,fail:pn.GTE},exclusiveMinimum:{okStr:">",ok:pn.GT,fail:pn.LTE}},WP={message:({keyword:r,schemaCode:e})=>(0,ec.str)`must be ${tc[r].okStr} ${e}`,params:({keyword:r,schemaCode:e})=>(0,ec._)`{comparison: ${tc[r].okStr}, limit: ${e}}`},GP={keyword:Object.keys(tc),type:"number",schemaType:"number",$data:!0,error:WP,code(r){let{keyword:e,data:t,schemaCode:n}=r;r.fail$data((0,ec._)`${t} ${tc[e].fail} ${n} || isNaN(${t})`)}};Uu.default=GP});var Yg=A(Vu=>{"use strict";Object.defineProperty(Vu,"__esModule",{value:!0});var io=U(),JP={message:({schemaCode:r})=>(0,io.str)`must be multiple of ${r}`,params:({schemaCode:r})=>(0,io._)`{multipleOf: ${r}}`},YP={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:JP,code(r){let{gen:e,data:t,schemaCode:n,it:i}=r,s=i.opts.multipleOfPrecision,o=e.let("res"),a=s?(0,io._)`Math.abs(Math.round(${o}) - ${o}) > 1e-${s}`:(0,io._)`${o} !== parseInt(${o})`;r.fail$data((0,io._)`(${n} === 0 || (${o} = ${t}/${n}, ${a}))`)}};Vu.default=YP});var Qg=A(Hu=>{"use strict";Object.defineProperty(Hu,"__esModule",{value:!0});function Xg(r){let e=r.length,t=0,n=0,i;for(;n=55296&&i<=56319&&n{"use strict";Object.defineProperty(zu,"__esModule",{value:!0});var ii=U(),XP=Q(),QP=Qg(),ZP={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}}`},e1={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:ZP,code(r){let{keyword:e,data:t,schemaCode:n,it:i}=r,s=e==="maxLength"?ii.operators.GT:ii.operators.LT,o=i.opts.unicode===!1?(0,ii._)`${t}.length`:(0,ii._)`${(0,XP.useFunc)(r.gen,QP.default)}(${t})`;r.fail$data((0,ii._)`${o} ${s} ${n}`)}};zu.default=e1});var eb=A(Ku=>{"use strict";Object.defineProperty(Ku,"__esModule",{value:!0});var t1=Nt(),r1=Q(),Bi=U(),n1={message:({schemaCode:r})=>(0,Bi.str)`must match pattern "${r}"`,params:({schemaCode:r})=>(0,Bi._)`{pattern: ${r}}`},i1={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:n1,code(r){let{gen:e,data:t,$data:n,schema:i,schemaCode:s,it:o}=r,a=o.opts.unicodeRegExp?"u":"";if(n){let{regExp:c}=o.opts.code,l=c.code==="new RegExp"?(0,Bi._)`new RegExp`:(0,r1.useFunc)(e,c),u=e.let("valid");e.try(()=>e.assign(u,(0,Bi._)`${l}(${s}, ${a}).test(${t})`),()=>e.assign(u,!1)),r.fail$data((0,Bi._)`!${u}`)}else{let c=(0,t1.usePattern)(r,i);r.fail$data((0,Bi._)`!${c}.test(${t})`)}}};Ku.default=i1});var tb=A(Wu=>{"use strict";Object.defineProperty(Wu,"__esModule",{value:!0});var so=U(),s1={message({keyword:r,schemaCode:e}){let t=r==="maxProperties"?"more":"fewer";return(0,so.str)`must NOT have ${t} than ${e} properties`},params:({schemaCode:r})=>(0,so._)`{limit: ${r}}`},o1={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:s1,code(r){let{keyword:e,data:t,schemaCode:n}=r,i=e==="maxProperties"?so.operators.GT:so.operators.LT;r.fail$data((0,so._)`Object.keys(${t}).length ${i} ${n}`)}};Wu.default=o1});var rb=A(Gu=>{"use strict";Object.defineProperty(Gu,"__esModule",{value:!0});var oo=Nt(),ao=U(),a1=Q(),c1={message:({params:{missingProperty:r}})=>(0,ao.str)`must have required property '${r}'`,params:({params:{missingProperty:r}})=>(0,ao._)`{missingProperty: ${r}}`},l1={keyword:"required",type:"object",schemaType:"array",$data:!0,error:c1,code(r){let{gen:e,schema:t,schemaCode:n,data:i,$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?.[h]===void 0&&!m.has(h)){let y=o.schemaEnv.baseId+o.errSchemaPath,g=`required property "${h}" is not defined at "${y}" (strictRequired)`;(0,a1.checkStrictMode)(o,g,o.opts.strictRequired)}}function l(){if(c||s)r.block$data(ao.nil,d);else for(let p of t)(0,oo.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,oo.checkMissingProp)(r,t,p)),(0,oo.reportMissingProp)(r,p),e.else()}function d(){e.forOf("prop",n,p=>{r.setParams({missingProperty:p}),e.if((0,oo.noPropertyInData)(e,i,p,a.ownProperties),()=>r.error())})}function f(p,m){r.setParams({missingProperty:p}),e.forOf(p,n,()=>{e.assign(m,(0,oo.propertyInData)(e,i,p,a.ownProperties)),e.if((0,ao.not)(m),()=>{r.error(),e.break()})},ao.nil)}}};Gu.default=l1});var nb=A(Ju=>{"use strict";Object.defineProperty(Ju,"__esModule",{value:!0});var co=U(),d1={message({keyword:r,schemaCode:e}){let t=r==="maxItems"?"more":"fewer";return(0,co.str)`must NOT have ${t} than ${e} items`},params:({schemaCode:r})=>(0,co._)`{limit: ${r}}`},u1={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:d1,code(r){let{keyword:e,data:t,schemaCode:n}=r,i=e==="maxItems"?co.operators.GT:co.operators.LT;r.fail$data((0,co._)`${t}.length ${i} ${n}`)}};Ju.default=u1});var rc=A(Yu=>{"use strict";Object.defineProperty(Yu,"__esModule",{value:!0});var ib=fu();ib.code='require("ajv/dist/runtime/equal").default';Yu.default=ib});var sb=A(Qu=>{"use strict";Object.defineProperty(Qu,"__esModule",{value:!0});var Xu=Ws(),Fe=U(),f1=Q(),p1=rc(),h1={message:({params:{i:r,j:e}})=>(0,Fe.str)`must NOT have duplicate items (items ## ${e} and ${r} are identical)`,params:({params:{i:r,j:e}})=>(0,Fe._)`{i: ${r}, j: ${e}}`},m1={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:h1,code(r){let{gen:e,data:t,$data:n,schema:i,parentSchema:s,schemaCode:o,it:a}=r;if(!n&&!i)return;let c=e.let("valid"),l=s.items?(0,Xu.getSchemaTypes)(s.items):[];r.block$data(c,u,(0,Fe._)`${o} === false`),r.ok(c);function u(){let m=e.let("i",(0,Fe._)`${t}.length`),h=e.let("j");r.setParams({i:m,j:h}),e.assign(c,!0),e.if((0,Fe._)`${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"),g=(0,Xu.checkDataTypes)(l,y,a.opts.strictNumbers,Xu.DataType.Wrong),b=e.const("indices",(0,Fe._)`{}`);e.for((0,Fe._)`;${m}--;`,()=>{e.let(y,(0,Fe._)`${t}[${m}]`),e.if(g,(0,Fe._)`continue`),l.length>1&&e.if((0,Fe._)`typeof ${y} == "string"`,(0,Fe._)`${y} += "_"`),e.if((0,Fe._)`typeof ${b}[${y}] == "number"`,()=>{e.assign(h,(0,Fe._)`${b}[${y}]`),r.error(),e.assign(c,!1).break()}).code((0,Fe._)`${b}[${y}] = ${m}`)})}function p(m,h){let y=(0,f1.useFunc)(e,p1.default),g=e.name("outer");e.label(g).for((0,Fe._)`;${m}--;`,()=>e.for((0,Fe._)`${h} = ${m}; ${h}--;`,()=>e.if((0,Fe._)`${y}(${t}[${m}], ${t}[${h}])`,()=>{r.error(),e.assign(c,!1).break(g)})))}}};Qu.default=m1});var ob=A(ef=>{"use strict";Object.defineProperty(ef,"__esModule",{value:!0});var Zu=U(),y1=Q(),g1=rc(),b1={message:"must be equal to constant",params:({schemaCode:r})=>(0,Zu._)`{allowedValue: ${r}}`},v1={keyword:"const",$data:!0,error:b1,code(r){let{gen:e,data:t,$data:n,schemaCode:i,schema:s}=r;n||s&&typeof s=="object"?r.fail$data((0,Zu._)`!${(0,y1.useFunc)(e,g1.default)}(${t}, ${i})`):r.fail((0,Zu._)`${s} !== ${t}`)}};ef.default=v1});var ab=A(tf=>{"use strict";Object.defineProperty(tf,"__esModule",{value:!0});var lo=U(),w1=Q(),_1=rc(),S1={message:"must be equal to one of the allowed values",params:({schemaCode:r})=>(0,lo._)`{allowedValues: ${r}}`},$1={keyword:"enum",schemaType:"array",$data:!0,error:S1,code(r){let{gen:e,data:t,$data:n,schema:i,schemaCode:s,it:o}=r;if(!n&&i.length===0)throw new Error("enum must have non-empty array");let a=i.length>=o.opts.loopEnum,c,l=()=>c??(c=(0,w1.useFunc)(e,_1.default)),u;if(a||n)u=e.let("valid"),r.block$data(u,d);else{if(!Array.isArray(i))throw new Error("ajv implementation error");let p=e.const("vSchema",s);u=(0,lo.or)(...i.map((m,h)=>f(p,h)))}r.pass(u);function d(){e.assign(u,!1),e.forOf("v",s,p=>e.if((0,lo._)`${l()}(${t}, ${p})`,()=>e.assign(u,!0).break()))}function f(p,m){let h=i[m];return typeof h=="object"&&h!==null?(0,lo._)`${l()}(${t}, ${p}[${m}])`:(0,lo._)`${t} === ${h}`}}};tf.default=$1});var nf=A(rf=>{"use strict";Object.defineProperty(rf,"__esModule",{value:!0});var x1=Jg(),E1=Yg(),A1=Zg(),k1=eb(),P1=tb(),C1=rb(),M1=nb(),T1=sb(),R1=ob(),I1=ab(),O1=[x1.default,E1.default,A1.default,k1.default,P1.default,C1.default,M1.default,T1.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},R1.default,I1.default];rf.default=O1});var of=A(uo=>{"use strict";Object.defineProperty(uo,"__esModule",{value:!0});uo.validateAdditionalItems=void 0;var si=U(),sf=Q(),D1={message:({params:{len:r}})=>(0,si.str)`must NOT have more than ${r} items`,params:({params:{len:r}})=>(0,si._)`{limit: ${r}}`},N1={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:D1,code(r){let{parentSchema:e,it:t}=r,{items:n}=e;if(!Array.isArray(n)){(0,sf.checkStrictMode)(t,'"additionalItems" is ignored when "items" is not an array of schemas');return}cb(r,n)}};function cb(r,e){let{gen:t,schema:n,data:i,keyword:s,it:o}=r;o.items=!0;let a=t.const("len",(0,si._)`${i}.length`);if(n===!1)r.setParams({len:e.length}),r.pass((0,si._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,sf.alwaysValidSchema)(o,n)){let l=t.var("valid",(0,si._)`${a} <= ${e.length}`);t.if((0,si.not)(l),()=>c(l)),r.ok(l)}function c(l){t.forRange("i",e.length,a,u=>{r.subschema({keyword:s,dataProp:u,dataPropType:sf.Type.Num},l),o.allErrors||t.if((0,si.not)(l),()=>t.break())})}}uo.validateAdditionalItems=cb;uo.default=N1});var af=A(fo=>{"use strict";Object.defineProperty(fo,"__esModule",{value:!0});fo.validateTuple=void 0;var lb=U(),nc=Q(),L1=Nt(),F1={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(r){let{schema:e,it:t}=r;if(Array.isArray(e))return db(r,"additionalItems",e);t.items=!0,!(0,nc.alwaysValidSchema)(t,e)&&r.ok((0,L1.validateArray)(r))}};function db(r,e,t=r.schema){let{gen:n,parentSchema:i,data:s,keyword:o,it:a}=r;u(i),a.opts.unevaluated&&t.length&&a.items!==!0&&(a.items=nc.mergeEvaluated.items(n,t.length,a.items));let c=n.name("valid"),l=n.const("len",(0,lb._)`${s}.length`);t.forEach((d,f)=>{(0,nc.alwaysValidSchema)(a,d)||(n.if((0,lb._)`${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,nc.checkStrictMode)(a,y,f.strictTuples)}}}fo.validateTuple=db;fo.default=F1});var ub=A(cf=>{"use strict";Object.defineProperty(cf,"__esModule",{value:!0});var j1=af(),q1={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:r=>(0,j1.validateTuple)(r,"items")};cf.default=q1});var pb=A(lf=>{"use strict";Object.defineProperty(lf,"__esModule",{value:!0});var fb=U(),B1=Q(),U1=Nt(),V1=of(),H1={message:({params:{len:r}})=>(0,fb.str)`must NOT have more than ${r} items`,params:({params:{len:r}})=>(0,fb._)`{limit: ${r}}`},z1={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:H1,code(r){let{schema:e,parentSchema:t,it:n}=r,{prefixItems:i}=t;n.items=!0,!(0,B1.alwaysValidSchema)(n,e)&&(i?(0,V1.validateAdditionalItems)(r,i):r.ok((0,U1.validateArray)(r)))}};lf.default=z1});var hb=A(df=>{"use strict";Object.defineProperty(df,"__esModule",{value:!0});var Ft=U(),ic=Q(),K1={message:({params:{min:r,max:e}})=>e===void 0?(0,Ft.str)`must contain at least ${r} valid item(s)`:(0,Ft.str)`must contain at least ${r} and no more than ${e} valid item(s)`,params:({params:{min:r,max:e}})=>e===void 0?(0,Ft._)`{minContains: ${r}}`:(0,Ft._)`{minContains: ${r}, maxContains: ${e}}`},W1={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:K1,code(r){let{gen:e,schema:t,parentSchema:n,data:i,it:s}=r,o,a,{minContains:c,maxContains:l}=n;s.opts.next?(o=c===void 0?1:c,a=l):o=1;let u=e.const("len",(0,Ft._)`${i}.length`);if(r.setParams({min:o,max:a}),a===void 0&&o===0){(0,ic.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&o>a){(0,ic.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),r.fail();return}if((0,ic.alwaysValidSchema)(s,t)){let h=(0,Ft._)`${u} >= ${o}`;a!==void 0&&(h=(0,Ft._)`${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,Ft._)`${i}.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,g=>{r.subschema({keyword:"contains",dataProp:g,dataPropType:ic.Type.Num,compositeRule:!0},h),y()})}function m(h){e.code((0,Ft._)`${h}++`),a===void 0?e.if((0,Ft._)`${h} >= ${o}`,()=>e.assign(d,!0).break()):(e.if((0,Ft._)`${h} > ${a}`,()=>e.assign(d,!1).break()),o===1?e.assign(d,!0):e.if((0,Ft._)`${h} >= ${o}`,()=>e.assign(d,!0)))}}};df.default=W1});var sc=A(br=>{"use strict";Object.defineProperty(br,"__esModule",{value:!0});br.validateSchemaDeps=br.validatePropertyDeps=br.error=void 0;var uf=U(),G1=Q(),po=Nt();br.error={message:({params:{property:r,depsCount:e,deps:t}})=>{let n=e===1?"property":"properties";return(0,uf.str)`must have ${n} ${t} when property ${r} is present`},params:({params:{property:r,depsCount:e,deps:t,missingProperty:n}})=>(0,uf._)`{property: ${r}, missingProperty: ${n}, depsCount: ${e}, - deps: ${t}}`};var GC={keyword:"dependencies",type:"object",schemaType:"object",error:br.error,code(r){let[e,t]=JC(r);mb(r,e),yb(r,t)}};function JC({schema:r}){let e={},t={};for(let n in r){if(n==="__proto__")continue;let i=Array.isArray(r[n])?e:t;i[n]=r[n]}return[e,t]}function mb(r,e=r.schema){let{gen:t,data:n,it:i}=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,po.propertyInData)(t,n,o,i.opts.ownProperties);r.setParams({property:o,depsCount:a.length,deps:a.join(", ")}),i.allErrors?t.if(c,()=>{for(let l of a)(0,po.checkReportMissingProp)(r,l)}):(t.if((0,ff._)`${c} && (${(0,po.checkMissingProp)(r,a,s)})`),(0,po.reportMissingProp)(r,s),t.else())}}br.validatePropertyDeps=mb;function yb(r,e=r.schema){let{gen:t,data:n,keyword:i,it:s}=r,o=t.name("valid");for(let a in e)(0,WC.alwaysValidSchema)(s,e[a])||(t.if((0,po.propertyInData)(t,n,a,s.opts.ownProperties),()=>{let c=r.subschema({keyword:i,schemaProp:a},o);r.mergeValidEvaluated(c,o)},()=>t.var(o,!0)),r.ok(o))}br.validateSchemaDeps=yb;br.default=GC});var bb=A(pf=>{"use strict";Object.defineProperty(pf,"__esModule",{value:!0});var gb=U(),YC=Q(),XC={message:"property name must be valid",params:({params:r})=>(0,gb._)`{propertyName: ${r.propertyName}}`},QC={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:XC,code(r){let{gen:e,schema:t,data:n,it:i}=r;if((0,YC.alwaysValidSchema)(i,t))return;let s=e.name("valid");e.forIn("key",n,o=>{r.setParams({propertyName:o}),r.subschema({keyword:"propertyNames",data:o,dataTypes:["string"],propertyName:o,compositeRule:!0},s),e.if((0,gb.not)(s),()=>{r.error(!0),i.allErrors||e.break()})}),r.ok(s)}};pf.default=QC});var mf=A(hf=>{"use strict";Object.defineProperty(hf,"__esModule",{value:!0});var oc=Nt(),Xt=U(),ZC=Dt(),ac=Q(),e1={message:"must NOT have additional properties",params:({params:r})=>(0,Xt._)`{additionalProperty: ${r.additionalProperty}}`},t1={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:e1,code(r){let{gen:e,schema:t,parentSchema:n,data:i,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,ac.alwaysValidSchema)(o,t))return;let l=(0,oc.allSchemaProperties)(n.properties),u=(0,oc.allSchemaProperties)(n.patternProperties);d(),r.ok((0,Xt._)`${s} === ${ZC.default.errors}`);function d(){e.forIn("key",i,y=>{!l.length&&!u.length?h(y):e.if(f(y),()=>h(y))})}function f(y){let g;if(l.length>8){let b=(0,ac.schemaRefOrVal)(o,n.properties,"properties");g=(0,oc.isOwnProperty)(e,b,y)}else l.length?g=(0,Xt.or)(...l.map(b=>(0,Xt._)`${y} === ${b}`)):g=Xt.nil;return u.length&&(g=(0,Xt.or)(g,...u.map(b=>(0,Xt._)`${(0,oc.usePattern)(r,b)}.test(${y})`))),(0,Xt.not)(g)}function p(y){e.code((0,Xt._)`delete ${i}[${y}]`)}function h(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,ac.alwaysValidSchema)(o,t)){let g=e.name("valid");c.removeAdditional==="failing"?(m(y,g,!1),e.if((0,Xt.not)(g),()=>{r.reset(),p(y)})):(m(y,g),a||e.if((0,Xt.not)(g),()=>e.break()))}}function m(y,g,b){let v={keyword:"additionalProperties",dataProp:y,dataPropType:ac.Type.Str};b===!1&&Object.assign(v,{compositeRule:!0,createErrors:!1,allErrors:!1}),r.subschema(v,g)}}};hf.default=t1});var _b=A(gf=>{"use strict";Object.defineProperty(gf,"__esModule",{value:!0});var r1=Ni(),vb=Nt(),yf=Q(),wb=mf(),n1={keyword:"properties",type:"object",schemaType:"object",code(r){let{gen:e,schema:t,parentSchema:n,data:i,it:s}=r;s.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&wb.default.code(new r1.KeywordCxt(s,wb.default,"additionalProperties"));let o=(0,vb.allSchemaProperties)(t);for(let d of o)s.definedProperties.add(d);s.opts.unevaluated&&o.length&&s.props!==!0&&(s.props=yf.mergeEvaluated.props(e,(0,yf.toHash)(o),s.props));let a=o.filter(d=>!(0,yf.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,vb.propertyInData)(e,i,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)}}};gf.default=n1});var Eb=A(bf=>{"use strict";Object.defineProperty(bf,"__esModule",{value:!0});var Sb=Nt(),cc=U(),$b=Q(),xb=Q(),i1={keyword:"patternProperties",type:"object",schemaType:"object",code(r){let{gen:e,schema:t,data:n,parentSchema:i,it:s}=r,{opts:o}=s,a=(0,Sb.allSchemaProperties)(t),c=a.filter(m=>(0,$b.alwaysValidSchema)(s,t[m]));if(a.length===0||c.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let l=o.strictSchema&&!o.allowMatchingProperties&&i.properties,u=e.name("valid");s.props!==!0&&!(s.props instanceof cc.Name)&&(s.props=(0,xb.evaluatedPropsToName)(e,s.props));let{props:d}=s;f();function f(){for(let m of a)l&&p(m),s.allErrors?h(m):(e.var(u,!0),h(m),e.if(u))}function p(m){for(let y in l)new RegExp(m).test(y)&&(0,$b.checkStrictMode)(s,`property ${y} matches pattern ${m} (use allowMatchingProperties)`)}function h(m){e.forIn("key",n,y=>{e.if((0,cc._)`${(0,Sb.usePattern)(r,m)}.test(${y})`,()=>{let g=c.includes(m);g||r.subschema({keyword:"patternProperties",schemaProp:m,dataProp:y,dataPropType:xb.Type.Str},u),s.opts.unevaluated&&d!==!0?e.assign((0,cc._)`${d}[${y}]`,!0):!g&&!s.allErrors&&e.if((0,cc.not)(u),()=>e.break())})})}}};bf.default=i1});var Ab=A(vf=>{"use strict";Object.defineProperty(vf,"__esModule",{value:!0});var s1=Q(),o1={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(r){let{gen:e,schema:t,it:n}=r;if((0,s1.alwaysValidSchema)(n,t)){r.fail();return}let i=e.name("valid");r.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},i),r.failResult(i,()=>r.reset(),()=>r.error())},error:{message:"must NOT be valid"}};vf.default=o1});var kb=A(wf=>{"use strict";Object.defineProperty(wf,"__esModule",{value:!0});var a1=Nt(),c1={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:a1.validateUnion,error:{message:"must match a schema in anyOf"}};wf.default=c1});var Pb=A(_f=>{"use strict";Object.defineProperty(_f,"__esModule",{value:!0});var lc=U(),l1=Q(),d1={message:"must match exactly one schema in oneOf",params:({params:r})=>(0,lc._)`{passingSchemas: ${r.passing}}`},u1={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:d1,code(r){let{gen:e,schema:t,parentSchema:n,it:i}=r;if(!Array.isArray(t))throw new Error("ajv implementation error");if(i.opts.discriminator&&n.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,l1.alwaysValidSchema)(i,u)?e.var(c,!0):f=r.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,lc._)`${c} && ${o}`).assign(o,!1).assign(a,(0,lc._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(o,!0),e.assign(a,d),f&&r.mergeEvaluated(f,lc.Name)})})}}};_f.default=u1});var Cb=A(Sf=>{"use strict";Object.defineProperty(Sf,"__esModule",{value:!0});var f1=Q(),p1={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 i=e.name("valid");t.forEach((s,o)=>{if((0,f1.alwaysValidSchema)(n,s))return;let a=r.subschema({keyword:"allOf",schemaProp:o},i);r.ok(i),r.mergeEvaluated(a)})}};Sf.default=p1});var Rb=A($f=>{"use strict";Object.defineProperty($f,"__esModule",{value:!0});var dc=U(),Tb=Q(),h1={message:({params:r})=>(0,dc.str)`must match "${r.ifClause}" schema`,params:({params:r})=>(0,dc._)`{failingKeyword: ${r.ifClause}}`},m1={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:h1,code(r){let{gen:e,parentSchema:t,it:n}=r;t.then===void 0&&t.else===void 0&&(0,Tb.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let i=Mb(n,"then"),s=Mb(n,"else");if(!i&&!s)return;let o=e.let("valid",!0),a=e.name("_valid");if(c(),r.reset(),i&&s){let u=e.let("ifClause");r.setParams({ifClause:u}),e.if(a,l("then",u),l("else",u))}else i?e.if(a,l("then")):e.if((0,dc.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,dc._)`${u}`):r.setParams({ifClause:u})}}}};function Mb(r,e){let t=r.schema[e];return t!==void 0&&!(0,Tb.alwaysValidSchema)(r,t)}$f.default=m1});var Ib=A(xf=>{"use strict";Object.defineProperty(xf,"__esModule",{value:!0});var y1=Q(),g1={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:r,parentSchema:e,it:t}){e.if===void 0&&(0,y1.checkStrictMode)(t,`"${r}" without "if" is ignored`)}};xf.default=g1});var Af=A(Ef=>{"use strict";Object.defineProperty(Ef,"__esModule",{value:!0});var b1=af(),v1=ub(),w1=cf(),_1=pb(),S1=hb(),$1=sc(),x1=bb(),E1=mf(),A1=_b(),k1=Eb(),P1=Ab(),C1=kb(),M1=Pb(),T1=Cb(),R1=Rb(),I1=Ib();function O1(r=!1){let e=[P1.default,C1.default,M1.default,T1.default,R1.default,I1.default,x1.default,E1.default,$1.default,A1.default,k1.default];return r?e.push(v1.default,_1.default):e.push(b1.default,w1.default),e.push(S1.default),e}Ef.default=O1});var Pf=A(ho=>{"use strict";Object.defineProperty(ho,"__esModule",{value:!0});ho.dynamicAnchor=void 0;var kf=U(),D1=Dt(),Ob=Qs(),N1=Za(),L1={keyword:"$dynamicAnchor",schemaType:"string",code:r=>Db(r,r.schema)};function Db(r,e){let{gen:t,it:n}=r;n.schemaEnv.root.dynamicAnchors[e]=!0;let i=(0,kf._)`${D1.default.dynamicAnchors}${(0,kf.getProperty)(e)}`,s=n.errSchemaPath==="#"?n.validateName:F1(r);t.if((0,kf._)`!${i}`,()=>t.assign(i,s))}ho.dynamicAnchor=Db;function F1(r){let{schemaEnv:e,schema:t,self:n}=r.it,{root:i,baseId:s,localRefs:o,meta:a}=e.root,{schemaId:c}=n.opts,l=new Ob.SchemaEnv({schema:t,schemaId:c,root:i,baseId:s,localRefs:o,meta:a});return Ob.compileSchema.call(n,l),(0,N1.getValidate)(r,l)}ho.default=L1});var Cf=A(mo=>{"use strict";Object.defineProperty(mo,"__esModule",{value:!0});mo.dynamicRef=void 0;var Nb=U(),j1=Dt(),Lb=Za(),q1={keyword:"$dynamicRef",schemaType:"string",code:r=>Fb(r,r.schema)};function Fb(r,e){let{gen:t,keyword:n,it:i}=r;if(e[0]!=="#")throw new Error(`"${n}" only supports hash fragment reference`);let s=e.slice(1);if(i.allErrors)o();else{let c=t.let("valid",!1);o(c),r.ok(c)}function o(c){if(i.schemaEnv.root.dynamicAnchors[s]){let l=t.let("_v",(0,Nb._)`${j1.default.dynamicAnchors}${(0,Nb.getProperty)(s)}`);t.if(l,a(l,c),a(i.validateName,c))}else a(i.validateName,c)()}function a(c,l){return l?()=>t.block(()=>{(0,Lb.callRef)(r,c),t.let(l,!0)}):()=>(0,Lb.callRef)(r,c)}}mo.dynamicRef=Fb;mo.default=q1});var jb=A(Mf=>{"use strict";Object.defineProperty(Mf,"__esModule",{value:!0});var B1=Pf(),U1=Q(),V1={keyword:"$recursiveAnchor",schemaType:"boolean",code(r){r.schema?(0,B1.dynamicAnchor)(r,""):(0,U1.checkStrictMode)(r.it,"$recursiveAnchor: false is ignored")}};Mf.default=V1});var qb=A(Tf=>{"use strict";Object.defineProperty(Tf,"__esModule",{value:!0});var H1=Cf(),z1={keyword:"$recursiveRef",schemaType:"string",code:r=>(0,H1.dynamicRef)(r,r.schema)};Tf.default=z1});var Bb=A(Rf=>{"use strict";Object.defineProperty(Rf,"__esModule",{value:!0});var K1=Pf(),W1=Cf(),G1=jb(),J1=qb(),Y1=[K1.default,W1.default,G1.default,J1.default];Rf.default=Y1});var Vb=A(If=>{"use strict";Object.defineProperty(If,"__esModule",{value:!0});var Ub=sc(),X1={keyword:"dependentRequired",type:"object",schemaType:"object",error:Ub.error,code:r=>(0,Ub.validatePropertyDeps)(r)};If.default=X1});var Hb=A(Of=>{"use strict";Object.defineProperty(Of,"__esModule",{value:!0});var Q1=sc(),Z1={keyword:"dependentSchemas",type:"object",schemaType:"object",code:r=>(0,Q1.validateSchemaDeps)(r)};Of.default=Z1});var zb=A(Df=>{"use strict";Object.defineProperty(Df,"__esModule",{value:!0});var eM=Q(),tM={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword:r,parentSchema:e,it:t}){e.contains===void 0&&(0,eM.checkStrictMode)(t,`"${r}" without "contains" is ignored`)}};Df.default=tM});var Kb=A(Nf=>{"use strict";Object.defineProperty(Nf,"__esModule",{value:!0});var rM=Vb(),nM=Hb(),iM=zb(),sM=[rM.default,nM.default,iM.default];Nf.default=sM});var Gb=A(Lf=>{"use strict";Object.defineProperty(Lf,"__esModule",{value:!0});var hn=U(),Wb=Q(),oM=Dt(),aM={message:"must NOT have unevaluated properties",params:({params:r})=>(0,hn._)`{unevaluatedProperty: ${r.unevaluatedProperty}}`},cM={keyword:"unevaluatedProperties",type:"object",schemaType:["boolean","object"],trackErrors:!0,error:aM,code(r){let{gen:e,schema:t,data:n,errsCount:i,it:s}=r;if(!i)throw new Error("ajv implementation error");let{allErrors:o,props:a}=s;a instanceof hn.Name?e.if((0,hn._)`${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))),s.props=!0,r.ok((0,hn._)`${i} === ${oM.default.errors}`);function c(d){if(t===!1){r.setParams({unevaluatedProperty:d}),r.error(),o||e.break();return}if(!(0,Wb.alwaysValidSchema)(s,t)){let f=e.name("valid");r.subschema({keyword:"unevaluatedProperties",dataProp:d,dataPropType:Wb.Type.Str},f),o||e.if((0,hn.not)(f),()=>e.break())}}function l(d,f){return(0,hn._)`!${d} || !${d}[${f}]`}function u(d,f){let p=[];for(let h in d)d[h]===!0&&p.push((0,hn._)`${f} !== ${h}`);return(0,hn.and)(...p)}}};Lf.default=cM});var Yb=A(Ff=>{"use strict";Object.defineProperty(Ff,"__esModule",{value:!0});var oi=U(),Jb=Q(),lM={message:({params:{len:r}})=>(0,oi.str)`must NOT have more than ${r} items`,params:({params:{len:r}})=>(0,oi._)`{limit: ${r}}`},dM={keyword:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error:lM,code(r){let{gen:e,schema:t,data:n,it:i}=r,s=i.items||0;if(s===!0)return;let o=e.const("len",(0,oi._)`${n}.length`);if(t===!1)r.setParams({len:s}),r.fail((0,oi._)`${o} > ${s}`);else if(typeof t=="object"&&!(0,Jb.alwaysValidSchema)(i,t)){let c=e.var("valid",(0,oi._)`${o} <= ${s}`);e.if((0,oi.not)(c),()=>a(c,s)),r.ok(c)}i.items=!0;function a(c,l){e.forRange("i",l,o,u=>{r.subschema({keyword:"unevaluatedItems",dataProp:u,dataPropType:Jb.Type.Num},c),i.allErrors||e.if((0,oi.not)(c),()=>e.break())})}}};Ff.default=dM});var Xb=A(jf=>{"use strict";Object.defineProperty(jf,"__esModule",{value:!0});var uM=Gb(),fM=Yb(),pM=[uM.default,fM.default];jf.default=pM});var Qb=A(qf=>{"use strict";Object.defineProperty(qf,"__esModule",{value:!0});var $e=U(),hM={message:({schemaCode:r})=>(0,$e.str)`must match format "${r}"`,params:({schemaCode:r})=>(0,$e._)`{format: ${r}}`},mM={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:hM,code(r,e){let{gen:t,data:n,$data:i,schema:s,schemaCode:o,it:a}=r,{opts:c,errSchemaPath:l,schemaEnv:u,self:d}=a;if(!c.validateFormats)return;i?f():p();function f(){let h=t.scopeValue("formats",{ref:d.formats,code:c.code.formats}),m=t.const("fDef",(0,$e._)`${h}[${o}]`),y=t.let("fType"),g=t.let("format");t.if((0,$e._)`typeof ${m} == "object" && !(${m} instanceof RegExp)`,()=>t.assign(y,(0,$e._)`${m}.type || "string"`).assign(g,(0,$e._)`${m}.validate`),()=>t.assign(y,(0,$e._)`"string"`).assign(g,m)),r.fail$data((0,$e.or)(b(),v()));function b(){return c.strictSchema===!1?$e.nil:(0,$e._)`${o} && !${g}`}function v(){let S=u.$async?(0,$e._)`(${m}.async ? await ${g}(${n}) : ${g}(${n}))`:(0,$e._)`${g}(${n})`,_=(0,$e._)`(typeof ${g} == "function" ? ${S} : ${g}.test(${n}))`;return(0,$e._)`${g} && ${g} !== true && ${y} === ${e} && !${_}`}}function p(){let h=d.formats[s];if(!h){b();return}if(h===!0)return;let[m,y,g]=v(h);m===e&&r.pass(S());function b(){if(c.strictSchema===!1){d.logger.warn(_());return}throw new Error(_());function _(){return`unknown format "${s}" ignored in schema at path "${l}"`}}function v(_){let E=_ instanceof RegExp?(0,$e.regexpCode)(_):c.code.formats?(0,$e._)`${c.code.formats}${(0,$e.getProperty)(s)}`:void 0,k=t.scopeValue("formats",{key:s,ref:_,code:E});return typeof _=="object"&&!(_ instanceof RegExp)?[_.type||"string",_.validate,(0,$e._)`${k}.validate`]:["string",_,k]}function S(){if(typeof h=="object"&&!(h instanceof RegExp)&&h.async){if(!u.$async)throw new Error("async format in sync schema");return(0,$e._)`await ${g}(${n})`}return typeof y=="function"?(0,$e._)`${g}(${n})`:(0,$e._)`${g}.test(${n})`}}}};qf.default=mM});var Uf=A(Bf=>{"use strict";Object.defineProperty(Bf,"__esModule",{value:!0});var yM=Qb(),gM=[yM.default];Bf.default=gM});var Vf=A(Ui=>{"use strict";Object.defineProperty(Ui,"__esModule",{value:!0});Ui.contentVocabulary=Ui.metadataVocabulary=void 0;Ui.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Ui.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var ev=A(Hf=>{"use strict";Object.defineProperty(Hf,"__esModule",{value:!0});var bM=Uu(),vM=sf(),wM=Af(),_M=Bb(),SM=Kb(),$M=Xb(),xM=Uf(),Zb=Vf(),EM=[_M.default,bM.default,vM.default,(0,wM.default)(!0),xM.default,Zb.metadataVocabulary,Zb.contentVocabulary,SM.default,$M.default];Hf.default=EM});var rv=A(uc=>{"use strict";Object.defineProperty(uc,"__esModule",{value:!0});uc.DiscrError=void 0;var tv;(function(r){r.Tag="tag",r.Mapping="mapping"})(tv||(uc.DiscrError=tv={}))});var Wf=A(Kf=>{"use strict";Object.defineProperty(Kf,"__esModule",{value:!0});var Vi=U(),zf=rv(),nv=Qs(),AM=Li(),kM=Q(),PM={message:({params:{discrError:r,tagName:e}})=>r===zf.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:r,tag:e,tagName:t}})=>(0,Vi._)`{error: ${r}, tag: ${t}, tagValue: ${e}}`},CM={keyword:"discriminator",type:"object",schemaType:"object",error:PM,code(r){let{gen:e,data:t,schema:n,parentSchema:i,it:s}=r,{oneOf:o}=i;if(!s.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,Vi._)`${t}${(0,Vi.getProperty)(a)}`);e.if((0,Vi._)`typeof ${l} == "string"`,()=>u(),()=>r.error(!1,{discrError:zf.DiscrError.Tag,tag:l,tagName:a})),r.ok(c);function u(){let p=f();e.if(!1);for(let h in p)e.elseIf((0,Vi._)`${l} === ${h}`),e.assign(c,d(p[h]));e.else(),r.error(!1,{discrError:zf.DiscrError.Mapping,tag:l,tagName:a}),e.endIf()}function d(p){let h=e.name("valid"),m=r.subschema({keyword:"oneOf",schemaProp:p},h);return r.mergeEvaluated(m,Vi.Name),h}function f(){var p;let h={},m=g(i),y=!0;for(let S=0;S{MM.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 sv=A((Bq,TM)=>{TM.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 ov=A((Uq,RM)=>{RM.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 av=A((Vq,IM)=>{IM.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 cv=A((Hq,OM)=>{OM.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 lv=A((zq,DM)=>{DM.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 dv=A((Kq,NM)=>{NM.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 uv=A((Wq,LM)=>{LM.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 fv=A(Gf=>{"use strict";Object.defineProperty(Gf,"__esModule",{value:!0});var FM=iv(),jM=sv(),qM=ov(),BM=av(),UM=cv(),VM=lv(),HM=dv(),zM=uv(),KM=["/properties"];function WM(r){return[FM,jM,qM,BM,UM,e(this,VM),HM,e(this,zM)].forEach(t=>this.addMetaSchema(t,void 0,!1)),this;function e(t,n){return r?t.$dataMetaSchema(n,KM):n}}Gf.default=WM});var Xf=A((ye,Yf)=>{"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.Ajv2020=void 0;var GM=ju(),JM=ev(),YM=Wf(),XM=fv(),Jf="https://json-schema.org/draft/2020-12/schema",Hi=class extends GM.default{constructor(e={}){super({...e,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){super._addVocabularies(),JM.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(YM.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data:e,meta:t}=this.opts;t&&(XM.default.call(this,e),this.refs["http://json-schema.org/schema"]=Jf)}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Jf)?Jf:void 0)}};ye.Ajv2020=Hi;Yf.exports=ye=Hi;Yf.exports.Ajv2020=Hi;Object.defineProperty(ye,"__esModule",{value:!0});ye.default=Hi;var QM=Ni();Object.defineProperty(ye,"KeywordCxt",{enumerable:!0,get:function(){return QM.KeywordCxt}});var zi=U();Object.defineProperty(ye,"_",{enumerable:!0,get:function(){return zi._}});Object.defineProperty(ye,"str",{enumerable:!0,get:function(){return zi.str}});Object.defineProperty(ye,"stringify",{enumerable:!0,get:function(){return zi.stringify}});Object.defineProperty(ye,"nil",{enumerable:!0,get:function(){return zi.nil}});Object.defineProperty(ye,"Name",{enumerable:!0,get:function(){return zi.Name}});Object.defineProperty(ye,"CodeGen",{enumerable:!0,get:function(){return zi.CodeGen}});var ZM=Xs();Object.defineProperty(ye,"ValidationError",{enumerable:!0,get:function(){return ZM.default}});var eT=Li();Object.defineProperty(ye,"MissingRefError",{enumerable:!0,get:function(){return eT.default}})});var wv=A(wr=>{"use strict";Object.defineProperty(wr,"__esModule",{value:!0});wr.formatNames=wr.fastFormats=wr.fullFormats=void 0;function vr(r,e){return{validate:r,compare:e}}wr.fullFormats={date:vr(yv,tp),time:vr(Zf(!0),rp),"date-time":vr(pv(!0),bv),"iso-time":vr(Zf(),gv),"iso-date-time":vr(pv(),vv),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:oT,"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:pT,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:aT,int32:{type:"number",validate:dT},int64:{type:"number",validate:uT},float:{type:"number",validate:mv},double:{type:"number",validate:mv},password:!0,binary:!0};wr.fastFormats={...wr.fullFormats,date:vr(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,tp),time:vr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,rp),"date-time":vr(/^\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,bv),"iso-time":vr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,gv),"iso-date-time":vr(/^\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,vv),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};wr.formatNames=Object.keys(wr.fullFormats);function tT(r){return r%4===0&&(r%100!==0||r%400===0)}var rT=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,nT=[0,31,28,31,30,31,30,31,31,30,31,30,31];function yv(r){let e=rT.exec(r);if(!e)return!1;let t=+e[1],n=+e[2],i=+e[3];return n>=1&&n<=12&&i>=1&&i<=(n===2&&tT(t)?29:nT[n])}function tp(r,e){if(r&&e)return r>e?1:r23||u>59||r&&!a)return!1;if(i<=23&&s<=59&&o<60)return!0;let d=s-u*c,f=i-l*c-(d<0?1:0);return(f===23||f===-1)&&(d===59||d===-1)&&o<61}}function rp(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 gv(r,e){if(!(r&&e))return;let t=Qf.exec(r),n=Qf.exec(e);if(t&&n)return r=t[1]+t[2]+t[3],e=n[1]+n[2]+n[3],r>e?1:r=cT}function uT(r){return Number.isInteger(r)}function mv(){return!0}var fT=/[^\\]\\Z/;function pT(r){if(fT.test(r))return!1;try{return new RegExp(r),!0}catch{return!1}}});var Sv=A(np=>{"use strict";Object.defineProperty(np,"__esModule",{value:!0});var hT=Uu(),mT=sf(),yT=Af(),gT=Uf(),_v=Vf(),bT=[hT.default,mT.default,(0,yT.default)(),gT.default,_v.metadataVocabulary,_v.contentVocabulary];np.default=bT});var $v=A((Xq,vT)=>{vT.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 Ev=A((ge,ip)=>{"use strict";Object.defineProperty(ge,"__esModule",{value:!0});ge.MissingRefError=ge.ValidationError=ge.CodeGen=ge.Name=ge.nil=ge.stringify=ge.str=ge._=ge.KeywordCxt=ge.Ajv=void 0;var wT=ju(),_T=Sv(),ST=Wf(),xv=$v(),$T=["/properties"],fc="http://json-schema.org/draft-07/schema",Ki=class extends wT.default{_addVocabularies(){super._addVocabularies(),_T.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(ST.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(xv,$T):xv;this.addMetaSchema(e,fc,!1),this.refs["http://json-schema.org/schema"]=fc}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(fc)?fc:void 0)}};ge.Ajv=Ki;ip.exports=ge=Ki;ip.exports.Ajv=Ki;Object.defineProperty(ge,"__esModule",{value:!0});ge.default=Ki;var xT=Ni();Object.defineProperty(ge,"KeywordCxt",{enumerable:!0,get:function(){return xT.KeywordCxt}});var Wi=U();Object.defineProperty(ge,"_",{enumerable:!0,get:function(){return Wi._}});Object.defineProperty(ge,"str",{enumerable:!0,get:function(){return Wi.str}});Object.defineProperty(ge,"stringify",{enumerable:!0,get:function(){return Wi.stringify}});Object.defineProperty(ge,"nil",{enumerable:!0,get:function(){return Wi.nil}});Object.defineProperty(ge,"Name",{enumerable:!0,get:function(){return Wi.Name}});Object.defineProperty(ge,"CodeGen",{enumerable:!0,get:function(){return Wi.CodeGen}});var ET=Xs();Object.defineProperty(ge,"ValidationError",{enumerable:!0,get:function(){return ET.default}});var AT=Li();Object.defineProperty(ge,"MissingRefError",{enumerable:!0,get:function(){return AT.default}})});var Av=A(Gi=>{"use strict";Object.defineProperty(Gi,"__esModule",{value:!0});Gi.formatLimitDefinition=void 0;var kT=Ev(),Qt=U(),mn=Qt.operators,pc={formatMaximum:{okStr:"<=",ok:mn.LTE,fail:mn.GT},formatMinimum:{okStr:">=",ok:mn.GTE,fail:mn.LT},formatExclusiveMaximum:{okStr:"<",ok:mn.LT,fail:mn.GTE},formatExclusiveMinimum:{okStr:">",ok:mn.GT,fail:mn.LTE}},PT={message:({keyword:r,schemaCode:e})=>(0,Qt.str)`should be ${pc[r].okStr} ${e}`,params:({keyword:r,schemaCode:e})=>(0,Qt._)`{comparison: ${pc[r].okStr}, limit: ${e}}`};Gi.formatLimitDefinition={keyword:Object.keys(pc),type:"string",schemaType:"string",$data:!0,error:PT,code(r){let{gen:e,data:t,schemaCode:n,keyword:i,it:s}=r,{opts:o,self:a}=s;if(!o.validateFormats)return;let c=new kT.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,Qt._)`${f}[${c.schemaCode}]`);r.fail$data((0,Qt.or)((0,Qt._)`typeof ${p} != "object"`,(0,Qt._)`${p} instanceof RegExp`,(0,Qt._)`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(`"${i}": format "${f}" does not define "compare" function`);let h=e.scopeValue("formats",{key:f,ref:p,code:o.code.formats?(0,Qt._)`${o.code.formats}${(0,Qt.getProperty)(f)}`:void 0});r.fail$data(d(h))}function d(f){return(0,Qt._)`${f}.compare(${t}, ${n}) ${pc[i].fail} 0`}},dependencies:["format"]};var CT=r=>(r.addKeyword(Gi.formatLimitDefinition),r);Gi.default=CT});var ap=A((yo,Cv)=>{"use strict";Object.defineProperty(yo,"__esModule",{value:!0});var Ji=wv(),MT=Av(),sp=U(),kv=new sp.Name("fullFormats"),TT=new sp.Name("fastFormats"),op=(r,e={keywords:!0})=>{if(Array.isArray(e))return Pv(r,e,Ji.fullFormats,kv),r;let[t,n]=e.mode==="fast"?[Ji.fastFormats,TT]:[Ji.fullFormats,kv],i=e.formats||Ji.formatNames;return Pv(r,i,t,n),e.keywords&&(0,MT.default)(r),r};op.get=(r,e="full")=>{let n=(e==="fast"?Ji.fastFormats:Ji.fullFormats)[r];if(!n)throw new Error(`Unknown format "${r}"`);return n};function Pv(r,e,t,n){var i,s;(i=(s=r.opts.code).formats)!==null&&i!==void 0||(s.formats=(0,sp._)`require("ajv-formats/dist/formats").${n}`);for(let o of e)r.addFormat(o,t[o])}Cv.exports=yo=op;Object.defineProperty(yo,"__esModule",{value:!0});yo.default=op});var go=A((Zq,Ov)=>{"use strict";var Mv="[^\\\\/]",RT="(?=.)",Tv="[^/]",cp="(?:\\/|$)",Rv="(?:^|\\/)",lp=`\\.{1,2}${cp}`,IT="(?!\\.)",OT=`(?!${Rv}${lp})`,DT=`(?!\\.{0,1}${cp})`,NT=`(?!${lp})`,LT="[^.\\/]",FT=`${Tv}*?`,jT="/",Iv={DOT_LITERAL:"\\.",PLUS_LITERAL:"\\+",QMARK_LITERAL:"\\?",SLASH_LITERAL:"\\/",ONE_CHAR:RT,QMARK:Tv,END_ANCHOR:cp,DOTS_SLASH:lp,NO_DOT:IT,NO_DOTS:OT,NO_DOT_SLASH:DT,NO_DOTS_SLASH:NT,QMARK_NO_DOT:LT,STAR:FT,START_ANCHOR:Rv,SEP:jT},qT={...Iv,SLASH_LITERAL:"[\\\\/]",QMARK:Mv,STAR:`${Mv}*?`,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:"\\"},BT={__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"};Ov.exports={DEFAULT_MAX_EXTGLOB_RECURSION:0,MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:BT,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?qT:Iv}}});var bo=A(ht=>{"use strict";var{REGEX_BACKSLASH:UT,REGEX_REMOVE_BACKSLASH:VT,REGEX_SPECIAL_CHARS:HT,REGEX_SPECIAL_CHARS_GLOBAL:zT}=go();ht.isObject=r=>r!==null&&typeof r=="object"&&!Array.isArray(r);ht.hasRegexChars=r=>HT.test(r);ht.isRegexChar=r=>r.length===1&&ht.hasRegexChars(r);ht.escapeRegex=r=>r.replace(zT,"\\$1");ht.toPosixSlashes=r=>r.replace(UT,"/");ht.isWindows=()=>{if(typeof navigator<"u"&&navigator.platform){let r=navigator.platform.toLowerCase();return r==="win32"||r==="windows"}return typeof process<"u"&&process.platform?process.platform==="win32":!1};ht.removeBackslashes=r=>r.replace(VT,e=>e==="\\"?"":e);ht.escapeLast=(r,e,t)=>{let n=r.lastIndexOf(e,t);return n===-1?r:r[n-1]==="\\"?ht.escapeLast(r,e,n-1):`${r.slice(0,n)}\\${r.slice(n)}`};ht.removePrefix=(r,e={})=>{let t=r;return t.startsWith("./")&&(t=t.slice(2),e.prefix="./"),t};ht.wrapOutput=(r,e={},t={})=>{let n=t.contains?"":"^",i=t.contains?"":"$",s=`${n}(?:${r})${i}`;return e.negated===!0&&(s=`(?:^(?!${s}).*$)`),s};ht.basename=(r,{windows:e}={})=>{let t=r.split(e?/[\\/]/:"/"),n=t[t.length-1];return n===""?t[t.length-2]:n}});var Uv=A((tB,Bv)=>{"use strict";var Dv=bo(),{CHAR_ASTERISK:dp,CHAR_AT:KT,CHAR_BACKWARD_SLASH:Yi,CHAR_COMMA:WT,CHAR_DOT:up,CHAR_EXCLAMATION_MARK:fp,CHAR_FORWARD_SLASH:qv,CHAR_LEFT_CURLY_BRACE:pp,CHAR_LEFT_PARENTHESES:hc,CHAR_LEFT_SQUARE_BRACKET:GT,CHAR_PLUS:JT,CHAR_QUESTION_MARK:Nv,CHAR_RIGHT_CURLY_BRACE:YT,CHAR_RIGHT_PARENTHESES:Lv,CHAR_RIGHT_SQUARE_BRACKET:XT}=go(),Fv=r=>r===qv||r===Yi,jv=r=>{r.isPrefix!==!0&&(r.depth=r.isGlobstar?1/0:1)},QT=(r,e)=>{let t=e||{},n=r.length-1,i=t.parts===!0||t.tokens===!0||t.scanToEnd===!0,s=[],o=[],a=[],c=r,l=-1,u=0,d=0,f=!1,p=!1,h=!1,m=!1,y=!1,g=!1,b=!1,v=!1,S=!1,_=!1,E=0,k,$,M={value:"",depth:0,isGlob:!1},x=()=>l>=n,q=()=>c.charCodeAt(l+1),T=()=>(k=$,c.charCodeAt(++l));for(;l0&&(P=c.slice(0,u),c=c.slice(u),d-=u),V&&h===!0&&d>0?(V=c.slice(0,d),C=c.slice(d)):h===!0?(V="",C=c):V=c,V&&V!==""&&V!=="/"&&V!==c&&Fv(V.charCodeAt(V.length-1))&&(V=V.slice(0,-1)),t.unescape===!0&&(C&&(C=Dv.removeBackslashes(C)),V&&b===!0&&(V=Dv.removeBackslashes(V)));let Be={prefix:P,input:r,start:u,base:V,glob:C,isBrace:f,isBracket:p,isGlob:h,isExtglob:m,isGlobstar:y,negated:v,negatedExtglob:S};if(t.tokens===!0&&(Be.maxDepth=0,Fv($)||o.push(M),Be.tokens=o),t.parts===!0||t.tokens===!0){let ce;for(let ke=0;ke=u&&(a.push(Hn),ce=Ns)}let ct=ce!==void 0?ce+1:u,xt=r.slice(ct);a.push(xt),t.tokens&&ce&&ce+1{"use strict";var vo=go(),Et=bo(),{MAX_LENGTH:mc,POSIX_REGEX_SOURCE:ZT,REGEX_NON_SPECIAL_CHARS:eR,REGEX_SPECIAL_CHARS_BACKREF:tR,REPLACEMENTS:Vv}=vo,rR=(r,e)=>{if(typeof e.expandRange=="function")return e.expandRange(...r,e);r.sort();let t=`[${r.join("-")}]`;try{new RegExp(t)}catch{return r.map(i=>Et.escapeRegex(i)).join("..")}return t},Xi=(r,e)=>`Missing ${r}: "${e}" - use "\\\\${e}" to match literal characters`,Hv=r=>{let e=[],t=0,n=0,i=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==='"'){i=i===1?0:1,s+=a;continue}if(i===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(s),s="";continue}}}s+=a}return e.push(s),e},nR=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},mp=r=>{let e=r.trim(),t=!0;for(;t===!0;)t=!1,/^@\([^\\()[\]{}|]+\)$/.test(e)&&(e=e.slice(2,-1),t=!0);if(nR(e))return e.replace(/\\(.)/g,"$1")},iR=r=>{let e=r.map(mp).filter(Boolean);for(let t=0;t{if(r[0]!=="+"&&r[0]!=="*"||r[1]!=="(")return;let t=0,n=0,i=0,s=!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}}}}},sR=r=>`${r.length===1?Et.escapeRegex(r[0]):`[${r.map(t=>Et.escapeRegex(t)).join("")}]`}*`,oR=r=>{let e=0,t=[];for(;eo.trim());if(i.length!==1)return;let s=mp(i[0]);if(!s||s.length!==1)return;t.push(s),e+=n.end+1}if(!(t.length<1))return t},aR=r=>{let e=0,t=r.trim(),n=hp(t);for(;n;)e++,t=n.body.trim(),n=hp(t);return e},cR=(r,e)=>{if(e.maxExtglobRecursion===!1)return{risky:!1};let t=typeof e.maxExtglobRecursion=="number"?e.maxExtglobRecursion:vo.DEFAULT_MAX_EXTGLOB_RECURSION,n=Hv(r).map(a=>a.trim());if(n.length>1&&(n.some(a=>a==="")||n.some(a=>/^[*?]+$/.test(a))||iR(n)))return{risky:!0};let i=[],s=!1,o=!0;for(let a of n){let c=oR(a);if(c){s=!0,i.push(...c);continue}let l=mp(a);if(l&&l.length===1){i.push(l);continue}if(o=!1,aR(a)>t)return{risky:!0}}return s?o?{risky:!0,safeOutput:sR([...new Set(i)])}:{risky:!0}:{risky:!1}},yp=(r,e)=>{if(typeof r!="string")throw new TypeError("Expected a string");r=Vv[r]||r;let t={...e},n=typeof t.maxLength=="number"?Math.min(mc,t.maxLength):mc,i=r.length;if(i>n)throw new SyntaxError(`Input length: ${i}, exceeds maximum allowed length: ${n}`);let s={type:"bos",value:"",output:t.prepend||""},o=[s],a=t.capture?"":"?:",c=vo.globChars(t.windows),l=vo.extglobChars(c),{DOT_LITERAL:u,PLUS_LITERAL:d,SLASH_LITERAL:f,ONE_CHAR:p,DOTS_SLASH:h,NO_DOT:m,NO_DOT_SLASH:y,NO_DOTS_SLASH:g,QMARK:b,QMARK_NO_DOT:v,STAR:S,START_ANCHOR:_}=c,E=I=>`(${a}(?:(?!${_}${I.dot?h:u}).)*?)`,k=t.dot?"":m,$=t.dot?b:v,M=t.bash===!0?E(t):S;t.capture&&(M=`(${M})`),typeof t.noext=="boolean"&&(t.noextglob=t.noext);let x={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=Et.removePrefix(r,x),i=r.length;let q=[],T=[],V=[],P=s,C,Be=()=>x.index===i-1,ce=x.peek=(I=1)=>r[x.index+I],ct=x.advance=()=>r[++x.index]||"",xt=()=>r.slice(x.index+1),ke=(I="",ve=0)=>{x.consumed+=I,x.index+=ve},Ai=I=>{x.output+=I.output!=null?I.output:I.value,ke(I.value)},Ns=()=>{let I=1;for(;ce()==="!"&&(ce(2)!=="("||ce(3)==="?");)ct(),x.start++,I++;return I%2===0?!1:(x.negated=!0,x.start++,!0)},Hn=I=>{x[I]++,V.push(I)},on=I=>{x[I]--,V.pop()},Z=I=>{if(P.type==="globstar"){let ve=x.braces>0&&(I.type==="comma"||I.type==="brace"),R=I.extglob===!0||q.length&&(I.type==="pipe"||I.type==="paren");I.type!=="slash"&&I.type!=="paren"&&!ve&&!R&&(x.output=x.output.slice(0,-P.output.length),P.type="star",P.value="*",P.output=M,x.output+=P.output)}if(q.length&&I.type!=="paren"&&(q[q.length-1].inner+=I.value),(I.value||I.output)&&Ai(I),P&&P.type==="text"&&I.type==="text"){P.output=(P.output||P.value)+I.value,P.value+=I.value;return}I.prev=P,o.push(I),P=I},ka=(I,ve)=>{let R={...l[ve],conditions:1,inner:""};R.prev=P,R.parens=x.parens,R.output=x.output,R.startIndex=x.index,R.tokensIndex=o.length;let ee=(t.capture?"(":"")+R.open;Hn("parens"),Z({type:I,value:ve,output:x.output?"":p}),Z({type:"paren",extglob:!0,value:ct(),output:ee}),q.push(R)},Xx=I=>{let ve=r.slice(I.startIndex,x.index+1),R=r.slice(I.startIndex+2,x.index),ee=cR(R,t);if((I.type==="plus"||I.type==="star")&&ee.risky){let ue=ee.safeOutput?(I.output?"":p)+(t.capture?`(${ee.safeOutput})`:ee.safeOutput):void 0,hr=o[I.tokensIndex];hr.type="text",hr.value=ve,hr.output=ue||Et.escapeRegex(ve);for(let zn=I.tokensIndex+1;zn1&&I.inner.includes("/")&&(ue=E(t)),(ue!==M||Be()||/^\)+$/.test(xt()))&&(he=I.close=`)$))${ue}`),I.inner.includes("*")&&(Pe=xt())&&/^\.[^\\/.]+$/.test(Pe)){let hr=yp(Pe,{...e,fastpaths:!1}).output;he=I.close=`)${hr})${ue})`}I.prev.type==="bos"&&(x.negatedExtglob=!0)}Z({type:"paren",extglob:!0,value:C,output:he}),on("parens")};if(t.fastpaths!==!1&&!/(^[*!]|[/()[\]{}"])/.test(r)){let I=!1,ve=r.replace(tR,(R,ee,he,Pe,ue,hr)=>Pe==="\\"?(I=!0,R):Pe==="?"?ee?ee+Pe+(ue?b.repeat(ue.length):""):hr===0?$+(ue?b.repeat(ue.length):""):b.repeat(he.length):Pe==="."?u.repeat(he.length):Pe==="*"?ee?ee+Pe+(ue?M:""):M:ee?R:`\\${R}`);return I===!0&&(t.unescape===!0?ve=ve.replace(/\\/g,""):ve=ve.replace(/\\+/g,R=>R.length%2===0?"\\\\":R?"\\":"")),ve===r&&t.contains===!0?(x.output=r,x):(x.output=Et.wrapOutput(ve,x,e),x)}for(;!Be();){if(C=ct(),C==="\0")continue;if(C==="\\"){let R=ce();if(R==="/"&&t.bash!==!0||R==="."||R===";")continue;if(!R){C+="\\",Z({type:"text",value:C});continue}let ee=/^\\+/.exec(xt()),he=0;if(ee&&ee[0].length>2&&(he=ee[0].length,x.index+=he,he%2!==0&&(C+="\\")),t.unescape===!0?C=ct():C+=ct(),x.brackets===0){Z({type:"text",value:C});continue}}if(x.brackets>0&&(C!=="]"||P.value==="["||P.value==="[^")){if(t.posix!==!1&&C===":"){let R=P.value.slice(1);if(R.includes("[")&&(P.posix=!0,R.includes(":"))){let ee=P.value.lastIndexOf("["),he=P.value.slice(0,ee),Pe=P.value.slice(ee+2),ue=ZT[Pe];if(ue){P.value=he+ue,x.backtrack=!0,ct(),!s.output&&o.indexOf(P)===1&&(s.output=p);continue}}}(C==="["&&ce()!==":"||C==="-"&&ce()==="]")&&(C=`\\${C}`),C==="]"&&(P.value==="["||P.value==="[^")&&(C=`\\${C}`),t.posix===!0&&C==="!"&&P.value==="["&&(C="^"),P.value+=C,Ai({value:C});continue}if(x.quotes===1&&C!=='"'){C=Et.escapeRegex(C),P.value+=C,Ai({value:C});continue}if(C==='"'){x.quotes=x.quotes===1?0:1,t.keepQuotes===!0&&Z({type:"text",value:C});continue}if(C==="("){Hn("parens"),Z({type:"paren",value:C});continue}if(C===")"){if(x.parens===0&&t.strictBrackets===!0)throw new SyntaxError(Xi("opening","("));let R=q[q.length-1];if(R&&x.parens===R.parens+1){Xx(q.pop());continue}Z({type:"paren",value:C,output:x.parens?")":"\\)"}),on("parens");continue}if(C==="["){if(t.nobracket===!0||!xt().includes("]")){if(t.nobracket!==!0&&t.strictBrackets===!0)throw new SyntaxError(Xi("closing","]"));C=`\\${C}`}else Hn("brackets");Z({type:"bracket",value:C});continue}if(C==="]"){if(t.nobracket===!0||P&&P.type==="bracket"&&P.value.length===1){Z({type:"text",value:C,output:`\\${C}`});continue}if(x.brackets===0){if(t.strictBrackets===!0)throw new SyntaxError(Xi("opening","["));Z({type:"text",value:C,output:`\\${C}`});continue}on("brackets");let R=P.value.slice(1);if(P.posix!==!0&&R[0]==="^"&&!R.includes("/")&&(C=`/${C}`),P.value+=C,Ai({value:C}),t.literalBrackets===!1||Et.hasRegexChars(R))continue;let ee=Et.escapeRegex(P.value);if(x.output=x.output.slice(0,-P.value.length),t.literalBrackets===!0){x.output+=ee,P.value=ee;continue}P.value=`(${a}${ee}|${P.value})`,x.output+=P.value;continue}if(C==="{"&&t.nobrace!==!0){Hn("braces");let R={type:"brace",value:C,output:"(",outputIndex:x.output.length,tokensIndex:x.tokens.length};T.push(R),Z(R);continue}if(C==="}"){let R=T[T.length-1];if(t.nobrace===!0||!R){Z({type:"text",value:C,output:C});continue}let ee=")";if(R.dots===!0){let he=o.slice(),Pe=[];for(let ue=he.length-1;ue>=0&&(o.pop(),he[ue].type!=="brace");ue--)he[ue].type!=="dots"&&Pe.unshift(he[ue].value);ee=rR(Pe,t),x.backtrack=!0}if(R.comma!==!0&&R.dots!==!0){let he=x.output.slice(0,R.outputIndex),Pe=x.tokens.slice(R.tokensIndex);R.value=R.output="\\{",C=ee="\\}",x.output=he;for(let ue of Pe)x.output+=ue.output||ue.value}Z({type:"brace",value:C,output:ee}),on("braces"),T.pop();continue}if(C==="|"){q.length>0&&q[q.length-1].conditions++,Z({type:"text",value:C});continue}if(C===","){let R=C,ee=T[T.length-1];ee&&V[V.length-1]==="braces"&&(ee.comma=!0,R="|"),Z({type:"comma",value:C,output:R});continue}if(C==="/"){if(P.type==="dot"&&x.index===x.start+1){x.start=x.index+1,x.consumed="",x.output="",o.pop(),P=s;continue}Z({type:"slash",value:C,output:f});continue}if(C==="."){if(x.braces>0&&P.type==="dot"){P.value==="."&&(P.output=u);let R=T[T.length-1];P.type="dots",P.output+=C,P.value+=C,R.dots=!0;continue}if(x.braces+x.parens===0&&P.type!=="bos"&&P.type!=="slash"){Z({type:"text",value:C,output:u});continue}Z({type:"dot",value:C,output:u});continue}if(C==="?"){if(!(P&&P.value==="(")&&t.noextglob!==!0&&ce()==="("&&ce(2)!=="?"){ka("qmark",C);continue}if(P&&P.type==="paren"){let ee=ce(),he=C;(P.value==="("&&!/[!=<:]/.test(ee)||ee==="<"&&!/<([!=]|\w+>)/.test(xt()))&&(he=`\\${C}`),Z({type:"text",value:C,output:he});continue}if(t.dot!==!0&&(P.type==="slash"||P.type==="bos")){Z({type:"qmark",value:C,output:v});continue}Z({type:"qmark",value:C,output:b});continue}if(C==="!"){if(t.noextglob!==!0&&ce()==="("&&(ce(2)!=="?"||!/[!=<:]/.test(ce(3)))){ka("negate",C);continue}if(t.nonegate!==!0&&x.index===0){Ns();continue}}if(C==="+"){if(t.noextglob!==!0&&ce()==="("&&ce(2)!=="?"){ka("plus",C);continue}if(P&&P.value==="("||t.regex===!1){Z({type:"plus",value:C,output:d});continue}if(P&&(P.type==="bracket"||P.type==="paren"||P.type==="brace")||x.parens>0){Z({type:"plus",value:C});continue}Z({type:"plus",value:d});continue}if(C==="@"){if(t.noextglob!==!0&&ce()==="("&&ce(2)!=="?"){Z({type:"at",extglob:!0,value:C,output:""});continue}Z({type:"text",value:C});continue}if(C!=="*"){(C==="$"||C==="^")&&(C=`\\${C}`);let R=eR.exec(xt());R&&(C+=R[0],x.index+=R[0].length),Z({type:"text",value:C});continue}if(P&&(P.type==="globstar"||P.star===!0)){P.type="star",P.star=!0,P.value+=C,P.output=M,x.backtrack=!0,x.globstar=!0,ke(C);continue}let I=xt();if(t.noextglob!==!0&&/^\([^?]/.test(I)){ka("star",C);continue}if(P.type==="star"){if(t.noglobstar===!0){ke(C);continue}let R=P.prev,ee=R.prev,he=R.type==="slash"||R.type==="bos",Pe=ee&&(ee.type==="star"||ee.type==="globstar");if(t.bash===!0&&(!he||I[0]&&I[0]!=="/")){Z({type:"star",value:C,output:""});continue}let ue=x.braces>0&&(R.type==="comma"||R.type==="brace"),hr=q.length&&(R.type==="pipe"||R.type==="paren");if(!he&&R.type!=="paren"&&!ue&&!hr){Z({type:"star",value:C,output:""});continue}for(;I.slice(0,3)==="/**";){let ki=r[x.index+4];if(ki&&ki!=="/")break;I=I.slice(3),ke("/**",3)}let zn=Be()||x.parens>0&&I===")".repeat(x.parens)&&!q.some(ki=>ki.type==="negate");if(R.type==="bos"&&Be()){P.type="globstar",P.value+=C,P.output=E(t),x.output=P.output,x.globstar=!0,ke(C);continue}if(R.type==="slash"&&R.prev.type!=="bos"&&!Pe&&zn){x.output=x.output.slice(0,-(R.output+P.output).length),R.output=`(?:${R.output}`,P.type="globstar",P.output=E(t)+(t.strictSlashes?")":"|$)"),P.value+=C,x.globstar=!0,x.output+=R.output+P.output,ke(C);continue}if(R.type==="slash"&&R.prev.type!=="bos"&&I[0]==="/"){let ki=I[1]!==void 0?"|$":"";x.output=x.output.slice(0,-(R.output+P.output).length),R.output=`(?:${R.output}`,P.type="globstar",P.output=`${E(t)}${f}|${f}${ki})`,P.value+=C,x.output+=R.output+P.output,x.globstar=!0,ke(C+ct()),Z({type:"slash",value:"/",output:""});continue}if(R.type==="bos"&&I[0]==="/"){P.type="globstar",P.value+=C,P.output=`(?:^|${f}|${E(t)}${f})`,x.output=P.output,x.globstar=!0,ke(C+ct()),Z({type:"slash",value:"/",output:""});continue}x.output=x.output.slice(0,-P.output.length),P.type="globstar",P.output=E(t),P.value+=C,x.output+=P.output,x.globstar=!0,ke(C);continue}let ve={type:"star",value:C,output:M};if(t.bash===!0){ve.output=".*?",(P.type==="bos"||P.type==="slash")&&(ve.output=k+ve.output),Z(ve);continue}if(P&&(P.type==="bracket"||P.type==="paren")&&t.regex===!0){ve.output=C,Z(ve);continue}(x.index===x.start||P.type==="slash"||P.type==="dot")&&(P.type==="dot"?(x.output+=y,P.output+=y):t.dot===!0?(x.output+=g,P.output+=g):(x.output+=k,P.output+=k),ce()!=="*"&&(x.output+=p,P.output+=p)),Z(ve)}for(;x.brackets>0;){if(t.strictBrackets===!0)throw new SyntaxError(Xi("closing","]"));x.output=Et.escapeLast(x.output,"["),on("brackets")}for(;x.parens>0;){if(t.strictBrackets===!0)throw new SyntaxError(Xi("closing",")"));x.output=Et.escapeLast(x.output,"("),on("parens")}for(;x.braces>0;){if(t.strictBrackets===!0)throw new SyntaxError(Xi("closing","}"));x.output=Et.escapeLast(x.output,"{"),on("braces")}if(t.strictSlashes!==!0&&(P.type==="star"||P.type==="bracket")&&Z({type:"maybe_slash",value:"",output:`${f}?`}),x.backtrack===!0){x.output="";for(let I of x.tokens)x.output+=I.output!=null?I.output:I.value,I.suffix&&(x.output+=I.suffix)}return x};yp.fastpaths=(r,e)=>{let t={...e},n=typeof t.maxLength=="number"?Math.min(mc,t.maxLength):mc,i=r.length;if(i>n)throw new SyntaxError(`Input length: ${i}, exceeds maximum allowed length: ${n}`);r=Vv[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}=vo.globChars(t.windows),h=t.dot?u:l,m=t.dot?d:l,y=t.capture?"":"?:",g={negated:!1,prefix:""},b=t.bash===!0?".*?":f;t.capture&&(b=`(${b})`);let v=k=>k.noglobstar===!0?b:`(${y}(?:(?!${p}${k.dot?c:s}).)*?)`,S=k=>{switch(k){case"*":return`${h}${a}${b}`;case".*":return`${s}${a}${b}`;case"*.*":return`${h}${b}${s}${a}${b}`;case"*/*":return`${h}${b}${o}${a}${m}${b}`;case"**":return h+v(t);case"**/*":return`(?:${h}${v(t)}${o})?${m}${a}${b}`;case"**/*.*":return`(?:${h}${v(t)}${o})?${m}${b}${s}${a}${b}`;case"**/.*":return`(?:${h}${v(t)}${o})?${s}${a}${b}`;default:{let $=/^(.*?)\.(\w+)$/.exec(k);if(!$)return;let M=S($[1]);return M?M+s+$[2]:void 0}}},_=Et.removePrefix(r,g),E=S(_);return E&&t.strictSlashes!==!0&&(E+=`${o}?`),E};zv.exports=yp});var Jv=A((nB,Gv)=>{"use strict";var lR=Uv(),gp=Kv(),Wv=bo(),dR=go(),uR=r=>r&&typeof r=="object"&&!Array.isArray(r),xe=(r,e,t=!1)=>{if(Array.isArray(r)){let u=r.map(f=>xe(f,e,t));return f=>{for(let p of u){let h=p(f);if(h)return h}return!1}}let n=uR(r)&&r.tokens&&r.input;if(r===""||typeof r!="string"&&!n)throw new TypeError("Expected pattern to be a non-empty string");let i=e||{},s=i.windows,o=n?xe.compileRe(r,e):xe.makeRe(r,e,!1,!0),a=o.state;delete o.state;let c=()=>!1;if(i.ignore){let u={...e,ignore:null,onMatch:null,onResult:null};c=xe(i.ignore,u,t)}let l=(u,d=!1)=>{let{isMatch:f,match:p,output:h}=xe.test(u,o,e,{glob:r,posix:s}),m={glob:r,state:a,regex:o,posix:s,input:u,output:h,match:p,isMatch:f};return typeof i.onResult=="function"&&i.onResult(m),f===!1?(m.isMatch=!1,d?m:!1):c(u)?(typeof i.onIgnore=="function"&&i.onIgnore(m),m.isMatch=!1,d?m:!1):(typeof i.onMatch=="function"&&i.onMatch(m),d?m:!0)};return t&&(l.state=a),l};xe.test=(r,e,t,{glob:n,posix:i}={})=>{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||(i?Wv.toPosixSlashes:null),a=r===n,c=a&&o?o(r):r;return a===!1&&(c=o?o(r):r,a=c===n),(a===!1||s.capture===!0)&&(s.matchBase===!0||s.basename===!0?a=xe.matchBase(r,e,t,i):a=e.exec(c)),{isMatch:!!a,match:a,output:c}};xe.matchBase=(r,e,t,n=t&&t.windows)=>(e instanceof RegExp?e:xe.makeRe(e,t)).test(Wv.basename(r,{windows:n}));xe.isMatch=(r,e,t)=>xe(e,t)(r);xe.parse=(r,e)=>Array.isArray(r)?r.map(t=>xe.parse(t,e)):gp(r,{...e,fastpaths:!1});xe.scan=(r,e)=>lR(r,e);xe.compileRe=(r,e,t=!1,n=!1)=>{if(t===!0)return r.output;let i=e||{},s=i.contains?"":"^",o=i.contains?"":"$",a=`${s}(?:${r.output})${o}`;r&&r.negated===!0&&(a=`^(?!${a}).*$`);let c=xe.toRegex(a,e);return n===!0&&(c.state=r),c};xe.makeRe=(r,e={},t=!1,n=!1)=>{if(!r||typeof r!="string")throw new TypeError("Expected a non-empty string");let i={negated:!1,fastpaths:!0};return e.fastpaths!==!1&&(r[0]==="."||r[0]==="*")&&(i.output=gp.fastpaths(r,e)),i.output||(i=gp(r,e)),xe.compileRe(i,e,t,n)};xe.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/$^/}};xe.constants=dR;Gv.exports=xe});var bp=A((iB,Qv)=>{"use strict";var Yv=Jv(),fR=bo();function Xv(r,e,t=!1){return e&&(e.windows===null||e.windows===void 0)&&(e={...e,windows:fR.isWindows()}),Yv(r,e,t)}Object.assign(Xv,Yv);Qv.exports=Xv});function vp(r,e){return yc(e.split("/"),r.split("/"))}function yc(r,e){if(e.length===0)return r.length===0;let[t,...n]=e;return t==="**"?yc(r,n)||r.length>0&&yc(r.slice(1),e):r.length===0?!1:Qi([...r[0]],[...t])&&yc(r.slice(1),n)}function Qi(r,e){if(e.length===0)return r.length===0;let[t,...n]=e;if(t==="*")return Qi(r,n)||r.length>0&&Qi(r.slice(1),e);if(t==="?")return r.length>0&&Qi(r.slice(1),n);if(t==="["){let i=pR(n);if(i)return r.length>0&&i.matches(r[0])&&Qi(r.slice(1),i.after)}return r[0]===t&&Qi(r.slice(1),n)}function pR(r){let e=r[0]==="!",t=[],n=e?1:0,i=!0;for(;n{let c=wo(a);return t.some(([l,u])=>l<=c&&c<=u)!==e},after:r.slice(n+1)};n+2{});var mw={};ay(mw,{MdbasePathError:()=>So,applyReadDefaults:()=>jR,buildInitialFrontmatter:()=>Ip,buildTypeTemplate:()=>Rp,buildUniqueNotePath:()=>Dp,coerceFieldInput:()=>Sc,createNoteFromType:()=>VR,createTypeDefinition:()=>qR,ensureCollectionInitialized:()=>$o,fieldsFromV03Schema:()=>gn,formatMarkdown:()=>mt,getPromptFields:()=>Op,getTopLevelFieldFromIssuePath:()=>Np,getTypesForFile:()=>Ke,isExcluded:()=>yt,loadContractDefinitions:()=>Pp,loadMdbaseConfig:()=>ai,loadTypeDefinitions:()=>kp,normalizeSafeRelativePath:()=>yn,parseFrontmatter:()=>Me,readCollectionRecords:()=>Ap,resolveFilenameForType:()=>fw,resolveFolderForType:()=>uw,schemaFromV03Fields:()=>es,slugify:()=>xp,v03TypeDefFromFrontmatter:()=>wc,validateCollection:()=>Tp,validateFile:()=>_c,validateRecordAgainstType:()=>ts});function mR(){return _o||(_o=new tw.Ajv2020({allErrors:!0,strict:!1,allowUnionTypes:!0}),(0,rw.default)(_o),_o)}function W(r){return!!r&&typeof r=="object"&&!Array.isArray(r)}function Oe(r){return JSON.parse(JSON.stringify(r))}function yR(r){if(r===!0)return!0;if(r===!1)return!1;if(r==="warn")return"warn"}function wp(r){return Array.isArray(r)?`[${r.map(e=>wp(e)).join(",")}]`:W(r)?`{${Object.keys(r).sort().map(t=>`${JSON.stringify(t)}:${wp(r[t])}`).join(",")}}`:JSON.stringify(r)}function gR(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 bR(r){let e=new Map,t=new Set,n=i=>{let s=e.get(i);if(s)return s;let o=r.get(i);if(!o)return null;if(t.has(i)){let l={...o,fields:Oe(o.fields)};return e.set(i,l),l}t.add(i);let a=o.extends?n(o.extends):null;t.delete(i);let c={...o,fields:a?{...Oe(a.fields),...Oe(o.fields)}:Oe(o.fields),display_name_key:o.display_name_key??a?.display_name_key,path_pattern:o.path_pattern??a?.path_pattern,filename_pattern:o.filename_pattern??a?.filename_pattern,strict:o.strict!==void 0?o.strict:a?.strict,match:o.match??a?.match};return e.set(i,c),c};for(let i of r.keys())n(i);return e}function nw(r){let e=(0,oe.normalizePath)(r),t=e.lastIndexOf("/");return t>=0?e.slice(0,t):""}function iw(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 sw(r){return/^[a-z][a-z0-9+.-]*:\/\//i.test(r)}function ow(r,e,t){let n=iw(t);if(!n||sw(n))return null;let i=new Set,s=(0,oe.normalizePath)(n);i.add(s),s.endsWith(".md")||i.add(`${s}.md`);let o=nw(e);if(o){let c=(0,oe.normalizePath)(`${o}/${n}`);i.add(c),c.endsWith(".md")||i.add(`${c}.md`)}for(let c of i){let l=r.getAbstractFileByPath(c);if(l instanceof oe.TFile)return l}let a=n.replace(/\.md$/i,"");return r.getMarkdownFiles().find(c=>c.basename===a)??null}function vR(r,e,t){return sw(iw(t))||ow(r,e,t)!==null}function Me(r){let e=(0,oe.getFrontMatterInfo)(r);if(!e.exists)return{hasFrontmatter:!1,frontmatter:{},body:r};try{let t=e.frontmatter,n=(0,oe.parseYaml)(t);return n==null&&t.trim()!==""?{hasFrontmatter:!0,frontmatter:{},body:r.slice(e.contentStart),error:"Frontmatter must be a YAML object"}:n!=null&&!W(n)?{hasFrontmatter:!0,frontmatter:{},body:r.slice(e.contentStart),error:"Frontmatter must be a YAML object"}:{hasFrontmatter:!0,frontmatter:n??{},body:r.slice(e.contentStart)}}catch(t){return{hasFrontmatter:!0,frontmatter:{},body:r.slice(e.contentStart),error:t instanceof Error?t.message:String(t)}}}function mt(r,e=""){if(Object.keys(r).length===0)return e;let t=(0,oe.stringifyYaml)(r).trimEnd(),n=e.replace(/^\n+/,"");return`--- + deps: ${t}}`};var J1={keyword:"dependencies",type:"object",schemaType:"object",error:br.error,code(r){let[e,t]=Y1(r);mb(r,e),yb(r,t)}};function Y1({schema:r}){let e={},t={};for(let n in r){if(n==="__proto__")continue;let i=Array.isArray(r[n])?e:t;i[n]=r[n]}return[e,t]}function mb(r,e=r.schema){let{gen:t,data:n,it:i}=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,po.propertyInData)(t,n,o,i.opts.ownProperties);r.setParams({property:o,depsCount:a.length,deps:a.join(", ")}),i.allErrors?t.if(c,()=>{for(let l of a)(0,po.checkReportMissingProp)(r,l)}):(t.if((0,uf._)`${c} && (${(0,po.checkMissingProp)(r,a,s)})`),(0,po.reportMissingProp)(r,s),t.else())}}br.validatePropertyDeps=mb;function yb(r,e=r.schema){let{gen:t,data:n,keyword:i,it:s}=r,o=t.name("valid");for(let a in e)(0,G1.alwaysValidSchema)(s,e[a])||(t.if((0,po.propertyInData)(t,n,a,s.opts.ownProperties),()=>{let c=r.subschema({keyword:i,schemaProp:a},o);r.mergeValidEvaluated(c,o)},()=>t.var(o,!0)),r.ok(o))}br.validateSchemaDeps=yb;br.default=J1});var bb=A(ff=>{"use strict";Object.defineProperty(ff,"__esModule",{value:!0});var gb=U(),X1=Q(),Q1={message:"property name must be valid",params:({params:r})=>(0,gb._)`{propertyName: ${r.propertyName}}`},Z1={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:Q1,code(r){let{gen:e,schema:t,data:n,it:i}=r;if((0,X1.alwaysValidSchema)(i,t))return;let s=e.name("valid");e.forIn("key",n,o=>{r.setParams({propertyName:o}),r.subschema({keyword:"propertyNames",data:o,dataTypes:["string"],propertyName:o,compositeRule:!0},s),e.if((0,gb.not)(s),()=>{r.error(!0),i.allErrors||e.break()})}),r.ok(s)}};ff.default=Z1});var hf=A(pf=>{"use strict";Object.defineProperty(pf,"__esModule",{value:!0});var oc=Nt(),Xt=U(),eC=Dt(),ac=Q(),tC={message:"must NOT have additional properties",params:({params:r})=>(0,Xt._)`{additionalProperty: ${r.additionalProperty}}`},rC={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:tC,code(r){let{gen:e,schema:t,parentSchema:n,data:i,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,ac.alwaysValidSchema)(o,t))return;let l=(0,oc.allSchemaProperties)(n.properties),u=(0,oc.allSchemaProperties)(n.patternProperties);d(),r.ok((0,Xt._)`${s} === ${eC.default.errors}`);function d(){e.forIn("key",i,y=>{!l.length&&!u.length?m(y):e.if(f(y),()=>m(y))})}function f(y){let g;if(l.length>8){let b=(0,ac.schemaRefOrVal)(o,n.properties,"properties");g=(0,oc.isOwnProperty)(e,b,y)}else l.length?g=(0,Xt.or)(...l.map(b=>(0,Xt._)`${y} === ${b}`)):g=Xt.nil;return u.length&&(g=(0,Xt.or)(g,...u.map(b=>(0,Xt._)`${(0,oc.usePattern)(r,b)}.test(${y})`))),(0,Xt.not)(g)}function p(y){e.code((0,Xt._)`delete ${i}[${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,ac.alwaysValidSchema)(o,t)){let g=e.name("valid");c.removeAdditional==="failing"?(h(y,g,!1),e.if((0,Xt.not)(g),()=>{r.reset(),p(y)})):(h(y,g),a||e.if((0,Xt.not)(g),()=>e.break()))}}function h(y,g,b){let v={keyword:"additionalProperties",dataProp:y,dataPropType:ac.Type.Str};b===!1&&Object.assign(v,{compositeRule:!0,createErrors:!1,allErrors:!1}),r.subschema(v,g)}}};pf.default=rC});var _b=A(yf=>{"use strict";Object.defineProperty(yf,"__esModule",{value:!0});var nC=Ni(),vb=Nt(),mf=Q(),wb=hf(),iC={keyword:"properties",type:"object",schemaType:"object",code(r){let{gen:e,schema:t,parentSchema:n,data:i,it:s}=r;s.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&wb.default.code(new nC.KeywordCxt(s,wb.default,"additionalProperties"));let o=(0,vb.allSchemaProperties)(t);for(let d of o)s.definedProperties.add(d);s.opts.unevaluated&&o.length&&s.props!==!0&&(s.props=mf.mergeEvaluated.props(e,(0,mf.toHash)(o),s.props));let a=o.filter(d=>!(0,mf.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,vb.propertyInData)(e,i,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)}}};yf.default=iC});var Eb=A(gf=>{"use strict";Object.defineProperty(gf,"__esModule",{value:!0});var Sb=Nt(),cc=U(),$b=Q(),xb=Q(),sC={keyword:"patternProperties",type:"object",schemaType:"object",code(r){let{gen:e,schema:t,data:n,parentSchema:i,it:s}=r,{opts:o}=s,a=(0,Sb.allSchemaProperties)(t),c=a.filter(h=>(0,$b.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&&i.properties,u=e.name("valid");s.props!==!0&&!(s.props instanceof cc.Name)&&(s.props=(0,xb.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,$b.checkStrictMode)(s,`property ${y} matches pattern ${h} (use allowMatchingProperties)`)}function m(h){e.forIn("key",n,y=>{e.if((0,cc._)`${(0,Sb.usePattern)(r,h)}.test(${y})`,()=>{let g=c.includes(h);g||r.subschema({keyword:"patternProperties",schemaProp:h,dataProp:y,dataPropType:xb.Type.Str},u),s.opts.unevaluated&&d!==!0?e.assign((0,cc._)`${d}[${y}]`,!0):!g&&!s.allErrors&&e.if((0,cc.not)(u),()=>e.break())})})}}};gf.default=sC});var Ab=A(bf=>{"use strict";Object.defineProperty(bf,"__esModule",{value:!0});var oC=Q(),aC={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(r){let{gen:e,schema:t,it:n}=r;if((0,oC.alwaysValidSchema)(n,t)){r.fail();return}let i=e.name("valid");r.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},i),r.failResult(i,()=>r.reset(),()=>r.error())},error:{message:"must NOT be valid"}};bf.default=aC});var kb=A(vf=>{"use strict";Object.defineProperty(vf,"__esModule",{value:!0});var cC=Nt(),lC={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:cC.validateUnion,error:{message:"must match a schema in anyOf"}};vf.default=lC});var Pb=A(wf=>{"use strict";Object.defineProperty(wf,"__esModule",{value:!0});var lc=U(),dC=Q(),uC={message:"must match exactly one schema in oneOf",params:({params:r})=>(0,lc._)`{passingSchemas: ${r.passing}}`},fC={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:uC,code(r){let{gen:e,schema:t,parentSchema:n,it:i}=r;if(!Array.isArray(t))throw new Error("ajv implementation error");if(i.opts.discriminator&&n.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,dC.alwaysValidSchema)(i,u)?e.var(c,!0):f=r.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,lc._)`${c} && ${o}`).assign(o,!1).assign(a,(0,lc._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(o,!0),e.assign(a,d),f&&r.mergeEvaluated(f,lc.Name)})})}}};wf.default=fC});var Cb=A(_f=>{"use strict";Object.defineProperty(_f,"__esModule",{value:!0});var pC=Q(),hC={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 i=e.name("valid");t.forEach((s,o)=>{if((0,pC.alwaysValidSchema)(n,s))return;let a=r.subschema({keyword:"allOf",schemaProp:o},i);r.ok(i),r.mergeEvaluated(a)})}};_f.default=hC});var Rb=A(Sf=>{"use strict";Object.defineProperty(Sf,"__esModule",{value:!0});var dc=U(),Tb=Q(),mC={message:({params:r})=>(0,dc.str)`must match "${r.ifClause}" schema`,params:({params:r})=>(0,dc._)`{failingKeyword: ${r.ifClause}}`},yC={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:mC,code(r){let{gen:e,parentSchema:t,it:n}=r;t.then===void 0&&t.else===void 0&&(0,Tb.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let i=Mb(n,"then"),s=Mb(n,"else");if(!i&&!s)return;let o=e.let("valid",!0),a=e.name("_valid");if(c(),r.reset(),i&&s){let u=e.let("ifClause");r.setParams({ifClause:u}),e.if(a,l("then",u),l("else",u))}else i?e.if(a,l("then")):e.if((0,dc.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,dc._)`${u}`):r.setParams({ifClause:u})}}}};function Mb(r,e){let t=r.schema[e];return t!==void 0&&!(0,Tb.alwaysValidSchema)(r,t)}Sf.default=yC});var Ib=A($f=>{"use strict";Object.defineProperty($f,"__esModule",{value:!0});var gC=Q(),bC={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:r,parentSchema:e,it:t}){e.if===void 0&&(0,gC.checkStrictMode)(t,`"${r}" without "if" is ignored`)}};$f.default=bC});var Ef=A(xf=>{"use strict";Object.defineProperty(xf,"__esModule",{value:!0});var vC=of(),wC=ub(),_C=af(),SC=pb(),$C=hb(),xC=sc(),EC=bb(),AC=hf(),kC=_b(),PC=Eb(),CC=Ab(),MC=kb(),TC=Pb(),RC=Cb(),IC=Rb(),OC=Ib();function DC(r=!1){let e=[CC.default,MC.default,TC.default,RC.default,IC.default,OC.default,EC.default,AC.default,xC.default,kC.default,PC.default];return r?e.push(wC.default,SC.default):e.push(vC.default,_C.default),e.push($C.default),e}xf.default=DC});var kf=A(ho=>{"use strict";Object.defineProperty(ho,"__esModule",{value:!0});ho.dynamicAnchor=void 0;var Af=U(),NC=Dt(),Ob=Qs(),LC=Za(),FC={keyword:"$dynamicAnchor",schemaType:"string",code:r=>Db(r,r.schema)};function Db(r,e){let{gen:t,it:n}=r;n.schemaEnv.root.dynamicAnchors[e]=!0;let i=(0,Af._)`${NC.default.dynamicAnchors}${(0,Af.getProperty)(e)}`,s=n.errSchemaPath==="#"?n.validateName:jC(r);t.if((0,Af._)`!${i}`,()=>t.assign(i,s))}ho.dynamicAnchor=Db;function jC(r){let{schemaEnv:e,schema:t,self:n}=r.it,{root:i,baseId:s,localRefs:o,meta:a}=e.root,{schemaId:c}=n.opts,l=new Ob.SchemaEnv({schema:t,schemaId:c,root:i,baseId:s,localRefs:o,meta:a});return Ob.compileSchema.call(n,l),(0,LC.getValidate)(r,l)}ho.default=FC});var Pf=A(mo=>{"use strict";Object.defineProperty(mo,"__esModule",{value:!0});mo.dynamicRef=void 0;var Nb=U(),qC=Dt(),Lb=Za(),BC={keyword:"$dynamicRef",schemaType:"string",code:r=>Fb(r,r.schema)};function Fb(r,e){let{gen:t,keyword:n,it:i}=r;if(e[0]!=="#")throw new Error(`"${n}" only supports hash fragment reference`);let s=e.slice(1);if(i.allErrors)o();else{let c=t.let("valid",!1);o(c),r.ok(c)}function o(c){if(i.schemaEnv.root.dynamicAnchors[s]){let l=t.let("_v",(0,Nb._)`${qC.default.dynamicAnchors}${(0,Nb.getProperty)(s)}`);t.if(l,a(l,c),a(i.validateName,c))}else a(i.validateName,c)()}function a(c,l){return l?()=>t.block(()=>{(0,Lb.callRef)(r,c),t.let(l,!0)}):()=>(0,Lb.callRef)(r,c)}}mo.dynamicRef=Fb;mo.default=BC});var jb=A(Cf=>{"use strict";Object.defineProperty(Cf,"__esModule",{value:!0});var UC=kf(),VC=Q(),HC={keyword:"$recursiveAnchor",schemaType:"boolean",code(r){r.schema?(0,UC.dynamicAnchor)(r,""):(0,VC.checkStrictMode)(r.it,"$recursiveAnchor: false is ignored")}};Cf.default=HC});var qb=A(Mf=>{"use strict";Object.defineProperty(Mf,"__esModule",{value:!0});var zC=Pf(),KC={keyword:"$recursiveRef",schemaType:"string",code:r=>(0,zC.dynamicRef)(r,r.schema)};Mf.default=KC});var Bb=A(Tf=>{"use strict";Object.defineProperty(Tf,"__esModule",{value:!0});var WC=kf(),GC=Pf(),JC=jb(),YC=qb(),XC=[WC.default,GC.default,JC.default,YC.default];Tf.default=XC});var Vb=A(Rf=>{"use strict";Object.defineProperty(Rf,"__esModule",{value:!0});var Ub=sc(),QC={keyword:"dependentRequired",type:"object",schemaType:"object",error:Ub.error,code:r=>(0,Ub.validatePropertyDeps)(r)};Rf.default=QC});var Hb=A(If=>{"use strict";Object.defineProperty(If,"__esModule",{value:!0});var ZC=sc(),eM={keyword:"dependentSchemas",type:"object",schemaType:"object",code:r=>(0,ZC.validateSchemaDeps)(r)};If.default=eM});var zb=A(Of=>{"use strict";Object.defineProperty(Of,"__esModule",{value:!0});var tM=Q(),rM={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword:r,parentSchema:e,it:t}){e.contains===void 0&&(0,tM.checkStrictMode)(t,`"${r}" without "contains" is ignored`)}};Of.default=rM});var Kb=A(Df=>{"use strict";Object.defineProperty(Df,"__esModule",{value:!0});var nM=Vb(),iM=Hb(),sM=zb(),oM=[nM.default,iM.default,sM.default];Df.default=oM});var Gb=A(Nf=>{"use strict";Object.defineProperty(Nf,"__esModule",{value:!0});var hn=U(),Wb=Q(),aM=Dt(),cM={message:"must NOT have unevaluated properties",params:({params:r})=>(0,hn._)`{unevaluatedProperty: ${r.unevaluatedProperty}}`},lM={keyword:"unevaluatedProperties",type:"object",schemaType:["boolean","object"],trackErrors:!0,error:cM,code(r){let{gen:e,schema:t,data:n,errsCount:i,it:s}=r;if(!i)throw new Error("ajv implementation error");let{allErrors:o,props:a}=s;a instanceof hn.Name?e.if((0,hn._)`${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))),s.props=!0,r.ok((0,hn._)`${i} === ${aM.default.errors}`);function c(d){if(t===!1){r.setParams({unevaluatedProperty:d}),r.error(),o||e.break();return}if(!(0,Wb.alwaysValidSchema)(s,t)){let f=e.name("valid");r.subschema({keyword:"unevaluatedProperties",dataProp:d,dataPropType:Wb.Type.Str},f),o||e.if((0,hn.not)(f),()=>e.break())}}function l(d,f){return(0,hn._)`!${d} || !${d}[${f}]`}function u(d,f){let p=[];for(let m in d)d[m]===!0&&p.push((0,hn._)`${f} !== ${m}`);return(0,hn.and)(...p)}}};Nf.default=lM});var Yb=A(Lf=>{"use strict";Object.defineProperty(Lf,"__esModule",{value:!0});var oi=U(),Jb=Q(),dM={message:({params:{len:r}})=>(0,oi.str)`must NOT have more than ${r} items`,params:({params:{len:r}})=>(0,oi._)`{limit: ${r}}`},uM={keyword:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error:dM,code(r){let{gen:e,schema:t,data:n,it:i}=r,s=i.items||0;if(s===!0)return;let o=e.const("len",(0,oi._)`${n}.length`);if(t===!1)r.setParams({len:s}),r.fail((0,oi._)`${o} > ${s}`);else if(typeof t=="object"&&!(0,Jb.alwaysValidSchema)(i,t)){let c=e.var("valid",(0,oi._)`${o} <= ${s}`);e.if((0,oi.not)(c),()=>a(c,s)),r.ok(c)}i.items=!0;function a(c,l){e.forRange("i",l,o,u=>{r.subschema({keyword:"unevaluatedItems",dataProp:u,dataPropType:Jb.Type.Num},c),i.allErrors||e.if((0,oi.not)(c),()=>e.break())})}}};Lf.default=uM});var Xb=A(Ff=>{"use strict";Object.defineProperty(Ff,"__esModule",{value:!0});var fM=Gb(),pM=Yb(),hM=[fM.default,pM.default];Ff.default=hM});var Qb=A(jf=>{"use strict";Object.defineProperty(jf,"__esModule",{value:!0});var $e=U(),mM={message:({schemaCode:r})=>(0,$e.str)`must match format "${r}"`,params:({schemaCode:r})=>(0,$e._)`{format: ${r}}`},yM={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:mM,code(r,e){let{gen:t,data:n,$data:i,schema:s,schemaCode:o,it:a}=r,{opts:c,errSchemaPath:l,schemaEnv:u,self:d}=a;if(!c.validateFormats)return;i?f():p();function f(){let m=t.scopeValue("formats",{ref:d.formats,code:c.code.formats}),h=t.const("fDef",(0,$e._)`${m}[${o}]`),y=t.let("fType"),g=t.let("format");t.if((0,$e._)`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>t.assign(y,(0,$e._)`${h}.type || "string"`).assign(g,(0,$e._)`${h}.validate`),()=>t.assign(y,(0,$e._)`"string"`).assign(g,h)),r.fail$data((0,$e.or)(b(),v()));function b(){return c.strictSchema===!1?$e.nil:(0,$e._)`${o} && !${g}`}function v(){let S=u.$async?(0,$e._)`(${h}.async ? await ${g}(${n}) : ${g}(${n}))`:(0,$e._)`${g}(${n})`,_=(0,$e._)`(typeof ${g} == "function" ? ${S} : ${g}.test(${n}))`;return(0,$e._)`${g} && ${g} !== true && ${y} === ${e} && !${_}`}}function p(){let m=d.formats[s];if(!m){b();return}if(m===!0)return;let[h,y,g]=v(m);h===e&&r.pass(S());function b(){if(c.strictSchema===!1){d.logger.warn(_());return}throw new Error(_());function _(){return`unknown format "${s}" ignored in schema at path "${l}"`}}function v(_){let E=_ instanceof RegExp?(0,$e.regexpCode)(_):c.code.formats?(0,$e._)`${c.code.formats}${(0,$e.getProperty)(s)}`:void 0,k=t.scopeValue("formats",{key:s,ref:_,code:E});return typeof _=="object"&&!(_ instanceof RegExp)?[_.type||"string",_.validate,(0,$e._)`${k}.validate`]:["string",_,k]}function S(){if(typeof m=="object"&&!(m instanceof RegExp)&&m.async){if(!u.$async)throw new Error("async format in sync schema");return(0,$e._)`await ${g}(${n})`}return typeof y=="function"?(0,$e._)`${g}(${n})`:(0,$e._)`${g}.test(${n})`}}}};jf.default=yM});var Bf=A(qf=>{"use strict";Object.defineProperty(qf,"__esModule",{value:!0});var gM=Qb(),bM=[gM.default];qf.default=bM});var Uf=A(Ui=>{"use strict";Object.defineProperty(Ui,"__esModule",{value:!0});Ui.contentVocabulary=Ui.metadataVocabulary=void 0;Ui.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Ui.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var ev=A(Vf=>{"use strict";Object.defineProperty(Vf,"__esModule",{value:!0});var vM=Bu(),wM=nf(),_M=Ef(),SM=Bb(),$M=Kb(),xM=Xb(),EM=Bf(),Zb=Uf(),AM=[SM.default,vM.default,wM.default,(0,_M.default)(!0),EM.default,Zb.metadataVocabulary,Zb.contentVocabulary,$M.default,xM.default];Vf.default=AM});var rv=A(uc=>{"use strict";Object.defineProperty(uc,"__esModule",{value:!0});uc.DiscrError=void 0;var tv;(function(r){r.Tag="tag",r.Mapping="mapping"})(tv||(uc.DiscrError=tv={}))});var Kf=A(zf=>{"use strict";Object.defineProperty(zf,"__esModule",{value:!0});var Vi=U(),Hf=rv(),nv=Qs(),kM=Li(),PM=Q(),CM={message:({params:{discrError:r,tagName:e}})=>r===Hf.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:r,tag:e,tagName:t}})=>(0,Vi._)`{error: ${r}, tag: ${t}, tagValue: ${e}}`},MM={keyword:"discriminator",type:"object",schemaType:"object",error:CM,code(r){let{gen:e,data:t,schema:n,parentSchema:i,it:s}=r,{oneOf:o}=i;if(!s.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,Vi._)`${t}${(0,Vi.getProperty)(a)}`);e.if((0,Vi._)`typeof ${l} == "string"`,()=>u(),()=>r.error(!1,{discrError:Hf.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,Vi._)`${l} === ${m}`),e.assign(c,d(p[m]));e.else(),r.error(!1,{discrError:Hf.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,Vi.Name),m}function f(){var p;let m={},h=g(i),y=!0;for(let S=0;S{TM.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 sv=A((Bq,RM)=>{RM.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 ov=A((Uq,IM)=>{IM.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 av=A((Vq,OM)=>{OM.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 cv=A((Hq,DM)=>{DM.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 lv=A((zq,NM)=>{NM.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 dv=A((Kq,LM)=>{LM.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 uv=A((Wq,FM)=>{FM.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 fv=A(Wf=>{"use strict";Object.defineProperty(Wf,"__esModule",{value:!0});var jM=iv(),qM=sv(),BM=ov(),UM=av(),VM=cv(),HM=lv(),zM=dv(),KM=uv(),WM=["/properties"];function GM(r){return[jM,qM,BM,UM,VM,e(this,HM),zM,e(this,KM)].forEach(t=>this.addMetaSchema(t,void 0,!1)),this;function e(t,n){return r?t.$dataMetaSchema(n,WM):n}}Wf.default=GM});var Yf=A((ye,Jf)=>{"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.Ajv2020=void 0;var JM=Fu(),YM=ev(),XM=Kf(),QM=fv(),Gf="https://json-schema.org/draft/2020-12/schema",Hi=class extends JM.default{constructor(e={}){super({...e,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){super._addVocabularies(),YM.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(XM.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data:e,meta:t}=this.opts;t&&(QM.default.call(this,e),this.refs["http://json-schema.org/schema"]=Gf)}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Gf)?Gf:void 0)}};ye.Ajv2020=Hi;Jf.exports=ye=Hi;Jf.exports.Ajv2020=Hi;Object.defineProperty(ye,"__esModule",{value:!0});ye.default=Hi;var ZM=Ni();Object.defineProperty(ye,"KeywordCxt",{enumerable:!0,get:function(){return ZM.KeywordCxt}});var zi=U();Object.defineProperty(ye,"_",{enumerable:!0,get:function(){return zi._}});Object.defineProperty(ye,"str",{enumerable:!0,get:function(){return zi.str}});Object.defineProperty(ye,"stringify",{enumerable:!0,get:function(){return zi.stringify}});Object.defineProperty(ye,"nil",{enumerable:!0,get:function(){return zi.nil}});Object.defineProperty(ye,"Name",{enumerable:!0,get:function(){return zi.Name}});Object.defineProperty(ye,"CodeGen",{enumerable:!0,get:function(){return zi.CodeGen}});var eT=Xs();Object.defineProperty(ye,"ValidationError",{enumerable:!0,get:function(){return eT.default}});var tT=Li();Object.defineProperty(ye,"MissingRefError",{enumerable:!0,get:function(){return tT.default}})});var wv=A(wr=>{"use strict";Object.defineProperty(wr,"__esModule",{value:!0});wr.formatNames=wr.fastFormats=wr.fullFormats=void 0;function vr(r,e){return{validate:r,compare:e}}wr.fullFormats={date:vr(yv,ep),time:vr(Qf(!0),tp),"date-time":vr(pv(!0),bv),"iso-time":vr(Qf(),gv),"iso-date-time":vr(pv(),vv),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:aT,"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:hT,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:cT,int32:{type:"number",validate:uT},int64:{type:"number",validate:fT},float:{type:"number",validate:mv},double:{type:"number",validate:mv},password:!0,binary:!0};wr.fastFormats={...wr.fullFormats,date:vr(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,ep),time:vr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,tp),"date-time":vr(/^\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,bv),"iso-time":vr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,gv),"iso-date-time":vr(/^\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,vv),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};wr.formatNames=Object.keys(wr.fullFormats);function rT(r){return r%4===0&&(r%100!==0||r%400===0)}var nT=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,iT=[0,31,28,31,30,31,30,31,31,30,31,30,31];function yv(r){let e=nT.exec(r);if(!e)return!1;let t=+e[1],n=+e[2],i=+e[3];return n>=1&&n<=12&&i>=1&&i<=(n===2&&rT(t)?29:iT[n])}function ep(r,e){if(r&&e)return r>e?1:r23||u>59||r&&!a)return!1;if(i<=23&&s<=59&&o<60)return!0;let d=s-u*c,f=i-l*c-(d<0?1:0);return(f===23||f===-1)&&(d===59||d===-1)&&o<61}}function tp(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 gv(r,e){if(!(r&&e))return;let t=Xf.exec(r),n=Xf.exec(e);if(t&&n)return r=t[1]+t[2]+t[3],e=n[1]+n[2]+n[3],r>e?1:r=lT}function fT(r){return Number.isInteger(r)}function mv(){return!0}var pT=/[^\\]\\Z/;function hT(r){if(pT.test(r))return!1;try{return new RegExp(r),!0}catch{return!1}}});var Sv=A(rp=>{"use strict";Object.defineProperty(rp,"__esModule",{value:!0});var mT=Bu(),yT=nf(),gT=Ef(),bT=Bf(),_v=Uf(),vT=[mT.default,yT.default,(0,gT.default)(),bT.default,_v.metadataVocabulary,_v.contentVocabulary];rp.default=vT});var $v=A((Xq,wT)=>{wT.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 Ev=A((ge,np)=>{"use strict";Object.defineProperty(ge,"__esModule",{value:!0});ge.MissingRefError=ge.ValidationError=ge.CodeGen=ge.Name=ge.nil=ge.stringify=ge.str=ge._=ge.KeywordCxt=ge.Ajv=void 0;var _T=Fu(),ST=Sv(),$T=Kf(),xv=$v(),xT=["/properties"],fc="http://json-schema.org/draft-07/schema",Ki=class extends _T.default{_addVocabularies(){super._addVocabularies(),ST.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword($T.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(xv,xT):xv;this.addMetaSchema(e,fc,!1),this.refs["http://json-schema.org/schema"]=fc}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(fc)?fc:void 0)}};ge.Ajv=Ki;np.exports=ge=Ki;np.exports.Ajv=Ki;Object.defineProperty(ge,"__esModule",{value:!0});ge.default=Ki;var ET=Ni();Object.defineProperty(ge,"KeywordCxt",{enumerable:!0,get:function(){return ET.KeywordCxt}});var Wi=U();Object.defineProperty(ge,"_",{enumerable:!0,get:function(){return Wi._}});Object.defineProperty(ge,"str",{enumerable:!0,get:function(){return Wi.str}});Object.defineProperty(ge,"stringify",{enumerable:!0,get:function(){return Wi.stringify}});Object.defineProperty(ge,"nil",{enumerable:!0,get:function(){return Wi.nil}});Object.defineProperty(ge,"Name",{enumerable:!0,get:function(){return Wi.Name}});Object.defineProperty(ge,"CodeGen",{enumerable:!0,get:function(){return Wi.CodeGen}});var AT=Xs();Object.defineProperty(ge,"ValidationError",{enumerable:!0,get:function(){return AT.default}});var kT=Li();Object.defineProperty(ge,"MissingRefError",{enumerable:!0,get:function(){return kT.default}})});var Av=A(Gi=>{"use strict";Object.defineProperty(Gi,"__esModule",{value:!0});Gi.formatLimitDefinition=void 0;var PT=Ev(),Qt=U(),mn=Qt.operators,pc={formatMaximum:{okStr:"<=",ok:mn.LTE,fail:mn.GT},formatMinimum:{okStr:">=",ok:mn.GTE,fail:mn.LT},formatExclusiveMaximum:{okStr:"<",ok:mn.LT,fail:mn.GTE},formatExclusiveMinimum:{okStr:">",ok:mn.GT,fail:mn.LTE}},CT={message:({keyword:r,schemaCode:e})=>(0,Qt.str)`should be ${pc[r].okStr} ${e}`,params:({keyword:r,schemaCode:e})=>(0,Qt._)`{comparison: ${pc[r].okStr}, limit: ${e}}`};Gi.formatLimitDefinition={keyword:Object.keys(pc),type:"string",schemaType:"string",$data:!0,error:CT,code(r){let{gen:e,data:t,schemaCode:n,keyword:i,it:s}=r,{opts:o,self:a}=s;if(!o.validateFormats)return;let c=new PT.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,Qt._)`${f}[${c.schemaCode}]`);r.fail$data((0,Qt.or)((0,Qt._)`typeof ${p} != "object"`,(0,Qt._)`${p} instanceof RegExp`,(0,Qt._)`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(`"${i}": format "${f}" does not define "compare" function`);let m=e.scopeValue("formats",{key:f,ref:p,code:o.code.formats?(0,Qt._)`${o.code.formats}${(0,Qt.getProperty)(f)}`:void 0});r.fail$data(d(m))}function d(f){return(0,Qt._)`${f}.compare(${t}, ${n}) ${pc[i].fail} 0`}},dependencies:["format"]};var MT=r=>(r.addKeyword(Gi.formatLimitDefinition),r);Gi.default=MT});var op=A((yo,Cv)=>{"use strict";Object.defineProperty(yo,"__esModule",{value:!0});var Ji=wv(),TT=Av(),ip=U(),kv=new ip.Name("fullFormats"),RT=new ip.Name("fastFormats"),sp=(r,e={keywords:!0})=>{if(Array.isArray(e))return Pv(r,e,Ji.fullFormats,kv),r;let[t,n]=e.mode==="fast"?[Ji.fastFormats,RT]:[Ji.fullFormats,kv],i=e.formats||Ji.formatNames;return Pv(r,i,t,n),e.keywords&&(0,TT.default)(r),r};sp.get=(r,e="full")=>{let n=(e==="fast"?Ji.fastFormats:Ji.fullFormats)[r];if(!n)throw new Error(`Unknown format "${r}"`);return n};function Pv(r,e,t,n){var i,s;(i=(s=r.opts.code).formats)!==null&&i!==void 0||(s.formats=(0,ip._)`require("ajv-formats/dist/formats").${n}`);for(let o of e)r.addFormat(o,t[o])}Cv.exports=yo=sp;Object.defineProperty(yo,"__esModule",{value:!0});yo.default=sp});var go=A((Zq,Ov)=>{"use strict";var Mv="[^\\\\/]",IT="(?=.)",Tv="[^/]",ap="(?:\\/|$)",Rv="(?:^|\\/)",cp=`\\.{1,2}${ap}`,OT="(?!\\.)",DT=`(?!${Rv}${cp})`,NT=`(?!\\.{0,1}${ap})`,LT=`(?!${cp})`,FT="[^.\\/]",jT=`${Tv}*?`,qT="/",Iv={DOT_LITERAL:"\\.",PLUS_LITERAL:"\\+",QMARK_LITERAL:"\\?",SLASH_LITERAL:"\\/",ONE_CHAR:IT,QMARK:Tv,END_ANCHOR:ap,DOTS_SLASH:cp,NO_DOT:OT,NO_DOTS:DT,NO_DOT_SLASH:NT,NO_DOTS_SLASH:LT,QMARK_NO_DOT:FT,STAR:jT,START_ANCHOR:Rv,SEP:qT},BT={...Iv,SLASH_LITERAL:"[\\\\/]",QMARK:Mv,STAR:`${Mv}*?`,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:"\\"},UT={__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"};Ov.exports={DEFAULT_MAX_EXTGLOB_RECURSION:0,MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:UT,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?BT:Iv}}});var bo=A(ht=>{"use strict";var{REGEX_BACKSLASH:VT,REGEX_REMOVE_BACKSLASH:HT,REGEX_SPECIAL_CHARS:zT,REGEX_SPECIAL_CHARS_GLOBAL:KT}=go();ht.isObject=r=>r!==null&&typeof r=="object"&&!Array.isArray(r);ht.hasRegexChars=r=>zT.test(r);ht.isRegexChar=r=>r.length===1&&ht.hasRegexChars(r);ht.escapeRegex=r=>r.replace(KT,"\\$1");ht.toPosixSlashes=r=>r.replace(VT,"/");ht.isWindows=()=>{if(typeof navigator<"u"&&navigator.platform){let r=navigator.platform.toLowerCase();return r==="win32"||r==="windows"}return typeof process<"u"&&process.platform?process.platform==="win32":!1};ht.removeBackslashes=r=>r.replace(HT,e=>e==="\\"?"":e);ht.escapeLast=(r,e,t)=>{let n=r.lastIndexOf(e,t);return n===-1?r:r[n-1]==="\\"?ht.escapeLast(r,e,n-1):`${r.slice(0,n)}\\${r.slice(n)}`};ht.removePrefix=(r,e={})=>{let t=r;return t.startsWith("./")&&(t=t.slice(2),e.prefix="./"),t};ht.wrapOutput=(r,e={},t={})=>{let n=t.contains?"":"^",i=t.contains?"":"$",s=`${n}(?:${r})${i}`;return e.negated===!0&&(s=`(?:^(?!${s}).*$)`),s};ht.basename=(r,{windows:e}={})=>{let t=r.split(e?/[\\/]/:"/"),n=t[t.length-1];return n===""?t[t.length-2]:n}});var Uv=A((tB,Bv)=>{"use strict";var Dv=bo(),{CHAR_ASTERISK:lp,CHAR_AT:WT,CHAR_BACKWARD_SLASH:Yi,CHAR_COMMA:GT,CHAR_DOT:dp,CHAR_EXCLAMATION_MARK:up,CHAR_FORWARD_SLASH:qv,CHAR_LEFT_CURLY_BRACE:fp,CHAR_LEFT_PARENTHESES:hc,CHAR_LEFT_SQUARE_BRACKET:JT,CHAR_PLUS:YT,CHAR_QUESTION_MARK:Nv,CHAR_RIGHT_CURLY_BRACE:XT,CHAR_RIGHT_PARENTHESES:Lv,CHAR_RIGHT_SQUARE_BRACKET:QT}=go(),Fv=r=>r===qv||r===Yi,jv=r=>{r.isPrefix!==!0&&(r.depth=r.isGlobstar?1/0:1)},ZT=(r,e)=>{let t=e||{},n=r.length-1,i=t.parts===!0||t.tokens===!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,g=!1,b=!1,v=!1,S=!1,_=!1,E=0,k,$,M={value:"",depth:0,isGlob:!1},x=()=>l>=n,q=()=>c.charCodeAt(l+1),T=()=>(k=$,c.charCodeAt(++l));for(;l0&&(P=c.slice(0,u),c=c.slice(u),d-=u),V&&m===!0&&d>0?(V=c.slice(0,d),C=c.slice(d)):m===!0?(V="",C=c):V=c,V&&V!==""&&V!=="/"&&V!==c&&Fv(V.charCodeAt(V.length-1))&&(V=V.slice(0,-1)),t.unescape===!0&&(C&&(C=Dv.removeBackslashes(C)),V&&b===!0&&(V=Dv.removeBackslashes(V)));let Be={prefix:P,input:r,start:u,base:V,glob:C,isBrace:f,isBracket:p,isGlob:m,isExtglob:h,isGlobstar:y,negated:v,negatedExtglob:S};if(t.tokens===!0&&(Be.maxDepth=0,Fv($)||o.push(M),Be.tokens=o),t.parts===!0||t.tokens===!0){let ce;for(let ke=0;ke=u&&(a.push(Hn),ce=Ns)}let ct=ce!==void 0?ce+1:u,xt=r.slice(ct);a.push(xt),t.tokens&&ce&&ce+1{"use strict";var vo=go(),Et=bo(),{MAX_LENGTH:mc,POSIX_REGEX_SOURCE:eR,REGEX_NON_SPECIAL_CHARS:tR,REGEX_SPECIAL_CHARS_BACKREF:rR,REPLACEMENTS:Vv}=vo,nR=(r,e)=>{if(typeof e.expandRange=="function")return e.expandRange(...r,e);r.sort();let t=`[${r.join("-")}]`;try{new RegExp(t)}catch{return r.map(i=>Et.escapeRegex(i)).join("..")}return t},Xi=(r,e)=>`Missing ${r}: "${e}" - use "\\\\${e}" to match literal characters`,Hv=r=>{let e=[],t=0,n=0,i=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==='"'){i=i===1?0:1,s+=a;continue}if(i===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(s),s="";continue}}}s+=a}return e.push(s),e},iR=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},hp=r=>{let e=r.trim(),t=!0;for(;t===!0;)t=!1,/^@\([^\\()[\]{}|]+\)$/.test(e)&&(e=e.slice(2,-1),t=!0);if(iR(e))return e.replace(/\\(.)/g,"$1")},sR=r=>{let e=r.map(hp).filter(Boolean);for(let t=0;t{if(r[0]!=="+"&&r[0]!=="*"||r[1]!=="(")return;let t=0,n=0,i=0,s=!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}}}}},oR=r=>`${r.length===1?Et.escapeRegex(r[0]):`[${r.map(t=>Et.escapeRegex(t)).join("")}]`}*`,aR=r=>{let e=0,t=[];for(;eo.trim());if(i.length!==1)return;let s=hp(i[0]);if(!s||s.length!==1)return;t.push(s),e+=n.end+1}if(!(t.length<1))return t},cR=r=>{let e=0,t=r.trim(),n=pp(t);for(;n;)e++,t=n.body.trim(),n=pp(t);return e},lR=(r,e)=>{if(e.maxExtglobRecursion===!1)return{risky:!1};let t=typeof e.maxExtglobRecursion=="number"?e.maxExtglobRecursion:vo.DEFAULT_MAX_EXTGLOB_RECURSION,n=Hv(r).map(a=>a.trim());if(n.length>1&&(n.some(a=>a==="")||n.some(a=>/^[*?]+$/.test(a))||sR(n)))return{risky:!0};let i=[],s=!1,o=!0;for(let a of n){let c=aR(a);if(c){s=!0,i.push(...c);continue}let l=hp(a);if(l&&l.length===1){i.push(l);continue}if(o=!1,cR(a)>t)return{risky:!0}}return s?o?{risky:!0,safeOutput:oR([...new Set(i)])}:{risky:!0}:{risky:!1}},mp=(r,e)=>{if(typeof r!="string")throw new TypeError("Expected a string");r=Vv[r]||r;let t={...e},n=typeof t.maxLength=="number"?Math.min(mc,t.maxLength):mc,i=r.length;if(i>n)throw new SyntaxError(`Input length: ${i}, exceeds maximum allowed length: ${n}`);let s={type:"bos",value:"",output:t.prepend||""},o=[s],a=t.capture?"":"?:",c=vo.globChars(t.windows),l=vo.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:g,QMARK:b,QMARK_NO_DOT:v,STAR:S,START_ANCHOR:_}=c,E=I=>`(${a}(?:(?!${_}${I.dot?m:u}).)*?)`,k=t.dot?"":h,$=t.dot?b:v,M=t.bash===!0?E(t):S;t.capture&&(M=`(${M})`),typeof t.noext=="boolean"&&(t.noextglob=t.noext);let x={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=Et.removePrefix(r,x),i=r.length;let q=[],T=[],V=[],P=s,C,Be=()=>x.index===i-1,ce=x.peek=(I=1)=>r[x.index+I],ct=x.advance=()=>r[++x.index]||"",xt=()=>r.slice(x.index+1),ke=(I="",ve=0)=>{x.consumed+=I,x.index+=ve},Ai=I=>{x.output+=I.output!=null?I.output:I.value,ke(I.value)},Ns=()=>{let I=1;for(;ce()==="!"&&(ce(2)!=="("||ce(3)==="?");)ct(),x.start++,I++;return I%2===0?!1:(x.negated=!0,x.start++,!0)},Hn=I=>{x[I]++,V.push(I)},on=I=>{x[I]--,V.pop()},Z=I=>{if(P.type==="globstar"){let ve=x.braces>0&&(I.type==="comma"||I.type==="brace"),R=I.extglob===!0||q.length&&(I.type==="pipe"||I.type==="paren");I.type!=="slash"&&I.type!=="paren"&&!ve&&!R&&(x.output=x.output.slice(0,-P.output.length),P.type="star",P.value="*",P.output=M,x.output+=P.output)}if(q.length&&I.type!=="paren"&&(q[q.length-1].inner+=I.value),(I.value||I.output)&&Ai(I),P&&P.type==="text"&&I.type==="text"){P.output=(P.output||P.value)+I.value,P.value+=I.value;return}I.prev=P,o.push(I),P=I},ka=(I,ve)=>{let R={...l[ve],conditions:1,inner:""};R.prev=P,R.parens=x.parens,R.output=x.output,R.startIndex=x.index,R.tokensIndex=o.length;let ee=(t.capture?"(":"")+R.open;Hn("parens"),Z({type:I,value:ve,output:x.output?"":p}),Z({type:"paren",extglob:!0,value:ct(),output:ee}),q.push(R)},Qx=I=>{let ve=r.slice(I.startIndex,x.index+1),R=r.slice(I.startIndex+2,x.index),ee=lR(R,t);if((I.type==="plus"||I.type==="star")&&ee.risky){let ue=ee.safeOutput?(I.output?"":p)+(t.capture?`(${ee.safeOutput})`:ee.safeOutput):void 0,hr=o[I.tokensIndex];hr.type="text",hr.value=ve,hr.output=ue||Et.escapeRegex(ve);for(let zn=I.tokensIndex+1;zn1&&I.inner.includes("/")&&(ue=E(t)),(ue!==M||Be()||/^\)+$/.test(xt()))&&(he=I.close=`)$))${ue}`),I.inner.includes("*")&&(Pe=xt())&&/^\.[^\\/.]+$/.test(Pe)){let hr=mp(Pe,{...e,fastpaths:!1}).output;he=I.close=`)${hr})${ue})`}I.prev.type==="bos"&&(x.negatedExtglob=!0)}Z({type:"paren",extglob:!0,value:C,output:he}),on("parens")};if(t.fastpaths!==!1&&!/(^[*!]|[/()[\]{}"])/.test(r)){let I=!1,ve=r.replace(rR,(R,ee,he,Pe,ue,hr)=>Pe==="\\"?(I=!0,R):Pe==="?"?ee?ee+Pe+(ue?b.repeat(ue.length):""):hr===0?$+(ue?b.repeat(ue.length):""):b.repeat(he.length):Pe==="."?u.repeat(he.length):Pe==="*"?ee?ee+Pe+(ue?M:""):M:ee?R:`\\${R}`);return I===!0&&(t.unescape===!0?ve=ve.replace(/\\/g,""):ve=ve.replace(/\\+/g,R=>R.length%2===0?"\\\\":R?"\\":"")),ve===r&&t.contains===!0?(x.output=r,x):(x.output=Et.wrapOutput(ve,x,e),x)}for(;!Be();){if(C=ct(),C==="\0")continue;if(C==="\\"){let R=ce();if(R==="/"&&t.bash!==!0||R==="."||R===";")continue;if(!R){C+="\\",Z({type:"text",value:C});continue}let ee=/^\\+/.exec(xt()),he=0;if(ee&&ee[0].length>2&&(he=ee[0].length,x.index+=he,he%2!==0&&(C+="\\")),t.unescape===!0?C=ct():C+=ct(),x.brackets===0){Z({type:"text",value:C});continue}}if(x.brackets>0&&(C!=="]"||P.value==="["||P.value==="[^")){if(t.posix!==!1&&C===":"){let R=P.value.slice(1);if(R.includes("[")&&(P.posix=!0,R.includes(":"))){let ee=P.value.lastIndexOf("["),he=P.value.slice(0,ee),Pe=P.value.slice(ee+2),ue=eR[Pe];if(ue){P.value=he+ue,x.backtrack=!0,ct(),!s.output&&o.indexOf(P)===1&&(s.output=p);continue}}}(C==="["&&ce()!==":"||C==="-"&&ce()==="]")&&(C=`\\${C}`),C==="]"&&(P.value==="["||P.value==="[^")&&(C=`\\${C}`),t.posix===!0&&C==="!"&&P.value==="["&&(C="^"),P.value+=C,Ai({value:C});continue}if(x.quotes===1&&C!=='"'){C=Et.escapeRegex(C),P.value+=C,Ai({value:C});continue}if(C==='"'){x.quotes=x.quotes===1?0:1,t.keepQuotes===!0&&Z({type:"text",value:C});continue}if(C==="("){Hn("parens"),Z({type:"paren",value:C});continue}if(C===")"){if(x.parens===0&&t.strictBrackets===!0)throw new SyntaxError(Xi("opening","("));let R=q[q.length-1];if(R&&x.parens===R.parens+1){Qx(q.pop());continue}Z({type:"paren",value:C,output:x.parens?")":"\\)"}),on("parens");continue}if(C==="["){if(t.nobracket===!0||!xt().includes("]")){if(t.nobracket!==!0&&t.strictBrackets===!0)throw new SyntaxError(Xi("closing","]"));C=`\\${C}`}else Hn("brackets");Z({type:"bracket",value:C});continue}if(C==="]"){if(t.nobracket===!0||P&&P.type==="bracket"&&P.value.length===1){Z({type:"text",value:C,output:`\\${C}`});continue}if(x.brackets===0){if(t.strictBrackets===!0)throw new SyntaxError(Xi("opening","["));Z({type:"text",value:C,output:`\\${C}`});continue}on("brackets");let R=P.value.slice(1);if(P.posix!==!0&&R[0]==="^"&&!R.includes("/")&&(C=`/${C}`),P.value+=C,Ai({value:C}),t.literalBrackets===!1||Et.hasRegexChars(R))continue;let ee=Et.escapeRegex(P.value);if(x.output=x.output.slice(0,-P.value.length),t.literalBrackets===!0){x.output+=ee,P.value=ee;continue}P.value=`(${a}${ee}|${P.value})`,x.output+=P.value;continue}if(C==="{"&&t.nobrace!==!0){Hn("braces");let R={type:"brace",value:C,output:"(",outputIndex:x.output.length,tokensIndex:x.tokens.length};T.push(R),Z(R);continue}if(C==="}"){let R=T[T.length-1];if(t.nobrace===!0||!R){Z({type:"text",value:C,output:C});continue}let ee=")";if(R.dots===!0){let he=o.slice(),Pe=[];for(let ue=he.length-1;ue>=0&&(o.pop(),he[ue].type!=="brace");ue--)he[ue].type!=="dots"&&Pe.unshift(he[ue].value);ee=nR(Pe,t),x.backtrack=!0}if(R.comma!==!0&&R.dots!==!0){let he=x.output.slice(0,R.outputIndex),Pe=x.tokens.slice(R.tokensIndex);R.value=R.output="\\{",C=ee="\\}",x.output=he;for(let ue of Pe)x.output+=ue.output||ue.value}Z({type:"brace",value:C,output:ee}),on("braces"),T.pop();continue}if(C==="|"){q.length>0&&q[q.length-1].conditions++,Z({type:"text",value:C});continue}if(C===","){let R=C,ee=T[T.length-1];ee&&V[V.length-1]==="braces"&&(ee.comma=!0,R="|"),Z({type:"comma",value:C,output:R});continue}if(C==="/"){if(P.type==="dot"&&x.index===x.start+1){x.start=x.index+1,x.consumed="",x.output="",o.pop(),P=s;continue}Z({type:"slash",value:C,output:f});continue}if(C==="."){if(x.braces>0&&P.type==="dot"){P.value==="."&&(P.output=u);let R=T[T.length-1];P.type="dots",P.output+=C,P.value+=C,R.dots=!0;continue}if(x.braces+x.parens===0&&P.type!=="bos"&&P.type!=="slash"){Z({type:"text",value:C,output:u});continue}Z({type:"dot",value:C,output:u});continue}if(C==="?"){if(!(P&&P.value==="(")&&t.noextglob!==!0&&ce()==="("&&ce(2)!=="?"){ka("qmark",C);continue}if(P&&P.type==="paren"){let ee=ce(),he=C;(P.value==="("&&!/[!=<:]/.test(ee)||ee==="<"&&!/<([!=]|\w+>)/.test(xt()))&&(he=`\\${C}`),Z({type:"text",value:C,output:he});continue}if(t.dot!==!0&&(P.type==="slash"||P.type==="bos")){Z({type:"qmark",value:C,output:v});continue}Z({type:"qmark",value:C,output:b});continue}if(C==="!"){if(t.noextglob!==!0&&ce()==="("&&(ce(2)!=="?"||!/[!=<:]/.test(ce(3)))){ka("negate",C);continue}if(t.nonegate!==!0&&x.index===0){Ns();continue}}if(C==="+"){if(t.noextglob!==!0&&ce()==="("&&ce(2)!=="?"){ka("plus",C);continue}if(P&&P.value==="("||t.regex===!1){Z({type:"plus",value:C,output:d});continue}if(P&&(P.type==="bracket"||P.type==="paren"||P.type==="brace")||x.parens>0){Z({type:"plus",value:C});continue}Z({type:"plus",value:d});continue}if(C==="@"){if(t.noextglob!==!0&&ce()==="("&&ce(2)!=="?"){Z({type:"at",extglob:!0,value:C,output:""});continue}Z({type:"text",value:C});continue}if(C!=="*"){(C==="$"||C==="^")&&(C=`\\${C}`);let R=tR.exec(xt());R&&(C+=R[0],x.index+=R[0].length),Z({type:"text",value:C});continue}if(P&&(P.type==="globstar"||P.star===!0)){P.type="star",P.star=!0,P.value+=C,P.output=M,x.backtrack=!0,x.globstar=!0,ke(C);continue}let I=xt();if(t.noextglob!==!0&&/^\([^?]/.test(I)){ka("star",C);continue}if(P.type==="star"){if(t.noglobstar===!0){ke(C);continue}let R=P.prev,ee=R.prev,he=R.type==="slash"||R.type==="bos",Pe=ee&&(ee.type==="star"||ee.type==="globstar");if(t.bash===!0&&(!he||I[0]&&I[0]!=="/")){Z({type:"star",value:C,output:""});continue}let ue=x.braces>0&&(R.type==="comma"||R.type==="brace"),hr=q.length&&(R.type==="pipe"||R.type==="paren");if(!he&&R.type!=="paren"&&!ue&&!hr){Z({type:"star",value:C,output:""});continue}for(;I.slice(0,3)==="/**";){let ki=r[x.index+4];if(ki&&ki!=="/")break;I=I.slice(3),ke("/**",3)}let zn=Be()||x.parens>0&&I===")".repeat(x.parens)&&!q.some(ki=>ki.type==="negate");if(R.type==="bos"&&Be()){P.type="globstar",P.value+=C,P.output=E(t),x.output=P.output,x.globstar=!0,ke(C);continue}if(R.type==="slash"&&R.prev.type!=="bos"&&!Pe&&zn){x.output=x.output.slice(0,-(R.output+P.output).length),R.output=`(?:${R.output}`,P.type="globstar",P.output=E(t)+(t.strictSlashes?")":"|$)"),P.value+=C,x.globstar=!0,x.output+=R.output+P.output,ke(C);continue}if(R.type==="slash"&&R.prev.type!=="bos"&&I[0]==="/"){let ki=I[1]!==void 0?"|$":"";x.output=x.output.slice(0,-(R.output+P.output).length),R.output=`(?:${R.output}`,P.type="globstar",P.output=`${E(t)}${f}|${f}${ki})`,P.value+=C,x.output+=R.output+P.output,x.globstar=!0,ke(C+ct()),Z({type:"slash",value:"/",output:""});continue}if(R.type==="bos"&&I[0]==="/"){P.type="globstar",P.value+=C,P.output=`(?:^|${f}|${E(t)}${f})`,x.output=P.output,x.globstar=!0,ke(C+ct()),Z({type:"slash",value:"/",output:""});continue}x.output=x.output.slice(0,-P.output.length),P.type="globstar",P.output=E(t),P.value+=C,x.output+=P.output,x.globstar=!0,ke(C);continue}let ve={type:"star",value:C,output:M};if(t.bash===!0){ve.output=".*?",(P.type==="bos"||P.type==="slash")&&(ve.output=k+ve.output),Z(ve);continue}if(P&&(P.type==="bracket"||P.type==="paren")&&t.regex===!0){ve.output=C,Z(ve);continue}(x.index===x.start||P.type==="slash"||P.type==="dot")&&(P.type==="dot"?(x.output+=y,P.output+=y):t.dot===!0?(x.output+=g,P.output+=g):(x.output+=k,P.output+=k),ce()!=="*"&&(x.output+=p,P.output+=p)),Z(ve)}for(;x.brackets>0;){if(t.strictBrackets===!0)throw new SyntaxError(Xi("closing","]"));x.output=Et.escapeLast(x.output,"["),on("brackets")}for(;x.parens>0;){if(t.strictBrackets===!0)throw new SyntaxError(Xi("closing",")"));x.output=Et.escapeLast(x.output,"("),on("parens")}for(;x.braces>0;){if(t.strictBrackets===!0)throw new SyntaxError(Xi("closing","}"));x.output=Et.escapeLast(x.output,"{"),on("braces")}if(t.strictSlashes!==!0&&(P.type==="star"||P.type==="bracket")&&Z({type:"maybe_slash",value:"",output:`${f}?`}),x.backtrack===!0){x.output="";for(let I of x.tokens)x.output+=I.output!=null?I.output:I.value,I.suffix&&(x.output+=I.suffix)}return x};mp.fastpaths=(r,e)=>{let t={...e},n=typeof t.maxLength=="number"?Math.min(mc,t.maxLength):mc,i=r.length;if(i>n)throw new SyntaxError(`Input length: ${i}, exceeds maximum allowed length: ${n}`);r=Vv[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}=vo.globChars(t.windows),m=t.dot?u:l,h=t.dot?d:l,y=t.capture?"":"?:",g={negated:!1,prefix:""},b=t.bash===!0?".*?":f;t.capture&&(b=`(${b})`);let v=k=>k.noglobstar===!0?b:`(${y}(?:(?!${p}${k.dot?c:s}).)*?)`,S=k=>{switch(k){case"*":return`${m}${a}${b}`;case".*":return`${s}${a}${b}`;case"*.*":return`${m}${b}${s}${a}${b}`;case"*/*":return`${m}${b}${o}${a}${h}${b}`;case"**":return m+v(t);case"**/*":return`(?:${m}${v(t)}${o})?${h}${a}${b}`;case"**/*.*":return`(?:${m}${v(t)}${o})?${h}${b}${s}${a}${b}`;case"**/.*":return`(?:${m}${v(t)}${o})?${s}${a}${b}`;default:{let $=/^(.*?)\.(\w+)$/.exec(k);if(!$)return;let M=S($[1]);return M?M+s+$[2]:void 0}}},_=Et.removePrefix(r,g),E=S(_);return E&&t.strictSlashes!==!0&&(E+=`${o}?`),E};zv.exports=mp});var Jv=A((nB,Gv)=>{"use strict";var dR=Uv(),yp=Kv(),Wv=bo(),uR=go(),fR=r=>r&&typeof r=="object"&&!Array.isArray(r),xe=(r,e,t=!1)=>{if(Array.isArray(r)){let u=r.map(f=>xe(f,e,t));return f=>{for(let p of u){let m=p(f);if(m)return m}return!1}}let n=fR(r)&&r.tokens&&r.input;if(r===""||typeof r!="string"&&!n)throw new TypeError("Expected pattern to be a non-empty string");let i=e||{},s=i.windows,o=n?xe.compileRe(r,e):xe.makeRe(r,e,!1,!0),a=o.state;delete o.state;let c=()=>!1;if(i.ignore){let u={...e,ignore:null,onMatch:null,onResult:null};c=xe(i.ignore,u,t)}let l=(u,d=!1)=>{let{isMatch:f,match:p,output:m}=xe.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 i.onResult=="function"&&i.onResult(h),f===!1?(h.isMatch=!1,d?h:!1):c(u)?(typeof i.onIgnore=="function"&&i.onIgnore(h),h.isMatch=!1,d?h:!1):(typeof i.onMatch=="function"&&i.onMatch(h),d?h:!0)};return t&&(l.state=a),l};xe.test=(r,e,t,{glob:n,posix:i}={})=>{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||(i?Wv.toPosixSlashes:null),a=r===n,c=a&&o?o(r):r;return a===!1&&(c=o?o(r):r,a=c===n),(a===!1||s.capture===!0)&&(s.matchBase===!0||s.basename===!0?a=xe.matchBase(r,e,t,i):a=e.exec(c)),{isMatch:!!a,match:a,output:c}};xe.matchBase=(r,e,t,n=t&&t.windows)=>(e instanceof RegExp?e:xe.makeRe(e,t)).test(Wv.basename(r,{windows:n}));xe.isMatch=(r,e,t)=>xe(e,t)(r);xe.parse=(r,e)=>Array.isArray(r)?r.map(t=>xe.parse(t,e)):yp(r,{...e,fastpaths:!1});xe.scan=(r,e)=>dR(r,e);xe.compileRe=(r,e,t=!1,n=!1)=>{if(t===!0)return r.output;let i=e||{},s=i.contains?"":"^",o=i.contains?"":"$",a=`${s}(?:${r.output})${o}`;r&&r.negated===!0&&(a=`^(?!${a}).*$`);let c=xe.toRegex(a,e);return n===!0&&(c.state=r),c};xe.makeRe=(r,e={},t=!1,n=!1)=>{if(!r||typeof r!="string")throw new TypeError("Expected a non-empty string");let i={negated:!1,fastpaths:!0};return e.fastpaths!==!1&&(r[0]==="."||r[0]==="*")&&(i.output=yp.fastpaths(r,e)),i.output||(i=yp(r,e)),xe.compileRe(i,e,t,n)};xe.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/$^/}};xe.constants=uR;Gv.exports=xe});var gp=A((iB,Qv)=>{"use strict";var Yv=Jv(),pR=bo();function Xv(r,e,t=!1){return e&&(e.windows===null||e.windows===void 0)&&(e={...e,windows:pR.isWindows()}),Yv(r,e,t)}Object.assign(Xv,Yv);Qv.exports=Xv});function bp(r,e){return yc(e.split("/"),r.split("/"))}function yc(r,e){if(e.length===0)return r.length===0;let[t,...n]=e;return t==="**"?yc(r,n)||r.length>0&&yc(r.slice(1),e):r.length===0?!1:Qi([...r[0]],[...t])&&yc(r.slice(1),n)}function Qi(r,e){if(e.length===0)return r.length===0;let[t,...n]=e;if(t==="*")return Qi(r,n)||r.length>0&&Qi(r.slice(1),e);if(t==="?")return r.length>0&&Qi(r.slice(1),n);if(t==="["){let i=hR(n);if(i)return r.length>0&&i.matches(r[0])&&Qi(r.slice(1),i.after)}return r[0]===t&&Qi(r.slice(1),n)}function hR(r){let e=r[0]==="!",t=[],n=e?1:0,i=!0;for(;n{let c=wo(a);return t.some(([l,u])=>l<=c&&c<=u)!==e},after:r.slice(n+1)};n+2{});var mw={};ay(mw,{MdbasePathError:()=>So,applyReadDefaults:()=>qR,buildInitialFrontmatter:()=>Rp,buildTypeTemplate:()=>Tp,buildUniqueNotePath:()=>Op,coerceFieldInput:()=>Sc,createNoteFromType:()=>HR,createTypeDefinition:()=>BR,ensureCollectionInitialized:()=>$o,fieldsFromV03Schema:()=>gn,formatMarkdown:()=>mt,getPromptFields:()=>Ip,getTopLevelFieldFromIssuePath:()=>Dp,getTypesForFile:()=>Ke,isExcluded:()=>yt,loadContractDefinitions:()=>kp,loadMdbaseConfig:()=>ai,loadTypeDefinitions:()=>Ap,normalizeSafeRelativePath:()=>yn,parseFrontmatter:()=>Me,readCollectionRecords:()=>Ep,resolveFilenameForType:()=>fw,resolveFolderForType:()=>uw,schemaFromV03Fields:()=>es,slugify:()=>$p,v03TypeDefFromFrontmatter:()=>wc,validateCollection:()=>Mp,validateFile:()=>_c,validateRecordAgainstType:()=>ts});function yR(){return _o||(_o=new tw.Ajv2020({allErrors:!0,strict:!1,allowUnionTypes:!0}),(0,rw.default)(_o),_o)}function W(r){return!!r&&typeof r=="object"&&!Array.isArray(r)}function Oe(r){return JSON.parse(JSON.stringify(r))}function gR(r){if(r===!0)return!0;if(r===!1)return!1;if(r==="warn")return"warn"}function vp(r){return Array.isArray(r)?`[${r.map(e=>vp(e)).join(",")}]`:W(r)?`{${Object.keys(r).sort().map(t=>`${JSON.stringify(t)}:${vp(r[t])}`).join(",")}}`:JSON.stringify(r)}function bR(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 vR(r){let e=new Map,t=new Set,n=i=>{let s=e.get(i);if(s)return s;let o=r.get(i);if(!o)return null;if(t.has(i)){let l={...o,fields:Oe(o.fields)};return e.set(i,l),l}t.add(i);let a=o.extends?n(o.extends):null;t.delete(i);let c={...o,fields:a?{...Oe(a.fields),...Oe(o.fields)}:Oe(o.fields),display_name_key:o.display_name_key??a?.display_name_key,path_pattern:o.path_pattern??a?.path_pattern,filename_pattern:o.filename_pattern??a?.filename_pattern,strict:o.strict!==void 0?o.strict:a?.strict,match:o.match??a?.match};return e.set(i,c),c};for(let i of r.keys())n(i);return e}function nw(r){let e=(0,oe.normalizePath)(r),t=e.lastIndexOf("/");return t>=0?e.slice(0,t):""}function iw(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 sw(r){return/^[a-z][a-z0-9+.-]*:\/\//i.test(r)}function ow(r,e,t){let n=iw(t);if(!n||sw(n))return null;let i=new Set,s=(0,oe.normalizePath)(n);i.add(s),s.endsWith(".md")||i.add(`${s}.md`);let o=nw(e);if(o){let c=(0,oe.normalizePath)(`${o}/${n}`);i.add(c),c.endsWith(".md")||i.add(`${c}.md`)}for(let c of i){let l=r.getAbstractFileByPath(c);if(l instanceof oe.TFile)return l}let a=n.replace(/\.md$/i,"");return r.getMarkdownFiles().find(c=>c.basename===a)??null}function wR(r,e,t){return sw(iw(t))||ow(r,e,t)!==null}function Me(r){let e=(0,oe.getFrontMatterInfo)(r);if(!e.exists)return{hasFrontmatter:!1,frontmatter:{},body:r};try{let t=e.frontmatter,n=(0,oe.parseYaml)(t);return n==null&&t.trim()!==""?{hasFrontmatter:!0,frontmatter:{},body:r.slice(e.contentStart),error:"Frontmatter must be a YAML object"}:n!=null&&!W(n)?{hasFrontmatter:!0,frontmatter:{},body:r.slice(e.contentStart),error:"Frontmatter must be a YAML object"}:{hasFrontmatter:!0,frontmatter:n??{},body:r.slice(e.contentStart)}}catch(t){return{hasFrontmatter:!0,frontmatter:{},body:r.slice(e.contentStart),error:t instanceof Error?t.message:String(t)}}}function mt(r,e=""){if(Object.keys(r).length===0)return e;let t=(0,oe.stringifyYaml)(r).trimEnd(),n=e.replace(/^\n+/,"");return`--- ${t} --- -${n}`}async function ai(r){let e=r.getAbstractFileByPath("mdbase.yaml");if(!(e instanceof oe.TFile))return null;try{let t=await r.cachedRead(e),n=(0,oe.parseYaml)(t);if(!W(n))return null;let i=W(n.settings)?n.settings:{},s=W(n.runtime)?n.runtime:void 0;return{spec_version:typeof n.spec_version=="string"?n.spec_version:qr.spec_version,name:typeof n.name=="string"?n.name:qr.name,description:typeof n.description=="string"?n.description:qr.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 i.types_folder=="string"?i.types_folder:qr.settings.types_folder,contracts_folder:typeof i.contracts_folder=="string"?i.contracts_folder:qr.settings.contracts_folder,explicit_type_keys:Array.isArray(i.explicit_type_keys)?i.explicit_type_keys.filter(o=>typeof o=="string"):[...qr.settings.explicit_type_keys],...typeof i.default_strict=="boolean"?{default_strict:i.default_strict}:{},...typeof i.include_subfolders=="boolean"?{include_subfolders:i.include_subfolders}:{},exclude:Array.isArray(i.exclude)?i.exclude.filter(o=>typeof o=="string"):Mp(n.spec_version)?[]:[...hR]}}}catch{return null}}async function $o(r,e={}){let t=[];if(!(r.getAbstractFileByPath("mdbase.yaml")instanceof oe.TFile)){let l=(0,oe.stringifyYaml)(qr).trimEnd()+` -`;await r.create("mdbase.yaml",l),t.push("mdbase.yaml")}let i=await ai(r)??qr,s=i.settings.types_folder;await r.adapter.exists(s)||(await r.createFolder(s),t.push(s));let a=(0,oe.normalizePath)(`${s}/note.md`);if(!await r.adapter.exists(a)&&e.seedNoteType!==!1){let l=Rp("note",void 0,i.spec_version);await r.create(a,l),t.push(a)}return{created:t}}function aw(r,e){let t=W(r)?r:{},n=Array.isArray(t.type)?t.type.find(s=>s!=="null"):t.type,i={required:e};return Array.isArray(t.enum)?(i.type="enum",i.values=Oe(t.enum)):n==="array"?(i.type="list",i.items=aw(t.items,!1)):n==="object"?(i.type="object",i.fields=gn(t)):n==="string"&&t.format==="date"?i.type="date":n==="string"&&t.format==="date-time"?i.type="datetime":n==="string"&&t.format==="time"?i.type="time":typeof n=="string"?i.type=n:i.type="any",t.default!==void 0&&(i.default=Oe(t.default)),typeof t.description=="string"&&(i.description=t.description),typeof t.minimum=="number"&&(i.min=t.minimum),typeof t.maximum=="number"&&(i.max=t.maximum),typeof t.minLength=="number"&&(i.min_length=t.minLength),typeof t.maxLength=="number"&&(i.max_length=t.maxLength),typeof t.pattern=="string"&&(i.pattern=t.pattern),typeof t.minItems=="number"&&(i.min_length=t.minItems),typeof t.maxItems=="number"&&(i.max_length=t.maxItems),i}function gn(r){let e=W(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,i])=>[n,aw(i,t.has(n))]))}function cw(r,e){let t={...Oe(e)},n=r.type??"string",i=()=>{delete t.properties,delete t.required,delete t.additionalProperties},s=()=>{delete t.items};if(n==="enum")delete t.type,t.enum=Oe(r.values??[]),delete t.format,i(),s();else if(n==="list")t.type="array",delete t.enum,delete t.format,i(),t.items=cw(r.items??{type:"any"},W(t.items)?t.items:{});else if(n==="object"){t.type="object",delete t.enum,delete t.format,s();let c=es(r.fields??{},W(t)?t:{},!1);t.properties=c.properties,c.required?t.required=c.required:delete t.required}else n==="link"?(t.type="string",delete t.enum,delete t.format,i(),s()):["date","datetime","time"].includes(n)?(t.type="string",t.format=n==="datetime"?"date-time":n,delete t.enum,i(),s()):["string","integer","number","boolean"].includes(n)?(t.type=n,delete t.format,delete t.enum,i(),s()):(delete t.type,delete t.enum,delete t.format,i(),s());r.default!==void 0?t.default=Oe(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 es(r,e={},t=!1){let n=W(e.properties)?e.properties:{},i=Object.create(null),s=[];for(let[a,c]of Object.entries(r))i[a]=cw(c,W(n[a])?n[a]:{}),c.required===!0&&s.push(a);let o={...Oe(e),type:"object",properties:i,additionalProperties:!t};return s.length>0?o.required=s:delete o.required,o}function lw(r,e){if(!e)return r;if(!e.startsWith("/"))return;let t=r;for(let n of e.slice(1).split("/")){let i=n.replace(/~1/g,"/").replace(/~0/g,"~");if(Array.isArray(t)){let s=Number(i);if(!Number.isInteger(s)||s<0||s>=t.length)return;t=t[s]}else if(W(t)&&i in t)t=t[i];else return}return t}async function dw(r,e,t){let[n,i=""]=t.split("#",2);if(!n||/^[a-z][a-z0-9+.-]*:/i.test(n)||n.startsWith("/"))return null;let s=nw(e),o=[];for(let l of`${s}/${n}`.replace(/\\/g,"/").split("/"))if(!(!l||l==="."))if(l===".."){if(o.length===0)return null;o.pop()}else o.push(l);let a=(0,oe.normalizePath)(o.join("/")),c=r.getAbstractFileByPath(a);if(!(c instanceof oe.TFile))return null;try{let l=JSON.parse(await r.cachedRead(c)),u=lw(l,i);return W(u)?u:null}catch{return null}}function wc(r,e,t){let n=W(r.collection)?Oe(r.collection):void 0,i=gn(t);for(let s of n?.unique??[])typeof s.field=="string"&&i[s.field]&&(i[s.field].unique=!0,i[s.field].unique_scope=s.scope);for(let[s,o]of Object.entries(n?.links??{}))i[s]&&(i[s].target=o.target_type,i[s].validate_exists=o.validate_exists);return{name:String(r.name),version:typeof r.version=="number"?r.version:void 0,description:typeof r.description=="string"?r.description:void 0,display_name_key:n?.display?.name_field,path_pattern:n?.path?.pattern,strict:t.additionalProperties===!1,match:W(r.match)?r.match:void 0,fields:i,filePath:e,specProfile:"v0.3",schema:Oe(t),collection:n,originalFrontmatter:Oe(r)}}async function Ap(r,e){let t=[];for(let n of r.getMarkdownFiles()){if(yt(n.path,e))continue;let i=Me(await r.cachedRead(n));i.error||t.push({path:n.path,frontmatter:i.frontmatter})}return t}function ts(r,e,t){let n=[];return hw(r,e,t,n),n}async function kp(r,e){let t=new Map,n=`${(0,oe.normalizePath)(e.settings.types_folder)}/`;for(let i of r.getMarkdownFiles()){if(!i.path.startsWith(n))continue;let s=await r.cachedRead(i),o=Me(s);if(!o.hasFrontmatter||o.error)continue;let a=o.frontmatter;if(e.spec_version.startsWith("0.3.")){if(a.kind!=="mdbase.type"||typeof a.name!="string"||!W(a.schema))continue;let u=a.schema,d=W(u.value)?u.value:null;if(!d&&typeof u.ref=="string"&&(d=await dw(r,i.path,u.ref)),!d)continue;t.set(a.name,wc(a,i.path,d));continue}if(!W(a.fields))continue;let c=typeof a.name=="string"&&a.name.trim().length>0?a.name.trim():i.basename,l={};for(let[u,d]of Object.entries(a.fields))W(d)&&(l[u]=d);t.set(c,{name:c,extends:typeof a.extends=="string"?a.extends:void 0,display_name_key:typeof a.display_name_key=="string"?a.display_name_key:void 0,path_pattern:typeof a.path_pattern=="string"?a.path_pattern:void 0,filename_pattern:typeof a.filename_pattern=="string"?a.filename_pattern:void 0,strict:yR(a.strict),match:W(a.match)?a.match:void 0,fields:l,filePath:i.path,specProfile:"v0.2",originalFrontmatter:Oe(a)})}return bR(t)}async function Pp(r,e){let t=new Map,n=`${(0,oe.normalizePath)(e.settings.contracts_folder||"_contracts")}/`;for(let i of r.getMarkdownFiles()){if(!i.path.startsWith(n))continue;let s=Me(await r.cachedRead(i));if(!s.hasFrontmatter||s.error)continue;let o=s.frontmatter;if(o.kind!=="mdbase.contract"||o.contract_type!=="record"||typeof o.id!="string"||typeof o.version!="string")continue;let a=W(o.record_schema)?o.record_schema:{},c=W(o.binding_schema)?o.binding_schema:void 0,l=await ew(r,i.path,a);if(!l)continue;let u=c?await ew(r,i.path,c):null,d=`${o.id}@${o.version}`;t.set(d,{contract_type:"record",id:o.id,version:o.version,digest:typeof o.digest=="string"?o.digest:"",schema:l,...u?{binding_schema:u}:{},implementations:[]})}return t}async function ew(r,e,t){return W(t.value)?Oe(t.value):typeof t.ref!="string"?null:dw(r,e,t.ref)}function wR(r,e){for(let t of e){let n=r[t];if(Array.isArray(n))return n.filter(s=>typeof s=="string")}for(let t of e){let n=r[t];if(typeof n=="string"&&n.trim().length>0)return[n.trim()]}return null}function Cp(r,e){return r.replace(/\{([^}]+)\}/g,(t,n)=>{let i=e[n];return i==null?"":Array.isArray(i)?i.filter(s=>["string","number","boolean"].includes(typeof s)).map(String).join("-"):typeof i=="string"?i:typeof i=="number"||typeof i=="boolean"?String(i):""})}function yn(r){let e=r.replace(/\\/g,"/");if(!e||e.startsWith("/")||/^[A-Za-z]:\//.test(e)||e.includes("\0"))throw new So("invalid_path",`Invalid collection-relative path: ${r}`);let t=e.split("/");if(t.includes(".."))throw new So("path_traversal",`Path escapes the collection root: ${r}`);return(0,oe.normalizePath)(t.filter(n=>n&&n!==".").join("/"))}function _R(r){let e=r.search(/[*?]|\[/),n=(e===-1?r:r.slice(0,e)).replace(/\/+$/,"");if(n.endsWith(".md")){let i=n.lastIndexOf("/");return i>=0?n.slice(0,i):""}return n}function uw(r,e){if(r.path_pattern){let t=(0,oe.normalizePath)(Cp(r.path_pattern,e));if(t.endsWith(".md")){let n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}return t.replace(/\/+$/,"")}return r.match?.path_glob?_R(r.match.path_glob):""}function fw(r,e){let t=r.display_name_key??"title",n=e[t],i=`${r.name}-${new Date().toISOString().slice(0,10)}`,s=typeof n=="string"&&n.trim().length>0?n:i;if(r.filename_pattern&&r.filename_pattern.trim().length>0){let o=(0,oe.normalizePath)(Cp(r.filename_pattern,e)),c=(o.split("/").pop()??o).replace(/\.md$/i,"").trim();if(c.length>0)return`${xp(c)}.md`}return`${xp(s)}.md`}function Zi(r){return Array.isArray(r)?`[${r.map(Zi).join(",")}]`:W(r)?`{${Object.keys(r).sort().map(e=>`${JSON.stringify(e)}:${Zi(r[e])}`).join(",")}}`:JSON.stringify(r)}function SR(r,e){let t=[r];for(let n of e.split(".").filter(Boolean)){let i=n.endsWith("[]"),s=i?n.slice(0,-2):n,o=[];for(let a of t){if(!W(a)||!Object.prototype.hasOwnProperty.call(a,s))continue;let c=a[s];i&&Array.isArray(c)?o.push(...c):i||o.push(c)}if(!o.length)return{present:!1,value:void 0};t=o}return{present:!0,value:t[0]}}function gc(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 $R(r,e,t,n){let i=(s,o)=>Zi(s)===Zi(o);switch(e){case"eq":case"const":return r.present&&r.value!=null&&i(r.value,t);case"neq":return r.present&&r.value!=null&&!i(r.value,t);case"gt":return gc(r.value,t,(s,o)=>s>o);case"gte":return gc(r.value,t,(s,o)=>s>=o);case"lt":return gc(r.value,t,(s,o)=>ss<=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(s=>i(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=>i(o,s)));case"containsAny":return!Array.isArray(r.value)||!Array.isArray(t)?!1:t.some(s=>r.value.some(o=>i(o,s)));case"in":return r.value!=null&&Array.isArray(t)&&t.some(s=>i(s,r.value));case"startsWith":case"starts_with":return typeof r.value=="string"&&typeof t=="string"&&r.value.startsWith(t);case"endsWith":case"ends_with":return typeof r.value=="string"&&typeof t=="string"&&r.value.endsWith(t);case"matches":try{return typeof r.value=="string"&&typeof t=="string"&&new RegExp(t.replace(/\\\\/g,"\\")).test(r.value)}catch{return!1}default:return!1}}function vc(r,e,t){if("and"in r)return Array.isArray(r.and)&&r.and.every(n=>W(n)&&vc(n,e,t));if("or"in r)return Array.isArray(r.or)&&r.or.some(n=>W(n)&&vc(n,e,t));if("not"in r)return W(r.not)&&!vc(r.not,e,t);for(let[n,i]of Object.entries(r)){let s=SR(e,n);if(!W(i)){if(!s.present||Zi(s.value)!==Zi(i))return!1;continue}for(let[o,a]of Object.entries(i))if(!$R(s,o,a,t))return!1}return!0}function Ke(r,e,t,n){let i=wR(e,t.settings.explicit_type_keys);if(i)return i;let s=[];for(let[o,a]of n.entries()){let c=a.match;if(!c)continue;let l=!0;if(typeof c.path_glob=="string"&&!LR(c.path_glob,r,t)&&(l=!1),l&&Array.isArray(c.fields_present)){for(let u of c.fields_present)if(!(u in e)){l=!1;break}}l&&W(c.where)&&(l=vc(c.where,e,t.spec_version)),l&&typeof c.where=="string"&&(l=!1),l&&s.push(o)}return s}function pw(r){return r==null||typeof r=="string"&&r.trim().length===0}function xR(r){return/^\d{4}-\d{2}-\d{2}$/.test(r)}function ER(r){return/^\d{2}:\d{2}(:\d{2})?$/.test(r)}function AR(r){return typeof r=="string"||Array.isArray(r)?r.length:null}function Ce(r,e,t,n,i,s){r.push({path:e,code:n,message:i,severity:t,field:s})}function jt(r,e,t,n,i){typeof r=="number"&&(typeof e.min=="number"&&re.max&&Ce(i,n,"error","above_max",`'${t}' is ${r}; must be at most ${e.max}`,t));let s=AR(r);if(s!=null&&(typeof e.min_length=="number"&&se.max_length&&Ce(i,n,"error","above_max_length",`'${t}' has length ${s}; limit is ${e.max_length}`,t)),typeof e.pattern=="string"&&typeof r=="string")try{new RegExp(e.pattern).test(r)||Ce(i,n,"error","pattern_mismatch",`'${t}' is ${Sp(r)}; does not match /${e.pattern}/`,t)}catch(o){Ce(i,n,"warn","invalid_pattern",`Field '${t}' has invalid regex pattern: ${o instanceof Error?o.message:String(o)}`,t)}}function _p(r,e,t,n,i,s){let o=e.type??"any";if(r==null)return;e.deprecated===!0&&Ce(i,n,"warn","deprecated_field",`Field '${t}' is marked deprecated`,t);let a=c=>{Ce(i,n,"error","invalid_type",`Field '${t}' expected ${c}`,t)};switch(o){case"any":jt(r,e,t,n,i);return;case"string":if(typeof r!="string"){a("a string");return}jt(r,e,t,n,i);return;case"integer":if(typeof r!="number"||!Number.isInteger(r)){a("an integer");return}jt(r,e,t,n,i);return;case"number":if(typeof r!="number"||Number.isNaN(r)){a("a number");return}jt(r,e,t,n,i);return;case"boolean":typeof r!="boolean"&&a("a boolean");return;case"date":if(typeof r!="string"||!xR(r)){a("a date (YYYY-MM-DD)");return}jt(r,e,t,n,i);return;case"datetime":if(typeof r!="string"||Number.isNaN(Date.parse(r))){a("a datetime string");return}jt(r,e,t,n,i);return;case"time":if(typeof r!="string"||!ER(r)){a("a time string (HH:MM)");return}jt(r,e,t,n,i);return;case"enum":{let c=Array.isArray(e.values)?e.values:[];if(!c.includes(r)){Ce(i,n,"error","invalid_enum",`Field '${t}' must be one of: ${c.map(l=>String(l)).join(", ")}`,t);return}jt(r,e,t,n,i);return}case"list":{if(!Array.isArray(r)){a("a list");return}jt(r,e,t,n,i),e.items&&r.forEach((c,l)=>{_p(c,e.items,`${t}[${l}]`,n,i,s)});return}case"object":{if(!W(r)){a("an object");return}if(e.fields&&W(e.fields))for(let[c,l]of Object.entries(e.fields)){if(!W(l))continue;let u=l,d=`${t}.${c}`,f=r[c];if(u.required&&pw(f)){Ce(i,n,"error","missing_required",`Missing required field '${d}'`,d);continue}_p(f,u,d,n,i,s)}return}case"link":{if(typeof r!="string"&&!W(r)){a("a link string");return}if(e.validate_exists===!0&&s){let c=typeof r=="string"?r:typeof r.path=="string"?r.path:typeof r.file=="string"?r.file:"";(!c||!vR(s,n,c))&&Ce(i,n,"error","missing_link_target",`Field '${t}' references a missing note`,t)}return}case"tags":if(typeof r=="string"){jt(r,e,t,n,i);return}if(Array.isArray(r)&&r.every(c=>typeof c=="string")){jt(r,e,t,n,i);return}a("a tag string or list of strings");return;default:jt(r,e,t,n,i);return}}function kR(r){return r.replace(/^\//,"").split("/").filter(Boolean).map(t=>t.replace(/~1/g,"/").replace(/~0/g,"~")).join(".")||void 0}function PR(r){return r.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase()}function Sp(r){return r===null?"empty":typeof r=="string"?r.trim()?`'${r.length>40?`${r.slice(0,39)}\u2026`:r}'`:"empty":typeof r=="number"||typeof r=="boolean"?String(r):Array.isArray(r)?`a list of ${r.length}`:W(r)?"an object":r===void 0?"missing":JSON.stringify(r)??"unknown"}function bc(r,e){return`${r} ${e}${r===1?"":"s"}`}function TR(r,e,t,n){let i=r.params,s=e?`'${e}'`:"This note",o=Sp(t);switch(r.keyword){case"required":return`Missing required field '${e??String(i.missingProperty)}'`;case"additionalProperties":return`Field '${e??String(i.additionalProperty)}' is not declared by type '${n}'`;case"type":{let c=(Array.isArray(i.type)?i.type.join(","):typeof i.type=="string"?i.type:"").split(",").map(l=>CR[l]??l).join(" or ");return`${s} is ${o}; expected ${c}`}case"enum":{let a=Array.isArray(i.allowedValues)?i.allowedValues.map(l=>String(l)):[],c=a.length>6?`${a.slice(0,6).join(", ")}, \u2026`:a.join(", ");return`${s} is ${o}; expected one of ${c}`}case"const":return`${s} is ${o}; expected ${Sp(i.allowedValue)}`;case"maximum":return`${s} is ${o}; must be at most ${String(i.limit)}`;case"minimum":return`${s} is ${o}; must be at least ${String(i.limit)}`;case"exclusiveMaximum":return`${s} is ${o}; must be less than ${String(i.limit)}`;case"exclusiveMinimum":return`${s} is ${o}; must be more than ${String(i.limit)}`;case"maxLength":return`${s} is ${bc(typeof t=="string"?t.length:0,"character")}; limit is ${String(i.limit)}`;case"minLength":return`${s} is ${bc(typeof t=="string"?t.length:0,"character")}; needs at least ${String(i.limit)}`;case"maxItems":return`${s} has ${bc(Array.isArray(t)?t.length:0,"item")}; limit is ${String(i.limit)}`;case"minItems":return`${s} has ${bc(Array.isArray(t)?t.length:0,"item")}; needs at least ${String(i.limit)}`;case"uniqueItems":return`${s} contains duplicate items`;case"pattern":return`${s} is ${o}; does not match ${String(i.pattern)}`;case"format":return`${s} is ${o}; expected ${MR[String(i.format)]??String(i.format)}`;default:return`${s}: ${r.message??"invalid value"}`}}function RR(r,e,t,n={}){let i=r.params,s=kR(r.instancePath),o=typeof i.missingProperty=="string"?i.missingProperty:typeof i.additionalProperty=="string"?i.additionalProperty:void 0,a=s&&o?`${s}.${o}`:o??s,c=r.keyword==="format"?"format_invalid":`schema_${PR(r.keyword)}`,l=lw(n,r.instancePath);return{path:e,code:c,message:TR(r,a,l,t),severity:"error",field:a,type:t,schema_location:`embedded://type/schema#${r.schemaPath}`,details:{instance_path:r.instancePath,schema_path:r.schemaPath,technical_message:`JSON Schema ${r.keyword} failed for type '${t}': ${r.message??"invalid value"}`,...o===void 0?{}:{property:o}}}}function $p(r){if(Array.isArray(r)){for(let e of r){let t=$p(e);if(t)return t}return null}if(!W(r))return null;if(typeof r.$ref=="string"&&!r.$ref.startsWith("#"))return r.$ref;for(let e of Object.values(r)){let t=$p(e);if(t)return t}return null}function IR(r,e,t,n){if(!t.schema)return;let i=$p(t.schema);if(i){n.push({path:r,code:/^[a-z][a-z0-9+.-]*:/i.test(i)?"schema_ref_forbidden":"unsupported_profile",message:`Unsupported JSON Schema reference '${i}' for type '${t.name}'`,severity:"error",type:t.name});return}try{let s=mR().compile(t.schema);if(s(e))return;for(let o of s.errors??[])n.push(RR(o,r,t.name,e))}catch(s){n.push({path:r,code:"invalid_embedded_schema",message:s instanceof Error?s.message:String(s),severity:"error",type:t.name})}}async function OR(r,e,t,n,i,s,o){for(let[a,c]of Object.entries(n.collection?.links??{})){let l=t[a],u=Array.isArray(l)?l:[l];for(let d of u){if(d==null||typeof d!="string")continue;let f=ow(r,e,d);if(!f&&c.validate_exists===!0){Ce(o,e,"error","link_not_found",`Field '${a}' references a missing note`,a);continue}if(f&&c.target_type&&c.target_type!=="any"){let p=Me(await r.cachedRead(f));Ke(f.path,p.frontmatter,i,s).includes(c.target_type)||Ce(o,e,"error","link_wrong_type",`Field '${a}' must reference type '${c.target_type}'`,a)}}}}function hw(r,e,t,n,i){if(t.specProfile==="v0.3"){IR(r,e,t,n);return}for(let[s,o]of Object.entries(t.fields)){if(!W(o))continue;let a=o,c=e[s];if(a.required&&pw(c)){Ce(n,r,"error","missing_required",`Missing required field '${s}' for type '${t.name}'`,s);continue}_p(c,a,s,r,n,i)}}function DR(r){let e=new Set;for(let t of r)for(let n of Object.keys(t.fields))e.add(n);return e}function NR(r,e){let t=!1,n=!1;for(let i of r){if(i.strict===!0)return!0;i.strict==="warn"&&(t=!0),i.strict===void 0&&(n=!0)}return t||n&&e.settings.default_strict?"warn":!1}function yt(r,e){let t=(0,oe.normalizePath)(r),n=(0,oe.normalizePath)(e.settings.types_folder);if(t.startsWith(`${n}/`)||t===n)return!0;if(Mp(e.spec_version)){let i=(0,oe.normalizePath)(e.settings.contracts_folder??"_contracts");return t===i||t.startsWith(`${i}/`)||t.split("/").some(s=>s.startsWith(".")||s==="node_modules")?!0:e.settings.exclude.some(s=>vp(s,t))}if(e.settings.include_subfolders===!1&&t.includes("/"))return!0;for(let i of e.settings.exclude)if((0,Ep.default)(i,{dot:!0,matchBase:!i.includes("/")})(t)||!i.includes("*")&&!i.includes("?")&&!i.includes("/")&&t.startsWith(`${i}/`))return!0;return!1}function Mp(r){return typeof r=="string"&&r.startsWith("0.3.")}function LR(r,e,t){return Mp(t.spec_version)?vp(r,e):(0,Ep.default)(r,{dot:!0})(e)}async function _c(r,e,t,n){if(yt(e.path,t))return[];let i=[],s=await r.cachedRead(e),o=Me(s);if(o.error)return Ce(i,e.path,"error","invalid_frontmatter",o.error),i;let a=o.frontmatter,c=Ke(e.path,a,t,n);if(c.length===0)return Ce(i,e.path,"warn","no_matching_type","No type could be resolved for this file"),i;let l=c.map(f=>n.get(f)).filter(f=>!!f),u=c.filter(f=>!n.has(f));if(u.length>0&&Ce(i,e.path,"error","unknown_type",`Resolved types are not defined: ${u.join(", ")}`),l.length===0)return i;for(let f of l)hw(e.path,a,f,i,r),f.specProfile==="v0.3"&&await OR(r,e.path,a,f,t,n,i);let d=t.spec_version.startsWith("0.3.")?!1:NR(l,t);if(d!==!1){let f=DR(l),p=new Set(t.settings.explicit_type_keys),h=d===!0?"error":"warn";for(let m of Object.keys(a))f.has(m)||p.has(m)||Ce(i,e.path,h,"unknown_field",`Unknown field '${m}' in strict mode`,m)}return i}async function FR(r,e,t,n={}){let i=new Map;for(let o of r.getMarkdownFiles()){if(yt(o.path,e))continue;n.signal?.throwIfAborted();let a=await r.cachedRead(o),c=Me(a);if(c.error)continue;let u=Ke(o.path,c.frontmatter,e,t).map(d=>t.get(d)).filter(d=>!!d);for(let d of u)for(let[f,p]of Object.entries(d.fields)){if(!W(p))continue;let h=p;if(h.unique!==!0)continue;let m=c.frontmatter[f];if(m==null)continue;let y=wp(m),g=h.unique_scope==="collection"?"collection":"type",b=`${g==="collection"?"*":d.name}::${f}::${y}`,v=i.get(b)??[];v.some(S=>S.path===o.path)||(v.push({path:o.path,typeName:d.name,fieldName:f,scope:g,specProfile:d.specProfile,value:m,fingerprint:y}),i.set(b,v))}}let s=[];for(let o of i.values())if(!(o.length<=1))for(let a of o){let c=o.filter(l=>l.path!==a.path).map(l=>l.path).join(", ");Ce(s,a.path,"error",a.specProfile==="v0.3"?"duplicate_value":"duplicate_unique",a.scope==="collection"?`Field '${a.fieldName}' must be unique across the collection. Duplicate found in: ${c}`:`Field '${a.fieldName}' must be unique for type '${a.typeName}'. Duplicate found in: ${c}`,a.fieldName)}return s}function jR(r,e){let t=Oe(r);for(let n of e)for(let[i,s]of Object.entries(n.collection?.read_defaults??{}))i in t||(t[i]=Oe(s));return t}async function Tp(r,e,t,n={}){let i=[],s=r.getMarkdownFiles().filter(a=>!yt(a.path,e));n.onProgress?.({completed:0,total:s.length,phase:"notes"});for(let[a,c]of s.entries()){n.signal?.throwIfAborted();let l=await _c(r,c,e,t);n.signal?.throwIfAborted(),n.onFile?.(c,l),i.push(...l),n.onProgress?.({completed:a+1,total:s.length,phase:"notes"}),a%25===0&&await new Promise(u=>setTimeout(u,0))}n.signal?.throwIfAborted(),n.onProgress?.({completed:s.length,total:s.length,phase:"uniqueness"});let o=await FR(r,e,t,n);return n.signal?.throwIfAborted(),i.push(...o),i}function Rp(r,e,t=qr.spec_version){if(t.startsWith("0.3.")){let i={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()&&(i.match={path_glob:e.trim()}),`${mt(i,`# ${r} +${n}`}async function ai(r){let e=r.getAbstractFileByPath("mdbase.yaml");if(!(e instanceof oe.TFile))return null;try{let t=await r.cachedRead(e),n=(0,oe.parseYaml)(t);if(!W(n))return null;let i=W(n.settings)?n.settings:{},s=W(n.runtime)?n.runtime:void 0;return{spec_version:typeof n.spec_version=="string"?n.spec_version:qr.spec_version,name:typeof n.name=="string"?n.name:qr.name,description:typeof n.description=="string"?n.description:qr.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 i.types_folder=="string"?i.types_folder:qr.settings.types_folder,contracts_folder:typeof i.contracts_folder=="string"?i.contracts_folder:qr.settings.contracts_folder,explicit_type_keys:Array.isArray(i.explicit_type_keys)?i.explicit_type_keys.filter(o=>typeof o=="string"):[...qr.settings.explicit_type_keys],...typeof i.default_strict=="boolean"?{default_strict:i.default_strict}:{},...typeof i.include_subfolders=="boolean"?{include_subfolders:i.include_subfolders}:{},exclude:Array.isArray(i.exclude)?i.exclude.filter(o=>typeof o=="string"):Cp(n.spec_version)?[]:[...mR]}}}catch{return null}}async function $o(r,e={}){let t=[];if(!(r.getAbstractFileByPath("mdbase.yaml")instanceof oe.TFile)){let l=(0,oe.stringifyYaml)(qr).trimEnd()+` +`;await r.create("mdbase.yaml",l),t.push("mdbase.yaml")}let i=await ai(r)??qr,s=i.settings.types_folder;await r.adapter.exists(s)||(await r.createFolder(s),t.push(s));let a=(0,oe.normalizePath)(`${s}/note.md`);if(!await r.adapter.exists(a)&&e.seedNoteType!==!1){let l=Tp("note",void 0,i.spec_version);await r.create(a,l),t.push(a)}return{created:t}}function aw(r,e){let t=W(r)?r:{},n=Array.isArray(t.type)?t.type.find(s=>s!=="null"):t.type,i={required:e};return Array.isArray(t.enum)?(i.type="enum",i.values=Oe(t.enum)):n==="array"?(i.type="list",i.items=aw(t.items,!1)):n==="object"?(i.type="object",i.fields=gn(t)):n==="string"&&t.format==="date"?i.type="date":n==="string"&&t.format==="date-time"?i.type="datetime":n==="string"&&t.format==="time"?i.type="time":typeof n=="string"?i.type=n:i.type="any",t.default!==void 0&&(i.default=Oe(t.default)),typeof t.description=="string"&&(i.description=t.description),typeof t.minimum=="number"&&(i.min=t.minimum),typeof t.maximum=="number"&&(i.max=t.maximum),typeof t.minLength=="number"&&(i.min_length=t.minLength),typeof t.maxLength=="number"&&(i.max_length=t.maxLength),typeof t.pattern=="string"&&(i.pattern=t.pattern),typeof t.minItems=="number"&&(i.min_length=t.minItems),typeof t.maxItems=="number"&&(i.max_length=t.maxItems),i}function gn(r){let e=W(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,i])=>[n,aw(i,t.has(n))]))}function cw(r,e){let t={...Oe(e)},n=r.type??"string",i=()=>{delete t.properties,delete t.required,delete t.additionalProperties},s=()=>{delete t.items};if(n==="enum")delete t.type,t.enum=Oe(r.values??[]),delete t.format,i(),s();else if(n==="list")t.type="array",delete t.enum,delete t.format,i(),t.items=cw(r.items??{type:"any"},W(t.items)?t.items:{});else if(n==="object"){t.type="object",delete t.enum,delete t.format,s();let c=es(r.fields??{},W(t)?t:{},!1);t.properties=c.properties,c.required?t.required=c.required:delete t.required}else n==="link"?(t.type="string",delete t.enum,delete t.format,i(),s()):["date","datetime","time"].includes(n)?(t.type="string",t.format=n==="datetime"?"date-time":n,delete t.enum,i(),s()):["string","integer","number","boolean"].includes(n)?(t.type=n,delete t.format,delete t.enum,i(),s()):(delete t.type,delete t.enum,delete t.format,i(),s());r.default!==void 0?t.default=Oe(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 es(r,e={},t=!1){let n=W(e.properties)?e.properties:{},i=Object.create(null),s=[];for(let[a,c]of Object.entries(r))i[a]=cw(c,W(n[a])?n[a]:{}),c.required===!0&&s.push(a);let o={...Oe(e),type:"object",properties:i,additionalProperties:!t};return s.length>0?o.required=s:delete o.required,o}function lw(r,e){if(!e)return r;if(!e.startsWith("/"))return;let t=r;for(let n of e.slice(1).split("/")){let i=n.replace(/~1/g,"/").replace(/~0/g,"~");if(Array.isArray(t)){let s=Number(i);if(!Number.isInteger(s)||s<0||s>=t.length)return;t=t[s]}else if(W(t)&&i in t)t=t[i];else return}return t}async function dw(r,e,t){let[n,i=""]=t.split("#",2);if(!n||/^[a-z][a-z0-9+.-]*:/i.test(n)||n.startsWith("/"))return null;let s=nw(e),o=[];for(let l of`${s}/${n}`.replace(/\\/g,"/").split("/"))if(!(!l||l==="."))if(l===".."){if(o.length===0)return null;o.pop()}else o.push(l);let a=(0,oe.normalizePath)(o.join("/")),c=r.getAbstractFileByPath(a);if(!(c instanceof oe.TFile))return null;try{let l=JSON.parse(await r.cachedRead(c)),u=lw(l,i);return W(u)?u:null}catch{return null}}function wc(r,e,t){let n=W(r.collection)?Oe(r.collection):void 0,i=gn(t);for(let s of n?.unique??[])typeof s.field=="string"&&i[s.field]&&(i[s.field].unique=!0,i[s.field].unique_scope=s.scope);for(let[s,o]of Object.entries(n?.links??{}))i[s]&&(i[s].target=o.target_type,i[s].validate_exists=o.validate_exists);return{name:String(r.name),version:typeof r.version=="number"?r.version:void 0,description:typeof r.description=="string"?r.description:void 0,display_name_key:n?.display?.name_field,path_pattern:n?.path?.pattern,strict:t.additionalProperties===!1,match:W(r.match)?r.match:void 0,fields:i,filePath:e,specProfile:"v0.3",schema:Oe(t),collection:n,originalFrontmatter:Oe(r)}}async function Ep(r,e){let t=[];for(let n of r.getMarkdownFiles()){if(yt(n.path,e))continue;let i=Me(await r.cachedRead(n));i.error||t.push({path:n.path,frontmatter:i.frontmatter})}return t}function ts(r,e,t){let n=[];return hw(r,e,t,n),n}async function Ap(r,e){let t=new Map,n=`${(0,oe.normalizePath)(e.settings.types_folder)}/`;for(let i of r.getMarkdownFiles()){if(!i.path.startsWith(n))continue;let s=await r.cachedRead(i),o=Me(s);if(!o.hasFrontmatter||o.error)continue;let a=o.frontmatter;if(e.spec_version.startsWith("0.3.")){if(a.kind!=="mdbase.type"||typeof a.name!="string"||!W(a.schema))continue;let u=a.schema,d=W(u.value)?u.value:null;if(!d&&typeof u.ref=="string"&&(d=await dw(r,i.path,u.ref)),!d)continue;t.set(a.name,wc(a,i.path,d));continue}if(!W(a.fields))continue;let c=typeof a.name=="string"&&a.name.trim().length>0?a.name.trim():i.basename,l={};for(let[u,d]of Object.entries(a.fields))W(d)&&(l[u]=d);t.set(c,{name:c,extends:typeof a.extends=="string"?a.extends:void 0,display_name_key:typeof a.display_name_key=="string"?a.display_name_key:void 0,path_pattern:typeof a.path_pattern=="string"?a.path_pattern:void 0,filename_pattern:typeof a.filename_pattern=="string"?a.filename_pattern:void 0,strict:gR(a.strict),match:W(a.match)?a.match:void 0,fields:l,filePath:i.path,specProfile:"v0.2",originalFrontmatter:Oe(a)})}return vR(t)}async function kp(r,e){let t=new Map,n=`${(0,oe.normalizePath)(e.settings.contracts_folder||"_contracts")}/`;for(let i of r.getMarkdownFiles()){if(!i.path.startsWith(n))continue;let s=Me(await r.cachedRead(i));if(!s.hasFrontmatter||s.error)continue;let o=s.frontmatter;if(o.kind!=="mdbase.contract"||o.contract_type!=="record"||typeof o.id!="string"||typeof o.version!="string")continue;let a=W(o.record_schema)?o.record_schema:{},c=W(o.binding_schema)?o.binding_schema:void 0,l=await ew(r,i.path,a);if(!l)continue;let u=c?await ew(r,i.path,c):null,d=`${o.id}@${o.version}`;t.set(d,{contract_type:"record",id:o.id,version:o.version,digest:typeof o.digest=="string"?o.digest:"",schema:l,...u?{binding_schema:u}:{},implementations:[]})}return t}async function ew(r,e,t){return W(t.value)?Oe(t.value):typeof t.ref!="string"?null:dw(r,e,t.ref)}function _R(r,e){for(let t of e){let n=r[t];if(Array.isArray(n))return n.filter(s=>typeof s=="string")}for(let t of e){let n=r[t];if(typeof n=="string"&&n.trim().length>0)return[n.trim()]}return null}function Pp(r,e){return r.replace(/\{([^}]+)\}/g,(t,n)=>{let i=e[n];return i==null?"":Array.isArray(i)?i.filter(s=>["string","number","boolean"].includes(typeof s)).map(String).join("-"):typeof i=="string"?i:typeof i=="number"||typeof i=="boolean"?String(i):""})}function yn(r){let e=r.replace(/\\/g,"/");if(!e||e.startsWith("/")||/^[A-Za-z]:\//.test(e)||e.includes("\0"))throw new So("invalid_path",`Invalid collection-relative path: ${r}`);let t=e.split("/");if(t.includes(".."))throw new So("path_traversal",`Path escapes the collection root: ${r}`);return(0,oe.normalizePath)(t.filter(n=>n&&n!==".").join("/"))}function SR(r){let e=r.search(/[*?]|\[/),n=(e===-1?r:r.slice(0,e)).replace(/\/+$/,"");if(n.endsWith(".md")){let i=n.lastIndexOf("/");return i>=0?n.slice(0,i):""}return n}function uw(r,e){if(r.path_pattern){let t=(0,oe.normalizePath)(Pp(r.path_pattern,e));if(t.endsWith(".md")){let n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}return t.replace(/\/+$/,"")}return r.match?.path_glob?SR(r.match.path_glob):""}function fw(r,e){let t=r.display_name_key??"title",n=e[t],i=`${r.name}-${new Date().toISOString().slice(0,10)}`,s=typeof n=="string"&&n.trim().length>0?n:i;if(r.filename_pattern&&r.filename_pattern.trim().length>0){let o=(0,oe.normalizePath)(Pp(r.filename_pattern,e)),c=(o.split("/").pop()??o).replace(/\.md$/i,"").trim();if(c.length>0)return`${$p(c)}.md`}return`${$p(s)}.md`}function Zi(r){return Array.isArray(r)?`[${r.map(Zi).join(",")}]`:W(r)?`{${Object.keys(r).sort().map(e=>`${JSON.stringify(e)}:${Zi(r[e])}`).join(",")}}`:JSON.stringify(r)}function $R(r,e){let t=[r];for(let n of e.split(".").filter(Boolean)){let i=n.endsWith("[]"),s=i?n.slice(0,-2):n,o=[];for(let a of t){if(!W(a)||!Object.prototype.hasOwnProperty.call(a,s))continue;let c=a[s];i&&Array.isArray(c)?o.push(...c):i||o.push(c)}if(!o.length)return{present:!1,value:void 0};t=o}return{present:!0,value:t[0]}}function gc(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 xR(r,e,t,n){let i=(s,o)=>Zi(s)===Zi(o);switch(e){case"eq":case"const":return r.present&&r.value!=null&&i(r.value,t);case"neq":return r.present&&r.value!=null&&!i(r.value,t);case"gt":return gc(r.value,t,(s,o)=>s>o);case"gte":return gc(r.value,t,(s,o)=>s>=o);case"lt":return gc(r.value,t,(s,o)=>ss<=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(s=>i(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=>i(o,s)));case"containsAny":return!Array.isArray(r.value)||!Array.isArray(t)?!1:t.some(s=>r.value.some(o=>i(o,s)));case"in":return r.value!=null&&Array.isArray(t)&&t.some(s=>i(s,r.value));case"startsWith":case"starts_with":return typeof r.value=="string"&&typeof t=="string"&&r.value.startsWith(t);case"endsWith":case"ends_with":return typeof r.value=="string"&&typeof t=="string"&&r.value.endsWith(t);case"matches":try{return typeof r.value=="string"&&typeof t=="string"&&new RegExp(t.replace(/\\\\/g,"\\")).test(r.value)}catch{return!1}default:return!1}}function vc(r,e,t){if("and"in r)return Array.isArray(r.and)&&r.and.every(n=>W(n)&&vc(n,e,t));if("or"in r)return Array.isArray(r.or)&&r.or.some(n=>W(n)&&vc(n,e,t));if("not"in r)return W(r.not)&&!vc(r.not,e,t);for(let[n,i]of Object.entries(r)){let s=$R(e,n);if(!W(i)){if(!s.present||Zi(s.value)!==Zi(i))return!1;continue}for(let[o,a]of Object.entries(i))if(!xR(s,o,a,t))return!1}return!0}function Ke(r,e,t,n){let i=_R(e,t.settings.explicit_type_keys);if(i)return i;let s=[];for(let[o,a]of n.entries()){let c=a.match;if(!c)continue;let l=!0;if(typeof c.path_glob=="string"&&!FR(c.path_glob,r,t)&&(l=!1),l&&Array.isArray(c.fields_present)){for(let u of c.fields_present)if(!(u in e)){l=!1;break}}l&&W(c.where)&&(l=vc(c.where,e,t.spec_version)),l&&typeof c.where=="string"&&(l=!1),l&&s.push(o)}return s}function pw(r){return r==null||typeof r=="string"&&r.trim().length===0}function ER(r){return/^\d{4}-\d{2}-\d{2}$/.test(r)}function AR(r){return/^\d{2}:\d{2}(:\d{2})?$/.test(r)}function kR(r){return typeof r=="string"||Array.isArray(r)?r.length:null}function Ce(r,e,t,n,i,s){r.push({path:e,code:n,message:i,severity:t,field:s})}function jt(r,e,t,n,i){typeof r=="number"&&(typeof e.min=="number"&&re.max&&Ce(i,n,"error","above_max",`'${t}' is ${r}; must be at most ${e.max}`,t));let s=kR(r);if(s!=null&&(typeof e.min_length=="number"&&se.max_length&&Ce(i,n,"error","above_max_length",`'${t}' has length ${s}; limit is ${e.max_length}`,t)),typeof e.pattern=="string"&&typeof r=="string")try{new RegExp(e.pattern).test(r)||Ce(i,n,"error","pattern_mismatch",`'${t}' is ${_p(r)}; does not match /${e.pattern}/`,t)}catch(o){Ce(i,n,"warn","invalid_pattern",`Field '${t}' has invalid regex pattern: ${o instanceof Error?o.message:String(o)}`,t)}}function wp(r,e,t,n,i,s){let o=e.type??"any";if(r==null)return;e.deprecated===!0&&Ce(i,n,"warn","deprecated_field",`Field '${t}' is marked deprecated`,t);let a=c=>{Ce(i,n,"error","invalid_type",`Field '${t}' expected ${c}`,t)};switch(o){case"any":jt(r,e,t,n,i);return;case"string":if(typeof r!="string"){a("a string");return}jt(r,e,t,n,i);return;case"integer":if(typeof r!="number"||!Number.isInteger(r)){a("an integer");return}jt(r,e,t,n,i);return;case"number":if(typeof r!="number"||Number.isNaN(r)){a("a number");return}jt(r,e,t,n,i);return;case"boolean":typeof r!="boolean"&&a("a boolean");return;case"date":if(typeof r!="string"||!ER(r)){a("a date (YYYY-MM-DD)");return}jt(r,e,t,n,i);return;case"datetime":if(typeof r!="string"||Number.isNaN(Date.parse(r))){a("a datetime string");return}jt(r,e,t,n,i);return;case"time":if(typeof r!="string"||!AR(r)){a("a time string (HH:MM)");return}jt(r,e,t,n,i);return;case"enum":{let c=Array.isArray(e.values)?e.values:[];if(!c.includes(r)){Ce(i,n,"error","invalid_enum",`Field '${t}' must be one of: ${c.map(l=>String(l)).join(", ")}`,t);return}jt(r,e,t,n,i);return}case"list":{if(!Array.isArray(r)){a("a list");return}jt(r,e,t,n,i),e.items&&r.forEach((c,l)=>{wp(c,e.items,`${t}[${l}]`,n,i,s)});return}case"object":{if(!W(r)){a("an object");return}if(e.fields&&W(e.fields))for(let[c,l]of Object.entries(e.fields)){if(!W(l))continue;let u=l,d=`${t}.${c}`,f=r[c];if(u.required&&pw(f)){Ce(i,n,"error","missing_required",`Missing required field '${d}'`,d);continue}wp(f,u,d,n,i,s)}return}case"link":{if(typeof r!="string"&&!W(r)){a("a link string");return}if(e.validate_exists===!0&&s){let c=typeof r=="string"?r:typeof r.path=="string"?r.path:typeof r.file=="string"?r.file:"";(!c||!wR(s,n,c))&&Ce(i,n,"error","missing_link_target",`Field '${t}' references a missing note`,t)}return}case"tags":if(typeof r=="string"){jt(r,e,t,n,i);return}if(Array.isArray(r)&&r.every(c=>typeof c=="string")){jt(r,e,t,n,i);return}a("a tag string or list of strings");return;default:jt(r,e,t,n,i);return}}function PR(r){return r.replace(/^\//,"").split("/").filter(Boolean).map(t=>t.replace(/~1/g,"/").replace(/~0/g,"~")).join(".")||void 0}function CR(r){return r.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase()}function _p(r){return r===null?"empty":typeof r=="string"?r.trim()?`'${r.length>40?`${r.slice(0,39)}\u2026`:r}'`:"empty":typeof r=="number"||typeof r=="boolean"?String(r):Array.isArray(r)?`a list of ${r.length}`:W(r)?"an object":r===void 0?"missing":JSON.stringify(r)??"unknown"}function bc(r,e){return`${r} ${e}${r===1?"":"s"}`}function RR(r,e,t,n){let i=r.params,s=e?`'${e}'`:"This note",o=_p(t);switch(r.keyword){case"required":return`Missing required field '${e??String(i.missingProperty)}'`;case"additionalProperties":return`Field '${e??String(i.additionalProperty)}' is not declared by type '${n}'`;case"type":{let c=(Array.isArray(i.type)?i.type.join(","):typeof i.type=="string"?i.type:"").split(",").map(l=>MR[l]??l).join(" or ");return`${s} is ${o}; expected ${c}`}case"enum":{let a=Array.isArray(i.allowedValues)?i.allowedValues.map(l=>String(l)):[],c=a.length>6?`${a.slice(0,6).join(", ")}, \u2026`:a.join(", ");return`${s} is ${o}; expected one of ${c}`}case"const":return`${s} is ${o}; expected ${_p(i.allowedValue)}`;case"maximum":return`${s} is ${o}; must be at most ${String(i.limit)}`;case"minimum":return`${s} is ${o}; must be at least ${String(i.limit)}`;case"exclusiveMaximum":return`${s} is ${o}; must be less than ${String(i.limit)}`;case"exclusiveMinimum":return`${s} is ${o}; must be more than ${String(i.limit)}`;case"maxLength":return`${s} is ${bc(typeof t=="string"?t.length:0,"character")}; limit is ${String(i.limit)}`;case"minLength":return`${s} is ${bc(typeof t=="string"?t.length:0,"character")}; needs at least ${String(i.limit)}`;case"maxItems":return`${s} has ${bc(Array.isArray(t)?t.length:0,"item")}; limit is ${String(i.limit)}`;case"minItems":return`${s} has ${bc(Array.isArray(t)?t.length:0,"item")}; needs at least ${String(i.limit)}`;case"uniqueItems":return`${s} contains duplicate items`;case"pattern":return`${s} is ${o}; does not match ${String(i.pattern)}`;case"format":return`${s} is ${o}; expected ${TR[String(i.format)]??String(i.format)}`;default:return`${s}: ${r.message??"invalid value"}`}}function IR(r,e,t,n={}){let i=r.params,s=PR(r.instancePath),o=typeof i.missingProperty=="string"?i.missingProperty:typeof i.additionalProperty=="string"?i.additionalProperty:void 0,a=s&&o?`${s}.${o}`:o??s,c=r.keyword==="format"?"format_invalid":`schema_${CR(r.keyword)}`,l=lw(n,r.instancePath);return{path:e,code:c,message:RR(r,a,l,t),severity:"error",field:a,type:t,schema_location:`embedded://type/schema#${r.schemaPath}`,details:{instance_path:r.instancePath,schema_path:r.schemaPath,technical_message:`JSON Schema ${r.keyword} failed for type '${t}': ${r.message??"invalid value"}`,...o===void 0?{}:{property:o}}}}function Sp(r){if(Array.isArray(r)){for(let e of r){let t=Sp(e);if(t)return t}return null}if(!W(r))return null;if(typeof r.$ref=="string"&&!r.$ref.startsWith("#"))return r.$ref;for(let e of Object.values(r)){let t=Sp(e);if(t)return t}return null}function OR(r,e,t,n){if(!t.schema)return;let i=Sp(t.schema);if(i){n.push({path:r,code:/^[a-z][a-z0-9+.-]*:/i.test(i)?"schema_ref_forbidden":"unsupported_profile",message:`Unsupported JSON Schema reference '${i}' for type '${t.name}'`,severity:"error",type:t.name});return}try{let s=yR().compile(t.schema);if(s(e))return;for(let o of s.errors??[])n.push(IR(o,r,t.name,e))}catch(s){n.push({path:r,code:"invalid_embedded_schema",message:s instanceof Error?s.message:String(s),severity:"error",type:t.name})}}async function DR(r,e,t,n,i,s,o){for(let[a,c]of Object.entries(n.collection?.links??{})){let l=t[a],u=Array.isArray(l)?l:[l];for(let d of u){if(d==null||typeof d!="string")continue;let f=ow(r,e,d);if(!f&&c.validate_exists===!0){Ce(o,e,"error","link_not_found",`Field '${a}' references a missing note`,a);continue}if(f&&c.target_type&&c.target_type!=="any"){let p=Me(await r.cachedRead(f));Ke(f.path,p.frontmatter,i,s).includes(c.target_type)||Ce(o,e,"error","link_wrong_type",`Field '${a}' must reference type '${c.target_type}'`,a)}}}}function hw(r,e,t,n,i){if(t.specProfile==="v0.3"){OR(r,e,t,n);return}for(let[s,o]of Object.entries(t.fields)){if(!W(o))continue;let a=o,c=e[s];if(a.required&&pw(c)){Ce(n,r,"error","missing_required",`Missing required field '${s}' for type '${t.name}'`,s);continue}wp(c,a,s,r,n,i)}}function NR(r){let e=new Set;for(let t of r)for(let n of Object.keys(t.fields))e.add(n);return e}function LR(r,e){let t=!1,n=!1;for(let i of r){if(i.strict===!0)return!0;i.strict==="warn"&&(t=!0),i.strict===void 0&&(n=!0)}return t||n&&e.settings.default_strict?"warn":!1}function yt(r,e){let t=(0,oe.normalizePath)(r),n=(0,oe.normalizePath)(e.settings.types_folder);if(t.startsWith(`${n}/`)||t===n)return!0;if(Cp(e.spec_version)){let i=(0,oe.normalizePath)(e.settings.contracts_folder??"_contracts");return t===i||t.startsWith(`${i}/`)||t.split("/").some(s=>s.startsWith(".")||s==="node_modules")?!0:e.settings.exclude.some(s=>bp(s,t))}if(e.settings.include_subfolders===!1&&t.includes("/"))return!0;for(let i of e.settings.exclude)if((0,xp.default)(i,{dot:!0,matchBase:!i.includes("/")})(t)||!i.includes("*")&&!i.includes("?")&&!i.includes("/")&&t.startsWith(`${i}/`))return!0;return!1}function Cp(r){return typeof r=="string"&&r.startsWith("0.3.")}function FR(r,e,t){return Cp(t.spec_version)?bp(r,e):(0,xp.default)(r,{dot:!0})(e)}async function _c(r,e,t,n){if(yt(e.path,t))return[];let i=[],s=await r.cachedRead(e),o=Me(s);if(o.error)return Ce(i,e.path,"error","invalid_frontmatter",o.error),i;let a=o.frontmatter,c=Ke(e.path,a,t,n);if(c.length===0)return Ce(i,e.path,"warn","no_matching_type","No type could be resolved for this file"),i;let l=c.map(f=>n.get(f)).filter(f=>!!f),u=c.filter(f=>!n.has(f));if(u.length>0&&Ce(i,e.path,"error","unknown_type",`Resolved types are not defined: ${u.join(", ")}`),l.length===0)return i;for(let f of l)hw(e.path,a,f,i,r),f.specProfile==="v0.3"&&await DR(r,e.path,a,f,t,n,i);let d=t.spec_version.startsWith("0.3.")?!1:LR(l,t);if(d!==!1){let f=NR(l),p=new Set(t.settings.explicit_type_keys),m=d===!0?"error":"warn";for(let h of Object.keys(a))f.has(h)||p.has(h)||Ce(i,e.path,m,"unknown_field",`Unknown field '${h}' in strict mode`,h)}return i}async function jR(r,e,t,n={}){let i=new Map;for(let o of r.getMarkdownFiles()){if(yt(o.path,e))continue;n.signal?.throwIfAborted();let a=await r.cachedRead(o),c=Me(a);if(c.error)continue;let u=Ke(o.path,c.frontmatter,e,t).map(d=>t.get(d)).filter(d=>!!d);for(let d of u)for(let[f,p]of Object.entries(d.fields)){if(!W(p))continue;let m=p;if(m.unique!==!0)continue;let h=c.frontmatter[f];if(h==null)continue;let y=vp(h),g=m.unique_scope==="collection"?"collection":"type",b=`${g==="collection"?"*":d.name}::${f}::${y}`,v=i.get(b)??[];v.some(S=>S.path===o.path)||(v.push({path:o.path,typeName:d.name,fieldName:f,scope:g,specProfile:d.specProfile,value:h,fingerprint:y}),i.set(b,v))}}let s=[];for(let o of i.values())if(!(o.length<=1))for(let a of o){let c=o.filter(l=>l.path!==a.path).map(l=>l.path).join(", ");Ce(s,a.path,"error",a.specProfile==="v0.3"?"duplicate_value":"duplicate_unique",a.scope==="collection"?`Field '${a.fieldName}' must be unique across the collection. Duplicate found in: ${c}`:`Field '${a.fieldName}' must be unique for type '${a.typeName}'. Duplicate found in: ${c}`,a.fieldName)}return s}function qR(r,e){let t=Oe(r);for(let n of e)for(let[i,s]of Object.entries(n.collection?.read_defaults??{}))i in t||(t[i]=Oe(s));return t}async function Mp(r,e,t,n={}){let i=[],s=r.getMarkdownFiles().filter(a=>!yt(a.path,e));n.onProgress?.({completed:0,total:s.length,phase:"notes"});for(let[a,c]of s.entries()){n.signal?.throwIfAborted();let l=await _c(r,c,e,t);n.signal?.throwIfAborted(),n.onFile?.(c,l),i.push(...l),n.onProgress?.({completed:a+1,total:s.length,phase:"notes"}),a%25===0&&await new Promise(u=>setTimeout(u,0))}n.signal?.throwIfAborted(),n.onProgress?.({completed:s.length,total:s.length,phase:"uniqueness"});let o=await jR(r,e,t,n);return n.signal?.throwIfAborted(),i.push(...o),i}function Tp(r,e,t=qr.spec_version){if(t.startsWith("0.3.")){let i={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()&&(i.match={path_glob:e.trim()}),`${mt(i,`# ${r} Type definition for ${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()}),`${mt(n,`# ${r} Type definition for ${r}.`)} -`}async function qR(r,e,t,n){let i=t.trim(),s=(0,oe.normalizePath)(`${e.settings.types_folder}/${i}.md`);if(await r.adapter.exists(s))throw new Error(`Type already exists: ${s}`);let o=Rp(i,n,e.spec_version);return await r.create(s,o),s}function Ip(r,e){let t={},n=e.settings.explicit_type_keys[0]??"type";t[n]=n==="types"?[r.name]:r.name;for(let[i,s]of Object.entries(r.fields)){if(!W(s))continue;let o=s;o.default!==void 0&&(t[i]=Oe(o.default))}return t}function Op(r,e){let t=[];for(let[n,i]of Object.entries(r.fields)){if(!W(i))continue;let s=i;s.computed||s.required&&e[n]===void 0&&t.push([n,s])}return t}function Sc(r,e){let t=r.trim();switch(e.type??"string"){case"string":case"date":case"datetime":case"time":case"link":case"enum":case"any":return t;case"integer":{let i=Number(t);if(!/^[+-]?\d+$/.test(t)||!Number.isSafeInteger(i))throw new Error("Expected a whole integer");return i}case"number":{let i=Number(t);if(!/^[+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?$/i.test(t)||!Number.isFinite(i))throw new Error("Expected a finite number");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":{if(t.startsWith("[")||/^-\s/.test(t)){let s=(0,oe.parseYaml)(t);if(!Array.isArray(s))throw new Error("Expected a YAML or JSON list");return s}let i=t.split(",").map(s=>s.trim()).filter(s=>s.length>0);return e.items?i.map(s=>Sc(s,e.items)):i}case"object":{let i=(0,oe.parseYaml)(t);if(!W(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 xp(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 BR(r,e){let t=(0,oe.normalizePath)(e).replace(/\/+$/,"");if(!t)return;let n=t.split("/"),i="";for(let s of n)i=i?`${i}/${s}`:s,await r.adapter.exists(i)||await r.createFolder(i)}function UR(r,e){if(!r.path_pattern||r.path_pattern.trim().length===0)return null;let t=(0,oe.normalizePath)(Cp(r.path_pattern,e));return t.endsWith(".md")?t:null}async function Dp(r,e,t){let n=UR(e,t),i=uw(e,t),s=n?n.split("/").pop()??n:fw(e,t),o=yn(n||`${i?`${i}/`:""}${s.endsWith(".md")?s:`${s}.md`}`),a=o,c=2;for(;r.getAbstractFileByPath(a);)a=o.replace(/\.md$/,`-${c}.md`),c+=1;return a}async function VR(r,e,t,n=""){let i=yn(e),s=i.lastIndexOf("/");if(s>0&&await BR(r,i.slice(0,s)),await r.adapter.exists(i))throw new Error(`File already exists: ${i}`);let o=`${mt(t,n)} -`;return r.create(i,o)}function Np(r){return gR(r)}var oe,tw,rw,Ep,So,qr,hR,_o,CR,MR,qt=oy(()=>{oe=require("obsidian"),tw=Kn(Xf(),1),rw=Kn(ap(),1),Ep=Kn(bp(),1);Zv();So=class extends Error{constructor(t,n){super(n);this.code=t;this.name="MdbasePathError"}},qr={spec_version:"0.3.0",name:"My mdbase collection",description:"Typed markdown collection",settings:{types_folder:"_types",contracts_folder:"_contracts",explicit_type_keys:["type","types"],exclude:[]}},hR=["_types",".obsidian",".git","node_modules",".trash",".mdbase"],_o=null;CR={string:"text",integer:"a whole number",number:"a number",boolean:"true or false",array:"a list",object:"an object",null:"empty"},MR={date:"a date (YYYY-MM-DD)","date-time":"a date and time",time:"a time (HH:MM)",email:"an email address",uri:"a URI"}});var ss=A((EB,kw)=>{"use strict";var QR="2.0.0",ZR=Number.MAX_SAFE_INTEGER||9007199254740991,eI=16,tI=250,rI=["major","premajor","minor","preminor","patch","prepatch","prerelease"];kw.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:eI,MAX_SAFE_BUILD_LENGTH:tI,MAX_SAFE_INTEGER:ZR,RELEASE_TYPES:rI,SEMVER_SPEC_VERSION:QR,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var Eo=A((AB,Pw)=>{"use strict";var nI=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...r)=>console.error("SEMVER",...r):()=>{};Pw.exports=nI});var os=A((Sr,Cw)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:Hp,MAX_SAFE_BUILD_LENGTH:iI,MAX_LENGTH:sI}=ss(),oI=Eo();Sr=Cw.exports={};var aI=Sr.re=[],cI=Sr.safeRe=[],D=Sr.src=[],lI=Sr.safeSrc=[],N=Sr.t={},dI=0,zp="[a-zA-Z0-9-]",uI=[["\\s",1],["\\d",sI],[zp,iI]],fI=r=>{for(let[e,t]of uI)r=r.split(`${e}*`).join(`${e}{0,${t}}`).split(`${e}+`).join(`${e}{1,${t}}`);return r},H=(r,e,t)=>{let n=fI(e),i=dI++;oI(r,i,e),N[r]=i,D[i]=e,lI[i]=n,aI[i]=new RegExp(e,t?"g":void 0),cI[i]=new RegExp(n,t?"g":void 0)};H("NUMERICIDENTIFIER","0|[1-9]\\d*");H("NUMERICIDENTIFIERLOOSE","\\d+");H("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${zp}*`);H("MAINVERSION",`(${D[N.NUMERICIDENTIFIER]})\\.(${D[N.NUMERICIDENTIFIER]})\\.(${D[N.NUMERICIDENTIFIER]})`);H("MAINVERSIONLOOSE",`(${D[N.NUMERICIDENTIFIERLOOSE]})\\.(${D[N.NUMERICIDENTIFIERLOOSE]})\\.(${D[N.NUMERICIDENTIFIERLOOSE]})`);H("PRERELEASEIDENTIFIER",`(?:${D[N.NONNUMERICIDENTIFIER]}|${D[N.NUMERICIDENTIFIER]})`);H("PRERELEASEIDENTIFIERLOOSE",`(?:${D[N.NONNUMERICIDENTIFIER]}|${D[N.NUMERICIDENTIFIERLOOSE]})`);H("PRERELEASE",`(?:-(${D[N.PRERELEASEIDENTIFIER]}(?:\\.${D[N.PRERELEASEIDENTIFIER]})*))`);H("PRERELEASELOOSE",`(?:-?(${D[N.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${D[N.PRERELEASEIDENTIFIERLOOSE]})*))`);H("BUILDIDENTIFIER",`${zp}+`);H("BUILD",`(?:\\+(${D[N.BUILDIDENTIFIER]}(?:\\.${D[N.BUILDIDENTIFIER]})*))`);H("FULLPLAIN",`v?${D[N.MAINVERSION]}${D[N.PRERELEASE]}?${D[N.BUILD]}?`);H("FULL",`^${D[N.FULLPLAIN]}$`);H("LOOSEPLAIN",`[v=\\s]*${D[N.MAINVERSIONLOOSE]}${D[N.PRERELEASELOOSE]}?${D[N.BUILD]}?`);H("LOOSE",`^${D[N.LOOSEPLAIN]}$`);H("GTLT","((?:<|>)?=?)");H("XRANGEIDENTIFIERLOOSE",`${D[N.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);H("XRANGEIDENTIFIER",`${D[N.NUMERICIDENTIFIER]}|x|X|\\*`);H("XRANGEPLAIN",`[v=\\s]*(${D[N.XRANGEIDENTIFIER]})(?:\\.(${D[N.XRANGEIDENTIFIER]})(?:\\.(${D[N.XRANGEIDENTIFIER]})(?:${D[N.PRERELEASE]})?${D[N.BUILD]}?)?)?`);H("XRANGEPLAINLOOSE",`[v=\\s]*(${D[N.XRANGEIDENTIFIERLOOSE]})(?:\\.(${D[N.XRANGEIDENTIFIERLOOSE]})(?:\\.(${D[N.XRANGEIDENTIFIERLOOSE]})(?:${D[N.PRERELEASELOOSE]})?${D[N.BUILD]}?)?)?`);H("XRANGE",`^${D[N.GTLT]}\\s*${D[N.XRANGEPLAIN]}$`);H("XRANGELOOSE",`^${D[N.GTLT]}\\s*${D[N.XRANGEPLAINLOOSE]}$`);H("COERCEPLAIN",`(^|[^\\d])(\\d{1,${Hp}})(?:\\.(\\d{1,${Hp}}))?(?:\\.(\\d{1,${Hp}}))?`);H("COERCE",`${D[N.COERCEPLAIN]}(?:$|[^\\d])`);H("COERCEFULL",D[N.COERCEPLAIN]+`(?:${D[N.PRERELEASE]})?(?:${D[N.BUILD]})?(?:$|[^\\d])`);H("COERCERTL",D[N.COERCE],!0);H("COERCERTLFULL",D[N.COERCEFULL],!0);H("LONETILDE","(?:~>?)");H("TILDETRIM",`(\\s*)${D[N.LONETILDE]}\\s+`,!0);Sr.tildeTrimReplace="$1~";H("TILDE",`^${D[N.LONETILDE]}${D[N.XRANGEPLAIN]}$`);H("TILDELOOSE",`^${D[N.LONETILDE]}${D[N.XRANGEPLAINLOOSE]}$`);H("LONECARET","(?:\\^)");H("CARETTRIM",`(\\s*)${D[N.LONECARET]}\\s+`,!0);Sr.caretTrimReplace="$1^";H("CARET",`^${D[N.LONECARET]}${D[N.XRANGEPLAIN]}$`);H("CARETLOOSE",`^${D[N.LONECARET]}${D[N.XRANGEPLAINLOOSE]}$`);H("COMPARATORLOOSE",`^${D[N.GTLT]}\\s*(${D[N.LOOSEPLAIN]})$|^$`);H("COMPARATOR",`^${D[N.GTLT]}\\s*(${D[N.FULLPLAIN]})$|^$`);H("COMPARATORTRIM",`(\\s*)${D[N.GTLT]}\\s*(${D[N.LOOSEPLAIN]}|${D[N.XRANGEPLAIN]})`,!0);Sr.comparatorTrimReplace="$1$2$3";H("HYPHENRANGE",`^\\s*(${D[N.XRANGEPLAIN]})\\s+-\\s+(${D[N.XRANGEPLAIN]})\\s*$`);H("HYPHENRANGELOOSE",`^\\s*(${D[N.XRANGEPLAINLOOSE]})\\s+-\\s+(${D[N.XRANGEPLAINLOOSE]})\\s*$`);H("STAR","(<|>)?=?\\s*\\*");H("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");H("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")});var Cc=A((kB,Mw)=>{"use strict";var pI=Object.freeze({loose:!0}),hI=Object.freeze({}),mI=r=>r?typeof r!="object"?pI:r:hI;Mw.exports=mI});var Kp=A((PB,Iw)=>{"use strict";var Tw=/^[0-9]+$/,Rw=(r,e)=>{if(typeof r=="number"&&typeof e=="number")return r===e?0:rRw(e,r);Iw.exports={compareIdentifiers:Rw,rcompareIdentifiers:yI}});var je=A((CB,Dw)=>{"use strict";var Mc=Eo(),{MAX_LENGTH:Ow,MAX_SAFE_INTEGER:Tc}=ss(),{safeRe:Rc,t:Ic}=os(),gI=Cc(),{compareIdentifiers:Wp}=Kp(),bI=(r,e)=>{let t=e.split(".");if(t.length>r.length)return!1;for(let n=0;nOw)throw new TypeError(`version is longer than ${Ow} characters`);Mc("SemVer",e,t),this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease;let n=e.trim().match(t.loose?Rc[Ic.LOOSE]:Rc[Ic.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>Tc||this.major<0)throw new TypeError("Invalid major version");if(this.minor>Tc||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>Tc||this.patch<0)throw new TypeError("Invalid patch version");n[4]?this.prerelease=n[4].split(".").map(i=>{if(/^[0-9]+$/.test(i)){let s=+i;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 n=this.prerelease[t],i=e.prerelease[t];if(Mc("prerelease compare",t,n,i),n===void 0&&i===void 0)return 0;if(i===void 0)return 1;if(n===void 0)return-1;if(n===i)continue;return Wp(n,i)}while(++t)}compareBuild(e){e instanceof r||(e=new r(e,this.options));let t=0;do{let n=this.build[t],i=e.build[t];if(Mc("build compare",t,n,i),n===void 0&&i===void 0)return 0;if(i===void 0)return 1;if(n===void 0)return-1;if(n===i)continue;return Wp(n,i)}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 i=`-${t}`.match(this.options.loose?Rc[Ic.PRERELEASELOOSE]:Rc[Ic.PRERELEASE]);if(!i||i[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 i=Number(n)?1:0;if(this.prerelease.length===0)this.prerelease=[i];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(".")&&n===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(i)}}if(t){let s=[t,i];if(n===!1&&(s=[t]),bI(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}};Dw.exports=Gp});var vn=A((MB,Lw)=>{"use strict";var Nw=je(),vI=(r,e,t=!1)=>{if(r instanceof Nw)return r;try{return new Nw(r,e)}catch(n){if(!t)return null;throw n}};Lw.exports=vI});var jw=A((TB,Fw)=>{"use strict";var wI=vn(),_I=(r,e)=>{let t=wI(r,e);return t?t.version:null};Fw.exports=_I});var Bw=A((RB,qw)=>{"use strict";var SI=vn(),$I=(r,e)=>{let t=SI(r.trim().replace(/^[=v]+/,""),e);return t?t.version:null};qw.exports=$I});var Hw=A((IB,Vw)=>{"use strict";var Uw=je(),xI=(r,e,t,n,i)=>{typeof t=="string"&&(i=n,n=t,t=void 0);try{return new Uw(r instanceof Uw?r.version:r,t).inc(e,n,i).version}catch{return null}};Vw.exports=xI});var Ww=A((OB,Kw)=>{"use strict";var zw=vn(),EI=(r,e)=>{let t=zw(r,null,!0),n=zw(e,null,!0),i=t.compare(n);if(i===0)return null;let s=i>0,o=s?t:n,a=s?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"};Kw.exports=EI});var Jw=A((DB,Gw)=>{"use strict";var AI=je(),kI=(r,e)=>new AI(r,e).major;Gw.exports=kI});var Xw=A((NB,Yw)=>{"use strict";var PI=je(),CI=(r,e)=>new PI(r,e).minor;Yw.exports=CI});var Zw=A((LB,Qw)=>{"use strict";var MI=je(),TI=(r,e)=>new MI(r,e).patch;Qw.exports=TI});var t_=A((FB,e_)=>{"use strict";var RI=vn(),II=(r,e)=>{let t=RI(r,e);return t&&t.prerelease.length?t.prerelease:null};e_.exports=II});var Bt=A((jB,n_)=>{"use strict";var r_=je(),OI=(r,e,t)=>new r_(r,t).compare(new r_(e,t));n_.exports=OI});var s_=A((qB,i_)=>{"use strict";var DI=Bt(),NI=(r,e,t)=>DI(e,r,t);i_.exports=NI});var a_=A((BB,o_)=>{"use strict";var LI=Bt(),FI=(r,e)=>LI(r,e,!0);o_.exports=FI});var Oc=A((UB,l_)=>{"use strict";var c_=je(),jI=(r,e,t)=>{let n=new c_(r,t),i=new c_(e,t);return n.compare(i)||n.compareBuild(i)};l_.exports=jI});var u_=A((VB,d_)=>{"use strict";var qI=Oc(),BI=(r,e)=>r.sort((t,n)=>qI(t,n,e));d_.exports=BI});var p_=A((HB,f_)=>{"use strict";var UI=Oc(),VI=(r,e)=>r.sort((t,n)=>UI(n,t,e));f_.exports=VI});var Ao=A((zB,h_)=>{"use strict";var HI=Bt(),zI=(r,e,t)=>HI(r,e,t)>0;h_.exports=zI});var Dc=A((KB,m_)=>{"use strict";var KI=Bt(),WI=(r,e,t)=>KI(r,e,t)<0;m_.exports=WI});var Jp=A((WB,y_)=>{"use strict";var GI=Bt(),JI=(r,e,t)=>GI(r,e,t)===0;y_.exports=JI});var Yp=A((GB,g_)=>{"use strict";var YI=Bt(),XI=(r,e,t)=>YI(r,e,t)!==0;g_.exports=XI});var Nc=A((JB,b_)=>{"use strict";var QI=Bt(),ZI=(r,e,t)=>QI(r,e,t)>=0;b_.exports=ZI});var Lc=A((YB,v_)=>{"use strict";var eO=Bt(),tO=(r,e,t)=>eO(r,e,t)<=0;v_.exports=tO});var Xp=A((XB,w_)=>{"use strict";var rO=Jp(),nO=Yp(),iO=Ao(),sO=Nc(),oO=Dc(),aO=Lc(),cO=(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 rO(r,t,n);case"!=":return nO(r,t,n);case">":return iO(r,t,n);case">=":return sO(r,t,n);case"<":return oO(r,t,n);case"<=":return aO(r,t,n);default:throw new TypeError(`Invalid operator: ${e}`)}};w_.exports=cO});var S_=A((QB,__)=>{"use strict";var lO=je(),dO=vn(),{safeRe:Fc,t:jc}=os(),uO=(r,e)=>{if(r instanceof lO)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?Fc[jc.COERCEFULL]:Fc[jc.COERCE]);else{let c=e.includePrerelease?Fc[jc.COERCERTLFULL]:Fc[jc.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],i=t[3]||"0",s=t[4]||"0",o=e.includePrerelease&&t[5]?`-${t[5]}`:"",a=e.includePrerelease&&t[6]?`+${t[6]}`:"";return dO(`${n}.${i}.${s}${o}${a}`,e)};__.exports=uO});var x_=A((ZB,$_)=>{"use strict";var fO=vn(),pO=ss(),hO=je(),mO=(r,e,t)=>{if(!pO.RELEASE_TYPES.includes(e))return null;let n=yO(r,t);return n&&gO(n,e)},yO=(r,e)=>{let t=r instanceof hO?r.version:r;return fO(t,e)},gO=(r,e)=>{if(bO(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()},bO=r=>r.startsWith("pre");$_.exports=mO});var A_=A((eU,E_)=>{"use strict";var Qp=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 i=this.map.keys().next().value;this.delete(i)}this.map.set(e,t)}return this}};E_.exports=Qp});var Ut=A((tU,M_)=>{"use strict";var vO=/\s+/g,Zp=class r{constructor(e,t){if(t=_O(t),e instanceof r)return e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease?e:new r(e.raw,t);if(e instanceof eh)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(vO," "),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(i=>!P_(i[0])),this.set.length===0)this.set=[n];else if(this.set.length>1){for(let i of this.set)if(i.length===1&&MO(i[0])){this.set=[i];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(CO,"");let n=((this.options.includePrerelease&&kO)|(this.options.loose&&PO))+":"+e,i=k_.get(n);if(i)return i;let s=this.options.loose,o=s?rt[qe.HYPHENRANGELOOSE]:rt[qe.HYPHENRANGE];e=e.replace(o,BO(this.options.includePrerelease)),be("hyphen replace",e),e=e.replace(rt[qe.COMPARATORTRIM],xO),be("comparator trim",e),e=e.replace(rt[qe.TILDETRIM],EO),be("tilde trim",e),e=e.replace(rt[qe.CARETTRIM],AO),be("caret trim",e);let a=e.split(" ").map(d=>TO(d,this.options)).join(" ").split(/\s+/).map(d=>qO(d,this.options));s&&(a=a.filter(d=>(be("loose invalid filter",d,this.options),!!d.match(rt[qe.COMPARATORLOOSE])))),be("range list",a);let c=new Map,l=a.map(d=>new eh(d,this.options));for(let d of l){if(P_(d))return[d];c.set(d.value,d)}c.size>1&&c.has("")&&c.delete("");let u=[...c.values()];return k_.set(n,u),u}intersects(e,t){if(!(e instanceof r))throw new TypeError("a Range is required");return this.set.some(n=>C_(n,t)&&e.set.some(i=>C_(i,t)&&n.every(s=>i.every(o=>s.intersects(o,t)))))}test(e){if(!e)return!1;if(typeof e=="string")try{e=new SO(e,this.options)}catch{return!1}for(let t=0;tr.value==="<0.0.0-0",MO=r=>r.value==="",C_=(r,e)=>{let t=!0,n=r.slice(),i=n.pop();for(;t&&n.length;)t=n.every(s=>i.intersects(s,e)),i=n.pop();return t},TO=(r,e)=>(r=r.replace(rt[qe.BUILD],""),be("comp",r,e),r=DO(r,e),be("caret",r),r=IO(r,e),be("tildes",r),r=LO(r,e),be("xrange",r),r=jO(r,e),be("stars",r),r),Te=r=>!r||r.toLowerCase()==="x"||r==="*",RO=(r,e,t)=>Te(r)&&!Te(e)||Te(e)&&t&&!Te(t),IO=(r,e)=>r.trim().split(/\s+/).map(t=>OO(t,e)).join(" "),OO=(r,e)=>{let t=e.loose?rt[qe.TILDELOOSE]:rt[qe.TILDE],n=e.includePrerelease?"-0":"";return r.replace(t,(i,s,o,a,c)=>{be("tilde",r,i,s,o,a,c);let l;return Te(s)?l="":Te(o)?l=`>=${s}.0.0${n} <${+s+1}.0.0-0`:Te(a)?l=`>=${s}.${o}.0${n} <${s}.${+o+1}.0-0`:c?(be("replaceTilde pr",c),l=`>=${s}.${o}.${a}-${c} <${s}.${+o+1}.0-0`):l=`>=${s}.${o}.${a} <${s}.${+o+1}.0-0`,be("tilde return",l),l})},DO=(r,e)=>r.trim().split(/\s+/).map(t=>NO(t,e)).join(" "),NO=(r,e)=>{be("caret",r,e);let t=e.loose?rt[qe.CARETLOOSE]:rt[qe.CARET],n=e.includePrerelease?"-0":"";return r.replace(t,(i,s,o,a,c)=>{be("caret",r,i,s,o,a,c);let l;return Te(s)?l="":Te(o)?l=`>=${s}.0.0${n} <${+s+1}.0.0-0`:Te(a)?s==="0"?l=`>=${s}.${o}.0${n} <${s}.${+o+1}.0-0`:l=`>=${s}.${o}.0${n} <${+s+1}.0.0-0`:c?(be("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`):(be("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`),be("caret return",l),l})},LO=(r,e)=>(be("replaceXRanges",r,e),r.split(/\s+/).map(t=>FO(t,e)).join(" ")),FO=(r,e)=>{r=r.trim();let t=e.loose?rt[qe.XRANGELOOSE]:rt[qe.XRANGE];return r.replace(t,(n,i,s,o,a,c)=>{if(be("xRange",r,n,i,s,o,a,c),RO(s,o,a))return r;let l=Te(s),u=l||Te(o),d=u||Te(a),f=d;return i==="="&&f&&(i=""),c=e.includePrerelease?"-0":"",l?i===">"||i==="<"?n="<0.0.0-0":n="*":i&&f?(u&&(o=0),a=0,i===">"?(i=">=",u?(s=+s+1,o=0,a=0):(o=+o+1,a=0)):i==="<="&&(i="<",u?s=+s+1:o=+o+1),i==="<"&&(c="-0"),n=`${i+s}.${o}.${a}${c}`):u?n=`>=${s}.0.0${c} <${+s+1}.0.0-0`:d&&(n=`>=${s}.${o}.0${c} <${s}.${+o+1}.0-0`),be("xRange return",n),n})},jO=(r,e)=>(be("replaceStars",r,e),r.trim().replace(rt[qe.STAR],"")),qO=(r,e)=>(be("replaceGTE0",r,e),r.trim().replace(rt[e.includePrerelease?qe.GTE0PRE:qe.GTE0],"")),BO=r=>(e,t,n,i,s,o,a,c,l,u,d,f)=>(Te(n)?t="":Te(i)?t=`>=${n}.0.0${r?"-0":""}`:Te(s)?t=`>=${n}.${i}.0${r?"-0":""}`:o?t=`>=${t}`:t=`>=${t}${r?"-0":""}`,Te(l)?c="":Te(u)?c=`<${+l+1}.0.0-0`:Te(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()),UO=(r,e,t)=>{for(let n=0;n0){let i=r[n].semver;if(i.major===e.major&&i.minor===e.minor&&i.patch===e.patch)return!0}return!1}return!0}});var ko=A((rU,N_)=>{"use strict";var Po=Symbol("SemVer ANY"),nh=class r{static get ANY(){return Po}constructor(e,t){if(t=T_(t),e instanceof r){if(e.loose===!!t.loose)return e;e=e.value}e=e.trim().split(/\s+/).join(" "),rh("comparator",e,t),this.options=t,this.loose=!!t.loose,this.parse(e),this.semver===Po?this.value="":this.value=this.operator+this.semver.version,rh("comp",this)}parse(e){let t=this.options.loose?R_[I_.COMPARATORLOOSE]:R_[I_.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 O_(n[2],this.options.loose):this.semver=Po}toString(){return this.value}test(e){if(rh("Comparator.test",e,this.options.loose),this.semver===Po||e===Po)return!0;if(typeof e=="string")try{e=new O_(e,this.options)}catch{return!1}return th(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 D_(e.value,t).test(this.value):e.operator===""?e.value===""?!0:new D_(this.value,t).test(e.semver):(t=T_(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("=")||th(this.semver,"<",e.semver,t)&&this.operator.startsWith(">")&&e.operator.startsWith("<")||th(this.semver,">",e.semver,t)&&this.operator.startsWith("<")&&e.operator.startsWith(">")))}};N_.exports=nh;var T_=Cc(),{safeRe:R_,t:I_}=os(),th=Xp(),rh=Eo(),O_=je(),D_=Ut()});var Co=A((nU,L_)=>{"use strict";var VO=Ut(),HO=(r,e,t)=>{try{e=new VO(e,t)}catch{return!1}return e.test(r)};L_.exports=HO});var j_=A((iU,F_)=>{"use strict";var zO=Ut(),KO=(r,e)=>new zO(r,e).set.map(t=>t.map(n=>n.value).join(" ").trim().split(" "));F_.exports=KO});var B_=A((sU,q_)=>{"use strict";var WO=je(),GO=Ut(),JO=(r,e,t)=>{let n=null,i=null,s=null;try{s=new GO(e,t)}catch{return null}return r.forEach(o=>{s.test(o)&&(!n||i.compare(o)===-1)&&(n=o,i=new WO(n,t))}),n};q_.exports=JO});var V_=A((oU,U_)=>{"use strict";var YO=je(),XO=Ut(),QO=(r,e,t)=>{let n=null,i=null,s=null;try{s=new XO(e,t)}catch{return null}return r.forEach(o=>{s.test(o)&&(!n||i.compare(o)===1)&&(n=o,i=new YO(n,t))}),n};U_.exports=QO});var K_=A((aU,z_)=>{"use strict";var ih=je(),ZO=Ut(),H_=Ao(),eD=(r,e)=>{r=new ZO(r,e);let t=new ih("0.0.0");if(r.test(t)||(t=new ih("0.0.0-0"),r.test(t)))return t;t=null;for(let n=0;n{let a=new ih(o.semver.version);switch(o.operator){case">":a.prerelease.length===0?a.patch++:a.prerelease.push(0),a.raw=a.format();case"":case">=":(!s||H_(a,s))&&(s=a);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${o.operator}`)}}),s&&(!t||H_(t,s))&&(t=s)}return t&&r.test(t)?t:null};z_.exports=eD});var G_=A((cU,W_)=>{"use strict";var tD=Ut(),rD=(r,e)=>{try{return new tD(r,e).range||"*"}catch{return null}};W_.exports=rD});var qc=A((lU,Q_)=>{"use strict";var nD=je(),X_=ko(),{ANY:iD}=X_,sD=Ut(),oD=Co(),J_=Ao(),Y_=Dc(),aD=Lc(),cD=Nc(),lD=(r,e,t,n)=>{r=new nD(r,n),e=new sD(e,n);let i,s,o,a,c;switch(t){case">":i=J_,s=aD,o=Y_,a=">",c=">=";break;case"<":i=Y_,s=cD,o=J_,a="<",c="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(oD(r,e,n))return!1;for(let l=0;l{p.semver===iD&&(p=new X_(">=0.0.0")),d=d||p,f=f||p,i(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)&&s(r,f.semver))return!1;if(f.operator===c&&o(r,f.semver))return!1}return!0};Q_.exports=lD});var e0=A((dU,Z_)=>{"use strict";var dD=qc(),uD=(r,e,t)=>dD(r,e,">",t);Z_.exports=uD});var r0=A((uU,t0)=>{"use strict";var fD=qc(),pD=(r,e,t)=>fD(r,e,"<",t);t0.exports=pD});var s0=A((fU,i0)=>{"use strict";var n0=Ut(),hD=(r,e,t)=>(r=new n0(r,t),e=new n0(e,t),r.intersects(e,t));i0.exports=hD});var a0=A((pU,o0)=>{"use strict";var mD=Co(),yD=Bt();o0.exports=(r,e,t)=>{let n=[],i=null,s=null,o=r.sort((u,d)=>yD(u,d,t));for(let u of o)mD(u,e,t)?(s=u,i||(i=u)):(s&&n.push([i,s]),s=null,i=null);i&&n.push([i,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 c0=Ut(),ah=ko(),{ANY:sh}=ah,oh=Co(),ch=Bt(),gD=(r,e,t={})=>{if(r===e)return!0;r=new c0(r,t),e=new c0(e,t);let n=!1;e:for(let i of r.set){for(let s of e.set){let o=vD(i,s,t);if(n=n||o!==null,o)continue e}if(n)return!1}return!0},bD=[new ah(">=0.0.0-0")],l0=[new ah(">=0.0.0")],vD=(r,e,t)=>{if(r===e)return!0;if(r.length===1&&r[0].semver===sh){if(e.length===1&&e[0].semver===sh)return!0;t.includePrerelease?r=bD:r=l0}if(e.length===1&&e[0].semver===sh){if(t.includePrerelease)return!0;e=l0}let n=new Set,i,s;for(let p of r)p.operator===">"||p.operator===">="?i=d0(i,p,t):p.operator==="<"||p.operator==="<="?s=u0(s,p,t):n.add(p.semver);if(n.size>1)return null;let o;if(i&&s){if(o=ch(i.semver,s.semver,t),o>0)return null;if(o===0&&(i.operator!==">="||s.operator!=="<="))return null}for(let p of n){if(i&&!oh(p,String(i),t)||s&&!oh(p,String(s),t))return null;for(let h of e)if(!oh(p,String(h),t))return!1;return!0}let a,c,l,u,d=s&&!t.includePrerelease&&s.semver.prerelease.length?s.semver:!1,f=i&&!t.includePrerelease&&i.semver.prerelease.length?i.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==="<=",i){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=d0(i,p,t),a===p&&a!==i)return!1}else if(i.operator===">="&&!p.test(i.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=u0(s,p,t),c===p&&c!==s)return!1}else if(s.operator==="<="&&!p.test(s.semver))return!1}if(!p.operator&&(s||i)&&o!==0)return!1}return!(i&&l&&!s&&o!==0||s&&u&&!i&&o!==0||f||d)},d0=(r,e,t)=>{if(!r)return e;let n=ch(r.semver,e.semver,t);return n>0?r:n<0||e.operator===">"&&r.operator===">="?e:r},u0=(r,e,t)=>{if(!r)return e;let n=ch(r.semver,e.semver,t);return n<0?r:n>0||e.operator==="<"&&r.operator==="<="?e:r};f0.exports=gD});var g0=A((mU,y0)=>{"use strict";var lh=os(),h0=ss(),wD=je(),m0=Kp(),_D=vn(),SD=jw(),$D=Bw(),xD=Hw(),ED=Ww(),AD=Jw(),kD=Xw(),PD=Zw(),CD=t_(),MD=Bt(),TD=s_(),RD=a_(),ID=Oc(),OD=u_(),DD=p_(),ND=Ao(),LD=Dc(),FD=Jp(),jD=Yp(),qD=Nc(),BD=Lc(),UD=Xp(),VD=S_(),HD=x_(),zD=ko(),KD=Ut(),WD=Co(),GD=j_(),JD=B_(),YD=V_(),XD=K_(),QD=G_(),ZD=qc(),eN=e0(),tN=r0(),rN=s0(),nN=a0(),iN=p0();y0.exports={parse:_D,valid:SD,clean:$D,inc:xD,diff:ED,major:AD,minor:kD,patch:PD,prerelease:CD,compare:MD,rcompare:TD,compareLoose:RD,compareBuild:ID,sort:OD,rsort:DD,gt:ND,lt:LD,eq:FD,neq:jD,gte:qD,lte:BD,cmp:UD,coerce:VD,truncate:HD,Comparator:zD,Range:KD,satisfies:WD,toComparators:GD,maxSatisfying:JD,minSatisfying:YD,minVersion:XD,validRange:QD,outside:ZD,gtr:eN,ltr:tN,intersects:rN,simplifyRange:nN,subset:iN,SemVer:wD,re:lh.re,src:lh.src,tokens:lh.t,SEMVER_SPEC_VERSION:h0.SEMVER_SPEC_VERSION,RELEASE_TYPES:h0.RELEASE_TYPES,compareIdentifiers:m0.compareIdentifiers,rcompareIdentifiers:m0.rcompareIdentifiers}});var uj={};ay(uj,{default:()=>Id});module.exports=nE(uj);var It=require("obsidian"),Dd="https://mdbase.dev/contracts/catalog.json",Ls="mdbase.lock.yaml",Nr=".mdbase/obsidian-pack-install.json";function mr(r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("Invalid contract catalog or type pack.");return r}function Wt(r){if(typeof r!="string"||!r)throw new Error("Missing catalog field.");return r}function dy(r){let e=Wt(r);if(!/^sha256:[a-f0-9]{64}$/.test(e))throw new Error("Invalid pack digest.");return e}function Ca(r){let e=Wt(r);if(e.includes("\\")||e.includes(":")||Array.from(e).some(t=>t.charCodeAt(0)<32)||e.split("/").some(t=>!t||t==="."||t===".."||t.startsWith(".")))throw new Error(`Unsafe pack path: ${e}`);return e}async function Pi(r){let e=typeof r=="string"?new TextEncoder().encode(r):r;return`sha256:${Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256",e))).map(t=>t.toString(16).padStart(2,"0")).join("")}`}function Nd(r){return Array.isArray(r)?`[${r.map(Nd).join(",")}]`:r&&typeof r=="object"?`{${Object.entries(r).sort(([e],[t])=>et?1:0).map(([e,t])=>`${JSON.stringify(e)}:${Nd(t)}`).join(",")}}`:JSON.stringify(r)}function iE(r){let e=new URL(Wt(r),Dd);if(e.origin!==new URL(Dd).origin||!e.pathname.startsWith("/contracts/"))throw new Error("Pack artifacts must come from the first-party contract catalog.");return e.href}async function sE(){let r=await(0,It.requestUrl)({url:Dd,throw:!1});if(r.status!==200)throw new Error(`Catalog unavailable (${r.status}). Your vault is unchanged. Try again when online.`);if(r.arrayBuffer.byteLength>1024*1024)throw new Error("Contract catalog is too large.");let e=mr(r.json);if(e.catalog_version!==2||!Array.isArray(e.packs))throw new Error("Unsupported contract catalog.");return e.packs.map(t=>{let n=mr(t),i=mr(n.display),s=mr(n.installation);if(!Number.isInteger(n.resource_count)||Number(n.resource_count)<1||Number(n.resource_count)>100)throw new Error("Invalid pack resource count.");return{id:Wt(n.id),version:Wt(n.version),digest:dy(n.digest),provision:iE(n.provision),resource_count:Number(n.resource_count),display:{name:Wt(i.name),summary:Wt(i.summary)},installation:{visibility:Wt(s.visibility),recommendation:Wt(s.recommendation),primary_type:s.primary_type==null?null:Wt(s.primary_type),...typeof s.caution=="string"?{caution:s.caution}:{}}}})}async function Wn(r,e){let t=r.vault.getAbstractFileByPath(e);if(t&&!(t instanceof It.TFile))throw new Error(`A folder occupies ${e}.`);return t instanceof It.TFile?r.vault.read(t):null}async function ly(r,e){let t=e.split("/");t.pop();let n="";for(let i of t)n=n?`${n}/${i}`:i,r.vault.getAbstractFileByPath(n)||await r.vault.createFolder(n)}async function oE(r,e){let t=await(0,It.requestUrl)({url:e.provision,throw:!1});if(t.status!==200)throw new Error(`Type pack unavailable (${t.status}).`);if(t.arrayBuffer.byteLength>1024*1024||await Pi(t.arrayBuffer)!==e.digest)throw new Error("The type pack does not match its catalog digest.");return aE(r,e,JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(t.arrayBuffer)))}async function aE(r,e,t){let n=mr(t),i=mr(n.manifest);if(i.kind!=="mdbase.type-pack"||i.id!==e.id||i.version!==e.version||!Array.isArray(i.resources)||i.resources.length!==e.resource_count||!Array.isArray(n.resources)||n.resources.length!==i.resources.length)throw new Error("The type-pack identity or resources do not match the catalog.");let s=new Map;for(let m of n.resources){let y=mr(m),g=Ca(y.source);if(s.has(g))throw new Error("Duplicate pack source.");let b=Wt(y.document);if(new TextEncoder().encode(b).byteLength>262144)throw new Error("Pack resource is too large.");s.set(g,b)}let o=new Set,a=[],c=[],l=await Wn(r,Ls),u=l?(0,It.parseYaml)(l):{kind:"mdbase.type-pack-lock",lock_version:1,packs:[]};if(u.kind!=="mdbase.type-pack-lock"||u.lock_version!==1||!Array.isArray(u.packs))throw new Error("Existing pack lock cannot be read safely.");let d=u.packs.find(m=>m.id===e.id),f=await Pi(Nd(i));if(d&&(d.version!==e.version||d.digest!==f))throw new Error("This pack is already installed at another revision. Upgrade it with mdbase editor; Obsidian currently supports fresh installs and same-version repair only.");for(let m of i.resources){let y=mr(m),g=Ca(y.source),b=Ca(y.target);if(!["contract","type","schema"].includes(String(y.kind))||!["managed","seed"].includes(String(y.mode))||o.has(b))throw new Error("Invalid pack resource or duplicate target.");let v=y.kind==="type"?"_types/":y.kind==="contract"?"_contracts/":"schemas/";if(!b.startsWith(v))throw new Error(`Unsupported pack target ${b}. Default definition folders are required.`);o.add(b);let S=s.get(g),_=dy(y.digest);if(!S||await Pi(S)!==_)throw new Error(`Resource digest mismatch: ${g}`);if(u.packs.some(M=>M.id!==e.id&&M.resources.some(x=>x.mode==="managed"&&x.target===b)))throw new Error(`${b} belongs to another installed pack.`);let E=await Wn(r,b),k=d?.resources.find(M=>M.target===b);if(y.mode==="managed"&&E!==null&&await Pi(E)!==_)throw new Error(`${b} already exists with different contents. Nothing was overwritten.`);let $=E===null&&!(y.mode==="seed"&&k)?"create":y.mode==="seed"?"preserve":"unchanged";a.push({path:b,before:E,after:S,action:$}),c.push({kind:y.kind,mode:y.mode,source:g,target:b,digest:_})}let p={id:e.id,version:e.version,digest:f,installed_by:d?.installed_by??"mdbase-obsidian",resources:c},h=`${JSON.stringify({...u,packs:[...u.packs.filter(m=>m.id!==e.id),p].sort((m,y)=>m.id.localeCompare(y.id))},null,2)} -`;return{pack:e,provision:t,lockBefore:l,lockAfter:h,files:a}}async function Ld(r){if(!await r.vault.adapter.exists(Nr))return;let e=mr(JSON.parse(await r.vault.adapter.read(Nr)));if(!Array.isArray(e.created))throw new Error("Invalid pack recovery journal.");if(await Wn(r,Ls)===e.lockAfter){await r.vault.adapter.remove(Nr);return}for(let t of[...e.created].reverse()){let n=mr(t),i=Ca(n.path),s=r.vault.getAbstractFileByPath(i);if(s instanceof It.TFile&&await Pi(await r.vault.read(s))===n.digest)await r.fileManager.trashFile(s);else if(s)throw new Error(`Pack recovery stopped: ${i} changed. Your edits and the journal were preserved.`)}await r.vault.adapter.remove(Nr)}var Od=new WeakSet;async function cE(r,e,t,n){if(Od.has(r))throw new Error("Another contract pack is installing. Wait for it to finish.");Od.add(r);try{await lE(r,e,t,n)}finally{Od.delete(r)}}async function lE(r,e,t,n){if(t(),await r.vault.adapter.exists(Nr))throw new Error("Recover the previous pack installation before trying again.");if(await Wn(r,Ls)!==e.lockBefore)throw new Error("Pack lock changed. Review again.");for(let s of e.files)if(await Wn(r,s.path)!==s.before)throw new Error(`${s.path} changed. Review again.`);await ly(r,Nr);let i={lockAfter:e.lockAfter,created:[]};await r.vault.adapter.write(Nr,JSON.stringify(i));try{let s=e.files.filter(a=>a.action==="create");n?.(0,s.length);for(let[a,c]of s.entries()){if(t(),await ly(r,c.path),await Wn(r,c.path)!==null)throw new Error(`${c.path} appeared during installation.`);if(i.created.push({path:c.path,digest:await Pi(c.after)}),await r.vault.adapter.write(Nr,JSON.stringify(i)),await r.vault.create(c.path,c.after),await Wn(r,c.path)!==c.after)throw new Error(`${c.path} changed during installation. Recovery will preserve competing edits.`);n?.(a+1,s.length)}t();let o=r.vault.getAbstractFileByPath(Ls);o instanceof It.TFile?await r.vault.process(o,a=>{if(a!==e.lockBefore)throw new Error("Pack lock changed during installation.");return e.lockAfter}):await r.vault.create(Ls,e.lockAfter),await r.vault.adapter.remove(Nr)}catch(s){throw await Ld(r),s}}var Ma=class extends It.Modal{constructor(t,n,i){super(t);this.assertWritable=n;this.installed=i;this.dismissed=!1}onOpen(){this.titleEl.setText("Ready-made types \xB7 mdbase-contracts"),this.load()}async load(){this.contentEl.empty(),this.contentEl.createEl("p",{text:"Loading first-party contract catalog\u2026"});try{let t=await sE();if(this.dismissed)return;this.contentEl.empty(),this.contentEl.createEl("p",{text:"Install standard application contracts plus editable starter types. Nothing grants applications access to your vault. Existing starter types are preserved."});let n=this.contentEl.createEl("details");n.createEl("summary",{text:"Advanced and integration packs"});for(let i of t.filter(s=>s.installation.visibility!=="hidden")){let s=(i.installation.visibility==="default"?this.contentEl:n).createDiv({cls:"mdbase-editor-section"});s.createEl("h3",{text:i.display.name}),s.createDiv({cls:"mdbase-muted",text:`Version ${i.version}`}),s.createEl("p",{text:i.display.summary}),i.installation.caution&&s.createEl("p",{text:i.installation.caution});let o=s.createEl("button",{text:"Review installation"}),a=s.createDiv();o.onclick=()=>{o.disabled=!0,oE(this.app,i).then(c=>{if(this.dismissed)return;a.empty();for(let u of c.files)a.createDiv({text:`${u.action} \xB7 ${u.path}`});let l=a.createEl("button",{text:"Install reviewed pack",cls:"mod-cta"});l.onclick=()=>{l.disabled=!0,cE(this.app,c,this.assertWritable,(u,d)=>{l.textContent=`Installing ${u} of ${d} files\u2026`}).then(async()=>{await this.installed(i.installation.primary_type),this.close()}).catch(u=>{a.createDiv({cls:"mdbase-inline-error",text:String(u)}),l.disabled=!1,l.textContent="Install reviewed pack"})}}).catch(c=>{a.createDiv({cls:"mdbase-inline-error",text:String(c)})}).finally(()=>{o.disabled=!1})}}}catch(t){if(this.dismissed)return;this.contentEl.empty(),this.contentEl.createEl("p",{cls:"mdbase-inline-error",text:String(t)}),this.contentEl.createEl("button",{text:"Retry catalog"}).onclick=()=>void this.load()}}onClose(){this.dismissed=!0}};var Ta=class{constructor(){this.checked=new Set;this.revision=0;this.lastCompletedAt=null;this.completedRevision=-1;this.cancelled=!1;this.progress=null}changed(e){this.revision++,e?this.checked.delete(e):this.checked.clear()}markChecked(e){this.checked.add(e)}isChecked(e){return this.checked.has(e)}summary(e){if(this.progress)return this.progress.phase==="uniqueness"?`Checked ${this.progress.completed} of ${this.progress.total} notes \xB7 checking uniqueness\u2026`:`Checking ${this.progress.completed} of ${this.progress.total} notes\u2026`;let t=e.filter(n=>this.checked.has(n)).length;return this.cancelled?`Validation stopped \xB7 ${t} of ${e.length} notes checked \xB7 results incomplete`:this.lastCompletedAt&&this.completedRevision===this.revision?`Validated ${new Date(this.lastCompletedAt).toLocaleTimeString()} \xB7 ${e.length} notes \xB7 including uniqueness`:this.lastCompletedAt?`Changed since last collection validation \xB7 ${t} of ${e.length} notes checked`:t?`Checked ${t} of ${e.length} notes \xB7 collection uniqueness not checked`:"Not checked yet"}};var tt=require("obsidian");var yw=require("obsidian");qt();function HR(r){let e=r.trim();if(!e||e.startsWith("/")||e.includes("\\")||Array.from(e).some(t=>t.charCodeAt(0)<32)||e.split("/").some(t=>!t||t==="."||t===".."||t.startsWith(".")))throw new Error("Choose a visible, vault-relative note path without .. or empty folders.");return e.endsWith(".md")?e:`${e}.md`}var $c=class extends yw.Modal{constructor(t,n,i,s,o){super(t);this.type=n;this.config=i;this.types=s;this.create=o;this.inputs=new Map;this.customPath=!1;this.suggestionVersion=0;this.creating=!1;this.dismissed=!1;this.frontmatter=Ip(n,i)}onOpen(){this.titleEl.setText(`New ${this.type.name}`),this.contentEl.addClass("mdbase-create-note");let t=Op(this.type,this.frontmatter),n=this.type.display_name_key??"title";!t.some(([c])=>c===n)&&this.frontmatter[n]==null&&t.unshift([n,this.type.fields[n]??{type:"string",description:"Used for the file name."}]);for(let[c,l]of t){let u=this.contentEl.createDiv({cls:"mdbase-form-row"}),d=u.createEl("label",{text:`${c}${l.required?" *":""}`});l.description&&u.createDiv({cls:"mdbase-form-description",text:l.description});let f;if(l.type==="boolean"||l.type==="enum"){let h=u.createEl("select");f=h,h.createEl("option",{value:"",text:"Choose\u2026"}),(l.type==="boolean"?[!0,!1]:l.values??[]).forEach((y,g)=>h.createEl("option",{value:String(g),text:String(y)}))}else if(["object","list","any"].includes(l.type??""))f=u.createEl("textarea"),f.placeholder=l.type==="object"?"YAML object":l.type==="list"?"YAML list or comma-separated values":"Value";else{let h=l.type==="date"?"date":l.type==="datetime"?"datetime-local":l.type==="time"?"time":"text";if(f=u.createEl("input",{type:h}),["integer","number"].includes(l.type??"")&&(f.inputMode="decimal"),l.type==="link"){let m=u.createEl("datalist");m.id=`mdbase-links-${this.inputs.size}`,this.app.vault.getMarkdownFiles().slice(0,500).forEach(y=>m.createEl("option",{value:`[[${y.path.replace(/\.md$/,"")}]]`})),f.setAttr("list",m.id)}}d.htmlFor=f.id=`mdbase-note-${c}`;let p=u.createDiv({cls:"mdbase-inline-error",attr:{"aria-live":"polite"}});f.addEventListener("input",()=>{this.readInputs(),this.suggestPath()}),f.addEventListener("change",()=>{this.readInputs(),this.suggestPath()}),this.inputs.set(c,{input:f,definition:l,error:p})}let i=this.contentEl.createDiv({cls:"mdbase-form-row"}),s=i.createEl("label",{text:"Location"});this.pathInput=i.createEl("input",{type:"text"}),s.htmlFor=this.pathInput.id="mdbase-note-location",this.pathInput.addEventListener("input",()=>{this.customPath=!0,this.problem.textContent=""});let o=i.createEl("button",{text:"Use suggested location"});o.onclick=()=>{this.customPath=!1,this.suggestPath()},this.problem=this.contentEl.createDiv({cls:"mdbase-inline-error",attr:{role:"alert"}});let a=this.contentEl.createDiv({cls:"modal-button-container"});a.createEl("button",{text:"Cancel"}).onclick=()=>{this.creating||this.close()},this.submit=a.createEl("button",{text:"Create note",cls:"mod-cta"}),this.submit.onclick=()=>void this.save(),this.suggestPath(),this.inputs.values().next().value?.input.focus()}readInputs(){let t=!0;for(let[n,{input:i,definition:s,error:o}]of this.inputs){o.textContent="";try{if(!i.value.trim()){if(delete this.frontmatter[n],s.required)throw new Error("Required");continue}let a=s.type==="boolean"?[!0,!1]:s.values??[];this.frontmatter[n]=["boolean","enum"].includes(s.type??"")?a[Number(i.value)]:Sc(i.value,s)}catch(a){t=!1,o.textContent=a instanceof Error?a.message:String(a)}}return t}async suggestPath(){let t=++this.suggestionVersion;try{let n=await Dp(this.app.vault,this.type,this.frontmatter);!this.dismissed&&t===this.suggestionVersion&&!this.customPath&&(this.pathInput.value=n)}catch(n){!this.dismissed&&t===this.suggestionVersion&&(this.problem.textContent=String(n))}}async save(){if(!(this.creating||!this.readInputs()))try{let t=HR(this.pathInput.value);if(yt(t,this.config))throw new Error("Choose a location included in this collection, not a definition or excluded folder.");if(this.app.vault.getAbstractFileByPath(t))throw new Error("A file already exists at this location. Choose another path.");let n=[...this.types.values()].flatMap(i=>i.name===this.type.name||this.type.extends===i.name?ts(t,this.frontmatter,i):[]);if(n.some(i=>i.severity==="error")){for(let i of n){let s=i.field?this.inputs.get(i.field):void 0;s&&(s.error.textContent=i.message)}throw new Error(n.filter(i=>i.severity==="error").map(i=>i.message).join(" \xB7 "))}this.creating=!0,this.submit.disabled=!0,await this.create(t,structuredClone(this.frontmatter)),this.close()}catch(t){this.problem.textContent=t instanceof Error?t.message:String(t)}finally{this.creating=!1,this.submit.disabled=!1}}onClose(){this.dismissed=!0}};qt();var rs=require("obsidian");var Lp=class extends rs.SuggestModal{constructor(t,n,i){super(t);this.resultHandled=!1;this.typeDefs=[...n].sort((s,o)=>s.name.localeCompare(o.name)),this.onResult=i,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(i=>{let s=i.match?.path_glob??"";return`${i.name} ${i.display_name_key??""} ${i.filePath} ${s}`.toLowerCase().includes(n)}).slice(0,100):this.typeDefs.slice(0,100)}renderSuggestion(t,n){let i=n.createDiv({cls:"mdbase-type-picker-suggestion"});i.createDiv({cls:"mdbase-type-picker-name",text:t.name});let s=i.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(t.fields??{}).length} fields`}),t.match?.path_glob&&i.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 Fp(r,e){return new Promise(t=>{new Lp(r,e,i=>{if(i.type==="selected"){t(i.typeDef);return}t(null)}).open()})}var xc=class extends rs.Modal{constructor(){super(...arguments);this.resolve=null;this.settled=!1}confirm(t,n=[]){return new Promise(i=>{this.resolve=i,this.titleEl.setText("Confirm high-impact type changes"),this.contentEl.createEl("p",{text:n.length?`${n.length} existing ${n.length===1?"note":"notes"} would fail validation. Only the type definition will be saved; notes are not changed.`:"These changes may invalidate existing notes. Only the type definition will be saved."});let s=this.contentEl.createEl("ul",{cls:"mdbase-confirm-change-list"});for(let l of t)s.createEl("li",{text:l.summary});if(n.length){let l=this.contentEl.createEl("ul",{cls:"mdbase-confirm-change-list mdbase-confirm-notes"});for(let u of n.slice(0,5))l.createEl("li",{text:u});n.length>5&&l.createEl("li",{text:`${n.length-5} more`})}let o=this.contentEl.createDiv({cls:"modal-button-container"}),a=o.createEl("button",{text:"Keep reviewing"});a.onclick=()=>this.finish(!1);let c=o.createEl("button",{text:"Save high-impact changes"});c.addClass("mod-warning"),c.onclick=()=>this.finish(!0),this.open()})}onClose(){this.settled||this.finish(!1,!1),this.contentEl.empty()}finish(t,n=!0){this.settled||(this.settled=!0,this.resolve?.(t),this.resolve=null,n&&this.close())}},Ec=class extends rs.Modal{constructor(){super(...arguments);this.resolve=null;this.settled=!1}confirm(t,n){return new Promise(i=>{this.resolve=i;let s=[...new Set(n.map(d=>d.path))],o=`${s.length} ${s.length===1?"note":"notes"}`;this.titleEl.setText(`${t} in ${o}?`),this.contentEl.createEl("p",{text:`Only the '${n[0]?.field??"affected"}' frontmatter field changes in each note. Notes that changed since validation are skipped.`});let a=this.contentEl.createEl("ul",{cls:"mdbase-confirm-change-list"});for(let d of s.slice(0,8))a.createEl("li",{text:d});s.length>8&&a.createEl("li",{text:`${s.length-8} more`});let c=this.contentEl.createDiv({cls:"modal-button-container"}),l=c.createEl("button",{text:"Cancel"});l.onclick=()=>this.finish(!1);let u=c.createEl("button",{text:`Update ${o}`});u.addClass("mod-cta"),u.onclick=()=>this.finish(!0),this.open()})}onClose(){this.settled||this.finish(!1,!1),this.contentEl.empty()}finish(t,n=!0){this.settled||(this.settled=!0,this.resolve?.(t),this.resolve=null,n&&this.close())}},Ac=class extends rs.Modal{constructor(){super(...arguments);this.resolve=null;this.settled=!1}choose(t){return new Promise(n=>{this.resolve=n,this.titleEl.setText("Disconnect this vault?"),this.contentEl.createEl("p",{text:`This stops synchronization with ${t}. It does not delete the hosted collection.`}),this.contentEl.createEl("p",{text:"Keep all local files, or remove unchanged synced files. Local edits are kept either way."});let i=this.contentEl.createDiv({cls:"modal-button-container"}),s=i.createEl("button",{text:"Cancel"});s.onclick=()=>this.finish(null);let o=i.createEl("button",{text:"Keep files",cls:"mod-cta"});o.onclick=()=>this.finish("keep");let a=i.createEl("button",{text:"Remove unchanged files"});a.addClass("mod-warning"),a.onclick=()=>this.finish("remove"),this.open()})}onClose(){this.settled||this.finish(null,!1),this.contentEl.empty()}finish(t,n=!0){this.settled||(this.settled=!0,this.resolve?.(t),this.resolve=null,n&&this.close())}};function gw(r){let{app:e}=r,t=()=>r.getMirrorProfile()!==null;r.addCommand({id:"mdbase-open",name:"Open workspace",callback:()=>void r.openWorkspace()}),r.addCommand({id:"mdbase-initialize-collection",name:"Initialize collection",checkCallback:n=>t()||e.vault.getAbstractFileByPath("mdbase.yaml")?!1:(n||KR(r),!0)}),r.addCommand({id:"mdbase-create-type",name:"Create type definition",callback:()=>void r.openWorkspace("types").then(n=>n.createNewType())}),r.addCommand({id:"mdbase-edit-type",name:"Edit type definition",callback:()=>void WR(r)}),r.addCommand({id:"mdbase-create-note-from-type",name:"Create note from type",callback:()=>void jp(r)}),r.addCommand({id:"mdbase-validate-current-note",name:"Validate current note",checkCallback:n=>{let i=e.workspace.getActiveFile();return!(i instanceof tt.TFile)||i.extension!=="md"?!1:(n||GR(r,i),!0)}}),r.addCommand({id:"mdbase-validate-collection",name:"Validate collection",callback:()=>void r.runCollectionValidation(!0)}),r.addCommand({id:"mdbase-sync-now",name:"Sync now",checkCallback:n=>t()?(n||zR(r),!0):!1}),r.addCommand({id:"mdbase-cancel-sync",name:"Cancel current sync",checkCallback:n=>r.sync.isSyncing()?(n||r.sync.cancel(),!0):!1}),r.addCommand({id:"mdbase-resolve-conflicts",name:"Resolve sync conflicts",checkCallback:n=>!t()||!r.sync.state.status?.conflicts.length?!1:(n||r.openWorkspace("sync").then(i=>i.focusSyncSection("conflicts")),!0)}),r.addCommand({id:"mdbase-reconnect",name:"Reconnect collection",checkCallback:n=>{let i=r.sync.state.problem;return!t()||!i||i.action!=="reauthorize"?!1:(n||r.openWorkspace("sync").then(s=>s.reconnectCollection()),!0)}}),r.addCommand({id:"mdbase-copy-sync-diagnostics",name:"Copy sync diagnostics",checkCallback:n=>t()?(n||r.copySyncDiagnostics(),!0):!1}),r.addCommand({id:"mdbase-note-sync-history",name:"Show sync history for current note",checkCallback:n=>{let i=e.workspace.getActiveFile();return!i||!t()?!1:(n||r.openNoteSyncHistory(i.path),!0)}}),r.registerEvent(e.workspace.on("file-menu",(n,i)=>{!(i instanceof tt.TFile)||!t()||n.addItem(s=>s.setTitle("Sync history").setIcon("history").onClick(()=>r.openNoteSyncHistory(i.path)))}))}async function zR(r){let e=await r.sync.syncNow(),{message:t,problem:n}=r.sync.state;if(e==="needs_review"){let i=r.sync.safety()?.reasons??[];new tt.Notice(`Review before syncing: ${i.join(", ").toLowerCase()||"changes need attention"}.`),await r.openWorkspace("sync")}else e==="busy"?new tt.Notice("A sync is already running."):e==="paused"?new tt.Notice("Sync is paused."):e==="failed"?new tt.Notice(n?.message??(t||"Sync failed.")):t&&new tt.Notice(t)}async function KR(r){r.connectSync.assertLocalAuthorityWritable();let{created:e}=await $o(r.app.vault,{seedNoteType:!1});r.invalidateSchemaCache(),new tt.Notice(e.length?`Initialized mdbase collection: ${e.join(", ")}`:"mdbase collection already initialized.")}async function WR(r){let e=await r.requireConfigAndTypes();if(!e)return;if(e.types.size===0){new tt.Notice("No type definitions found.");return}let t=r.app.workspace.getActiveFile(),n=[];if(t instanceof tt.TFile&&t.extension==="md"){let o=[...e.types.values()].find(a=>a.filePath===t.path);if(o)n=[o];else{let a=Me(await r.app.vault.cachedRead(t));a.error||(n=Ke(t.path,a.frontmatter,e.config,e.types).flatMap(c=>e.types.get(c)??[]))}}let i=n.length===1?n[0]:await Fp(r.app,n.length?n:[...e.types.values()]);if(!i)return;await(await r.openWorkspace("types")).editType(i.filePath)}async function GR(r,e){let t=await r.validateFileAndStore(e,"manual");if(t.length===0){new tt.Notice("No issues in current note.");return}new tt.Notice(`Found ${t.length} issue${t.length===1?"":"s"} in current note.`),(await r.openWorkspace("issues")).showIssuesForPath(e.path)}async function jp(r,e){r.connectSync.assertLocalAuthorityWritable();let t=await r.requireConfigAndTypes();if(!t)return;if(t.types.size===0){new tt.Notice("No type definitions found.");return}if(r.getMirrorProfile()?.mode==="read_only")throw new Error("This mirror has read-only access.");let n=e?t.types.get(e):await Fp(r.app,Array.from(t.types.values()));n&&new $c(r.app,n,t.config,t.types,async(i,s)=>{if(r.connectSync.assertLocalAuthorityWritable(),r.getMirrorProfile()?.mode==="read_only")throw new Error("This mirror has read-only access.");let{createNoteFromType:o}=await Promise.resolve().then(()=>(qt(),mw)),a=await o(r.app.vault,i,s);await r.app.workspace.getLeaf(!0).openFile(a),await r.validateFileAndStore(a,"manual")}).open()}var bw=require("obsidian");qt();function qp(r,e){let t=Me(r);if(t.error)throw new Error(`Invalid frontmatter: ${t.error}`);return JR(t.frontmatter,e)?{content:`--- +`}async function BR(r,e,t,n){let i=t.trim(),s=(0,oe.normalizePath)(`${e.settings.types_folder}/${i}.md`);if(await r.adapter.exists(s))throw new Error(`Type already exists: ${s}`);let o=Tp(i,n,e.spec_version);return await r.create(s,o),s}function Rp(r,e){let t={},n=e.settings.explicit_type_keys[0]??"type";t[n]=n==="types"?[r.name]:r.name;for(let[i,s]of Object.entries(r.fields)){if(!W(s))continue;let o=s;o.default!==void 0&&(t[i]=Oe(o.default))}return t}function Ip(r,e){let t=[];for(let[n,i]of Object.entries(r.fields)){if(!W(i))continue;let s=i;s.computed||s.required&&e[n]===void 0&&t.push([n,s])}return t}function Sc(r,e){let t=r.trim();switch(e.type??"string"){case"string":case"date":case"datetime":case"time":case"link":case"enum":case"any":return t;case"integer":{let i=Number(t);if(!/^[+-]?\d+$/.test(t)||!Number.isSafeInteger(i))throw new Error("Expected a whole integer");return i}case"number":{let i=Number(t);if(!/^[+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?$/i.test(t)||!Number.isFinite(i))throw new Error("Expected a finite number");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":{if(t.startsWith("[")||/^-\s/.test(t)){let s=(0,oe.parseYaml)(t);if(!Array.isArray(s))throw new Error("Expected a YAML or JSON list");return s}let i=t.split(",").map(s=>s.trim()).filter(s=>s.length>0);return e.items?i.map(s=>Sc(s,e.items)):i}case"object":{let i=(0,oe.parseYaml)(t);if(!W(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 $p(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 UR(r,e){let t=(0,oe.normalizePath)(e).replace(/\/+$/,"");if(!t)return;let n=t.split("/"),i="";for(let s of n)i=i?`${i}/${s}`:s,await r.adapter.exists(i)||await r.createFolder(i)}function VR(r,e){if(!r.path_pattern||r.path_pattern.trim().length===0)return null;let t=(0,oe.normalizePath)(Pp(r.path_pattern,e));return t.endsWith(".md")?t:null}async function Op(r,e,t){let n=VR(e,t),i=uw(e,t),s=n?n.split("/").pop()??n:fw(e,t),o=yn(n||`${i?`${i}/`:""}${s.endsWith(".md")?s:`${s}.md`}`),a=o,c=2;for(;r.getAbstractFileByPath(a);)a=o.replace(/\.md$/,`-${c}.md`),c+=1;return a}async function HR(r,e,t,n=""){let i=yn(e),s=i.lastIndexOf("/");if(s>0&&await UR(r,i.slice(0,s)),await r.adapter.exists(i))throw new Error(`File already exists: ${i}`);let o=`${mt(t,n)} +`;return r.create(i,o)}function Dp(r){return bR(r)}var oe,tw,rw,xp,So,qr,mR,_o,MR,TR,qt=oy(()=>{oe=require("obsidian"),tw=Kn(Yf(),1),rw=Kn(op(),1),xp=Kn(gp(),1);Zv();So=class extends Error{constructor(t,n){super(n);this.code=t;this.name="MdbasePathError"}},qr={spec_version:"0.3.0",name:"My mdbase collection",description:"Typed markdown collection",settings:{types_folder:"_types",contracts_folder:"_contracts",explicit_type_keys:["type","types"],exclude:[]}},mR=["_types",".obsidian",".git","node_modules",".trash",".mdbase"],_o=null;MR={string:"text",integer:"a whole number",number:"a number",boolean:"true or false",array:"a list",object:"an object",null:"empty"},TR={date:"a date (YYYY-MM-DD)","date-time":"a date and time",time:"a time (HH:MM)",email:"an email address",uri:"a URI"}});var ss=A((EB,kw)=>{"use strict";var ZR="2.0.0",eI=Number.MAX_SAFE_INTEGER||9007199254740991,tI=16,rI=250,nI=["major","premajor","minor","preminor","patch","prepatch","prerelease"];kw.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:tI,MAX_SAFE_BUILD_LENGTH:rI,MAX_SAFE_INTEGER:eI,RELEASE_TYPES:nI,SEMVER_SPEC_VERSION:ZR,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var Eo=A((AB,Pw)=>{"use strict";var iI=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...r)=>console.error("SEMVER",...r):()=>{};Pw.exports=iI});var os=A((Sr,Cw)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:Vp,MAX_SAFE_BUILD_LENGTH:sI,MAX_LENGTH:oI}=ss(),aI=Eo();Sr=Cw.exports={};var cI=Sr.re=[],lI=Sr.safeRe=[],D=Sr.src=[],dI=Sr.safeSrc=[],N=Sr.t={},uI=0,Hp="[a-zA-Z0-9-]",fI=[["\\s",1],["\\d",oI],[Hp,sI]],pI=r=>{for(let[e,t]of fI)r=r.split(`${e}*`).join(`${e}{0,${t}}`).split(`${e}+`).join(`${e}{1,${t}}`);return r},H=(r,e,t)=>{let n=pI(e),i=uI++;aI(r,i,e),N[r]=i,D[i]=e,dI[i]=n,cI[i]=new RegExp(e,t?"g":void 0),lI[i]=new RegExp(n,t?"g":void 0)};H("NUMERICIDENTIFIER","0|[1-9]\\d*");H("NUMERICIDENTIFIERLOOSE","\\d+");H("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${Hp}*`);H("MAINVERSION",`(${D[N.NUMERICIDENTIFIER]})\\.(${D[N.NUMERICIDENTIFIER]})\\.(${D[N.NUMERICIDENTIFIER]})`);H("MAINVERSIONLOOSE",`(${D[N.NUMERICIDENTIFIERLOOSE]})\\.(${D[N.NUMERICIDENTIFIERLOOSE]})\\.(${D[N.NUMERICIDENTIFIERLOOSE]})`);H("PRERELEASEIDENTIFIER",`(?:${D[N.NONNUMERICIDENTIFIER]}|${D[N.NUMERICIDENTIFIER]})`);H("PRERELEASEIDENTIFIERLOOSE",`(?:${D[N.NONNUMERICIDENTIFIER]}|${D[N.NUMERICIDENTIFIERLOOSE]})`);H("PRERELEASE",`(?:-(${D[N.PRERELEASEIDENTIFIER]}(?:\\.${D[N.PRERELEASEIDENTIFIER]})*))`);H("PRERELEASELOOSE",`(?:-?(${D[N.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${D[N.PRERELEASEIDENTIFIERLOOSE]})*))`);H("BUILDIDENTIFIER",`${Hp}+`);H("BUILD",`(?:\\+(${D[N.BUILDIDENTIFIER]}(?:\\.${D[N.BUILDIDENTIFIER]})*))`);H("FULLPLAIN",`v?${D[N.MAINVERSION]}${D[N.PRERELEASE]}?${D[N.BUILD]}?`);H("FULL",`^${D[N.FULLPLAIN]}$`);H("LOOSEPLAIN",`[v=\\s]*${D[N.MAINVERSIONLOOSE]}${D[N.PRERELEASELOOSE]}?${D[N.BUILD]}?`);H("LOOSE",`^${D[N.LOOSEPLAIN]}$`);H("GTLT","((?:<|>)?=?)");H("XRANGEIDENTIFIERLOOSE",`${D[N.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);H("XRANGEIDENTIFIER",`${D[N.NUMERICIDENTIFIER]}|x|X|\\*`);H("XRANGEPLAIN",`[v=\\s]*(${D[N.XRANGEIDENTIFIER]})(?:\\.(${D[N.XRANGEIDENTIFIER]})(?:\\.(${D[N.XRANGEIDENTIFIER]})(?:${D[N.PRERELEASE]})?${D[N.BUILD]}?)?)?`);H("XRANGEPLAINLOOSE",`[v=\\s]*(${D[N.XRANGEIDENTIFIERLOOSE]})(?:\\.(${D[N.XRANGEIDENTIFIERLOOSE]})(?:\\.(${D[N.XRANGEIDENTIFIERLOOSE]})(?:${D[N.PRERELEASELOOSE]})?${D[N.BUILD]}?)?)?`);H("XRANGE",`^${D[N.GTLT]}\\s*${D[N.XRANGEPLAIN]}$`);H("XRANGELOOSE",`^${D[N.GTLT]}\\s*${D[N.XRANGEPLAINLOOSE]}$`);H("COERCEPLAIN",`(^|[^\\d])(\\d{1,${Vp}})(?:\\.(\\d{1,${Vp}}))?(?:\\.(\\d{1,${Vp}}))?`);H("COERCE",`${D[N.COERCEPLAIN]}(?:$|[^\\d])`);H("COERCEFULL",D[N.COERCEPLAIN]+`(?:${D[N.PRERELEASE]})?(?:${D[N.BUILD]})?(?:$|[^\\d])`);H("COERCERTL",D[N.COERCE],!0);H("COERCERTLFULL",D[N.COERCEFULL],!0);H("LONETILDE","(?:~>?)");H("TILDETRIM",`(\\s*)${D[N.LONETILDE]}\\s+`,!0);Sr.tildeTrimReplace="$1~";H("TILDE",`^${D[N.LONETILDE]}${D[N.XRANGEPLAIN]}$`);H("TILDELOOSE",`^${D[N.LONETILDE]}${D[N.XRANGEPLAINLOOSE]}$`);H("LONECARET","(?:\\^)");H("CARETTRIM",`(\\s*)${D[N.LONECARET]}\\s+`,!0);Sr.caretTrimReplace="$1^";H("CARET",`^${D[N.LONECARET]}${D[N.XRANGEPLAIN]}$`);H("CARETLOOSE",`^${D[N.LONECARET]}${D[N.XRANGEPLAINLOOSE]}$`);H("COMPARATORLOOSE",`^${D[N.GTLT]}\\s*(${D[N.LOOSEPLAIN]})$|^$`);H("COMPARATOR",`^${D[N.GTLT]}\\s*(${D[N.FULLPLAIN]})$|^$`);H("COMPARATORTRIM",`(\\s*)${D[N.GTLT]}\\s*(${D[N.LOOSEPLAIN]}|${D[N.XRANGEPLAIN]})`,!0);Sr.comparatorTrimReplace="$1$2$3";H("HYPHENRANGE",`^\\s*(${D[N.XRANGEPLAIN]})\\s+-\\s+(${D[N.XRANGEPLAIN]})\\s*$`);H("HYPHENRANGELOOSE",`^\\s*(${D[N.XRANGEPLAINLOOSE]})\\s+-\\s+(${D[N.XRANGEPLAINLOOSE]})\\s*$`);H("STAR","(<|>)?=?\\s*\\*");H("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");H("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")});var Cc=A((kB,Mw)=>{"use strict";var hI=Object.freeze({loose:!0}),mI=Object.freeze({}),yI=r=>r?typeof r!="object"?hI:r:mI;Mw.exports=yI});var zp=A((PB,Iw)=>{"use strict";var Tw=/^[0-9]+$/,Rw=(r,e)=>{if(typeof r=="number"&&typeof e=="number")return r===e?0:rRw(e,r);Iw.exports={compareIdentifiers:Rw,rcompareIdentifiers:gI}});var je=A((CB,Dw)=>{"use strict";var Mc=Eo(),{MAX_LENGTH:Ow,MAX_SAFE_INTEGER:Tc}=ss(),{safeRe:Rc,t:Ic}=os(),bI=Cc(),{compareIdentifiers:Kp}=zp(),vI=(r,e)=>{let t=e.split(".");if(t.length>r.length)return!1;for(let n=0;nOw)throw new TypeError(`version is longer than ${Ow} characters`);Mc("SemVer",e,t),this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease;let n=e.trim().match(t.loose?Rc[Ic.LOOSE]:Rc[Ic.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>Tc||this.major<0)throw new TypeError("Invalid major version");if(this.minor>Tc||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>Tc||this.patch<0)throw new TypeError("Invalid patch version");n[4]?this.prerelease=n[4].split(".").map(i=>{if(/^[0-9]+$/.test(i)){let s=+i;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 n=this.prerelease[t],i=e.prerelease[t];if(Mc("prerelease compare",t,n,i),n===void 0&&i===void 0)return 0;if(i===void 0)return 1;if(n===void 0)return-1;if(n===i)continue;return Kp(n,i)}while(++t)}compareBuild(e){e instanceof r||(e=new r(e,this.options));let t=0;do{let n=this.build[t],i=e.build[t];if(Mc("build compare",t,n,i),n===void 0&&i===void 0)return 0;if(i===void 0)return 1;if(n===void 0)return-1;if(n===i)continue;return Kp(n,i)}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 i=`-${t}`.match(this.options.loose?Rc[Ic.PRERELEASELOOSE]:Rc[Ic.PRERELEASE]);if(!i||i[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 i=Number(n)?1:0;if(this.prerelease.length===0)this.prerelease=[i];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(".")&&n===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(i)}}if(t){let s=[t,i];if(n===!1&&(s=[t]),vI(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}};Dw.exports=Wp});var vn=A((MB,Lw)=>{"use strict";var Nw=je(),wI=(r,e,t=!1)=>{if(r instanceof Nw)return r;try{return new Nw(r,e)}catch(n){if(!t)return null;throw n}};Lw.exports=wI});var jw=A((TB,Fw)=>{"use strict";var _I=vn(),SI=(r,e)=>{let t=_I(r,e);return t?t.version:null};Fw.exports=SI});var Bw=A((RB,qw)=>{"use strict";var $I=vn(),xI=(r,e)=>{let t=$I(r.trim().replace(/^[=v]+/,""),e);return t?t.version:null};qw.exports=xI});var Hw=A((IB,Vw)=>{"use strict";var Uw=je(),EI=(r,e,t,n,i)=>{typeof t=="string"&&(i=n,n=t,t=void 0);try{return new Uw(r instanceof Uw?r.version:r,t).inc(e,n,i).version}catch{return null}};Vw.exports=EI});var Ww=A((OB,Kw)=>{"use strict";var zw=vn(),AI=(r,e)=>{let t=zw(r,null,!0),n=zw(e,null,!0),i=t.compare(n);if(i===0)return null;let s=i>0,o=s?t:n,a=s?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"};Kw.exports=AI});var Jw=A((DB,Gw)=>{"use strict";var kI=je(),PI=(r,e)=>new kI(r,e).major;Gw.exports=PI});var Xw=A((NB,Yw)=>{"use strict";var CI=je(),MI=(r,e)=>new CI(r,e).minor;Yw.exports=MI});var Zw=A((LB,Qw)=>{"use strict";var TI=je(),RI=(r,e)=>new TI(r,e).patch;Qw.exports=RI});var t_=A((FB,e_)=>{"use strict";var II=vn(),OI=(r,e)=>{let t=II(r,e);return t&&t.prerelease.length?t.prerelease:null};e_.exports=OI});var Bt=A((jB,n_)=>{"use strict";var r_=je(),DI=(r,e,t)=>new r_(r,t).compare(new r_(e,t));n_.exports=DI});var s_=A((qB,i_)=>{"use strict";var NI=Bt(),LI=(r,e,t)=>NI(e,r,t);i_.exports=LI});var a_=A((BB,o_)=>{"use strict";var FI=Bt(),jI=(r,e)=>FI(r,e,!0);o_.exports=jI});var Oc=A((UB,l_)=>{"use strict";var c_=je(),qI=(r,e,t)=>{let n=new c_(r,t),i=new c_(e,t);return n.compare(i)||n.compareBuild(i)};l_.exports=qI});var u_=A((VB,d_)=>{"use strict";var BI=Oc(),UI=(r,e)=>r.sort((t,n)=>BI(t,n,e));d_.exports=UI});var p_=A((HB,f_)=>{"use strict";var VI=Oc(),HI=(r,e)=>r.sort((t,n)=>VI(n,t,e));f_.exports=HI});var Ao=A((zB,h_)=>{"use strict";var zI=Bt(),KI=(r,e,t)=>zI(r,e,t)>0;h_.exports=KI});var Dc=A((KB,m_)=>{"use strict";var WI=Bt(),GI=(r,e,t)=>WI(r,e,t)<0;m_.exports=GI});var Gp=A((WB,y_)=>{"use strict";var JI=Bt(),YI=(r,e,t)=>JI(r,e,t)===0;y_.exports=YI});var Jp=A((GB,g_)=>{"use strict";var XI=Bt(),QI=(r,e,t)=>XI(r,e,t)!==0;g_.exports=QI});var Nc=A((JB,b_)=>{"use strict";var ZI=Bt(),eO=(r,e,t)=>ZI(r,e,t)>=0;b_.exports=eO});var Lc=A((YB,v_)=>{"use strict";var tO=Bt(),rO=(r,e,t)=>tO(r,e,t)<=0;v_.exports=rO});var Yp=A((XB,w_)=>{"use strict";var nO=Gp(),iO=Jp(),sO=Ao(),oO=Nc(),aO=Dc(),cO=Lc(),lO=(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 nO(r,t,n);case"!=":return iO(r,t,n);case">":return sO(r,t,n);case">=":return oO(r,t,n);case"<":return aO(r,t,n);case"<=":return cO(r,t,n);default:throw new TypeError(`Invalid operator: ${e}`)}};w_.exports=lO});var S_=A((QB,__)=>{"use strict";var dO=je(),uO=vn(),{safeRe:Fc,t:jc}=os(),fO=(r,e)=>{if(r instanceof dO)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?Fc[jc.COERCEFULL]:Fc[jc.COERCE]);else{let c=e.includePrerelease?Fc[jc.COERCERTLFULL]:Fc[jc.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],i=t[3]||"0",s=t[4]||"0",o=e.includePrerelease&&t[5]?`-${t[5]}`:"",a=e.includePrerelease&&t[6]?`+${t[6]}`:"";return uO(`${n}.${i}.${s}${o}${a}`,e)};__.exports=fO});var x_=A((ZB,$_)=>{"use strict";var pO=vn(),hO=ss(),mO=je(),yO=(r,e,t)=>{if(!hO.RELEASE_TYPES.includes(e))return null;let n=gO(r,t);return n&&bO(n,e)},gO=(r,e)=>{let t=r instanceof mO?r.version:r;return pO(t,e)},bO=(r,e)=>{if(vO(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()},vO=r=>r.startsWith("pre");$_.exports=yO});var A_=A((eU,E_)=>{"use strict";var Xp=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 i=this.map.keys().next().value;this.delete(i)}this.map.set(e,t)}return this}};E_.exports=Xp});var Ut=A((tU,M_)=>{"use strict";var wO=/\s+/g,Qp=class r{constructor(e,t){if(t=SO(t),e instanceof r)return e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease?e:new r(e.raw,t);if(e instanceof Zp)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(wO," "),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(i=>!P_(i[0])),this.set.length===0)this.set=[n];else if(this.set.length>1){for(let i of this.set)if(i.length===1&&TO(i[0])){this.set=[i];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(MO,"");let n=((this.options.includePrerelease&&PO)|(this.options.loose&&CO))+":"+e,i=k_.get(n);if(i)return i;let s=this.options.loose,o=s?rt[qe.HYPHENRANGELOOSE]:rt[qe.HYPHENRANGE];e=e.replace(o,UO(this.options.includePrerelease)),be("hyphen replace",e),e=e.replace(rt[qe.COMPARATORTRIM],EO),be("comparator trim",e),e=e.replace(rt[qe.TILDETRIM],AO),be("tilde trim",e),e=e.replace(rt[qe.CARETTRIM],kO),be("caret trim",e);let a=e.split(" ").map(d=>RO(d,this.options)).join(" ").split(/\s+/).map(d=>BO(d,this.options));s&&(a=a.filter(d=>(be("loose invalid filter",d,this.options),!!d.match(rt[qe.COMPARATORLOOSE])))),be("range list",a);let c=new Map,l=a.map(d=>new Zp(d,this.options));for(let d of l){if(P_(d))return[d];c.set(d.value,d)}c.size>1&&c.has("")&&c.delete("");let u=[...c.values()];return k_.set(n,u),u}intersects(e,t){if(!(e instanceof r))throw new TypeError("a Range is required");return this.set.some(n=>C_(n,t)&&e.set.some(i=>C_(i,t)&&n.every(s=>i.every(o=>s.intersects(o,t)))))}test(e){if(!e)return!1;if(typeof e=="string")try{e=new $O(e,this.options)}catch{return!1}for(let t=0;tr.value==="<0.0.0-0",TO=r=>r.value==="",C_=(r,e)=>{let t=!0,n=r.slice(),i=n.pop();for(;t&&n.length;)t=n.every(s=>i.intersects(s,e)),i=n.pop();return t},RO=(r,e)=>(r=r.replace(rt[qe.BUILD],""),be("comp",r,e),r=NO(r,e),be("caret",r),r=OO(r,e),be("tildes",r),r=FO(r,e),be("xrange",r),r=qO(r,e),be("stars",r),r),Te=r=>!r||r.toLowerCase()==="x"||r==="*",IO=(r,e,t)=>Te(r)&&!Te(e)||Te(e)&&t&&!Te(t),OO=(r,e)=>r.trim().split(/\s+/).map(t=>DO(t,e)).join(" "),DO=(r,e)=>{let t=e.loose?rt[qe.TILDELOOSE]:rt[qe.TILDE],n=e.includePrerelease?"-0":"";return r.replace(t,(i,s,o,a,c)=>{be("tilde",r,i,s,o,a,c);let l;return Te(s)?l="":Te(o)?l=`>=${s}.0.0${n} <${+s+1}.0.0-0`:Te(a)?l=`>=${s}.${o}.0${n} <${s}.${+o+1}.0-0`:c?(be("replaceTilde pr",c),l=`>=${s}.${o}.${a}-${c} <${s}.${+o+1}.0-0`):l=`>=${s}.${o}.${a} <${s}.${+o+1}.0-0`,be("tilde return",l),l})},NO=(r,e)=>r.trim().split(/\s+/).map(t=>LO(t,e)).join(" "),LO=(r,e)=>{be("caret",r,e);let t=e.loose?rt[qe.CARETLOOSE]:rt[qe.CARET],n=e.includePrerelease?"-0":"";return r.replace(t,(i,s,o,a,c)=>{be("caret",r,i,s,o,a,c);let l;return Te(s)?l="":Te(o)?l=`>=${s}.0.0${n} <${+s+1}.0.0-0`:Te(a)?s==="0"?l=`>=${s}.${o}.0${n} <${s}.${+o+1}.0-0`:l=`>=${s}.${o}.0${n} <${+s+1}.0.0-0`:c?(be("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`):(be("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`),be("caret return",l),l})},FO=(r,e)=>(be("replaceXRanges",r,e),r.split(/\s+/).map(t=>jO(t,e)).join(" ")),jO=(r,e)=>{r=r.trim();let t=e.loose?rt[qe.XRANGELOOSE]:rt[qe.XRANGE];return r.replace(t,(n,i,s,o,a,c)=>{if(be("xRange",r,n,i,s,o,a,c),IO(s,o,a))return r;let l=Te(s),u=l||Te(o),d=u||Te(a),f=d;return i==="="&&f&&(i=""),c=e.includePrerelease?"-0":"",l?i===">"||i==="<"?n="<0.0.0-0":n="*":i&&f?(u&&(o=0),a=0,i===">"?(i=">=",u?(s=+s+1,o=0,a=0):(o=+o+1,a=0)):i==="<="&&(i="<",u?s=+s+1:o=+o+1),i==="<"&&(c="-0"),n=`${i+s}.${o}.${a}${c}`):u?n=`>=${s}.0.0${c} <${+s+1}.0.0-0`:d&&(n=`>=${s}.${o}.0${c} <${s}.${+o+1}.0-0`),be("xRange return",n),n})},qO=(r,e)=>(be("replaceStars",r,e),r.trim().replace(rt[qe.STAR],"")),BO=(r,e)=>(be("replaceGTE0",r,e),r.trim().replace(rt[e.includePrerelease?qe.GTE0PRE:qe.GTE0],"")),UO=r=>(e,t,n,i,s,o,a,c,l,u,d,f)=>(Te(n)?t="":Te(i)?t=`>=${n}.0.0${r?"-0":""}`:Te(s)?t=`>=${n}.${i}.0${r?"-0":""}`:o?t=`>=${t}`:t=`>=${t}${r?"-0":""}`,Te(l)?c="":Te(u)?c=`<${+l+1}.0.0-0`:Te(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()),VO=(r,e,t)=>{for(let n=0;n0){let i=r[n].semver;if(i.major===e.major&&i.minor===e.minor&&i.patch===e.patch)return!0}return!1}return!0}});var ko=A((rU,N_)=>{"use strict";var Po=Symbol("SemVer ANY"),rh=class r{static get ANY(){return Po}constructor(e,t){if(t=T_(t),e instanceof r){if(e.loose===!!t.loose)return e;e=e.value}e=e.trim().split(/\s+/).join(" "),th("comparator",e,t),this.options=t,this.loose=!!t.loose,this.parse(e),this.semver===Po?this.value="":this.value=this.operator+this.semver.version,th("comp",this)}parse(e){let t=this.options.loose?R_[I_.COMPARATORLOOSE]:R_[I_.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 O_(n[2],this.options.loose):this.semver=Po}toString(){return this.value}test(e){if(th("Comparator.test",e,this.options.loose),this.semver===Po||e===Po)return!0;if(typeof e=="string")try{e=new O_(e,this.options)}catch{return!1}return eh(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 D_(e.value,t).test(this.value):e.operator===""?e.value===""?!0:new D_(this.value,t).test(e.semver):(t=T_(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("=")||eh(this.semver,"<",e.semver,t)&&this.operator.startsWith(">")&&e.operator.startsWith("<")||eh(this.semver,">",e.semver,t)&&this.operator.startsWith("<")&&e.operator.startsWith(">")))}};N_.exports=rh;var T_=Cc(),{safeRe:R_,t:I_}=os(),eh=Yp(),th=Eo(),O_=je(),D_=Ut()});var Co=A((nU,L_)=>{"use strict";var HO=Ut(),zO=(r,e,t)=>{try{e=new HO(e,t)}catch{return!1}return e.test(r)};L_.exports=zO});var j_=A((iU,F_)=>{"use strict";var KO=Ut(),WO=(r,e)=>new KO(r,e).set.map(t=>t.map(n=>n.value).join(" ").trim().split(" "));F_.exports=WO});var B_=A((sU,q_)=>{"use strict";var GO=je(),JO=Ut(),YO=(r,e,t)=>{let n=null,i=null,s=null;try{s=new JO(e,t)}catch{return null}return r.forEach(o=>{s.test(o)&&(!n||i.compare(o)===-1)&&(n=o,i=new GO(n,t))}),n};q_.exports=YO});var V_=A((oU,U_)=>{"use strict";var XO=je(),QO=Ut(),ZO=(r,e,t)=>{let n=null,i=null,s=null;try{s=new QO(e,t)}catch{return null}return r.forEach(o=>{s.test(o)&&(!n||i.compare(o)===1)&&(n=o,i=new XO(n,t))}),n};U_.exports=ZO});var K_=A((aU,z_)=>{"use strict";var nh=je(),eD=Ut(),H_=Ao(),tD=(r,e)=>{r=new eD(r,e);let t=new nh("0.0.0");if(r.test(t)||(t=new nh("0.0.0-0"),r.test(t)))return t;t=null;for(let n=0;n{let a=new nh(o.semver.version);switch(o.operator){case">":a.prerelease.length===0?a.patch++:a.prerelease.push(0),a.raw=a.format();case"":case">=":(!s||H_(a,s))&&(s=a);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${o.operator}`)}}),s&&(!t||H_(t,s))&&(t=s)}return t&&r.test(t)?t:null};z_.exports=tD});var G_=A((cU,W_)=>{"use strict";var rD=Ut(),nD=(r,e)=>{try{return new rD(r,e).range||"*"}catch{return null}};W_.exports=nD});var qc=A((lU,Q_)=>{"use strict";var iD=je(),X_=ko(),{ANY:sD}=X_,oD=Ut(),aD=Co(),J_=Ao(),Y_=Dc(),cD=Lc(),lD=Nc(),dD=(r,e,t,n)=>{r=new iD(r,n),e=new oD(e,n);let i,s,o,a,c;switch(t){case">":i=J_,s=cD,o=Y_,a=">",c=">=";break;case"<":i=Y_,s=lD,o=J_,a="<",c="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(aD(r,e,n))return!1;for(let l=0;l{p.semver===sD&&(p=new X_(">=0.0.0")),d=d||p,f=f||p,i(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)&&s(r,f.semver))return!1;if(f.operator===c&&o(r,f.semver))return!1}return!0};Q_.exports=dD});var e0=A((dU,Z_)=>{"use strict";var uD=qc(),fD=(r,e,t)=>uD(r,e,">",t);Z_.exports=fD});var r0=A((uU,t0)=>{"use strict";var pD=qc(),hD=(r,e,t)=>pD(r,e,"<",t);t0.exports=hD});var s0=A((fU,i0)=>{"use strict";var n0=Ut(),mD=(r,e,t)=>(r=new n0(r,t),e=new n0(e,t),r.intersects(e,t));i0.exports=mD});var a0=A((pU,o0)=>{"use strict";var yD=Co(),gD=Bt();o0.exports=(r,e,t)=>{let n=[],i=null,s=null,o=r.sort((u,d)=>gD(u,d,t));for(let u of o)yD(u,e,t)?(s=u,i||(i=u)):(s&&n.push([i,s]),s=null,i=null);i&&n.push([i,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 c0=Ut(),oh=ko(),{ANY:ih}=oh,sh=Co(),ah=Bt(),bD=(r,e,t={})=>{if(r===e)return!0;r=new c0(r,t),e=new c0(e,t);let n=!1;e:for(let i of r.set){for(let s of e.set){let o=wD(i,s,t);if(n=n||o!==null,o)continue e}if(n)return!1}return!0},vD=[new oh(">=0.0.0-0")],l0=[new oh(">=0.0.0")],wD=(r,e,t)=>{if(r===e)return!0;if(r.length===1&&r[0].semver===ih){if(e.length===1&&e[0].semver===ih)return!0;t.includePrerelease?r=vD:r=l0}if(e.length===1&&e[0].semver===ih){if(t.includePrerelease)return!0;e=l0}let n=new Set,i,s;for(let p of r)p.operator===">"||p.operator===">="?i=d0(i,p,t):p.operator==="<"||p.operator==="<="?s=u0(s,p,t):n.add(p.semver);if(n.size>1)return null;let o;if(i&&s){if(o=ah(i.semver,s.semver,t),o>0)return null;if(o===0&&(i.operator!==">="||s.operator!=="<="))return null}for(let p of n){if(i&&!sh(p,String(i),t)||s&&!sh(p,String(s),t))return null;for(let m of e)if(!sh(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=i&&!t.includePrerelease&&i.semver.prerelease.length?i.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==="<=",i){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=d0(i,p,t),a===p&&a!==i)return!1}else if(i.operator===">="&&!p.test(i.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=u0(s,p,t),c===p&&c!==s)return!1}else if(s.operator==="<="&&!p.test(s.semver))return!1}if(!p.operator&&(s||i)&&o!==0)return!1}return!(i&&l&&!s&&o!==0||s&&u&&!i&&o!==0||f||d)},d0=(r,e,t)=>{if(!r)return e;let n=ah(r.semver,e.semver,t);return n>0?r:n<0||e.operator===">"&&r.operator===">="?e:r},u0=(r,e,t)=>{if(!r)return e;let n=ah(r.semver,e.semver,t);return n<0?r:n>0||e.operator==="<"&&r.operator==="<="?e:r};f0.exports=bD});var g0=A((mU,y0)=>{"use strict";var ch=os(),h0=ss(),_D=je(),m0=zp(),SD=vn(),$D=jw(),xD=Bw(),ED=Hw(),AD=Ww(),kD=Jw(),PD=Xw(),CD=Zw(),MD=t_(),TD=Bt(),RD=s_(),ID=a_(),OD=Oc(),DD=u_(),ND=p_(),LD=Ao(),FD=Dc(),jD=Gp(),qD=Jp(),BD=Nc(),UD=Lc(),VD=Yp(),HD=S_(),zD=x_(),KD=ko(),WD=Ut(),GD=Co(),JD=j_(),YD=B_(),XD=V_(),QD=K_(),ZD=G_(),eN=qc(),tN=e0(),rN=r0(),nN=s0(),iN=a0(),sN=p0();y0.exports={parse:SD,valid:$D,clean:xD,inc:ED,diff:AD,major:kD,minor:PD,patch:CD,prerelease:MD,compare:TD,rcompare:RD,compareLoose:ID,compareBuild:OD,sort:DD,rsort:ND,gt:LD,lt:FD,eq:jD,neq:qD,gte:BD,lte:UD,cmp:VD,coerce:HD,truncate:zD,Comparator:KD,Range:WD,satisfies:GD,toComparators:JD,maxSatisfying:YD,minSatisfying:XD,minVersion:QD,validRange:ZD,outside:eN,gtr:tN,ltr:rN,intersects:nN,simplifyRange:iN,subset:sN,SemVer:_D,re:ch.re,src:ch.src,tokens:ch.t,SEMVER_SPEC_VERSION:h0.SEMVER_SPEC_VERSION,RELEASE_TYPES:h0.RELEASE_TYPES,compareIdentifiers:m0.compareIdentifiers,rcompareIdentifiers:m0.rcompareIdentifiers}});var uj={};ay(uj,{default:()=>Rd});module.exports=iE(uj);var It=require("obsidian"),Od="https://mdbase.dev/contracts/catalog.json",Ls="mdbase.lock.yaml",Nr=".mdbase/obsidian-pack-install.json";function mr(r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("Invalid contract catalog or type pack.");return r}function Wt(r){if(typeof r!="string"||!r)throw new Error("Missing catalog field.");return r}function dy(r){let e=Wt(r);if(!/^sha256:[a-f0-9]{64}$/.test(e))throw new Error("Invalid pack digest.");return e}function Ca(r){let e=Wt(r);if(e.includes("\\")||e.includes(":")||Array.from(e).some(t=>t.charCodeAt(0)<32)||e.split("/").some(t=>!t||t==="."||t===".."||t.startsWith(".")))throw new Error(`Unsafe pack path: ${e}`);return e}async function Pi(r){let e=typeof r=="string"?new TextEncoder().encode(r):r;return`sha256:${Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256",e))).map(t=>t.toString(16).padStart(2,"0")).join("")}`}function Dd(r){return Array.isArray(r)?`[${r.map(Dd).join(",")}]`:r&&typeof r=="object"?`{${Object.entries(r).sort(([e],[t])=>et?1:0).map(([e,t])=>`${JSON.stringify(e)}:${Dd(t)}`).join(",")}}`:JSON.stringify(r)}function sE(r){let e=new URL(Wt(r),Od);if(e.origin!==new URL(Od).origin||!e.pathname.startsWith("/contracts/"))throw new Error("Pack artifacts must come from the first-party contract catalog.");return e.href}async function oE(){let r=await(0,It.requestUrl)({url:Od,throw:!1});if(r.status!==200)throw new Error(`Catalog unavailable (${r.status}). Your vault is unchanged. Try again when online.`);if(r.arrayBuffer.byteLength>1024*1024)throw new Error("Contract catalog is too large.");let e=mr(r.json);if(e.catalog_version!==2||!Array.isArray(e.packs))throw new Error("Unsupported contract catalog.");return e.packs.map(t=>{let n=mr(t),i=mr(n.display),s=mr(n.installation);if(!Number.isInteger(n.resource_count)||Number(n.resource_count)<1||Number(n.resource_count)>100)throw new Error("Invalid pack resource count.");return{id:Wt(n.id),version:Wt(n.version),digest:dy(n.digest),provision:sE(n.provision),resource_count:Number(n.resource_count),display:{name:Wt(i.name),summary:Wt(i.summary)},installation:{visibility:Wt(s.visibility),recommendation:Wt(s.recommendation),primary_type:s.primary_type==null?null:Wt(s.primary_type),...typeof s.caution=="string"?{caution:s.caution}:{}}}})}async function Wn(r,e){let t=r.vault.getAbstractFileByPath(e);if(t&&!(t instanceof It.TFile))throw new Error(`A folder occupies ${e}.`);return t instanceof It.TFile?r.vault.read(t):null}async function ly(r,e){let t=e.split("/");t.pop();let n="";for(let i of t)n=n?`${n}/${i}`:i,r.vault.getAbstractFileByPath(n)||await r.vault.createFolder(n)}async function aE(r,e){let t=await(0,It.requestUrl)({url:e.provision,throw:!1});if(t.status!==200)throw new Error(`Type pack unavailable (${t.status}).`);if(t.arrayBuffer.byteLength>1024*1024||await Pi(t.arrayBuffer)!==e.digest)throw new Error("The type pack does not match its catalog digest.");return cE(r,e,JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(t.arrayBuffer)))}async function cE(r,e,t){let n=mr(t),i=mr(n.manifest);if(i.kind!=="mdbase.type-pack"||i.id!==e.id||i.version!==e.version||!Array.isArray(i.resources)||i.resources.length!==e.resource_count||!Array.isArray(n.resources)||n.resources.length!==i.resources.length)throw new Error("The type-pack identity or resources do not match the catalog.");let s=new Map;for(let h of n.resources){let y=mr(h),g=Ca(y.source);if(s.has(g))throw new Error("Duplicate pack source.");let b=Wt(y.document);if(new TextEncoder().encode(b).byteLength>262144)throw new Error("Pack resource is too large.");s.set(g,b)}let o=new Set,a=[],c=[],l=await Wn(r,Ls),u=l?(0,It.parseYaml)(l):{kind:"mdbase.type-pack-lock",lock_version:1,packs:[]};if(u.kind!=="mdbase.type-pack-lock"||u.lock_version!==1||!Array.isArray(u.packs))throw new Error("Existing pack lock cannot be read safely.");let d=u.packs.find(h=>h.id===e.id),f=await Pi(Dd(i));if(d&&(d.version!==e.version||d.digest!==f))throw new Error("This pack is already installed at another revision. Upgrade it with mdbase editor; Obsidian currently supports fresh installs and same-version repair only.");for(let h of i.resources){let y=mr(h),g=Ca(y.source),b=Ca(y.target);if(!["contract","type","schema"].includes(String(y.kind))||!["managed","seed"].includes(String(y.mode))||o.has(b))throw new Error("Invalid pack resource or duplicate target.");let v=y.kind==="type"?"_types/":y.kind==="contract"?"_contracts/":"schemas/";if(!b.startsWith(v))throw new Error(`Unsupported pack target ${b}. Default definition folders are required.`);o.add(b);let S=s.get(g),_=dy(y.digest);if(!S||await Pi(S)!==_)throw new Error(`Resource digest mismatch: ${g}`);if(u.packs.some(M=>M.id!==e.id&&M.resources.some(x=>x.mode==="managed"&&x.target===b)))throw new Error(`${b} belongs to another installed pack.`);let E=await Wn(r,b),k=d?.resources.find(M=>M.target===b);if(y.mode==="managed"&&E!==null&&await Pi(E)!==_)throw new Error(`${b} already exists with different contents. Nothing was overwritten.`);let $=E===null&&!(y.mode==="seed"&&k)?"create":y.mode==="seed"?"preserve":"unchanged";a.push({path:b,before:E,after:S,action:$}),c.push({kind:y.kind,mode:y.mode,source:g,target:b,digest:_})}let p={id:e.id,version:e.version,digest:f,installed_by:d?.installed_by??"mdbase-obsidian",resources:c},m=`${JSON.stringify({...u,packs:[...u.packs.filter(h=>h.id!==e.id),p].sort((h,y)=>h.id.localeCompare(y.id))},null,2)} +`;return{pack:e,provision:t,lockBefore:l,lockAfter:m,files:a}}async function Nd(r){if(!await r.vault.adapter.exists(Nr))return;let e=mr(JSON.parse(await r.vault.adapter.read(Nr)));if(!Array.isArray(e.created))throw new Error("Invalid pack recovery journal.");if(await Wn(r,Ls)===e.lockAfter){await r.vault.adapter.remove(Nr);return}for(let t of[...e.created].reverse()){let n=mr(t),i=Ca(n.path),s=r.vault.getAbstractFileByPath(i);if(s instanceof It.TFile&&await Pi(await r.vault.read(s))===n.digest)await r.fileManager.trashFile(s);else if(s)throw new Error(`Pack recovery stopped: ${i} changed. Your edits and the journal were preserved.`)}await r.vault.adapter.remove(Nr)}var Id=new WeakSet;async function lE(r,e,t,n){if(Id.has(r))throw new Error("Another contract pack is installing. Wait for it to finish.");Id.add(r);try{await dE(r,e,t,n)}finally{Id.delete(r)}}async function dE(r,e,t,n){if(t(),await r.vault.adapter.exists(Nr))throw new Error("Recover the previous pack installation before trying again.");if(await Wn(r,Ls)!==e.lockBefore)throw new Error("Pack lock changed. Review again.");for(let s of e.files)if(await Wn(r,s.path)!==s.before)throw new Error(`${s.path} changed. Review again.`);await ly(r,Nr);let i={lockAfter:e.lockAfter,created:[]};await r.vault.adapter.write(Nr,JSON.stringify(i));try{let s=e.files.filter(a=>a.action==="create");n?.(0,s.length);for(let[a,c]of s.entries()){if(t(),await ly(r,c.path),await Wn(r,c.path)!==null)throw new Error(`${c.path} appeared during installation.`);if(i.created.push({path:c.path,digest:await Pi(c.after)}),await r.vault.adapter.write(Nr,JSON.stringify(i)),await r.vault.create(c.path,c.after),await Wn(r,c.path)!==c.after)throw new Error(`${c.path} changed during installation. Recovery will preserve competing edits.`);n?.(a+1,s.length)}t();let o=r.vault.getAbstractFileByPath(Ls);o instanceof It.TFile?await r.vault.process(o,a=>{if(a!==e.lockBefore)throw new Error("Pack lock changed during installation.");return e.lockAfter}):await r.vault.create(Ls,e.lockAfter),await r.vault.adapter.remove(Nr)}catch(s){throw await Nd(r),s}}var Ma=class extends It.Modal{constructor(t,n,i){super(t);this.assertWritable=n;this.installed=i;this.dismissed=!1}onOpen(){this.titleEl.setText("Ready-made types \xB7 mdbase-contracts"),this.load()}async load(){this.contentEl.empty(),this.contentEl.createEl("p",{text:"Loading first-party contract catalog\u2026"});try{let t=await oE();if(this.dismissed)return;this.contentEl.empty(),this.contentEl.createEl("p",{text:"Install standard application contracts plus editable starter types. Nothing grants applications access to your vault. Existing starter types are preserved."});let n=this.contentEl.createEl("details");n.createEl("summary",{text:"Advanced and integration packs"});for(let i of t.filter(s=>s.installation.visibility!=="hidden")){let s=(i.installation.visibility==="default"?this.contentEl:n).createDiv({cls:"mdbase-editor-section"});s.createEl("h3",{text:i.display.name}),s.createDiv({cls:"mdbase-muted",text:`Version ${i.version}`}),s.createEl("p",{text:i.display.summary}),i.installation.caution&&s.createEl("p",{text:i.installation.caution});let o=s.createEl("button",{text:"Review installation"}),a=s.createDiv();o.onclick=()=>{o.disabled=!0,aE(this.app,i).then(c=>{if(this.dismissed)return;a.empty();for(let u of c.files)a.createDiv({text:`${u.action} \xB7 ${u.path}`});let l=a.createEl("button",{text:"Install reviewed pack",cls:"mod-cta"});l.onclick=()=>{l.disabled=!0,lE(this.app,c,this.assertWritable,(u,d)=>{l.textContent=`Installing ${u} of ${d} files\u2026`}).then(async()=>{await this.installed(i.installation.primary_type),this.close()}).catch(u=>{a.createDiv({cls:"mdbase-inline-error",text:String(u)}),l.disabled=!1,l.textContent="Install reviewed pack"})}}).catch(c=>{a.createDiv({cls:"mdbase-inline-error",text:String(c)})}).finally(()=>{o.disabled=!1})}}}catch(t){if(this.dismissed)return;this.contentEl.empty(),this.contentEl.createEl("p",{cls:"mdbase-inline-error",text:String(t)}),this.contentEl.createEl("button",{text:"Retry catalog"}).onclick=()=>void this.load()}}onClose(){this.dismissed=!0}};var Ta=class{constructor(){this.checked=new Set;this.revision=0;this.lastCompletedAt=null;this.completedRevision=-1;this.cancelled=!1;this.progress=null}changed(e){this.revision++,e?this.checked.delete(e):this.checked.clear()}markChecked(e){this.checked.add(e)}isChecked(e){return this.checked.has(e)}summary(e){if(this.progress)return this.progress.phase==="uniqueness"?`Checked ${this.progress.completed} of ${this.progress.total} notes \xB7 checking uniqueness\u2026`:`Checking ${this.progress.completed} of ${this.progress.total} notes\u2026`;let t=e.filter(n=>this.checked.has(n)).length;return this.cancelled?`Validation stopped \xB7 ${t} of ${e.length} notes checked \xB7 results incomplete`:this.lastCompletedAt&&this.completedRevision===this.revision?`Validated ${new Date(this.lastCompletedAt).toLocaleTimeString()} \xB7 ${e.length} notes \xB7 including uniqueness`:this.lastCompletedAt?`Changed since last collection validation \xB7 ${t} of ${e.length} notes checked`:t?`Checked ${t} of ${e.length} notes \xB7 collection uniqueness not checked`:"Not checked yet"}};var tt=require("obsidian");var yw=require("obsidian");qt();function zR(r){let e=r.trim();if(!e||e.startsWith("/")||e.includes("\\")||Array.from(e).some(t=>t.charCodeAt(0)<32)||e.split("/").some(t=>!t||t==="."||t===".."||t.startsWith(".")))throw new Error("Choose a visible, vault-relative note path without .. or empty folders.");return e.endsWith(".md")?e:`${e}.md`}var $c=class extends yw.Modal{constructor(t,n,i,s,o){super(t);this.type=n;this.config=i;this.types=s;this.create=o;this.inputs=new Map;this.customPath=!1;this.suggestionVersion=0;this.creating=!1;this.dismissed=!1;this.frontmatter=Rp(n,i)}onOpen(){this.titleEl.setText(`New ${this.type.name}`),this.contentEl.addClass("mdbase-create-note");let t=Ip(this.type,this.frontmatter),n=this.type.display_name_key??"title";!t.some(([c])=>c===n)&&this.frontmatter[n]==null&&t.unshift([n,this.type.fields[n]??{type:"string",description:"Used for the file name."}]);for(let[c,l]of t){let u=this.contentEl.createDiv({cls:"mdbase-form-row"}),d=u.createEl("label",{text:`${c}${l.required?" *":""}`});l.description&&u.createDiv({cls:"mdbase-form-description",text:l.description});let f;if(l.type==="boolean"||l.type==="enum"){let m=u.createEl("select");f=m,m.createEl("option",{value:"",text:"Choose\u2026"}),(l.type==="boolean"?[!0,!1]:l.values??[]).forEach((y,g)=>m.createEl("option",{value:String(g),text:String(y)}))}else if(["object","list","any"].includes(l.type??""))f=u.createEl("textarea"),f.placeholder=l.type==="object"?"YAML object":l.type==="list"?"YAML list or comma-separated values":"Value";else{let m=l.type==="date"?"date":l.type==="datetime"?"datetime-local":l.type==="time"?"time":"text";if(f=u.createEl("input",{type:m}),["integer","number"].includes(l.type??"")&&(f.inputMode="decimal"),l.type==="link"){let h=u.createEl("datalist");h.id=`mdbase-links-${this.inputs.size}`,this.app.vault.getMarkdownFiles().slice(0,500).forEach(y=>h.createEl("option",{value:`[[${y.path.replace(/\.md$/,"")}]]`})),f.setAttr("list",h.id)}}d.htmlFor=f.id=`mdbase-note-${c}`;let p=u.createDiv({cls:"mdbase-inline-error",attr:{"aria-live":"polite"}});f.addEventListener("input",()=>{this.readInputs(),this.suggestPath()}),f.addEventListener("change",()=>{this.readInputs(),this.suggestPath()}),this.inputs.set(c,{input:f,definition:l,error:p})}let i=this.contentEl.createDiv({cls:"mdbase-form-row"}),s=i.createEl("label",{text:"Location"});this.pathInput=i.createEl("input",{type:"text"}),s.htmlFor=this.pathInput.id="mdbase-note-location",this.pathInput.addEventListener("input",()=>{this.customPath=!0,this.problem.textContent=""});let o=i.createEl("button",{text:"Use suggested location"});o.onclick=()=>{this.customPath=!1,this.suggestPath()},this.problem=this.contentEl.createDiv({cls:"mdbase-inline-error",attr:{role:"alert"}});let a=this.contentEl.createDiv({cls:"modal-button-container"});a.createEl("button",{text:"Cancel"}).onclick=()=>{this.creating||this.close()},this.submit=a.createEl("button",{text:"Create note",cls:"mod-cta"}),this.submit.onclick=()=>void this.save(),this.suggestPath(),this.inputs.values().next().value?.input.focus()}readInputs(){let t=!0;for(let[n,{input:i,definition:s,error:o}]of this.inputs){o.textContent="";try{if(!i.value.trim()){if(delete this.frontmatter[n],s.required)throw new Error("Required");continue}let a=s.type==="boolean"?[!0,!1]:s.values??[];this.frontmatter[n]=["boolean","enum"].includes(s.type??"")?a[Number(i.value)]:Sc(i.value,s)}catch(a){t=!1,o.textContent=a instanceof Error?a.message:String(a)}}return t}async suggestPath(){let t=++this.suggestionVersion;try{let n=await Op(this.app.vault,this.type,this.frontmatter);!this.dismissed&&t===this.suggestionVersion&&!this.customPath&&(this.pathInput.value=n)}catch(n){!this.dismissed&&t===this.suggestionVersion&&(this.problem.textContent=String(n))}}async save(){if(!(this.creating||!this.readInputs()))try{let t=zR(this.pathInput.value);if(yt(t,this.config))throw new Error("Choose a location included in this collection, not a definition or excluded folder.");if(this.app.vault.getAbstractFileByPath(t))throw new Error("A file already exists at this location. Choose another path.");let n=[...this.types.values()].flatMap(i=>i.name===this.type.name||this.type.extends===i.name?ts(t,this.frontmatter,i):[]);if(n.some(i=>i.severity==="error")){for(let i of n){let s=i.field?this.inputs.get(i.field):void 0;s&&(s.error.textContent=i.message)}throw new Error(n.filter(i=>i.severity==="error").map(i=>i.message).join(" \xB7 "))}this.creating=!0,this.submit.disabled=!0,await this.create(t,structuredClone(this.frontmatter)),this.close()}catch(t){this.problem.textContent=t instanceof Error?t.message:String(t)}finally{this.creating=!1,this.submit.disabled=!1}}onClose(){this.dismissed=!0}};qt();var rs=require("obsidian");var Np=class extends rs.SuggestModal{constructor(t,n,i){super(t);this.resultHandled=!1;this.typeDefs=[...n].sort((s,o)=>s.name.localeCompare(o.name)),this.onResult=i,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(i=>{let s=i.match?.path_glob??"";return`${i.name} ${i.display_name_key??""} ${i.filePath} ${s}`.toLowerCase().includes(n)}).slice(0,100):this.typeDefs.slice(0,100)}renderSuggestion(t,n){let i=n.createDiv({cls:"mdbase-type-picker-suggestion"});i.createDiv({cls:"mdbase-type-picker-name",text:t.name});let s=i.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(t.fields??{}).length} fields`}),t.match?.path_glob&&i.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 Lp(r,e){return new Promise(t=>{new Np(r,e,i=>{if(i.type==="selected"){t(i.typeDef);return}t(null)}).open()})}var xc=class extends rs.Modal{constructor(){super(...arguments);this.resolve=null;this.settled=!1}confirm(t,n=[]){return new Promise(i=>{this.resolve=i,this.titleEl.setText("Confirm high-impact type changes"),this.contentEl.createEl("p",{text:n.length?`${n.length} existing ${n.length===1?"note":"notes"} would fail validation. Only the type definition will be saved; notes are not changed.`:"These changes may invalidate existing notes. Only the type definition will be saved."});let s=this.contentEl.createEl("ul",{cls:"mdbase-confirm-change-list"});for(let l of t)s.createEl("li",{text:l.summary});if(n.length){let l=this.contentEl.createEl("ul",{cls:"mdbase-confirm-change-list mdbase-confirm-notes"});for(let u of n.slice(0,5))l.createEl("li",{text:u});n.length>5&&l.createEl("li",{text:`${n.length-5} more`})}let o=this.contentEl.createDiv({cls:"modal-button-container"}),a=o.createEl("button",{text:"Keep reviewing"});a.onclick=()=>this.finish(!1);let c=o.createEl("button",{text:"Save high-impact changes"});c.addClass("mod-warning"),c.onclick=()=>this.finish(!0),this.open()})}onClose(){this.settled||this.finish(!1,!1),this.contentEl.empty()}finish(t,n=!0){this.settled||(this.settled=!0,this.resolve?.(t),this.resolve=null,n&&this.close())}},Ec=class extends rs.Modal{constructor(){super(...arguments);this.resolve=null;this.settled=!1}confirm(t,n){return new Promise(i=>{this.resolve=i;let s=[...new Set(n.map(d=>d.path))],o=`${s.length} ${s.length===1?"note":"notes"}`;this.titleEl.setText(`${t} in ${o}?`),this.contentEl.createEl("p",{text:`Only the '${n[0]?.field??"affected"}' frontmatter field changes in each note. Notes that changed since validation are skipped.`});let a=this.contentEl.createEl("ul",{cls:"mdbase-confirm-change-list"});for(let d of s.slice(0,8))a.createEl("li",{text:d});s.length>8&&a.createEl("li",{text:`${s.length-8} more`});let c=this.contentEl.createDiv({cls:"modal-button-container"}),l=c.createEl("button",{text:"Cancel"});l.onclick=()=>this.finish(!1);let u=c.createEl("button",{text:`Update ${o}`});u.addClass("mod-cta"),u.onclick=()=>this.finish(!0),this.open()})}onClose(){this.settled||this.finish(!1,!1),this.contentEl.empty()}finish(t,n=!0){this.settled||(this.settled=!0,this.resolve?.(t),this.resolve=null,n&&this.close())}},Ac=class extends rs.Modal{constructor(){super(...arguments);this.resolve=null;this.settled=!1}choose(t){return new Promise(n=>{this.resolve=n,this.titleEl.setText("Disconnect this vault?"),this.contentEl.createEl("p",{text:`This stops synchronization with ${t}. It does not delete the hosted collection.`}),this.contentEl.createEl("p",{text:"Keep all local files, or remove unchanged synced files. Local edits are kept either way."});let i=this.contentEl.createDiv({cls:"modal-button-container"}),s=i.createEl("button",{text:"Cancel"});s.onclick=()=>this.finish(null);let o=i.createEl("button",{text:"Keep files",cls:"mod-cta"});o.onclick=()=>this.finish("keep");let a=i.createEl("button",{text:"Remove unchanged files"});a.addClass("mod-warning"),a.onclick=()=>this.finish("remove"),this.open()})}onClose(){this.settled||this.finish(null,!1),this.contentEl.empty()}finish(t,n=!0){this.settled||(this.settled=!0,this.resolve?.(t),this.resolve=null,n&&this.close())}};function gw(r){let{app:e}=r,t=()=>r.getMirrorProfile()!==null;r.addCommand({id:"mdbase-open",name:"Open workspace",callback:()=>void r.openWorkspace()}),r.addCommand({id:"mdbase-initialize-collection",name:"Initialize collection",checkCallback:n=>t()||e.vault.getAbstractFileByPath("mdbase.yaml")?!1:(n||WR(r),!0)}),r.addCommand({id:"mdbase-create-type",name:"Create type definition",callback:()=>void r.openWorkspace("types").then(n=>n.createNewType())}),r.addCommand({id:"mdbase-edit-type",name:"Edit type definition",callback:()=>void GR(r)}),r.addCommand({id:"mdbase-create-note-from-type",name:"Create note from type",callback:()=>void Fp(r)}),r.addCommand({id:"mdbase-validate-current-note",name:"Validate current note",checkCallback:n=>{let i=e.workspace.getActiveFile();return!(i instanceof tt.TFile)||i.extension!=="md"?!1:(n||JR(r,i),!0)}}),r.addCommand({id:"mdbase-validate-collection",name:"Validate collection",callback:()=>void r.runCollectionValidation(!0)}),r.addCommand({id:"mdbase-sync-now",name:"Sync now",checkCallback:n=>t()?(n||KR(r),!0):!1}),r.addCommand({id:"mdbase-cancel-sync",name:"Cancel current sync",checkCallback:n=>r.sync.isSyncing()?(n||r.sync.cancel(),!0):!1}),r.addCommand({id:"mdbase-resolve-conflicts",name:"Resolve sync conflicts",checkCallback:n=>!t()||!r.sync.state.status?.conflicts.length?!1:(n||r.openWorkspace("sync").then(i=>i.focusSyncSection("conflicts")),!0)}),r.addCommand({id:"mdbase-reconnect",name:"Reconnect collection",checkCallback:n=>{let i=r.sync.state.problem;return!t()||!i||i.action!=="reauthorize"?!1:(n||r.openWorkspace("sync").then(s=>s.reconnectCollection()),!0)}}),r.addCommand({id:"mdbase-copy-sync-diagnostics",name:"Copy sync diagnostics",checkCallback:n=>t()?(n||r.copySyncDiagnostics(),!0):!1}),r.addCommand({id:"mdbase-note-sync-history",name:"Show sync history for current note",checkCallback:n=>{let i=e.workspace.getActiveFile();return!i||!t()?!1:(n||r.openNoteSyncHistory(i.path),!0)}}),r.registerEvent(e.workspace.on("file-menu",(n,i)=>{!(i instanceof tt.TFile)||!t()||n.addItem(s=>s.setTitle("Sync history").setIcon("history").onClick(()=>r.openNoteSyncHistory(i.path)))}))}async function KR(r){let e=await r.sync.syncNow(),{message:t,problem:n}=r.sync.state;if(e==="needs_review"){let i=r.sync.safety()?.reasons??[];new tt.Notice(`Review before syncing: ${i.join(", ").toLowerCase()||"changes need attention"}.`),await r.openWorkspace("sync")}else e==="busy"?new tt.Notice("A sync is already running."):e==="paused"?new tt.Notice("Sync is paused."):e==="failed"?new tt.Notice(n?.message??(t||"Sync failed.")):t&&new tt.Notice(t)}async function WR(r){r.connectSync.assertLocalAuthorityWritable();let{created:e}=await $o(r.app.vault,{seedNoteType:!1});r.invalidateSchemaCache(),new tt.Notice(e.length?`Initialized mdbase collection: ${e.join(", ")}`:"mdbase collection already initialized.")}async function GR(r){let e=await r.requireConfigAndTypes();if(!e)return;if(e.types.size===0){new tt.Notice("No type definitions found.");return}let t=r.app.workspace.getActiveFile(),n=[];if(t instanceof tt.TFile&&t.extension==="md"){let o=[...e.types.values()].find(a=>a.filePath===t.path);if(o)n=[o];else{let a=Me(await r.app.vault.cachedRead(t));a.error||(n=Ke(t.path,a.frontmatter,e.config,e.types).flatMap(c=>e.types.get(c)??[]))}}let i=n.length===1?n[0]:await Lp(r.app,n.length?n:[...e.types.values()]);if(!i)return;await(await r.openWorkspace("types")).editType(i.filePath)}async function JR(r,e){let t=await r.validateFileAndStore(e,"manual");if(t.length===0){new tt.Notice("No issues in current note.");return}new tt.Notice(`Found ${t.length} issue${t.length===1?"":"s"} in current note.`),(await r.openWorkspace("issues")).showIssuesForPath(e.path)}async function Fp(r,e){r.connectSync.assertLocalAuthorityWritable();let t=await r.requireConfigAndTypes();if(!t)return;if(t.types.size===0){new tt.Notice("No type definitions found.");return}if(r.getMirrorProfile()?.mode==="read_only")throw new Error("This mirror has read-only access.");let n=e?t.types.get(e):await Lp(r.app,Array.from(t.types.values()));n&&new $c(r.app,n,t.config,t.types,async(i,s)=>{if(r.connectSync.assertLocalAuthorityWritable(),r.getMirrorProfile()?.mode==="read_only")throw new Error("This mirror has read-only access.");let{createNoteFromType:o}=await Promise.resolve().then(()=>(qt(),mw)),a=await o(r.app.vault,i,s);await r.app.workspace.getLeaf(!0).openFile(a),await r.validateFileAndStore(a,"manual")}).open()}var bw=require("obsidian");qt();function jp(r,e){let t=Me(r);if(t.error)throw new Error(`Invalid frontmatter: ${t.error}`);return YR(t.frontmatter,e)?{content:`--- ${(0,bw.stringifyYaml)(t.frontmatter).trimEnd()} --- -${t.body}`,changed:!0}:{content:r,changed:!1}}function vw(r){if(!r.field)return null;if(["unknown_field","missing_required"].includes(r.code))return/[.[\]]/.test(r.field)?null:[r.field];if(!["schema_additional_properties","schema_required"].includes(r.code))return null;let e=r.details?.instance_path,t=r.details?.property;return typeof e!="string"||typeof t!="string"?null:[...e===""?[]:e.slice(1).split("/").map(n=>n.replace(/~1/g,"/").replace(/~0/g,"~")),t]}function ww(r){return vw(r)?["unknown_field","schema_additional_properties"].includes(r.code)?"Remove field":"Add placeholder":null}function JR(r,e){let t=vw(e);if(!t?.length)return!1;let n=r;for(let a of t.slice(0,-1)){if(!n||typeof n!="object"||!Object.prototype.hasOwnProperty.call(n,a))return!1;n=n[a]}if(!n||typeof n!="object"||Array.isArray(n))return!1;let i=n,s=t[t.length-1],o=Object.prototype.hasOwnProperty.call(i,s);if(["unknown_field","schema_additional_properties"].includes(e.code)){if(!o)return!1;delete i[s]}else{if(o)return!1;Object.defineProperty(i,s,{value:"TODO",enumerable:!0,configurable:!0,writable:!0})}return!0}var L=require("obsidian");var O=class extends Error{code;details;constructor(e,t,n){super(t),this.code=e,this.details=n,this.name="InteropError"}toPortableError(e){return{code:this.code,message:this.message,...this.details===void 0?{}:{details:this.details},...e===void 0?{}:{retryable:e}}}},xo=class extends Error{status;error;constructor(e,t){super(t.message),this.status=e,this.error=t,this.name="ActionHandlerError"}};var _w=Kn(Xf(),1),Sw=Kn(ap(),1);var Bp={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 YR=Sw.default;function $w(){return Object.fromEntries(Object.entries(Bp).map(([r,e])=>[r,structuredClone(e)]))}function Up(){let r=new _w.Ajv2020({allErrors:!0,strict:!1,validateFormats:!0});YR(r);let e=$w();r.addSchema(e.profile);for(let[t,n]of Object.entries(e))t!=="profile"&&r.addSchema(n);return r}function Br(r,e){let t=String(Bp[e].$id),n=r.getSchema(t);if(!n)throw new Error(`Canonical interoperability schema is unavailable: ${e}`);return n}function bn(r){return(r??[]).map(e=>`${e.instancePath||"/"} ${e.message??e.keyword}`).join("; ")}function _r(r,e){if(!("value"in r))throw new O("contract_digest_conflict",`${e} must be resolved to an inline JSON Schema before runtime registration.`);return structuredClone(r.value)}function xw(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=_r(r.record_schema,"record_schema"),r.binding_schema&&(e.binding_schema=_r(r.binding_schema,"binding_schema"));break;case"event":e.data_schema=_r(r.data_schema,"data_schema"),r.source_schema&&(e.source_schema=_r(r.source_schema,"source_schema"));break;case"action":e.input_schema=_r(r.input_schema,"input_schema"),r.output_schema&&(e.output_schema=_r(r.output_schema,"output_schema")),r.error_schema&&(e.error_schema=_r(r.error_schema,"error_schema")),r.provider_schema&&(e.provider_schema=_r(r.provider_schema,"provider_schema")),r.behavior&&(e.behavior=structuredClone(r.behavior));break}return e}async function kc(r){return is(xw(r))}async function is(r){return`sha256:${await XR(Vp(r))}`}function Ew(r,e){return{data:ns(r,e.data_schema,`${e.id} data_schema`),...e.source_schema?{source:ns(r,e.source_schema,`${e.id} source_schema`)}:{}}}function Aw(r,e){return{input:ns(r,e.input_schema,`${e.id} input_schema`),...e.output_schema?{output:ns(r,e.output_schema,`${e.id} output_schema`)}:{},...e.error_schema?{error:ns(r,e.error_schema,`${e.id} error_schema`)}:{},...e.provider_schema?{provider:ns(r,e.provider_schema,`${e.id} provider_schema`)}:{}}}function Pc(r,e,t,n){if(!(!r||r(e)))throw new O(t,`${n} failed JSON Schema validation: ${bn(r.errors)}`)}function ns(r,e,t){try{return r.compile(_r(e,t))}catch(n){throw new O("contract_digest_conflict",`${t} could not be compiled: ${n instanceof Error?n.message:String(n)}`)}}function Vp(r){return r===null||typeof r!="object"?JSON.stringify(r):Array.isArray(r)?`[${r.map(Vp).join(",")}]`:`{${Object.entries(r).filter(([,t])=>t!==void 0).sort(([t],[n])=>tn?1:0).map(([t,n])=>`${JSON.stringify(t)}:${Vp(n)}`).join(",")}}`}async function XR(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 Vr=Kn(g0(),1);var dh={delivery:["ephemeral"],ordering:["none"],cancellation:!0,deadlines:!0,provider_discovery:!0,request_deduplication:!0,cross_process_identity:!1},sN=new Set(["specversion","id","source","type","time","subject","datacontenttype","dataschema","data","mdbaseprofile","mdbasecontractversion","mdbasecontractdigest","mdbaseapplication","mdbaseimplementation","mdbaseimplementationversion","mdbaseinstanceid","correlationid","causationid"]),Mo=class{options;profileVersion="0.1";transport;ajv=Up();contractValidator=Br(this.ajv,"contract");eventValidator=Br(this.ajv,"event");actionRequestValidator=Br(this.ajv,"actionRequest");actionInvocationValidator=Br(this.ajv,"actionInvocation");actionOutcomeValidator=Br(this.ajv,"actionOutcome");eventSourceDeclarationValidator=Br(this.ajv,"eventSourceDeclaration");actionProviderDeclarationValidator=Br(this.ajv,"actionProviderDeclaration");contracts=new Map;clients=new Map;eventSources=new Map;actionProviders=new Map;subscriptions=new Map;activeActions=new Map;completedActions=new Map;admissionLocks=new Map;recentEvents=new Map;authorize;now;idFactory;recentEventLimit;completedRequestLimit;nextSequence=0;disposed=!1;constructor(e={}){this.options=e,this.authorize=e.authorize??(()=>!1),this.now=e.now??(()=>new Date),this.idFactory=e.idFactory??(t=>{this.nextSequence+=1;let n=typeof globalThis.crypto?.randomUUID=="function"?globalThis.crypto.randomUUID():`${this.now().getTime().toString(36)}-${this.nextSequence.toString(36)}`;return`${t}_${n}`}),this.recentEventLimit=Math.max(1,e.recentEventLimit??1e3),this.completedRequestLimit=Math.max(1,e.completedRequestLimit??1e3),this.transport={...dh,...structuredClone(e.transport??{}),delivery:[...e.transport?.delivery??dh.delivery],ordering:[...e.transport?.ordering??dh.ordering]}}connect(e){this.assertActive(),oN(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:i=>this.registerEventSource(t,i),publishEvent:i=>this.publishEvent(t,i),subscribeEvents:(i,s)=>this.subscribeEvents(t,i,s),registerActionProvider:i=>this.registerActionProvider(t,i),invokeAction:i=>this.invokeAction(t,i),cancelAction:(i,s)=>this.cancelAction(t,i,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){let n=this.requireClient(e);if(t.contracts.length===0)throw new O("request_rejected","An event-source declaration must include a contract.");let i=`${e}:${t.declaration_id}`;if(this.eventSources.has(i))throw new O("request_rejected",`Event-source declaration ${t.declaration_id} is already registered.`);let s=new Map;for(let l of t.contracts){let u=await this.prepareEventContract(l.contract),d=b0(l.requirement,u.reference);if(v0(d,u.reference),await this.assertAuthorized({operation:"register_event_source",principal:n.identity,contract:u.reference}),u.sourceValidator&&!u.sourceValidator(l.binding??{}))throw new O("request_rejected",`${u.reference.id} source binding is invalid: ${bn(u.sourceValidator.errors)}`);let f=Bc(u.reference);if(s.has(f))throw new O("contract_digest_conflict",`Event contract ${f} is repeated by one declaration.`);s.set(f,{contract:u,requirement:d,...l.binding===void 0?{}:{binding:structuredClone(l.binding)},...l.ordering===void 0?{}:{ordering:[...l.ordering]}})}let o={kind:"mdbase.event-source",profile_version:"0.1",declaration_id:t.declaration_id,source:structuredClone(n.identity),contracts:[...s.values()].map(({contract:l,requirement:u,binding:d,ordering:f})=>({requirement:structuredClone(u),resolved:structuredClone(l.reference),...d===void 0?{}:{binding:d},...f===void 0?{}:{ordering:f}}))},a={...o,declaration_digest:await is(o)};wn(this.eventSourceDeclarationValidator,a,"request_rejected","Event-source declaration"),this.commitContracts([...s.values()].map(({contract:l})=>l)),this.eventSources.set(i,{id:i,clientId:e,declaration:structuredClone(a),contracts:new Map([...s.entries()].map(([l,u])=>[l,{contract:u.contract,...u.binding===void 0?{}:{binding:u.binding}}]))}),n.sources.add(i);let c=!0;return{declaration:structuredClone(a),dispose:()=>{c&&(c=!1,this.removeEventSource(i))}}}async publishEvent(e,t){let n=this.requireClient(e),i=Bc(t.contract),s=[...n.sources].map(h=>this.eventSources.get(h)).find(h=>h?.contracts.has(i));if(!s)throw new O("unknown_contract",`This client has not registered event contract ${t.contract.id} ${t.contract.version}.`);let o=s.contracts.get(i)?.contract;if(!o)throw new O("unknown_contract",`Event contract ${i} is unavailable.`);if(t.contract.digest&&t.contract.digest!==o.reference.digest)throw new O("contract_digest_conflict",`Event contract ${i} has a different digest.`);await this.assertAuthorized({operation:"publish_event",principal:n.identity,contract:o.reference,...t.subject===void 0?{}:{subject:t.subject}}),uh(t.data,"invalid_event_data",`Event ${o.reference.id} data`),Pc(o.dataValidator,t.data,"invalid_event_data",`Event ${o.reference.id} data`);let a=t.extensions??{};for(let h of Object.keys(a))if(sN.has(h))throw new O("request_rejected",`Event extension ${h} is reserved.`);let c={...structuredClone(a),specversion:"1.0",id:t.id??this.idFactory("evt"),source:aN(n.identity),type:o.reference.id,time:t.time??this.now().toISOString(),...t.subject===void 0?{}:{subject:t.subject},datacontenttype:"application/json",dataschema:S0(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}};wn(this.eventValidator,c,"invalid_event_data","Event envelope"),fh(this.transport,c),cN(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 O("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)),_0(this.recentEvents,this.recentEventLimit);let d=[...this.subscriptions.values()].filter(({subscription:h})=>Uc(h.contract,o.reference)),f=await Promise.allSettled(d.map(async h=>await this.isAuthorized({operation:"subscribe_event",principal:h.principal,contract:o.reference,...c.subject===void 0?{}:{subject:c.subject}})?(await h.handler(structuredClone(c)),!0):!1)),p=0;for(let h of f)h.status==="fulfilled"&&h.value?p+=1:h.status==="rejected"&&this.report({severity:"error",code:"event_consumer_failed",message:`An event consumer failed while handling ${c.type}.`,contract:o.reference,cause:h.reason});return{event:structuredClone(c),deliveries:p,duplicate:!1}}async subscribeEvents(e,t,n){let i=this.requireClient(e);ph(t.contract),uN(this.transport,t.require_transport),await this.assertAuthorized({operation:"subscribe_event",principal:i.identity,contract:t.contract});let s=this.idFactory("subscription");this.subscriptions.set(s,{id:s,clientId:e,principal:structuredClone(i.identity),subscription:structuredClone(t),handler:n}),i.subscriptions.add(s);let o=!0;return{dispose:()=>{o&&(o=!1,this.removeSubscription(s))}}}async registerActionProvider(e,t){let n=this.requireClient(e);if(t.handlers.length===0)throw new O("request_rejected","An action-provider declaration must include a handler.");let i=`${e}:${t.declaration_id}`;if(this.actionProviders.has(i))throw new O("request_rejected",`Action-provider declaration ${t.declaration_id} is already registered.`);let s=[],o=new Set;for(let d of t.handlers){if(o.has(d.handler_id))throw new O("request_rejected",`Handler ${d.handler_id} is repeated.`);o.add(d.handler_id);let f=await this.prepareActionContract(d.contract),p=b0(d.requirement,f.reference);if(v0(p,f.reference),await this.assertAuthorized({operation:"register_action_provider",principal:n.identity,contract:f.reference,provider:n.identity}),f.providerValidator&&!f.providerValidator(d.binding??{}))throw new O("request_rejected",`${f.reference.id} provider binding is invalid: ${bn(f.providerValidator.errors)}`);let h=d.contract.behavior?.idempotency??"none";if(d.idempotency?.mode==="request"&&h==="none")throw new O("request_rejected",`${f.reference.id} does not permit request deduplication.`);if(h==="required"&&d.idempotency?.mode!=="request")throw new O("request_rejected",`${f.reference.id} requires a provider with request deduplication.`);let m=d.contract.behavior?.cancellation??"none";if(d.cancellation==="cooperative"&&m!=="cooperative")throw new O("request_rejected",`${f.reference.id} does not declare cooperative cancellation.`);s.push({contract:f,declaration:{handler_id:d.handler_id,requirement:p,resolved:structuredClone(f.reference),...d.binding===void 0?{}:{binding:structuredClone(d.binding)},...d.idempotency===void 0?{}:{idempotency:structuredClone(d.idempotency)},...d.cancellation===void 0?{}:{cancellation:d.cancellation},...d.max_concurrency===void 0?{}:{max_concurrency:d.max_concurrency}},handler:d.handler})}let a={kind:"mdbase.action-provider",profile_version:"0.1",declaration_id:t.declaration_id,provider:structuredClone(n.identity),handlers:s.map(({declaration:d})=>structuredClone(d))},c={...a,declaration_digest:await is(a)};wn(this.actionProviderDeclarationValidator,c,"request_rejected","Action-provider declaration"),this.commitContracts(s.map(({contract:d})=>d));let l=s.map(({contract:d,declaration:f,handler:p})=>({registrationId:i,clientId:e,declaration:structuredClone(c),handlerDeclaration:structuredClone(f),contract:d,handler:p,active:0}));this.actionProviders.set(i,{id:i,clientId:e,declaration:structuredClone(c),handlers:l}),n.providers.add(i);let u=!0;return{declaration:structuredClone(c),dispose:()=>{u&&(u=!1,this.removeActionProvider(i))}}}async invokeAction(e,t){let n=this.requireClient(e);ph(t.contract);let i=t.request_id??this.idFactory("req");this.cleanCompletedActions(),uh(t.input,"invalid_action_input",`Action ${t.contract.id} input`);let s={kind:"mdbase.action.request",profile_version:"0.1",request_id:i,contract:structuredClone(t.contract),caller:structuredClone(n.identity),created_at:t.created_at??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)};wn(this.actionRequestValidator,s,"request_rejected","Action request"),fh(this.transport,s);let o=await this.acquireAdmission(i);try{let a=await is(lN(s)),c=this.activeActions.get(i);if(c){if(w0(e,i,a,c),c.handler.handlerDeclaration.idempotency?.mode!=="request")throw new O("request_rejected",`Action request ${i} is already active without deduplication.`);return structuredClone(await c.promise)}let l=this.completedActions.get(i);if(l){if(w0(e,i,a,l),!l.reusable)throw new O("request_rejected",`Action request ${i} was already completed without deduplication.`);return structuredClone(l.outcome)}if(s.deadline&&new Date(s.deadline).getTime()<=this.now().getTime())throw new O("deadline_exceeded",`Action request ${i} passed its deadline before admission.`);if(s.deadline&&!this.transport.deadlines)throw new O("unsupported_transport_capability","The active transport cannot enforce action deadlines.");let u=this.resolveActionCandidates(s.contract,s.requested_provider);u.length===0&&this.throwResolutionFailure(s.contract,s.requested_provider);let d=[];for(let E of u)await this.isAuthorized({operation:"invoke_action",principal:n.identity,contract:E.contract.reference,provider:E.declaration.provider,...s.subject===void 0?{}:{subject:s.subject}})&&d.push(E);if(d.length===0)throw new O("unauthorized",`No authorized provider can execute ${s.contract.id}.`);if(d.length>1)throw new O("ambiguous_provider",`Action ${s.contract.id} has ${d.length} eligible providers; select one explicitly.`);let f=d[0];if(f.handlerDeclaration.max_concurrency!==void 0&&f.active>=f.handlerDeclaration.max_concurrency)throw new O("request_rejected",`Provider ${f.declaration.provider.implementation} is at capacity.`);if((f.contract.artifact.behavior?.idempotency??"none")==="required"&&!s.idempotency_key)throw new O("request_rejected",`${f.contract.reference.id} requires an idempotency key.`);Pc(f.contract.inputValidator,s.input,"invalid_action_input",`Action ${f.contract.reference.id} input`);let h={operation:"invoke_action",principal:n.identity,contract:f.contract.reference,provider:f.declaration.provider,...s.subject===void 0?{}:{subject:s.subject}},m=await this.options.authorizationContext?.(h),y={kind:"mdbase.action.invocation",profile_version:"0.1",invocation_id:this.idFactory("inv"),attempt_id:this.idFactory("attempt"),request_id:i,contract:structuredClone(f.contract.reference),caller:structuredClone(n.identity),provider:structuredClone(f.declaration.provider),provider_declaration_digest:f.declaration.declaration_digest,handler_id:f.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},...m===void 0?{}:{authorization_context:m},input:structuredClone(s.input)};wn(this.actionInvocationValidator,y,"request_rejected","Action invocation"),await this.options.onInvocation?.(structuredClone(y));let g=new AbortController,b;if(y.deadline){let E=Math.max(0,new Date(y.deadline).getTime()-this.now().getTime());b=setTimeout(()=>g.abort(new O("deadline_exceeded",`Action request ${i} exceeded its deadline.`)),E)}f.active+=1;let v=this.executeAction(f,y,g).finally(()=>{b!==void 0&&clearTimeout(b),f.active=Math.max(0,f.active-1),this.activeActions.delete(i)});this.activeActions.set(i,{clientId:e,requestId:i,requestDigest:a,handler:f,invocation:y,controller:g,promise:v}),o();let S=await v,_=f.handlerDeclaration.idempotency?.retention_seconds??300;return this.completedActions.set(i,{clientId:e,requestDigest:a,outcome:structuredClone(S),reusable:f.handlerDeclaration.idempotency?.mode==="request",expiresAt:this.now().getTime()+_*1e3}),_0(this.completedActions,this.completedRequestLimit),structuredClone(S)}finally{o()}}async executeAction(e,t,n){try{let i=await e.handler(structuredClone(t.input),{invocation:structuredClone(t),signal:n.signal});if(n.signal.aborted){let o=n.signal.reason;return o instanceof O&&o.code==="deadline_exceeded"?this.failureOutcome(t,"failed",o.toPortableError()):this.failureOutcome(t,"cancelled",{code:"cancelled",message:`Action request ${t.request_id} was cancelled.`})}uh(i,"invalid_action_output",`Action ${e.contract.reference.id} output`),Pc(e.contract.outputValidator,i,"invalid_action_output",`Action ${e.contract.reference.id} output`);let s={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 wn(this.actionOutcomeValidator,s,"invalid_action_output","Action outcome"),fh(this.transport,s),s}catch(i){if(i instanceof xo)return e.contract.errorValidator&&!e.contract.errorValidator(i.error.details??{})?this.failureOutcome(t,"failed",{code:"handler_failure",message:`Provider returned invalid declared error details: ${bn(e.contract.errorValidator.errors)}`}):this.failureOutcome(t,i.status,i.error);if(i instanceof O)return this.failureOutcome(t,i.code==="cancelled"?"cancelled":i.code==="outcome_indeterminate"?"outcome_indeterminate":"failed",i.toPortableError());if(n.signal.aborted||fN(i)){let s=n.signal.reason;return s instanceof O&&s.code==="deadline_exceeded"?this.failureOutcome(t,"failed",s.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 i={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 wn(this.actionOutcomeValidator,i,"invalid_action_output","Action outcome"),i}async cancelAction(e,t,n){let i=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 O("unauthorized",`Action request ${t} belongs to another caller.`);return a?structuredClone(a.outcome):null}if(o.clientId!==e)throw new O("unauthorized",`Action request ${t} belongs to another caller.`);if(await this.assertAuthorized({operation:"cancel_action",principal:i.identity,contract:o.invocation.contract,provider:o.invocation.provider,...o.invocation.subject===void 0?{}:{subject:o.invocation.subject}}),!this.transport.cancellation)throw new O("unsupported_transport_capability","The active transport cannot deliver cancellation.");if(o.handler.handlerDeclaration.cancellation!=="cooperative")throw new O("cancellation_unsupported",`Provider ${o.invocation.provider.implementation} does not support cancellation.`);return o.controller.abort(new O("cancelled",n?.trim()||`Action request ${t} was cancelled.`)),structuredClone(await o.promise)}resolveActionCandidates(e,t){let n=[...this.actionProviders.values()].flatMap(({handlers:s})=>s).filter(({contract:s,declaration:o})=>Uc(e,s.reference)&&dN(t,o.provider)),i=(0,Vr.maxSatisfying)([...new Set(n.map(({contract:s})=>s.reference.version))],e.version,{includePrerelease:!0});return i?n.filter(({contract:s})=>s.reference.version===i).sort((s,o)=>s.declaration.provider.application.localeCompare(o.declaration.provider.application)||s.declaration.provider.implementation.localeCompare(o.declaration.provider.implementation)||(s.declaration.provider.instance_id??"").localeCompare(o.declaration.provider.instance_id??"")||s.handlerDeclaration.handler_id.localeCompare(o.handlerDeclaration.handler_id)):[]}throwResolutionFailure(e,t){let n=[...this.contracts.values()].filter(i=>i.artifact.contract_type==="action"&&i.reference.id===e.id);throw n.length===0?new O("unknown_contract",`Action contract ${e.id} is unknown.`):n.some(({reference:i})=>Uc(e,i))?t?new O("requested_provider_unavailable",`The requested provider is unavailable for ${e.id}.`):new O("no_provider",`No provider is registered for ${e.id}.`):new O("unsupported_contract_version",`No ${e.id} artifact satisfies ${e.version}.`)}async prepareEventContract(e){if(this.assertContractArtifact(e),e.contract_type!=="event")throw new O("unknown_contract",`${e.id} is not an event contract.`);let t={id:e.id,version:e.version,digest:await kc(e)};this.assertNoContractConflict(t);let n=Ew(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 O("unknown_contract",`${e.id} is not an action contract.`);let t={id:e.id,version:e.version,digest:await kc(e)};this.assertNoContractConflict(t);let n=Aw(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(wn(this.contractValidator,e,"contract_digest_conflict",`Contract ${e.id||""}`),!(0,Vr.valid)(e.version))throw new O("unsupported_contract_version",`${e.id} version must be exact SemVer.`)}assertNoContractConflict(e){let t=this.contracts.get(Bc(e));if(t&&t.reference.digest!==e.digest)throw new O("contract_digest_conflict",`Contract ${e.id} ${e.version} conflicts with the registered artifact.`)}commitContracts(e){let t=new Map;for(let n of e){let i=Bc(n.reference),s=t.get(i)??this.contracts.get(i);if(s&&s.reference.digest!==n.reference.digest)throw new O("contract_digest_conflict",`Contract ${n.reference.id} ${n.reference.version} conflicts within the registration.`);t.set(i,n)}for(let[n,i]of t)this.contracts.has(n)||this.contracts.set(n,i)}async disposeClient(e,t=!1){let n=this.clients.get(e);if(!(!n||n.disposed)){n.disposed=!0;for(let i of[...n.subscriptions])this.removeSubscription(i);for(let i of[...n.sources])this.removeEventSource(i);for(let i of[...n.providers])this.removeActionProvider(i);for(let i of[...this.activeActions.values()])i.clientId===e&&i.handler.handlerDeclaration.cancellation==="cooperative"&&i.controller.abort(new O("cancelled","The caller unloaded.")),i.handler.clientId===e&&i.handler.handlerDeclaration.cancellation==="cooperative"&&i.controller.abort(new O("cancelled","The provider unloaded."));this.clients.delete(e),t||this.assertActive()}}removeEventSource(e){let t=this.eventSources.get(e);t&&(this.eventSources.delete(e),this.clients.get(t.clientId)?.sources.delete(e))}removeActionProvider(e){let t=this.actionProviders.get(e);if(t){this.actionProviders.delete(e),this.clients.get(t.clientId)?.providers.delete(e);for(let n of this.activeActions.values())n.handler.registrationId===e&&n.handler.handlerDeclaration.cancellation==="cooperative"&&n.controller.abort(new O("cancelled","The provider unloaded."))}}removeSubscription(e){let t=this.subscriptions.get(e);t&&(this.subscriptions.delete(e),this.clients.get(t.clientId)?.subscriptions.delete(e))}requireClient(e){this.assertActive();let t=this.clients.get(e);if(!t||t.disposed)throw new O("transport_unavailable","Interop client is disposed.");return t}assertActive(){if(this.disposed)throw new O("transport_unavailable","Interop bridge is disposed.")}async assertAuthorized(e){if(!await this.isAuthorized(e))throw new O("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){let t=this.admissionLocks.get(e)??Promise.resolve(),n,i=new Promise(a=>{n=a}),s=t.then(()=>i);this.admissionLocks.set(e,s),await t;let o=!1;return()=>{o||(o=!0,n(),this.admissionLocks.get(e)===s&&this.admissionLocks.delete(e))}}report(e){this.options.onDiagnostic?.(structuredClone(e))}};function wn(r,e,t,n){if(!r(e))throw new O(t,`${n} is invalid: ${bn(r.errors)}`)}function oN(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 O("request_rejected",`Implementation identity ${e} is invalid.`);if(!(0,Vr.valid)(r.version))throw new O("request_rejected","Implementation identity version must be exact SemVer.")}function ph(r){if(!/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)+$/u.test(r.id))throw new O("unknown_contract",`Contract ID ${r.id} is invalid.`);if(!(0,Vr.validRange)(r.version,{includePrerelease:!0}))throw new O("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 O("contract_digest_conflict","Contract digest is invalid.")}function b0(r,e){let t=r??{id:e.id,version:e.version,digest:e.digest};return ph(t),structuredClone(t)}function v0(r,e){if(!Uc(r,e))throw new O("unsupported_contract_version",`${e.id} ${e.version} does not satisfy its implementation requirement.`)}function Uc(r,e){return r.id===e.id&&(0,Vr.satisfies)(e.version,r.version,{includePrerelease:!0})&&(!r.digest||r.digest===e.digest)}function Bc(r){return`${r.id}@${r.version}`}function S0(r){return`urn:mdbase:contract:${r.id}:${r.version}:${r.digest}`}function aN(r){return`urn:mdbase:app:${[r.application,r.implementation,...r.instance_id?[r.instance_id]:[]].map(encodeURIComponent).join(":")}`}function cN(r,e){if(r.type!==e.id||r.mdbasecontractversion!==e.version||r.mdbasecontractdigest!==e.digest||r.dataschema!==S0(e))throw new O("contract_digest_conflict","Event contract evidence is inconsistent.")}function lN(r){let{created_at:e,...t}=r;return t}function w0(r,e,t,n){if(n.clientId!==r)throw new O("unauthorized",`Action request ${e} belongs to another caller.`);if(n.requestDigest!==t)throw new O("request_rejected",`Action request ${e} was reused with different content.`)}function uh(r,e,t){let n=new Set,i=(s,o)=>{if(!(s===null||typeof s=="boolean"||typeof s=="string")){if(typeof s=="number"){if(Number.isFinite(s))return;throw new O(e,`${t}${o} must be a finite JSON number.`)}if(typeof s!="object")throw new O(e,`${t}${o} is not a JSON value.`);if(n.has(s))throw new O(e,`${t}${o} contains a cycle.`);if(n.add(s),Array.isArray(s))s.forEach((a,c)=>i(a,`${o}/${c}`));else{let a=Object.getPrototypeOf(s);if(a!==Object.prototype&&a!==null)throw new O(e,`${t}${o} must be a plain JSON object.`);for(let[c,l]of Object.entries(s))i(l,`${o}/${c}`)}n.delete(s)}};i(r,"")}function fh(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 O("unsupported_transport_capability",`The portable envelope is ${n} bytes; the active transport allows ${r.max_payload_bytes}.`)}function dN(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 uN(r,e){if(e){if(e.delivery?.some(t=>!r.delivery.includes(t)))throw new O("unsupported_transport_capability","The active transport lacks a required delivery capability.");if(e.ordering?.some(t=>!r.ordering.includes(t)))throw new O("unsupported_transport_capability","The active transport lacks a required ordering capability.");for(let t of["cancellation","deadlines","provider_discovery","request_deduplication","cross_process_identity"])if(e[t]===!0&&r[t]!==!0)throw new O("unsupported_transport_capability",`The active transport lacks ${t}.`);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 fN(r){return r instanceof Error&&r.name==="AbortError"}var Vc=class{constructor(e,t){this.app=e;this.profileVersion="0.1";this.bridge=new Mo({authorize:()=>t(),transport:{delivery:["ephemeral"],ordering:["none"],cancellation:!0,deadlines:!0,provider_discovery:!0,request_deduplication:!0,cross_process_identity:!1},onDiagnostic:n=>{(n.severity==="error"?console.error:console.warn)(`[mdbase/interop] ${n.code}: ${n.message}`,n.cause??"")}}),this.transport=this.bridge.describe().transport}connect(e){let t=e.manifest?.id,n=e.manifest?.version;if(!t||!n)throw new Error("Only a loaded Obsidian plugin with manifest identity can connect to mdbase interop.");let i=this.app.plugins;if(!i||i.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()}};qt();var z=require("obsidian"),nx=Kn(bp(),1);var Hc=Symbol.for("yaml.alias"),zc=Symbol.for("yaml.document"),Zt=Symbol.for("yaml.map"),hh=Symbol.for("yaml.pair"),At=Symbol.for("yaml.scalar"),Hr=Symbol.for("yaml.seq"),nt=Symbol.for("yaml.node.type"),er=r=>!!r&&typeof r=="object"&&r[nt]===Hc,$r=r=>!!r&&typeof r=="object"&&r[nt]===zc,tr=r=>!!r&&typeof r=="object"&&r[nt]===Zt,te=r=>!!r&&typeof r=="object"&&r[nt]===hh,G=r=>!!r&&typeof r=="object"&&r[nt]===At,rr=r=>!!r&&typeof r=="object"&&r[nt]===Hr;function ae(r){if(r&&typeof r=="object")switch(r[nt]){case Zt:case Hr:return!0}return!1}function ne(r){if(r&&typeof r=="object")switch(r[nt]){case Hc:case Zt:case At:case Hr:return!0}return!1}var Kc=r=>(G(r)||ae(r))&&!!r.anchor;var gt=Symbol("break visit"),$0=Symbol("skip children"),xr=Symbol("remove node");function Er(r,e){let t=x0(e);$r(r)?as(null,r.contents,t,Object.freeze([r]))===xr&&(r.contents=null):as(null,r,t,Object.freeze([]))}Er.BREAK=gt;Er.SKIP=$0;Er.REMOVE=xr;function as(r,e,t,n){let i=E0(r,e,t,n);if(ne(i)||te(i))return A0(r,n,i),as(r,i,t,n);if(typeof i!="symbol"){if(ae(e)){n=Object.freeze(n.concat(e));for(let s=0;sr.replace(/[!,[\]{}]/g,e=>pN[e]),Ar=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]+/),i=n.shift();switch(i){case"%TAG":{if(n.length!==2&&(t(0,"%TAG directive should contain exactly two parts"),n.length<2))return!1;let[s,o]=n;return this.tags[s]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,n.length!==1)return t(0,"%YAML directive should contain exactly one part"),!1;let[s]=n;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 ${i}`,!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,i]=e.match(/^(.*!)([^!]*)$/s);i||t(`The ${e} tag has no suffix`);let s=this.tags[n];if(s)try{return s+decodeURIComponent(i)}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+hN(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),i;if(e&&n.length>0&&ne(e.contents)){let s={};Er(e.contents,(o,a)=>{ne(a)&&a.tag&&(s[a.tag]=!0)}),i=Object.keys(s)}else i=[];for(let[s,o]of n)s==="!!"&&o==="tag:yaml.org,2002:"||(!e||i.some(a=>a.startsWith(o)))&&t.push(`%TAG ${s} ${o}`);return t.join(` -`)}};Ar.defaultYaml={explicit:!1,version:"1.2"};Ar.defaultTags={"!!":"tag:yaml.org,2002:"};function Gc(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 mh(r){let e=new Set;return Er(r,{Value(t,n){n.anchor&&e.add(n.anchor)}}),e}function yh(r,e){for(let t=1;;++t){let n=`${r}${t}`;if(!e.has(n))return n}}function k0(r,e){let t=[],n=new Map,i=null;return{onAnchor:s=>{t.push(s),i??(i=mh(r));let o=yh(e,i);return i.add(o),o},setAnchors:()=>{for(let s of t){let o=n.get(s);if(typeof o=="object"&&o.anchor&&(G(o.node)||ae(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:n}}function _n(r,e,t,n){if(n&&typeof n=="object")if(Array.isArray(n))for(let i=0,s=n.length;iRe(n,String(i),t));if(r&&typeof r.toJSON=="function"){if(!t||!Kc(r))return r.toJSON(e,t);let n={aliasCount:0,count:1,res:void 0};t.anchors.set(r,n),t.onCreate=s=>{n.res=s,delete t.onCreate};let i=r.toJSON(e,t);return t.onCreate&&t.onCreate(i),i}return typeof r=="bigint"&&!t?.keep?Number(r):r}var Sn=class{constructor(e){Object.defineProperty(this,nt,{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:i,reviver:s}={}){if(!$r(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=Re(this,"",o);if(typeof i=="function")for(let{count:c,res:l}of o.anchors.values())i(l,c);return typeof s=="function"?_n(s,{"":a},"",a):a}};var zr=class extends Sn{constructor(e){super(Hc),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,t){if(t?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let n;t?.aliasResolveCache?n=t.aliasResolveCache:(n=[],Er(e,{Node:(s,o)=>{(er(o)||Kc(o))&&n.push(o)}}),t&&(t.aliasResolveCache=n));let i;for(let s of n){if(s===this)break;s.anchor===this.source&&(i=s)}if(i&&t){let{anchors:s,doc:o,maxAliasCount:a}=t,c=s.get(i);if(c||(Re(i,null,t),c=s.get(i)),c?.res===void 0){let l="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(l)}if(a>=0&&(c.count+=1,c.aliasCount===0&&(c.aliasCount=Jc(o,i,s)),c.count*c.aliasCount>a)){let l="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(l)}}return i}toJSON(e,t){if(!t)return{source:this.source};let n=this.resolve(t.doc,t);if(!n){let i=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(i)}return t.anchors.get(n).res}toString(e,t,n){let i=`*${this.source}`;if(e){if(Gc(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`${i} `}return i}};function Jc(r,e,t){if(er(e)){let n=e.resolve(r),i=t&&n&&t.get(n);return i?i.count*i.aliasCount:0}else if(ae(e)){let n=0;for(let i of e.items){let s=Jc(r,i,t);s>n&&(n=s)}return n}else if(te(e)){let n=Jc(r,e.key,t),i=Jc(r,e.value,t);return Math.max(n,i)}return 1}var Yc=r=>!r||typeof r!="function"&&typeof r!="object",F=class extends Sn{constructor(e){super(At),this.value=e}toJSON(e,t){return t?.keep?this.value:Re(this.value,e,t)}toString(){return String(this.value)}};F.BLOCK_FOLDED="BLOCK_FOLDED";F.BLOCK_LITERAL="BLOCK_LITERAL";F.PLAIN="PLAIN";F.QUOTE_DOUBLE="QUOTE_DOUBLE";F.QUOTE_SINGLE="QUOTE_SINGLE";var mN="tag:yaml.org,2002:";function yN(r,e,t){if(e){let n=t.filter(s=>s.tag===e),i=n.find(s=>!s.format)??n[0];if(!i)throw new Error(`Tag ${e} not found`);return i}return t.find(n=>n.identify?.(r)&&!n.format)}function Kr(r,e,t){if($r(r)&&(r=r.contents),ne(r))return r;if(te(r)){let d=t.schema[Zt].createNode?.(t.schema,null,t);return d.items.push(r),d}(r instanceof String||r instanceof Number||r instanceof Boolean||typeof BigInt<"u"&&r instanceof BigInt)&&(r=r.valueOf());let{aliasDuplicateObjects:n,onAnchor:i,onTagObj:s,schema:o,sourceObjects:a}=t,c;if(n&&r&&typeof r=="object"){if(c=a.get(r),c)return c.anchor??(c.anchor=i(r)),new zr(c.anchor);c={anchor:null,node:null},a.set(r,c)}e?.startsWith("!!")&&(e=mN+e.slice(2));let l=yN(r,e,o.tags);if(!l){if(r&&typeof r.toJSON=="function"&&(r=r.toJSON()),!r||typeof r!="object"){let d=new F(r);return c&&(c.node=d),d}l=r instanceof Map?o[Zt]:Symbol.iterator in Object(r)?o[Hr]:o[Zt]}s&&(s(l),delete t.onTagObj);let u=l?.createNode?l.createNode(t.schema,r,t):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(t.schema,r,t):new F(r);return e?u.tag=e:l.default||(u.tag=l.tag),c&&(c.node=u),u}function To(r,e,t){let n=t;for(let i=e.length-1;i>=0;--i){let s=e[i];if(typeof s=="number"&&Number.isInteger(s)&&s>=0){let o=[];o[s]=n,n=o}else n=new Map([[s,n]])}return Kr(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 ds=r=>r==null||typeof r=="object"&&!!r[Symbol.iterator]().next().done,ls=class extends Sn{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=>ne(n)||te(n)?n.clone(e):n),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(ds(e))this.add(t);else{let[n,...i]=e,s=this.get(n,!0);if(ae(s))s.addIn(i,t);else if(s===void 0&&this.schema)this.set(n,To(this.schema,i,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${i}`)}}deleteIn(e){let[t,...n]=e;if(n.length===0)return this.delete(t);let i=this.get(t,!0);if(ae(i))return i.deleteIn(n);throw new Error(`Expected YAML collection at ${t}. Remaining path: ${n}`)}getIn(e,t){let[n,...i]=e,s=this.get(n,!0);return i.length===0?!t&&G(s)?s.value:s:ae(s)?s.getIn(i,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!te(t))return!1;let n=t.value;return n==null||e&&G(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 i=this.get(t,!0);return ae(i)?i.hasIn(n):!1}setIn(e,t){let[n,...i]=e;if(i.length===0)this.set(n,t);else{let s=this.get(n,!0);if(ae(s))s.setIn(i,t);else if(s===void 0&&this.schema)this.set(n,To(this.schema,i,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${i}`)}}};var P0=r=>r.replace(/^(?!$)(?: $)?/gm,"#");function Vt(r,e){return/^\n+$/.test(r)?r.substring(1):e?r.replace(/^(?! *$)/gm,e):r}var kr=(r,e,t)=>r.endsWith(` +${t.body}`,changed:!0}:{content:r,changed:!1}}function vw(r){if(!r.field)return null;if(["unknown_field","missing_required"].includes(r.code))return/[.[\]]/.test(r.field)?null:[r.field];if(!["schema_additional_properties","schema_required"].includes(r.code))return null;let e=r.details?.instance_path,t=r.details?.property;return typeof e!="string"||typeof t!="string"?null:[...e===""?[]:e.slice(1).split("/").map(n=>n.replace(/~1/g,"/").replace(/~0/g,"~")),t]}function ww(r){return vw(r)?["unknown_field","schema_additional_properties"].includes(r.code)?"Remove field":"Add placeholder":null}function YR(r,e){let t=vw(e);if(!t?.length)return!1;let n=r;for(let a of t.slice(0,-1)){if(!n||typeof n!="object"||!Object.prototype.hasOwnProperty.call(n,a))return!1;n=n[a]}if(!n||typeof n!="object"||Array.isArray(n))return!1;let i=n,s=t[t.length-1],o=Object.prototype.hasOwnProperty.call(i,s);if(["unknown_field","schema_additional_properties"].includes(e.code)){if(!o)return!1;delete i[s]}else{if(o)return!1;Object.defineProperty(i,s,{value:"TODO",enumerable:!0,configurable:!0,writable:!0})}return!0}var L=require("obsidian");var O=class extends Error{code;details;constructor(e,t,n){super(t),this.code=e,this.details=n,this.name="InteropError"}toPortableError(e){return{code:this.code,message:this.message,...this.details===void 0?{}:{details:this.details},...e===void 0?{}:{retryable:e}}}},xo=class extends Error{status;error;constructor(e,t){super(t.message),this.status=e,this.error=t,this.name="ActionHandlerError"}};var _w=Kn(Yf(),1),Sw=Kn(op(),1);var qp={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 XR=Sw.default;function $w(){return Object.fromEntries(Object.entries(qp).map(([r,e])=>[r,structuredClone(e)]))}function Bp(){let r=new _w.Ajv2020({allErrors:!0,strict:!1,validateFormats:!0});XR(r);let e=$w();r.addSchema(e.profile);for(let[t,n]of Object.entries(e))t!=="profile"&&r.addSchema(n);return r}function Br(r,e){let t=String(qp[e].$id),n=r.getSchema(t);if(!n)throw new Error(`Canonical interoperability schema is unavailable: ${e}`);return n}function bn(r){return(r??[]).map(e=>`${e.instancePath||"/"} ${e.message??e.keyword}`).join("; ")}function _r(r,e){if(!("value"in r))throw new O("contract_digest_conflict",`${e} must be resolved to an inline JSON Schema before runtime registration.`);return structuredClone(r.value)}function xw(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=_r(r.record_schema,"record_schema"),r.binding_schema&&(e.binding_schema=_r(r.binding_schema,"binding_schema"));break;case"event":e.data_schema=_r(r.data_schema,"data_schema"),r.source_schema&&(e.source_schema=_r(r.source_schema,"source_schema"));break;case"action":e.input_schema=_r(r.input_schema,"input_schema"),r.output_schema&&(e.output_schema=_r(r.output_schema,"output_schema")),r.error_schema&&(e.error_schema=_r(r.error_schema,"error_schema")),r.provider_schema&&(e.provider_schema=_r(r.provider_schema,"provider_schema")),r.behavior&&(e.behavior=structuredClone(r.behavior));break}return e}async function kc(r){return is(xw(r))}async function is(r){return`sha256:${await QR(Up(r))}`}function Ew(r,e){return{data:ns(r,e.data_schema,`${e.id} data_schema`),...e.source_schema?{source:ns(r,e.source_schema,`${e.id} source_schema`)}:{}}}function Aw(r,e){return{input:ns(r,e.input_schema,`${e.id} input_schema`),...e.output_schema?{output:ns(r,e.output_schema,`${e.id} output_schema`)}:{},...e.error_schema?{error:ns(r,e.error_schema,`${e.id} error_schema`)}:{},...e.provider_schema?{provider:ns(r,e.provider_schema,`${e.id} provider_schema`)}:{}}}function Pc(r,e,t,n){if(!(!r||r(e)))throw new O(t,`${n} failed JSON Schema validation: ${bn(r.errors)}`)}function ns(r,e,t){try{return r.compile(_r(e,t))}catch(n){throw new O("contract_digest_conflict",`${t} could not be compiled: ${n instanceof Error?n.message:String(n)}`)}}function Up(r){return r===null||typeof r!="object"?JSON.stringify(r):Array.isArray(r)?`[${r.map(Up).join(",")}]`:`{${Object.entries(r).filter(([,t])=>t!==void 0).sort(([t],[n])=>tn?1:0).map(([t,n])=>`${JSON.stringify(t)}:${Up(n)}`).join(",")}}`}async function QR(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 Vr=Kn(g0(),1);var lh={delivery:["ephemeral"],ordering:["none"],cancellation:!0,deadlines:!0,provider_discovery:!0,request_deduplication:!0,cross_process_identity:!1},oN=new Set(["specversion","id","source","type","time","subject","datacontenttype","dataschema","data","mdbaseprofile","mdbasecontractversion","mdbasecontractdigest","mdbaseapplication","mdbaseimplementation","mdbaseimplementationversion","mdbaseinstanceid","correlationid","causationid"]),Mo=class{options;profileVersion="0.1";transport;ajv=Bp();contractValidator=Br(this.ajv,"contract");eventValidator=Br(this.ajv,"event");actionRequestValidator=Br(this.ajv,"actionRequest");actionInvocationValidator=Br(this.ajv,"actionInvocation");actionOutcomeValidator=Br(this.ajv,"actionOutcome");eventSourceDeclarationValidator=Br(this.ajv,"eventSourceDeclaration");actionProviderDeclarationValidator=Br(this.ajv,"actionProviderDeclaration");contracts=new Map;clients=new Map;eventSources=new Map;actionProviders=new Map;subscriptions=new Map;activeActions=new Map;completedActions=new Map;admissionLocks=new Map;recentEvents=new Map;authorize;now;idFactory;recentEventLimit;completedRequestLimit;nextSequence=0;disposed=!1;constructor(e={}){this.options=e,this.authorize=e.authorize??(()=>!1),this.now=e.now??(()=>new Date),this.idFactory=e.idFactory??(t=>{this.nextSequence+=1;let n=typeof globalThis.crypto?.randomUUID=="function"?globalThis.crypto.randomUUID():`${this.now().getTime().toString(36)}-${this.nextSequence.toString(36)}`;return`${t}_${n}`}),this.recentEventLimit=Math.max(1,e.recentEventLimit??1e3),this.completedRequestLimit=Math.max(1,e.completedRequestLimit??1e3),this.transport={...lh,...structuredClone(e.transport??{}),delivery:[...e.transport?.delivery??lh.delivery],ordering:[...e.transport?.ordering??lh.ordering]}}connect(e){this.assertActive(),aN(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:i=>this.registerEventSource(t,i),publishEvent:i=>this.publishEvent(t,i),subscribeEvents:(i,s)=>this.subscribeEvents(t,i,s),registerActionProvider:i=>this.registerActionProvider(t,i),invokeAction:i=>this.invokeAction(t,i),cancelAction:(i,s)=>this.cancelAction(t,i,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){let n=this.requireClient(e);if(t.contracts.length===0)throw new O("request_rejected","An event-source declaration must include a contract.");let i=`${e}:${t.declaration_id}`;if(this.eventSources.has(i))throw new O("request_rejected",`Event-source declaration ${t.declaration_id} is already registered.`);let s=new Map;for(let l of t.contracts){let u=await this.prepareEventContract(l.contract),d=b0(l.requirement,u.reference);if(v0(d,u.reference),await this.assertAuthorized({operation:"register_event_source",principal:n.identity,contract:u.reference}),u.sourceValidator&&!u.sourceValidator(l.binding??{}))throw new O("request_rejected",`${u.reference.id} source binding is invalid: ${bn(u.sourceValidator.errors)}`);let f=Bc(u.reference);if(s.has(f))throw new O("contract_digest_conflict",`Event contract ${f} is repeated by one declaration.`);s.set(f,{contract:u,requirement:d,...l.binding===void 0?{}:{binding:structuredClone(l.binding)},...l.ordering===void 0?{}:{ordering:[...l.ordering]}})}let o={kind:"mdbase.event-source",profile_version:"0.1",declaration_id:t.declaration_id,source:structuredClone(n.identity),contracts:[...s.values()].map(({contract:l,requirement:u,binding:d,ordering:f})=>({requirement:structuredClone(u),resolved:structuredClone(l.reference),...d===void 0?{}:{binding:d},...f===void 0?{}:{ordering:f}}))},a={...o,declaration_digest:await is(o)};wn(this.eventSourceDeclarationValidator,a,"request_rejected","Event-source declaration"),this.commitContracts([...s.values()].map(({contract:l})=>l)),this.eventSources.set(i,{id:i,clientId:e,declaration:structuredClone(a),contracts:new Map([...s.entries()].map(([l,u])=>[l,{contract:u.contract,...u.binding===void 0?{}:{binding:u.binding}}]))}),n.sources.add(i);let c=!0;return{declaration:structuredClone(a),dispose:()=>{c&&(c=!1,this.removeEventSource(i))}}}async publishEvent(e,t){let n=this.requireClient(e),i=Bc(t.contract),s=[...n.sources].map(m=>this.eventSources.get(m)).find(m=>m?.contracts.has(i));if(!s)throw new O("unknown_contract",`This client has not registered event contract ${t.contract.id} ${t.contract.version}.`);let o=s.contracts.get(i)?.contract;if(!o)throw new O("unknown_contract",`Event contract ${i} is unavailable.`);if(t.contract.digest&&t.contract.digest!==o.reference.digest)throw new O("contract_digest_conflict",`Event contract ${i} has a different digest.`);await this.assertAuthorized({operation:"publish_event",principal:n.identity,contract:o.reference,...t.subject===void 0?{}:{subject:t.subject}}),dh(t.data,"invalid_event_data",`Event ${o.reference.id} data`),Pc(o.dataValidator,t.data,"invalid_event_data",`Event ${o.reference.id} data`);let a=t.extensions??{};for(let m of Object.keys(a))if(oN.has(m))throw new O("request_rejected",`Event extension ${m} is reserved.`);let c={...structuredClone(a),specversion:"1.0",id:t.id??this.idFactory("evt"),source:cN(n.identity),type:o.reference.id,time:t.time??this.now().toISOString(),...t.subject===void 0?{}:{subject:t.subject},datacontenttype:"application/json",dataschema:S0(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}};wn(this.eventValidator,c,"invalid_event_data","Event envelope"),uh(this.transport,c),lN(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 O("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)),_0(this.recentEvents,this.recentEventLimit);let d=[...this.subscriptions.values()].filter(({subscription:m})=>Uc(m.contract,o.reference)),f=await Promise.allSettled(d.map(async m=>await this.isAuthorized({operation:"subscribe_event",principal:m.principal,contract:o.reference,...c.subject===void 0?{}:{subject:c.subject}})?(await m.handler(structuredClone(c)),!0):!1)),p=0;for(let m of f)m.status==="fulfilled"&&m.value?p+=1:m.status==="rejected"&&this.report({severity:"error",code:"event_consumer_failed",message:`An event consumer failed while handling ${c.type}.`,contract:o.reference,cause:m.reason});return{event:structuredClone(c),deliveries:p,duplicate:!1}}async subscribeEvents(e,t,n){let i=this.requireClient(e);fh(t.contract),fN(this.transport,t.require_transport),await this.assertAuthorized({operation:"subscribe_event",principal:i.identity,contract:t.contract});let s=this.idFactory("subscription");this.subscriptions.set(s,{id:s,clientId:e,principal:structuredClone(i.identity),subscription:structuredClone(t),handler:n}),i.subscriptions.add(s);let o=!0;return{dispose:()=>{o&&(o=!1,this.removeSubscription(s))}}}async registerActionProvider(e,t){let n=this.requireClient(e);if(t.handlers.length===0)throw new O("request_rejected","An action-provider declaration must include a handler.");let i=`${e}:${t.declaration_id}`;if(this.actionProviders.has(i))throw new O("request_rejected",`Action-provider declaration ${t.declaration_id} is already registered.`);let s=[],o=new Set;for(let d of t.handlers){if(o.has(d.handler_id))throw new O("request_rejected",`Handler ${d.handler_id} is repeated.`);o.add(d.handler_id);let f=await this.prepareActionContract(d.contract),p=b0(d.requirement,f.reference);if(v0(p,f.reference),await this.assertAuthorized({operation:"register_action_provider",principal:n.identity,contract:f.reference,provider:n.identity}),f.providerValidator&&!f.providerValidator(d.binding??{}))throw new O("request_rejected",`${f.reference.id} provider binding is invalid: ${bn(f.providerValidator.errors)}`);let m=d.contract.behavior?.idempotency??"none";if(d.idempotency?.mode==="request"&&m==="none")throw new O("request_rejected",`${f.reference.id} does not permit request deduplication.`);if(m==="required"&&d.idempotency?.mode!=="request")throw new O("request_rejected",`${f.reference.id} requires a provider with request deduplication.`);let h=d.contract.behavior?.cancellation??"none";if(d.cancellation==="cooperative"&&h!=="cooperative")throw new O("request_rejected",`${f.reference.id} does not declare cooperative cancellation.`);s.push({contract:f,declaration:{handler_id:d.handler_id,requirement:p,resolved:structuredClone(f.reference),...d.binding===void 0?{}:{binding:structuredClone(d.binding)},...d.idempotency===void 0?{}:{idempotency:structuredClone(d.idempotency)},...d.cancellation===void 0?{}:{cancellation:d.cancellation},...d.max_concurrency===void 0?{}:{max_concurrency:d.max_concurrency}},handler:d.handler})}let a={kind:"mdbase.action-provider",profile_version:"0.1",declaration_id:t.declaration_id,provider:structuredClone(n.identity),handlers:s.map(({declaration:d})=>structuredClone(d))},c={...a,declaration_digest:await is(a)};wn(this.actionProviderDeclarationValidator,c,"request_rejected","Action-provider declaration"),this.commitContracts(s.map(({contract:d})=>d));let l=s.map(({contract:d,declaration:f,handler:p})=>({registrationId:i,clientId:e,declaration:structuredClone(c),handlerDeclaration:structuredClone(f),contract:d,handler:p,active:0}));this.actionProviders.set(i,{id:i,clientId:e,declaration:structuredClone(c),handlers:l}),n.providers.add(i);let u=!0;return{declaration:structuredClone(c),dispose:()=>{u&&(u=!1,this.removeActionProvider(i))}}}async invokeAction(e,t){let n=this.requireClient(e);fh(t.contract);let i=t.request_id??this.idFactory("req");this.cleanCompletedActions(),dh(t.input,"invalid_action_input",`Action ${t.contract.id} input`);let s={kind:"mdbase.action.request",profile_version:"0.1",request_id:i,contract:structuredClone(t.contract),caller:structuredClone(n.identity),created_at:t.created_at??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)};wn(this.actionRequestValidator,s,"request_rejected","Action request"),uh(this.transport,s);let o=await this.acquireAdmission(i);try{let a=await is(dN(s)),c=this.activeActions.get(i);if(c){if(w0(e,i,a,c),c.handler.handlerDeclaration.idempotency?.mode!=="request")throw new O("request_rejected",`Action request ${i} is already active without deduplication.`);return structuredClone(await c.promise)}let l=this.completedActions.get(i);if(l){if(w0(e,i,a,l),!l.reusable)throw new O("request_rejected",`Action request ${i} was already completed without deduplication.`);return structuredClone(l.outcome)}if(s.deadline&&new Date(s.deadline).getTime()<=this.now().getTime())throw new O("deadline_exceeded",`Action request ${i} passed its deadline before admission.`);if(s.deadline&&!this.transport.deadlines)throw new O("unsupported_transport_capability","The active transport cannot enforce action deadlines.");let u=this.resolveActionCandidates(s.contract,s.requested_provider);u.length===0&&this.throwResolutionFailure(s.contract,s.requested_provider);let d=[];for(let E of u)await this.isAuthorized({operation:"invoke_action",principal:n.identity,contract:E.contract.reference,provider:E.declaration.provider,...s.subject===void 0?{}:{subject:s.subject}})&&d.push(E);if(d.length===0)throw new O("unauthorized",`No authorized provider can execute ${s.contract.id}.`);if(d.length>1)throw new O("ambiguous_provider",`Action ${s.contract.id} has ${d.length} eligible providers; select one explicitly.`);let f=d[0];if(f.handlerDeclaration.max_concurrency!==void 0&&f.active>=f.handlerDeclaration.max_concurrency)throw new O("request_rejected",`Provider ${f.declaration.provider.implementation} is at capacity.`);if((f.contract.artifact.behavior?.idempotency??"none")==="required"&&!s.idempotency_key)throw new O("request_rejected",`${f.contract.reference.id} requires an idempotency key.`);Pc(f.contract.inputValidator,s.input,"invalid_action_input",`Action ${f.contract.reference.id} input`);let m={operation:"invoke_action",principal:n.identity,contract:f.contract.reference,provider:f.declaration.provider,...s.subject===void 0?{}:{subject:s.subject}},h=await this.options.authorizationContext?.(m),y={kind:"mdbase.action.invocation",profile_version:"0.1",invocation_id:this.idFactory("inv"),attempt_id:this.idFactory("attempt"),request_id:i,contract:structuredClone(f.contract.reference),caller:structuredClone(n.identity),provider:structuredClone(f.declaration.provider),provider_declaration_digest:f.declaration.declaration_digest,handler_id:f.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},...h===void 0?{}:{authorization_context:h},input:structuredClone(s.input)};wn(this.actionInvocationValidator,y,"request_rejected","Action invocation"),await this.options.onInvocation?.(structuredClone(y));let g=new AbortController,b;if(y.deadline){let E=Math.max(0,new Date(y.deadline).getTime()-this.now().getTime());b=setTimeout(()=>g.abort(new O("deadline_exceeded",`Action request ${i} exceeded its deadline.`)),E)}f.active+=1;let v=this.executeAction(f,y,g).finally(()=>{b!==void 0&&clearTimeout(b),f.active=Math.max(0,f.active-1),this.activeActions.delete(i)});this.activeActions.set(i,{clientId:e,requestId:i,requestDigest:a,handler:f,invocation:y,controller:g,promise:v}),o();let S=await v,_=f.handlerDeclaration.idempotency?.retention_seconds??300;return this.completedActions.set(i,{clientId:e,requestDigest:a,outcome:structuredClone(S),reusable:f.handlerDeclaration.idempotency?.mode==="request",expiresAt:this.now().getTime()+_*1e3}),_0(this.completedActions,this.completedRequestLimit),structuredClone(S)}finally{o()}}async executeAction(e,t,n){try{let i=await e.handler(structuredClone(t.input),{invocation:structuredClone(t),signal:n.signal});if(n.signal.aborted){let o=n.signal.reason;return o instanceof O&&o.code==="deadline_exceeded"?this.failureOutcome(t,"failed",o.toPortableError()):this.failureOutcome(t,"cancelled",{code:"cancelled",message:`Action request ${t.request_id} was cancelled.`})}dh(i,"invalid_action_output",`Action ${e.contract.reference.id} output`),Pc(e.contract.outputValidator,i,"invalid_action_output",`Action ${e.contract.reference.id} output`);let s={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 wn(this.actionOutcomeValidator,s,"invalid_action_output","Action outcome"),uh(this.transport,s),s}catch(i){if(i instanceof xo)return e.contract.errorValidator&&!e.contract.errorValidator(i.error.details??{})?this.failureOutcome(t,"failed",{code:"handler_failure",message:`Provider returned invalid declared error details: ${bn(e.contract.errorValidator.errors)}`}):this.failureOutcome(t,i.status,i.error);if(i instanceof O)return this.failureOutcome(t,i.code==="cancelled"?"cancelled":i.code==="outcome_indeterminate"?"outcome_indeterminate":"failed",i.toPortableError());if(n.signal.aborted||pN(i)){let s=n.signal.reason;return s instanceof O&&s.code==="deadline_exceeded"?this.failureOutcome(t,"failed",s.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 i={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 wn(this.actionOutcomeValidator,i,"invalid_action_output","Action outcome"),i}async cancelAction(e,t,n){let i=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 O("unauthorized",`Action request ${t} belongs to another caller.`);return a?structuredClone(a.outcome):null}if(o.clientId!==e)throw new O("unauthorized",`Action request ${t} belongs to another caller.`);if(await this.assertAuthorized({operation:"cancel_action",principal:i.identity,contract:o.invocation.contract,provider:o.invocation.provider,...o.invocation.subject===void 0?{}:{subject:o.invocation.subject}}),!this.transport.cancellation)throw new O("unsupported_transport_capability","The active transport cannot deliver cancellation.");if(o.handler.handlerDeclaration.cancellation!=="cooperative")throw new O("cancellation_unsupported",`Provider ${o.invocation.provider.implementation} does not support cancellation.`);return o.controller.abort(new O("cancelled",n?.trim()||`Action request ${t} was cancelled.`)),structuredClone(await o.promise)}resolveActionCandidates(e,t){let n=[...this.actionProviders.values()].flatMap(({handlers:s})=>s).filter(({contract:s,declaration:o})=>Uc(e,s.reference)&&uN(t,o.provider)),i=(0,Vr.maxSatisfying)([...new Set(n.map(({contract:s})=>s.reference.version))],e.version,{includePrerelease:!0});return i?n.filter(({contract:s})=>s.reference.version===i).sort((s,o)=>s.declaration.provider.application.localeCompare(o.declaration.provider.application)||s.declaration.provider.implementation.localeCompare(o.declaration.provider.implementation)||(s.declaration.provider.instance_id??"").localeCompare(o.declaration.provider.instance_id??"")||s.handlerDeclaration.handler_id.localeCompare(o.handlerDeclaration.handler_id)):[]}throwResolutionFailure(e,t){let n=[...this.contracts.values()].filter(i=>i.artifact.contract_type==="action"&&i.reference.id===e.id);throw n.length===0?new O("unknown_contract",`Action contract ${e.id} is unknown.`):n.some(({reference:i})=>Uc(e,i))?t?new O("requested_provider_unavailable",`The requested provider is unavailable for ${e.id}.`):new O("no_provider",`No provider is registered for ${e.id}.`):new O("unsupported_contract_version",`No ${e.id} artifact satisfies ${e.version}.`)}async prepareEventContract(e){if(this.assertContractArtifact(e),e.contract_type!=="event")throw new O("unknown_contract",`${e.id} is not an event contract.`);let t={id:e.id,version:e.version,digest:await kc(e)};this.assertNoContractConflict(t);let n=Ew(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 O("unknown_contract",`${e.id} is not an action contract.`);let t={id:e.id,version:e.version,digest:await kc(e)};this.assertNoContractConflict(t);let n=Aw(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(wn(this.contractValidator,e,"contract_digest_conflict",`Contract ${e.id||""}`),!(0,Vr.valid)(e.version))throw new O("unsupported_contract_version",`${e.id} version must be exact SemVer.`)}assertNoContractConflict(e){let t=this.contracts.get(Bc(e));if(t&&t.reference.digest!==e.digest)throw new O("contract_digest_conflict",`Contract ${e.id} ${e.version} conflicts with the registered artifact.`)}commitContracts(e){let t=new Map;for(let n of e){let i=Bc(n.reference),s=t.get(i)??this.contracts.get(i);if(s&&s.reference.digest!==n.reference.digest)throw new O("contract_digest_conflict",`Contract ${n.reference.id} ${n.reference.version} conflicts within the registration.`);t.set(i,n)}for(let[n,i]of t)this.contracts.has(n)||this.contracts.set(n,i)}async disposeClient(e,t=!1){let n=this.clients.get(e);if(!(!n||n.disposed)){n.disposed=!0;for(let i of[...n.subscriptions])this.removeSubscription(i);for(let i of[...n.sources])this.removeEventSource(i);for(let i of[...n.providers])this.removeActionProvider(i);for(let i of[...this.activeActions.values()])i.clientId===e&&i.handler.handlerDeclaration.cancellation==="cooperative"&&i.controller.abort(new O("cancelled","The caller unloaded.")),i.handler.clientId===e&&i.handler.handlerDeclaration.cancellation==="cooperative"&&i.controller.abort(new O("cancelled","The provider unloaded."));this.clients.delete(e),t||this.assertActive()}}removeEventSource(e){let t=this.eventSources.get(e);t&&(this.eventSources.delete(e),this.clients.get(t.clientId)?.sources.delete(e))}removeActionProvider(e){let t=this.actionProviders.get(e);if(t){this.actionProviders.delete(e),this.clients.get(t.clientId)?.providers.delete(e);for(let n of this.activeActions.values())n.handler.registrationId===e&&n.handler.handlerDeclaration.cancellation==="cooperative"&&n.controller.abort(new O("cancelled","The provider unloaded."))}}removeSubscription(e){let t=this.subscriptions.get(e);t&&(this.subscriptions.delete(e),this.clients.get(t.clientId)?.subscriptions.delete(e))}requireClient(e){this.assertActive();let t=this.clients.get(e);if(!t||t.disposed)throw new O("transport_unavailable","Interop client is disposed.");return t}assertActive(){if(this.disposed)throw new O("transport_unavailable","Interop bridge is disposed.")}async assertAuthorized(e){if(!await this.isAuthorized(e))throw new O("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){let t=this.admissionLocks.get(e)??Promise.resolve(),n,i=new Promise(a=>{n=a}),s=t.then(()=>i);this.admissionLocks.set(e,s),await t;let o=!1;return()=>{o||(o=!0,n(),this.admissionLocks.get(e)===s&&this.admissionLocks.delete(e))}}report(e){this.options.onDiagnostic?.(structuredClone(e))}};function wn(r,e,t,n){if(!r(e))throw new O(t,`${n} is invalid: ${bn(r.errors)}`)}function aN(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 O("request_rejected",`Implementation identity ${e} is invalid.`);if(!(0,Vr.valid)(r.version))throw new O("request_rejected","Implementation identity version must be exact SemVer.")}function fh(r){if(!/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)+$/u.test(r.id))throw new O("unknown_contract",`Contract ID ${r.id} is invalid.`);if(!(0,Vr.validRange)(r.version,{includePrerelease:!0}))throw new O("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 O("contract_digest_conflict","Contract digest is invalid.")}function b0(r,e){let t=r??{id:e.id,version:e.version,digest:e.digest};return fh(t),structuredClone(t)}function v0(r,e){if(!Uc(r,e))throw new O("unsupported_contract_version",`${e.id} ${e.version} does not satisfy its implementation requirement.`)}function Uc(r,e){return r.id===e.id&&(0,Vr.satisfies)(e.version,r.version,{includePrerelease:!0})&&(!r.digest||r.digest===e.digest)}function Bc(r){return`${r.id}@${r.version}`}function S0(r){return`urn:mdbase:contract:${r.id}:${r.version}:${r.digest}`}function cN(r){return`urn:mdbase:app:${[r.application,r.implementation,...r.instance_id?[r.instance_id]:[]].map(encodeURIComponent).join(":")}`}function lN(r,e){if(r.type!==e.id||r.mdbasecontractversion!==e.version||r.mdbasecontractdigest!==e.digest||r.dataschema!==S0(e))throw new O("contract_digest_conflict","Event contract evidence is inconsistent.")}function dN(r){let{created_at:e,...t}=r;return t}function w0(r,e,t,n){if(n.clientId!==r)throw new O("unauthorized",`Action request ${e} belongs to another caller.`);if(n.requestDigest!==t)throw new O("request_rejected",`Action request ${e} was reused with different content.`)}function dh(r,e,t){let n=new Set,i=(s,o)=>{if(!(s===null||typeof s=="boolean"||typeof s=="string")){if(typeof s=="number"){if(Number.isFinite(s))return;throw new O(e,`${t}${o} must be a finite JSON number.`)}if(typeof s!="object")throw new O(e,`${t}${o} is not a JSON value.`);if(n.has(s))throw new O(e,`${t}${o} contains a cycle.`);if(n.add(s),Array.isArray(s))s.forEach((a,c)=>i(a,`${o}/${c}`));else{let a=Object.getPrototypeOf(s);if(a!==Object.prototype&&a!==null)throw new O(e,`${t}${o} must be a plain JSON object.`);for(let[c,l]of Object.entries(s))i(l,`${o}/${c}`)}n.delete(s)}};i(r,"")}function uh(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 O("unsupported_transport_capability",`The portable envelope is ${n} bytes; the active transport allows ${r.max_payload_bytes}.`)}function uN(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 fN(r,e){if(e){if(e.delivery?.some(t=>!r.delivery.includes(t)))throw new O("unsupported_transport_capability","The active transport lacks a required delivery capability.");if(e.ordering?.some(t=>!r.ordering.includes(t)))throw new O("unsupported_transport_capability","The active transport lacks a required ordering capability.");for(let t of["cancellation","deadlines","provider_discovery","request_deduplication","cross_process_identity"])if(e[t]===!0&&r[t]!==!0)throw new O("unsupported_transport_capability",`The active transport lacks ${t}.`);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 pN(r){return r instanceof Error&&r.name==="AbortError"}var Vc=class{constructor(e,t){this.app=e;this.profileVersion="0.1";this.bridge=new Mo({authorize:()=>t(),transport:{delivery:["ephemeral"],ordering:["none"],cancellation:!0,deadlines:!0,provider_discovery:!0,request_deduplication:!0,cross_process_identity:!1},onDiagnostic:n=>{(n.severity==="error"?console.error:console.warn)(`[mdbase/interop] ${n.code}: ${n.message}`,n.cause??"")}}),this.transport=this.bridge.describe().transport}connect(e){let t=e.manifest?.id,n=e.manifest?.version;if(!t||!n)throw new Error("Only a loaded Obsidian plugin with manifest identity can connect to mdbase interop.");let i=this.app.plugins;if(!i||i.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()}};qt();var z=require("obsidian"),ix=Kn(gp(),1);var Hc=Symbol.for("yaml.alias"),zc=Symbol.for("yaml.document"),Zt=Symbol.for("yaml.map"),ph=Symbol.for("yaml.pair"),At=Symbol.for("yaml.scalar"),Hr=Symbol.for("yaml.seq"),nt=Symbol.for("yaml.node.type"),er=r=>!!r&&typeof r=="object"&&r[nt]===Hc,$r=r=>!!r&&typeof r=="object"&&r[nt]===zc,tr=r=>!!r&&typeof r=="object"&&r[nt]===Zt,te=r=>!!r&&typeof r=="object"&&r[nt]===ph,G=r=>!!r&&typeof r=="object"&&r[nt]===At,rr=r=>!!r&&typeof r=="object"&&r[nt]===Hr;function ae(r){if(r&&typeof r=="object")switch(r[nt]){case Zt:case Hr:return!0}return!1}function ne(r){if(r&&typeof r=="object")switch(r[nt]){case Hc:case Zt:case At:case Hr:return!0}return!1}var Kc=r=>(G(r)||ae(r))&&!!r.anchor;var gt=Symbol("break visit"),$0=Symbol("skip children"),xr=Symbol("remove node");function Er(r,e){let t=x0(e);$r(r)?as(null,r.contents,t,Object.freeze([r]))===xr&&(r.contents=null):as(null,r,t,Object.freeze([]))}Er.BREAK=gt;Er.SKIP=$0;Er.REMOVE=xr;function as(r,e,t,n){let i=E0(r,e,t,n);if(ne(i)||te(i))return A0(r,n,i),as(r,i,t,n);if(typeof i!="symbol"){if(ae(e)){n=Object.freeze(n.concat(e));for(let s=0;sr.replace(/[!,[\]{}]/g,e=>hN[e]),Ar=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]+/),i=n.shift();switch(i){case"%TAG":{if(n.length!==2&&(t(0,"%TAG directive should contain exactly two parts"),n.length<2))return!1;let[s,o]=n;return this.tags[s]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,n.length!==1)return t(0,"%YAML directive should contain exactly one part"),!1;let[s]=n;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 ${i}`,!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,i]=e.match(/^(.*!)([^!]*)$/s);i||t(`The ${e} tag has no suffix`);let s=this.tags[n];if(s)try{return s+decodeURIComponent(i)}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+mN(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),i;if(e&&n.length>0&&ne(e.contents)){let s={};Er(e.contents,(o,a)=>{ne(a)&&a.tag&&(s[a.tag]=!0)}),i=Object.keys(s)}else i=[];for(let[s,o]of n)s==="!!"&&o==="tag:yaml.org,2002:"||(!e||i.some(a=>a.startsWith(o)))&&t.push(`%TAG ${s} ${o}`);return t.join(` +`)}};Ar.defaultYaml={explicit:!1,version:"1.2"};Ar.defaultTags={"!!":"tag:yaml.org,2002:"};function Gc(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 hh(r){let e=new Set;return Er(r,{Value(t,n){n.anchor&&e.add(n.anchor)}}),e}function mh(r,e){for(let t=1;;++t){let n=`${r}${t}`;if(!e.has(n))return n}}function k0(r,e){let t=[],n=new Map,i=null;return{onAnchor:s=>{t.push(s),i??(i=hh(r));let o=mh(e,i);return i.add(o),o},setAnchors:()=>{for(let s of t){let o=n.get(s);if(typeof o=="object"&&o.anchor&&(G(o.node)||ae(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:n}}function _n(r,e,t,n){if(n&&typeof n=="object")if(Array.isArray(n))for(let i=0,s=n.length;iRe(n,String(i),t));if(r&&typeof r.toJSON=="function"){if(!t||!Kc(r))return r.toJSON(e,t);let n={aliasCount:0,count:1,res:void 0};t.anchors.set(r,n),t.onCreate=s=>{n.res=s,delete t.onCreate};let i=r.toJSON(e,t);return t.onCreate&&t.onCreate(i),i}return typeof r=="bigint"&&!t?.keep?Number(r):r}var Sn=class{constructor(e){Object.defineProperty(this,nt,{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:i,reviver:s}={}){if(!$r(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=Re(this,"",o);if(typeof i=="function")for(let{count:c,res:l}of o.anchors.values())i(l,c);return typeof s=="function"?_n(s,{"":a},"",a):a}};var zr=class extends Sn{constructor(e){super(Hc),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,t){if(t?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let n;t?.aliasResolveCache?n=t.aliasResolveCache:(n=[],Er(e,{Node:(s,o)=>{(er(o)||Kc(o))&&n.push(o)}}),t&&(t.aliasResolveCache=n));let i;for(let s of n){if(s===this)break;s.anchor===this.source&&(i=s)}if(i&&t){let{anchors:s,doc:o,maxAliasCount:a}=t,c=s.get(i);if(c||(Re(i,null,t),c=s.get(i)),c?.res===void 0){let l="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(l)}if(a>=0&&(c.count+=1,c.aliasCount===0&&(c.aliasCount=Jc(o,i,s)),c.count*c.aliasCount>a)){let l="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(l)}}return i}toJSON(e,t){if(!t)return{source:this.source};let n=this.resolve(t.doc,t);if(!n){let i=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(i)}return t.anchors.get(n).res}toString(e,t,n){let i=`*${this.source}`;if(e){if(Gc(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`${i} `}return i}};function Jc(r,e,t){if(er(e)){let n=e.resolve(r),i=t&&n&&t.get(n);return i?i.count*i.aliasCount:0}else if(ae(e)){let n=0;for(let i of e.items){let s=Jc(r,i,t);s>n&&(n=s)}return n}else if(te(e)){let n=Jc(r,e.key,t),i=Jc(r,e.value,t);return Math.max(n,i)}return 1}var Yc=r=>!r||typeof r!="function"&&typeof r!="object",F=class extends Sn{constructor(e){super(At),this.value=e}toJSON(e,t){return t?.keep?this.value:Re(this.value,e,t)}toString(){return String(this.value)}};F.BLOCK_FOLDED="BLOCK_FOLDED";F.BLOCK_LITERAL="BLOCK_LITERAL";F.PLAIN="PLAIN";F.QUOTE_DOUBLE="QUOTE_DOUBLE";F.QUOTE_SINGLE="QUOTE_SINGLE";var yN="tag:yaml.org,2002:";function gN(r,e,t){if(e){let n=t.filter(s=>s.tag===e),i=n.find(s=>!s.format)??n[0];if(!i)throw new Error(`Tag ${e} not found`);return i}return t.find(n=>n.identify?.(r)&&!n.format)}function Kr(r,e,t){if($r(r)&&(r=r.contents),ne(r))return r;if(te(r)){let d=t.schema[Zt].createNode?.(t.schema,null,t);return d.items.push(r),d}(r instanceof String||r instanceof Number||r instanceof Boolean||typeof BigInt<"u"&&r instanceof BigInt)&&(r=r.valueOf());let{aliasDuplicateObjects:n,onAnchor:i,onTagObj:s,schema:o,sourceObjects:a}=t,c;if(n&&r&&typeof r=="object"){if(c=a.get(r),c)return c.anchor??(c.anchor=i(r)),new zr(c.anchor);c={anchor:null,node:null},a.set(r,c)}e?.startsWith("!!")&&(e=yN+e.slice(2));let l=gN(r,e,o.tags);if(!l){if(r&&typeof r.toJSON=="function"&&(r=r.toJSON()),!r||typeof r!="object"){let d=new F(r);return c&&(c.node=d),d}l=r instanceof Map?o[Zt]:Symbol.iterator in Object(r)?o[Hr]:o[Zt]}s&&(s(l),delete t.onTagObj);let u=l?.createNode?l.createNode(t.schema,r,t):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(t.schema,r,t):new F(r);return e?u.tag=e:l.default||(u.tag=l.tag),c&&(c.node=u),u}function To(r,e,t){let n=t;for(let i=e.length-1;i>=0;--i){let s=e[i];if(typeof s=="number"&&Number.isInteger(s)&&s>=0){let o=[];o[s]=n,n=o}else n=new Map([[s,n]])}return Kr(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 ds=r=>r==null||typeof r=="object"&&!!r[Symbol.iterator]().next().done,ls=class extends Sn{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=>ne(n)||te(n)?n.clone(e):n),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(ds(e))this.add(t);else{let[n,...i]=e,s=this.get(n,!0);if(ae(s))s.addIn(i,t);else if(s===void 0&&this.schema)this.set(n,To(this.schema,i,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${i}`)}}deleteIn(e){let[t,...n]=e;if(n.length===0)return this.delete(t);let i=this.get(t,!0);if(ae(i))return i.deleteIn(n);throw new Error(`Expected YAML collection at ${t}. Remaining path: ${n}`)}getIn(e,t){let[n,...i]=e,s=this.get(n,!0);return i.length===0?!t&&G(s)?s.value:s:ae(s)?s.getIn(i,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!te(t))return!1;let n=t.value;return n==null||e&&G(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 i=this.get(t,!0);return ae(i)?i.hasIn(n):!1}setIn(e,t){let[n,...i]=e;if(i.length===0)this.set(n,t);else{let s=this.get(n,!0);if(ae(s))s.setIn(i,t);else if(s===void 0&&this.schema)this.set(n,To(this.schema,i,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${i}`)}}};var P0=r=>r.replace(/^(?!$)(?: $)?/gm,"#");function Vt(r,e){return/^\n+$/.test(r)?r.substring(1):e?r.replace(/^(?! *$)/gm,e):r}var kr=(r,e,t)=>r.endsWith(` `)?Vt(t,e):t.includes(` `)?` -`+Vt(t,e):(r.endsWith(" ")?"":" ")+t;var gh="flow",Xc="block",Ro="quoted";function Io(r,e,t="flow",{indentAtStart:n,lineWidth:i=80,minContentWidth:s=20,onFold:o,onOverflow:a}={}){if(!i||i<0)return r;ii-Math.max(2,s)?l.push(0):d=i-n);let f,p,h=!1,m=-1,y=-1,g=-1;t===Xc&&(m=C0(r,m,e.length),m!==-1&&(d=m+c));for(let v;v=r[m+=1];){if(t===Ro&&v==="\\"){switch(y=m,r[m+1]){case"x":m+=3;break;case"u":m+=5;break;case"U":m+=9;break;default:m+=1}g=m}if(v===` -`)t===Xc&&(m=C0(r,m,e.length)),d=m+e.length+c,f=void 0;else{if(v===" "&&p&&p!==" "&&p!==` -`&&p!==" "){let S=r[m+1];S&&S!==" "&&S!==` -`&&S!==" "&&(f=m)}if(m>=d)if(f)l.push(f),d=f+c,f=void 0;else if(t===Ro){for(;p===" "||p===" ";)p=v,v=r[m+=1],h=!0;let S=m>g+1?m-2:y-1;if(u[S])return r;l.push(S),u[S]=!0,d=S+c,f=void 0}else h=!0}p=v}if(h&&a&&a(),l.length===0)return r;o&&o();let b=r.slice(0,l[0]);for(let v=0;vi-Math.max(2,s)?l.push(0):d=i-n);let f,p,m=!1,h=-1,y=-1,g=-1;t===Xc&&(h=C0(r,h,e.length),h!==-1&&(d=h+c));for(let v;v=r[h+=1];){if(t===Ro&&v==="\\"){switch(y=h,r[h+1]){case"x":h+=3;break;case"u":h+=5;break;case"U":h+=9;break;default:h+=1}g=h}if(v===` +`)t===Xc&&(h=C0(r,h,e.length)),d=h+e.length+c,f=void 0;else{if(v===" "&&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===Ro){for(;p===" "||p===" ";)p=v,v=r[h+=1],m=!0;let S=h>g+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=v}if(m&&a&&a(),l.length===0)return r;o&&o();let b=r.slice(0,l[0]);for(let v=0;v({indentAtStart:e?r.indent.length:r.indentAtStart,lineWidth:r.options.lineWidth,minContentWidth:r.options.minContentWidth}),el=r=>/^(%|---|\.\.\.)/m.test(r);function gN(r,e,t){if(!e||e<0)return!1;let n=e-t,i=r.length;if(i<=n)return!1;for(let s=0,o=0;s({indentAtStart:e?r.indent.length:r.indentAtStart,lineWidth:r.options.lineWidth,minContentWidth:r.options.minContentWidth}),el=r=>/^(%|---|\.\.\.)/m.test(r);function bN(r,e,t){if(!e||e<0)return!1;let n=e-t,i=r.length;if(i<=n)return!1;for(let s=0,o=0;sn)return!0;if(o=s+1,i-o<=n)return!1}return!0}function Oo(r,e){let t=JSON.stringify(r);if(e.options.doubleQuotedAsJSON)return t;let{implicitKey:n}=e,i=e.options.doubleQuotedMinMultiLineLength,s=e.indent||(el(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 _=t[f-1];if(_!==` -`&&_!==" "&&_!==" ")break}let p=t.substring(f),h=p.indexOf(` -`);h===-1?d="-":t===p||h!==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(vh,`$&${l}`));let m=!1,y,g=-1;for(y=0;y{E=!0});let $=Io(`${b}${_}${p}`,l,Xc,k);if(!E)return`>${S} ${l}${$}`}return t=t.replace(/\n+/g,`$&${l}`),`|${S} -${l}${b}${t}${p}`}function bN(r,e,t,n){let{type:i,value:s}=r,{actualString:o,implicitKey:a,indent:c,indentStep:l,inFlow:u}=e;if(a&&s.includes(` +${l}${b}${t}${p}`}function vN(r,e,t,n){let{type:i,value:s}=r,{actualString:o,implicitKey:a,indent:c,indentStep:l,inFlow:u}=e;if(a&&s.includes(` `)||u&&/[[\]{},]/.test(s))return us(s,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(s))return a||u||!s.includes(` `)?us(s,e):Qc(r,e,t,n);if(!a&&!u&&i!==F.PLAIN&&s.includes(` `))return Qc(r,e,t,n);if(el(s)){if(c==="")return e.forceBlockIndent=!0,Qc(r,e,t,n);if(a&&c===l)return us(s,e)}let d=s.replace(/\n+/g,`$& -${c}`);if(o){let f=m=>m.default&&m.tag!=="tag:yaml.org,2002:str"&&m.test?.test(d),{compat:p,tags:h}=e.doc.schema;if(h.some(f)||p?.some(f))return us(s,e)}return a?d:Io(d,c,gh,Zc(e,!1))}function ci(r,e,t,n){let{implicitKey:i,inFlow:s}=e,o=typeof r.value=="string"?r:Object.assign({},r,{value:String(r.value)}),{type:a}=r;a!==F.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=F.QUOTE_DOUBLE);let c=u=>{switch(u){case F.BLOCK_FOLDED:case F.BLOCK_LITERAL:return i||s?us(o.value,e):Qc(o,e,t,n);case F.QUOTE_DOUBLE:return Oo(o.value,e);case F.QUOTE_SINGLE:return bh(o.value,e);case F.PLAIN:return bN(o,e,t,n);default:return null}},l=c(a);if(l===null){let{defaultKeyType:u,defaultStringType:d}=e.options,f=i&&u||d;if(l=c(f),l===null)throw new Error(`Unsupported default string type ${f}`)}return l}function tl(r,e){let t=Object.assign({blockQuote:!0,commentString:P0,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 vN(r,e){if(e.tag){let i=r.filter(s=>s.tag===e.tag);if(i.length>0)return i.find(s=>s.format===e.format)??i[0]}let t,n;if(G(e)){n=e.value;let i=r.filter(s=>s.identify?.(n));if(i.length>1){let s=i.filter(o=>o.test);s.length>0&&(i=s)}t=i.find(s=>s.format===e.format)??i.find(s=>!s.format)}else n=e,t=r.find(i=>i.nodeClass&&n instanceof i.nodeClass);if(!t){let i=n?.constructor?.name??(n===null?"null":typeof n);throw new Error(`Tag not resolved for ${i} value`)}return t}function wN(r,e,{anchors:t,doc:n}){if(!n.directives)return"";let i=[],s=(G(r)||ae(r))&&r.anchor;s&&Gc(s)&&(t.add(s),i.push(`&${s}`));let o=r.tag??(e.default?null:e.tag);return o&&i.push(n.directives.tagString(o)),i.join(" ")}function Wr(r,e,t,n){if(te(r))return r.toString(e,t,n);if(er(r)){if(e.doc.directives)return r.toString(e);if(e.resolvedAliases?.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 i,s=ne(r)?r:e.doc.createNode(r,{onTagObj:c=>i=c});i??(i=vN(e.doc.schema.tags,s));let o=wN(s,i,e);o.length>0&&(e.indentAtStart=(e.indentAtStart??0)+o.length+1);let a=typeof i.stringify=="function"?i.stringify(s,e,t,n):G(s)?ci(s,e,t,n):s.toString(e,t,n);return o?G(s)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o} -${e.indent}${a}`:a}function M0({key:r,value:e},t,n,i){let{allNullValues:s,doc:o,indent:a,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:d}}=t,f=ne(r)&&r.comment||null;if(d){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(ae(r)||!ne(r)&&typeof r=="object"){let k="With simple keys, collection cannot be used as a key value";throw new Error(k)}}let p=!d&&(!r||f&&e==null&&!t.inFlow||ae(r)||(G(r)?r.type===F.BLOCK_FOLDED||r.type===F.BLOCK_LITERAL:typeof r=="object"));t=Object.assign({},t,{allNullValues:!1,implicitKey:!p&&(d||!s),indent:a+c});let h=!1,m=!1,y=Wr(r,t,()=>h=!0,()=>m=!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 h&&n&&n(),y===""?"?":p?`? ${y}`:y}else if(s&&!d||e==null&&p)return y=`? ${y}`,f&&!h?y+=kr(y,t.indent,l(f)):m&&i&&i(),y;h&&(f=null),p?(f&&(y+=kr(y,t.indent,l(f))),y=`? ${y} -${a}:`):(y=`${y}:`,f&&(y+=kr(y,t.indent,l(f))));let g,b,v;ne(e)?(g=!!e.spaceBefore,b=e.commentBefore,v=e.comment):(g=!1,b=null,v=null,e&&typeof e=="object"&&(e=o.createNode(e))),t.implicitKey=!1,!p&&!f&&G(e)&&(t.indentAtStart=y.length+1),m=!1,!u&&c.length>=2&&!t.inFlow&&!p&&rr(e)&&!e.flow&&!e.tag&&!e.anchor&&(t.indent=t.indent.substring(2));let S=!1,_=Wr(e,t,()=>S=!0,()=>m=!0),E=" ";if(f||g||b){if(E=g?` +${c}`);if(o){let f=h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(d),{compat:p,tags:m}=e.doc.schema;if(m.some(f)||p?.some(f))return us(s,e)}return a?d:Io(d,c,yh,Zc(e,!1))}function ci(r,e,t,n){let{implicitKey:i,inFlow:s}=e,o=typeof r.value=="string"?r:Object.assign({},r,{value:String(r.value)}),{type:a}=r;a!==F.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=F.QUOTE_DOUBLE);let c=u=>{switch(u){case F.BLOCK_FOLDED:case F.BLOCK_LITERAL:return i||s?us(o.value,e):Qc(o,e,t,n);case F.QUOTE_DOUBLE:return Oo(o.value,e);case F.QUOTE_SINGLE:return gh(o.value,e);case F.PLAIN:return vN(o,e,t,n);default:return null}},l=c(a);if(l===null){let{defaultKeyType:u,defaultStringType:d}=e.options,f=i&&u||d;if(l=c(f),l===null)throw new Error(`Unsupported default string type ${f}`)}return l}function tl(r,e){let t=Object.assign({blockQuote:!0,commentString:P0,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 wN(r,e){if(e.tag){let i=r.filter(s=>s.tag===e.tag);if(i.length>0)return i.find(s=>s.format===e.format)??i[0]}let t,n;if(G(e)){n=e.value;let i=r.filter(s=>s.identify?.(n));if(i.length>1){let s=i.filter(o=>o.test);s.length>0&&(i=s)}t=i.find(s=>s.format===e.format)??i.find(s=>!s.format)}else n=e,t=r.find(i=>i.nodeClass&&n instanceof i.nodeClass);if(!t){let i=n?.constructor?.name??(n===null?"null":typeof n);throw new Error(`Tag not resolved for ${i} value`)}return t}function _N(r,e,{anchors:t,doc:n}){if(!n.directives)return"";let i=[],s=(G(r)||ae(r))&&r.anchor;s&&Gc(s)&&(t.add(s),i.push(`&${s}`));let o=r.tag??(e.default?null:e.tag);return o&&i.push(n.directives.tagString(o)),i.join(" ")}function Wr(r,e,t,n){if(te(r))return r.toString(e,t,n);if(er(r)){if(e.doc.directives)return r.toString(e);if(e.resolvedAliases?.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 i,s=ne(r)?r:e.doc.createNode(r,{onTagObj:c=>i=c});i??(i=wN(e.doc.schema.tags,s));let o=_N(s,i,e);o.length>0&&(e.indentAtStart=(e.indentAtStart??0)+o.length+1);let a=typeof i.stringify=="function"?i.stringify(s,e,t,n):G(s)?ci(s,e,t,n):s.toString(e,t,n);return o?G(s)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o} +${e.indent}${a}`:a}function M0({key:r,value:e},t,n,i){let{allNullValues:s,doc:o,indent:a,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:d}}=t,f=ne(r)&&r.comment||null;if(d){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(ae(r)||!ne(r)&&typeof r=="object"){let k="With simple keys, collection cannot be used as a key value";throw new Error(k)}}let p=!d&&(!r||f&&e==null&&!t.inFlow||ae(r)||(G(r)?r.type===F.BLOCK_FOLDED||r.type===F.BLOCK_LITERAL:typeof r=="object"));t=Object.assign({},t,{allNullValues:!1,implicitKey:!p&&(d||!s),indent:a+c});let m=!1,h=!1,y=Wr(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&&n&&n(),y===""?"?":p?`? ${y}`:y}else if(s&&!d||e==null&&p)return y=`? ${y}`,f&&!m?y+=kr(y,t.indent,l(f)):h&&i&&i(),y;m&&(f=null),p?(f&&(y+=kr(y,t.indent,l(f))),y=`? ${y} +${a}:`):(y=`${y}:`,f&&(y+=kr(y,t.indent,l(f))));let g,b,v;ne(e)?(g=!!e.spaceBefore,b=e.commentBefore,v=e.comment):(g=!1,b=null,v=null,e&&typeof e=="object"&&(e=o.createNode(e))),t.implicitKey=!1,!p&&!f&&G(e)&&(t.indentAtStart=y.length+1),h=!1,!u&&c.length>=2&&!t.inFlow&&!p&&rr(e)&&!e.flow&&!e.tag&&!e.anchor&&(t.indent=t.indent.substring(2));let S=!1,_=Wr(e,t,()=>S=!0,()=>h=!0),E=" ";if(f||g||b){if(E=g?` `:"",b){let k=l(b);E+=` ${Vt(k,t.indent)}`}_===""&&!t.inFlow?E===` `&&v&&(E=` @@ -69,34 +69,34 @@ ${Vt(k,t.indent)}`}_===""&&!t.inFlow?E===` ${t.indent}`}else if(!p&&ae(e)){let k=_[0],$=_.indexOf(` `),M=$!==-1,x=t.inFlow??e.flow??e.items.length===0;if(M||!x){let q=!1;if(M&&(k==="&"||k==="!")){let T=_.indexOf(" ");k==="&"&&T!==-1&&T<$&&_[T+1]==="!"&&(T=_.indexOf(" ",T+1)),(T===-1||$r===nl||typeof r=="symbol"&&r.description===nl,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new F(Symbol(nl)),{addToJSMap:_h}),stringify:()=>nl},T0=(r,e)=>(nr.identify(e)||G(e)&&(!e.type||e.type===F.PLAIN)&&nr.identify(e.value))&&r?.doc.schema.tags.some(t=>t.tag===nr.tag&&t.default);function _h(r,e,t){let n=R0(r,t);if(rr(n))for(let i of n.items)wh(r,e,i);else if(Array.isArray(n))for(let i of n)wh(r,e,i);else wh(r,e,n)}function wh(r,e,t){let n=R0(r,t);if(!tr(n))throw new Error("Merge sources must be maps or map aliases");let i=n.toJSON(null,r,Map);for(let[s,o]of i)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 R0(r,e){return r&&er(e)?e.resolve(r.doc,r):e}function il(r,e,{key:t,value:n}){if(ne(t)&&t.addToJSMap)t.addToJSMap(r,e,n);else if(T0(r,t))_h(r,e,n);else{let i=Re(t,"",r);if(e instanceof Map)e.set(i,Re(n,i,r));else if(e instanceof Set)e.add(i);else{let s=_N(t,i,r),o=Re(n,s,r);s in e?Object.defineProperty(e,s,{value:o,writable:!0,enumerable:!0,configurable:!0}):e[s]=o}}return e}function _N(r,e,t){if(e===null)return"";if(typeof e!="object")return String(e);if(ne(r)&&t?.doc){let n=tl(t.doc,{});n.anchors=new Set;for(let s of t.anchors.keys())n.anchors.add(s.anchor);n.inFlow=!0,n.inStringifyKey=!0;let i=r.toString(n);if(!t.mapKeyWarned){let s=JSON.stringify(i);s.length>40&&(s=s.substring(0,36)+'..."'),rl(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 i}return JSON.stringify(e)}function fs(r,e,t){let n=Kr(r,void 0,t),i=Kr(e,void 0,t);return new _e(n,i)}var _e=class r{constructor(e,t=null){Object.defineProperty(this,nt,{value:hh}),this.key=e,this.value=t}clone(e){let{key:t,value:n}=this;return ne(t)&&(t=t.clone(e)),ne(n)&&(n=n.clone(e)),new r(t,n)}toJSON(e,t){let n=t?.mapAsMap?new Map:{};return il(t,n,this)}toString(e,t,n){return e?.doc?M0(this,e,t,n):JSON.stringify(this)}};function ol(r,e,t){return(e.inFlow??r.flow?$N:SN)(r,e,t)}function SN({comment:r,items:e},t,{blockItemPrefix:n,flowChars:i,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 h=0;hy=null,()=>d=!0);y&&(g+=kr(g,s,l(y))),d&&y&&(d=!1),f.push(n+g)}let p;if(f.length===0)p=i.start+i.end;else{p=f[0];for(let h=1;hr===nl||typeof r=="symbol"&&r.description===nl,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new F(Symbol(nl)),{addToJSMap:wh}),stringify:()=>nl},T0=(r,e)=>(nr.identify(e)||G(e)&&(!e.type||e.type===F.PLAIN)&&nr.identify(e.value))&&r?.doc.schema.tags.some(t=>t.tag===nr.tag&&t.default);function wh(r,e,t){let n=R0(r,t);if(rr(n))for(let i of n.items)vh(r,e,i);else if(Array.isArray(n))for(let i of n)vh(r,e,i);else vh(r,e,n)}function vh(r,e,t){let n=R0(r,t);if(!tr(n))throw new Error("Merge sources must be maps or map aliases");let i=n.toJSON(null,r,Map);for(let[s,o]of i)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 R0(r,e){return r&&er(e)?e.resolve(r.doc,r):e}function il(r,e,{key:t,value:n}){if(ne(t)&&t.addToJSMap)t.addToJSMap(r,e,n);else if(T0(r,t))wh(r,e,n);else{let i=Re(t,"",r);if(e instanceof Map)e.set(i,Re(n,i,r));else if(e instanceof Set)e.add(i);else{let s=SN(t,i,r),o=Re(n,s,r);s in e?Object.defineProperty(e,s,{value:o,writable:!0,enumerable:!0,configurable:!0}):e[s]=o}}return e}function SN(r,e,t){if(e===null)return"";if(typeof e!="object")return String(e);if(ne(r)&&t?.doc){let n=tl(t.doc,{});n.anchors=new Set;for(let s of t.anchors.keys())n.anchors.add(s.anchor);n.inFlow=!0,n.inStringifyKey=!0;let i=r.toString(n);if(!t.mapKeyWarned){let s=JSON.stringify(i);s.length>40&&(s=s.substring(0,36)+'..."'),rl(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 i}return JSON.stringify(e)}function fs(r,e,t){let n=Kr(r,void 0,t),i=Kr(e,void 0,t);return new _e(n,i)}var _e=class r{constructor(e,t=null){Object.defineProperty(this,nt,{value:ph}),this.key=e,this.value=t}clone(e){let{key:t,value:n}=this;return ne(t)&&(t=t.clone(e)),ne(n)&&(n=n.clone(e)),new r(t,n)}toJSON(e,t){let n=t?.mapAsMap?new Map:{};return il(t,n,this)}toString(e,t,n){return e?.doc?M0(this,e,t,n):JSON.stringify(this)}};function ol(r,e,t){return(e.inFlow??r.flow?xN:$N)(r,e,t)}function $N({comment:r,items:e},t,{blockItemPrefix:n,flowChars:i,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&&(g+=kr(g,s,l(y))),d&&y&&(d=!1),f.push(n+g)}let p;if(f.length===0)p=i.start+i.end;else{p=f[0];for(let m=1;my=null);l||(l=d.length>u||g.includes(` -`)),h0&&(l||(l=d.reduce((b,v)=>b+v.length+2,2)+(g.length+2)>e.options.lineWidth)),l&&(g+=",")),y&&(g+=kr(g,n,a(y))),d.push(g),u=d.length}let{start:f,end:p}=t;if(d.length===0)return f+p;if(!l){let h=d.reduce((m,y)=>m+y.length+2,2);l=e.options.lineWidth>0&&h>e.options.lineWidth}if(l){let h=f;for(let m of d)h+=m?` -${s}${i}${m}`:` -`;return`${h} -${i}${p}`}else return`${f}${o}${d.join(" ")}${o}${p}`}function sl({indent:r,options:{commentString:e}},t,n,i){if(n&&i&&(n=n.replace(/^\n+/,"")),n){let s=Vt(e(n),r);t.push(s.trimStart())}}function $n(r,e){let t=G(e)?e.value:e;for(let n of r)if(te(n)&&(n.key===e||n.key===t||G(n.key)&&n.key.value===t))return n}var Ee=class extends ls{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(Zt,e),this.items=[]}static from(e,t,n){let{keepUndefined:i,replacer:s}=n,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||i)&&o.items.push(fs(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){let n;te(e)?n=e:!e||typeof e!="object"||!("key"in e)?n=new _e(e,e?.value):n=new _e(e.key,e.value);let i=$n(this.items,n.key),s=this.schema?.sortMapEntries;if(i){if(!t)throw new Error(`Key ${n.key} already set`);G(i.value)&&Yc(n.value)?i.value.value=n.value:i.value=n.value}else if(s){let o=this.items.findIndex(a=>s(n,a)<0);o===-1?this.items.push(n):this.items.splice(o,0,n)}else this.items.push(n)}delete(e){let t=$n(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){let i=$n(this.items,e)?.value;return(!t&&G(i)?i.value:i)??void 0}has(e){return!!$n(this.items,e)}set(e,t){this.add(new _e(e,t),!0)}toJSON(e,t,n){let i=n?new n:t?.mapAsMap?new Map:{};t?.onCreate&&t.onCreate(i);for(let s of this.items)il(t,i,s);return i}toString(e,t,n){if(!e)return JSON.stringify(this);for(let i of this.items)if(!te(i))throw new Error(`Map items must all be pairs; found ${JSON.stringify(i)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),ol(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:n,onComment:t})}};var ir={collection:"map",default:!0,nodeClass:Ee,tag:"tag:yaml.org,2002:map",resolve(r,e){return tr(r)||e("Expected a mapping for this tag"),r},createNode:(r,e,t)=>Ee.from(r,e,t)};var We=class extends ls{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(Hr,e),this.items=[]}add(e){this.items.push(e)}delete(e){let t=al(e);return typeof t!="number"?!1:this.items.splice(t,1).length>0}get(e,t){let n=al(e);if(typeof n!="number")return;let i=this.items[n];return!t&&G(i)?i.value:i}has(e){let t=al(e);return typeof t=="number"&&t=0?e:null}var sr={collection:"seq",default:!0,nodeClass:We,tag:"tag:yaml.org,2002:seq",resolve(r,e){return rr(r)||e("Expected a sequence for this tag"),r},createNode:(r,e,t)=>We.from(r,e,t)};var xn={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),ci(r,e,t,n)}};var li={identify:r=>r==null,createNode:()=>new F(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new F(null),stringify:({source:r},e)=>typeof r=="string"&&li.test.test(r)?r:e.options.nullStr};var Do={identify:r=>typeof r=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:r=>new F(r[0]==="t"||r[0]==="T"),stringify({source:r,value:e},t){if(r&&Do.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 Ge({format:r,minFractionDigits:e,tag:t,value:n}){if(typeof n=="bigint")return String(n);let i=typeof n=="number"?n:Number(n);if(!isFinite(i))return isNaN(i)?".nan":i<0?"-.inf":".inf";let s=Object.is(n,-0)?"-0":JSON.stringify(n);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 cl={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:Ge},ll={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():Ge(r)}},dl={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 F(parseFloat(r)),t=r.indexOf(".");return t!==-1&&r[r.length-1]==="0"&&(e.minFractionDigits=r.length-t-1),e},stringify:Ge};var ul=r=>typeof r=="bigint"||Number.isInteger(r),Sh=(r,e,t,{intAsBigInt:n})=>n?BigInt(r):parseInt(r.substring(e),t);function I0(r,e,t){let{value:n}=r;return ul(n)&&n>=0?t+n.toString(e):Ge(r)}var fl={identify:r=>ul(r)&&r>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(r,e,t)=>Sh(r,2,8,t),stringify:r=>I0(r,8,"0o")},pl={identify:ul,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(r,e,t)=>Sh(r,0,10,t),stringify:Ge},hl={identify:r=>ul(r)&&r>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(r,e,t)=>Sh(r,2,16,t),stringify:r=>I0(r,16,"0x")};var O0=[ir,sr,xn,li,Do,fl,pl,hl,cl,ll,dl];function D0(r){return typeof r=="bigint"||Number.isInteger(r)}var ml=({value:r})=>JSON.stringify(r),xN=[{identify:r=>typeof r=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:r=>r,stringify:ml},{identify:r=>r==null,createNode:()=>new F(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:ml},{identify:r=>typeof r=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:r=>r==="true",stringify:ml},{identify:D0,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})=>D0(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:ml}],EN={default:!0,tag:"",test:/^/,resolve(r,e){return e(`Unresolved plain scalar ${JSON.stringify(r)}`),r}},N0=[ir,sr].concat(xN,EN);var No={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 i=0;i1&&e("Each pair must have its own sequence indicator");let i=n.items[0]||new _e(new F(null));if(n.commentBefore&&(i.key.commentBefore=i.key.commentBefore?`${n.commentBefore} +`+Vt(l(r),c),a&&a()):d&&o&&o(),p}function xN({items:r},e,{flowChars:t,itemIndent:n}){let{indent:i,indentStep:s,flowCollectionPadding:o,options:{commentString:a}}=e;n+=s;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||g.includes(` +`)),m0&&(l||(l=d.reduce((b,v)=>b+v.length+2,2)+(g.length+2)>e.options.lineWidth)),l&&(g+=",")),y&&(g+=kr(g,n,a(y))),d.push(g),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}${i}${h}`:` +`;return`${m} +${i}${p}`}else return`${f}${o}${d.join(" ")}${o}${p}`}function sl({indent:r,options:{commentString:e}},t,n,i){if(n&&i&&(n=n.replace(/^\n+/,"")),n){let s=Vt(e(n),r);t.push(s.trimStart())}}function $n(r,e){let t=G(e)?e.value:e;for(let n of r)if(te(n)&&(n.key===e||n.key===t||G(n.key)&&n.key.value===t))return n}var Ee=class extends ls{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(Zt,e),this.items=[]}static from(e,t,n){let{keepUndefined:i,replacer:s}=n,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||i)&&o.items.push(fs(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){let n;te(e)?n=e:!e||typeof e!="object"||!("key"in e)?n=new _e(e,e?.value):n=new _e(e.key,e.value);let i=$n(this.items,n.key),s=this.schema?.sortMapEntries;if(i){if(!t)throw new Error(`Key ${n.key} already set`);G(i.value)&&Yc(n.value)?i.value.value=n.value:i.value=n.value}else if(s){let o=this.items.findIndex(a=>s(n,a)<0);o===-1?this.items.push(n):this.items.splice(o,0,n)}else this.items.push(n)}delete(e){let t=$n(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){let i=$n(this.items,e)?.value;return(!t&&G(i)?i.value:i)??void 0}has(e){return!!$n(this.items,e)}set(e,t){this.add(new _e(e,t),!0)}toJSON(e,t,n){let i=n?new n:t?.mapAsMap?new Map:{};t?.onCreate&&t.onCreate(i);for(let s of this.items)il(t,i,s);return i}toString(e,t,n){if(!e)return JSON.stringify(this);for(let i of this.items)if(!te(i))throw new Error(`Map items must all be pairs; found ${JSON.stringify(i)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),ol(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:n,onComment:t})}};var ir={collection:"map",default:!0,nodeClass:Ee,tag:"tag:yaml.org,2002:map",resolve(r,e){return tr(r)||e("Expected a mapping for this tag"),r},createNode:(r,e,t)=>Ee.from(r,e,t)};var We=class extends ls{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(Hr,e),this.items=[]}add(e){this.items.push(e)}delete(e){let t=al(e);return typeof t!="number"?!1:this.items.splice(t,1).length>0}get(e,t){let n=al(e);if(typeof n!="number")return;let i=this.items[n];return!t&&G(i)?i.value:i}has(e){let t=al(e);return typeof t=="number"&&t=0?e:null}var sr={collection:"seq",default:!0,nodeClass:We,tag:"tag:yaml.org,2002:seq",resolve(r,e){return rr(r)||e("Expected a sequence for this tag"),r},createNode:(r,e,t)=>We.from(r,e,t)};var xn={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),ci(r,e,t,n)}};var li={identify:r=>r==null,createNode:()=>new F(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new F(null),stringify:({source:r},e)=>typeof r=="string"&&li.test.test(r)?r:e.options.nullStr};var Do={identify:r=>typeof r=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:r=>new F(r[0]==="t"||r[0]==="T"),stringify({source:r,value:e},t){if(r&&Do.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 Ge({format:r,minFractionDigits:e,tag:t,value:n}){if(typeof n=="bigint")return String(n);let i=typeof n=="number"?n:Number(n);if(!isFinite(i))return isNaN(i)?".nan":i<0?"-.inf":".inf";let s=Object.is(n,-0)?"-0":JSON.stringify(n);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 cl={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:Ge},ll={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():Ge(r)}},dl={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 F(parseFloat(r)),t=r.indexOf(".");return t!==-1&&r[r.length-1]==="0"&&(e.minFractionDigits=r.length-t-1),e},stringify:Ge};var ul=r=>typeof r=="bigint"||Number.isInteger(r),_h=(r,e,t,{intAsBigInt:n})=>n?BigInt(r):parseInt(r.substring(e),t);function I0(r,e,t){let{value:n}=r;return ul(n)&&n>=0?t+n.toString(e):Ge(r)}var fl={identify:r=>ul(r)&&r>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(r,e,t)=>_h(r,2,8,t),stringify:r=>I0(r,8,"0o")},pl={identify:ul,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(r,e,t)=>_h(r,0,10,t),stringify:Ge},hl={identify:r=>ul(r)&&r>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(r,e,t)=>_h(r,2,16,t),stringify:r=>I0(r,16,"0x")};var O0=[ir,sr,xn,li,Do,fl,pl,hl,cl,ll,dl];function D0(r){return typeof r=="bigint"||Number.isInteger(r)}var ml=({value:r})=>JSON.stringify(r),EN=[{identify:r=>typeof r=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:r=>r,stringify:ml},{identify:r=>r==null,createNode:()=>new F(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:ml},{identify:r=>typeof r=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:r=>r==="true",stringify:ml},{identify:D0,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})=>D0(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:ml}],AN={default:!0,tag:"",test:/^/,resolve(r,e){return e(`Unresolved plain scalar ${JSON.stringify(r)}`),r}},N0=[ir,sr].concat(EN,AN);var No={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 i=0;i1&&e("Each pair must have its own sequence indicator");let i=n.items[0]||new _e(new F(null));if(n.commentBefore&&(i.key.commentBefore=i.key.commentBefore?`${n.commentBefore} ${i.key.commentBefore}`:n.commentBefore),n.comment){let s=i.value??i.key;s.comment=s.comment?`${n.comment} -${s.comment}`:n.comment}n=i}r.items[t]=te(n)?n:new _e(n)}}else e("Expected a sequence for this tag");return r}function xh(r,e,t){let{replacer:n}=t,i=new We(r);i.tag="tag:yaml.org,2002:pairs";let s=0;if(e&&Symbol.iterator in Object(e))for(let o of e){typeof n=="function"&&(o=n.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;i.items.push(fs(a,c,t))}return i}var Lo={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:$h,createNode:xh};var ps=class r extends We{constructor(){super(),this.add=Ee.prototype.add.bind(this),this.delete=Ee.prototype.delete.bind(this),this.get=Ee.prototype.get.bind(this),this.has=Ee.prototype.has.bind(this),this.set=Ee.prototype.set.bind(this),this.tag=r.tag}toJSON(e,t){if(!t)return super.toJSON(e);let n=new Map;t?.onCreate&&t.onCreate(n);for(let i of this.items){let s,o;if(te(i)?(s=Re(i.key,"",t),o=Re(i.value,s,t)):s=Re(i,"",t),n.has(s))throw new Error("Ordered maps must not include duplicate keys");n.set(s,o)}return n}static from(e,t,n){let i=xh(e,t,n),s=new this;return s.items=i.items,s}};ps.tag="tag:yaml.org,2002:omap";var Fo={collection:"seq",identify:r=>r instanceof Map,nodeClass:ps,default:!1,tag:"tag:yaml.org,2002:omap",resolve(r,e){let t=$h(r,e),n=[];for(let{key:i}of t.items)G(i)&&(n.includes(i.value)?e(`Ordered maps must not include duplicate keys: ${i.value}`):n.push(i.value));return Object.assign(new ps,t)},createNode:(r,e,t)=>ps.from(r,e,t)};function L0({value:r,source:e},t){return e&&(r?Eh:Ah).test.test(e)?e:r?t.options.trueStr:t.options.falseStr}var Eh={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 F(!0),stringify:L0},Ah={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 F(!1),stringify:L0};var F0={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:Ge},j0={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():Ge(r)}},q0={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 F(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:Ge};var jo=r=>typeof r=="bigint"||Number.isInteger(r);function yl(r,e,t,{intAsBigInt:n}){let i=r[0];if((i==="-"||i==="+")&&(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 i==="-"?BigInt(-1)*o:o}let s=parseInt(r,t);return i==="-"?-1*s:s}function kh(r,e,t){let{value:n}=r;if(jo(n)){let i=n.toString(e);return n<0?"-"+t+i.substr(1):t+i}return Ge(r)}var B0={identify:jo,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(r,e,t)=>yl(r,2,2,t),stringify:r=>kh(r,2,"0b")},U0={identify:jo,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(r,e,t)=>yl(r,1,8,t),stringify:r=>kh(r,8,"0")},V0={identify:jo,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(r,e,t)=>yl(r,0,10,t),stringify:Ge},H0={identify:jo,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(r,e,t)=>yl(r,2,16,t),stringify:r=>kh(r,16,"0x")};var hs=class r extends Ee{constructor(e){super(e),this.tag=r.tag}add(e){let t;te(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),$n(this.items,t.key)||this.items.push(t)}get(e,t){let n=$n(this.items,e);return!t&&te(n)?G(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=$n(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new _e(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:i}=n,s=new this(e);if(t&&Symbol.iterator in Object(t))for(let o of t)typeof i=="function"&&(o=i.call(t,o,o)),s.items.push(fs(o,null,n));return s}};hs.tag="tag:yaml.org,2002:set";var qo={collection:"map",identify:r=>r instanceof Set,nodeClass:hs,default:!1,tag:"tag:yaml.org,2002:set",createNode:(r,e,t)=>hs.from(r,e,t),resolve(r,e){if(tr(r)){if(r.hasAllNullValues(!0))return Object.assign(new hs,r);e("Set items must all have null values")}else e("Expected a mapping for this tag");return r}};function Ph(r,e){let t=r[0],n=t==="-"||t==="+"?r.substring(1):r,i=o=>e?BigInt(o):Number(o),s=n.replace(/_/g,"").split(":").reduce((o,a)=>o*i(60)+i(a),i(0));return t==="-"?i(-1)*s:s}function z0(r){let{value:e}=r,t=o=>o;if(typeof e=="bigint")t=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return Ge(r);let n="";e<0&&(n="-",e*=t(-1));let i=t(60),s=[e%i];return e<60?s.unshift(0):(e=(e-s[0])/i,s.unshift(e%i),e>=60&&(e=(e-s[0])/i,s.unshift(e))),n+s.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var gl={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})=>Ph(r,t),stringify:z0},bl={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=>Ph(r,!1),stringify:z0},ms={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(ms.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,t,n,i,s,o,a]=e.map(Number),c=e[7]?Number((e[7]+"00").substr(1,3)):0,l=Date.UTC(t,n-1,i,s||0,o||0,a||0,c),u=e[8];if(u&&u!=="Z"){let d=Ph(u,!1);Math.abs(d)<30&&(d*=60),l-=6e4*d}return new Date(l)},stringify:({value:r})=>r?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};var Ch=[ir,sr,xn,li,Eh,Ah,B0,U0,V0,H0,F0,j0,q0,No,nr,Fo,Lo,qo,gl,bl,ms];var K0=new Map([["core",O0],["failsafe",[ir,sr,xn]],["json",N0],["yaml11",Ch],["yaml-1.1",Ch]]),W0={binary:No,bool:Do,float:dl,floatExp:ll,floatNaN:cl,floatTime:bl,int:pl,intHex:hl,intOct:fl,intTime:gl,map:ir,merge:nr,null:li,omap:Fo,pairs:Lo,seq:sr,set:qo,timestamp:ms},G0={"tag:yaml.org,2002:binary":No,"tag:yaml.org,2002:merge":nr,"tag:yaml.org,2002:omap":Fo,"tag:yaml.org,2002:pairs":Lo,"tag:yaml.org,2002:set":qo,"tag:yaml.org,2002:timestamp":ms};function vl(r,e,t){let n=K0.get(e);if(n&&!r)return t&&!n.includes(nr)?n.concat(nr):n.slice();let i=n;if(!i)if(Array.isArray(r))i=[];else{let s=Array.from(K0.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)i=i.concat(s);else typeof r=="function"&&(i=r(i.slice()));return t&&(i=i.concat(nr)),i.reduce((s,o)=>{let a=typeof o=="string"?W0[o]:o;if(!a){let c=JSON.stringify(o),l=Object.keys(W0).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 AN=(r,e)=>r.keye.key?1:0,Bo=class r{constructor({compat:e,customTags:t,merge:n,resolveKnownTags:i,schema:s,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?vl(e,"compat"):e?vl(null,e):null,this.name=typeof s=="string"&&s||"core",this.knownTags=i?G0:{},this.tags=vl(t,this.name,n),this.toStringOptions=a??null,Object.defineProperty(this,Zt,{value:ir}),Object.defineProperty(this,At,{value:xn}),Object.defineProperty(this,Hr,{value:sr}),this.sortMapEntries=typeof o=="function"?o:o===!0?AN:null}clone(){let e=Object.create(r.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};function J0(r,e){let t=[],n=e.directives===!0;if(e.directives!==!1&&r.directives){let c=r.directives.toString(r);c?(t.push(c),n=!0):r.directives.docStart&&(n=!0)}n&&t.push("---");let i=tl(r,e),{commentString:s}=i.options;if(r.commentBefore){t.length!==1&&t.unshift("");let c=s(r.commentBefore);t.unshift(Vt(c,""))}let o=!1,a=null;if(r.contents){if(ne(r.contents)){if(r.contents.spaceBefore&&n&&t.push(""),r.contents.commentBefore){let u=s(r.contents.commentBefore);t.push(Vt(u,""))}i.forceBlockIndent=!!r.comment,a=r.contents.comment}let c=a?void 0:()=>o=!0,l=Wr(r.contents,i,()=>a=null,c);a&&(l+=kr(l,"",s(a))),(l[0]==="|"||l[0]===">")&&t[t.length-1]==="---"?t[t.length-1]=`--- ${l}`:t.push(l)}else t.push(Wr(r.contents,i));if(r.directives?.docEnd)if(r.comment){let c=s(r.comment);c.includes(` +${s.comment}`:n.comment}n=i}r.items[t]=te(n)?n:new _e(n)}}else e("Expected a sequence for this tag");return r}function $h(r,e,t){let{replacer:n}=t,i=new We(r);i.tag="tag:yaml.org,2002:pairs";let s=0;if(e&&Symbol.iterator in Object(e))for(let o of e){typeof n=="function"&&(o=n.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;i.items.push(fs(a,c,t))}return i}var Lo={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Sh,createNode:$h};var ps=class r extends We{constructor(){super(),this.add=Ee.prototype.add.bind(this),this.delete=Ee.prototype.delete.bind(this),this.get=Ee.prototype.get.bind(this),this.has=Ee.prototype.has.bind(this),this.set=Ee.prototype.set.bind(this),this.tag=r.tag}toJSON(e,t){if(!t)return super.toJSON(e);let n=new Map;t?.onCreate&&t.onCreate(n);for(let i of this.items){let s,o;if(te(i)?(s=Re(i.key,"",t),o=Re(i.value,s,t)):s=Re(i,"",t),n.has(s))throw new Error("Ordered maps must not include duplicate keys");n.set(s,o)}return n}static from(e,t,n){let i=$h(e,t,n),s=new this;return s.items=i.items,s}};ps.tag="tag:yaml.org,2002:omap";var Fo={collection:"seq",identify:r=>r instanceof Map,nodeClass:ps,default:!1,tag:"tag:yaml.org,2002:omap",resolve(r,e){let t=Sh(r,e),n=[];for(let{key:i}of t.items)G(i)&&(n.includes(i.value)?e(`Ordered maps must not include duplicate keys: ${i.value}`):n.push(i.value));return Object.assign(new ps,t)},createNode:(r,e,t)=>ps.from(r,e,t)};function L0({value:r,source:e},t){return e&&(r?xh:Eh).test.test(e)?e:r?t.options.trueStr:t.options.falseStr}var xh={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 F(!0),stringify:L0},Eh={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 F(!1),stringify:L0};var F0={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:Ge},j0={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():Ge(r)}},q0={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 F(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:Ge};var jo=r=>typeof r=="bigint"||Number.isInteger(r);function yl(r,e,t,{intAsBigInt:n}){let i=r[0];if((i==="-"||i==="+")&&(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 i==="-"?BigInt(-1)*o:o}let s=parseInt(r,t);return i==="-"?-1*s:s}function Ah(r,e,t){let{value:n}=r;if(jo(n)){let i=n.toString(e);return n<0?"-"+t+i.substr(1):t+i}return Ge(r)}var B0={identify:jo,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(r,e,t)=>yl(r,2,2,t),stringify:r=>Ah(r,2,"0b")},U0={identify:jo,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(r,e,t)=>yl(r,1,8,t),stringify:r=>Ah(r,8,"0")},V0={identify:jo,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(r,e,t)=>yl(r,0,10,t),stringify:Ge},H0={identify:jo,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(r,e,t)=>yl(r,2,16,t),stringify:r=>Ah(r,16,"0x")};var hs=class r extends Ee{constructor(e){super(e),this.tag=r.tag}add(e){let t;te(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),$n(this.items,t.key)||this.items.push(t)}get(e,t){let n=$n(this.items,e);return!t&&te(n)?G(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=$n(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new _e(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:i}=n,s=new this(e);if(t&&Symbol.iterator in Object(t))for(let o of t)typeof i=="function"&&(o=i.call(t,o,o)),s.items.push(fs(o,null,n));return s}};hs.tag="tag:yaml.org,2002:set";var qo={collection:"map",identify:r=>r instanceof Set,nodeClass:hs,default:!1,tag:"tag:yaml.org,2002:set",createNode:(r,e,t)=>hs.from(r,e,t),resolve(r,e){if(tr(r)){if(r.hasAllNullValues(!0))return Object.assign(new hs,r);e("Set items must all have null values")}else e("Expected a mapping for this tag");return r}};function kh(r,e){let t=r[0],n=t==="-"||t==="+"?r.substring(1):r,i=o=>e?BigInt(o):Number(o),s=n.replace(/_/g,"").split(":").reduce((o,a)=>o*i(60)+i(a),i(0));return t==="-"?i(-1)*s:s}function z0(r){let{value:e}=r,t=o=>o;if(typeof e=="bigint")t=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return Ge(r);let n="";e<0&&(n="-",e*=t(-1));let i=t(60),s=[e%i];return e<60?s.unshift(0):(e=(e-s[0])/i,s.unshift(e%i),e>=60&&(e=(e-s[0])/i,s.unshift(e))),n+s.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var gl={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})=>kh(r,t),stringify:z0},bl={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=>kh(r,!1),stringify:z0},ms={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(ms.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,t,n,i,s,o,a]=e.map(Number),c=e[7]?Number((e[7]+"00").substr(1,3)):0,l=Date.UTC(t,n-1,i,s||0,o||0,a||0,c),u=e[8];if(u&&u!=="Z"){let d=kh(u,!1);Math.abs(d)<30&&(d*=60),l-=6e4*d}return new Date(l)},stringify:({value:r})=>r?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};var Ph=[ir,sr,xn,li,xh,Eh,B0,U0,V0,H0,F0,j0,q0,No,nr,Fo,Lo,qo,gl,bl,ms];var K0=new Map([["core",O0],["failsafe",[ir,sr,xn]],["json",N0],["yaml11",Ph],["yaml-1.1",Ph]]),W0={binary:No,bool:Do,float:dl,floatExp:ll,floatNaN:cl,floatTime:bl,int:pl,intHex:hl,intOct:fl,intTime:gl,map:ir,merge:nr,null:li,omap:Fo,pairs:Lo,seq:sr,set:qo,timestamp:ms},G0={"tag:yaml.org,2002:binary":No,"tag:yaml.org,2002:merge":nr,"tag:yaml.org,2002:omap":Fo,"tag:yaml.org,2002:pairs":Lo,"tag:yaml.org,2002:set":qo,"tag:yaml.org,2002:timestamp":ms};function vl(r,e,t){let n=K0.get(e);if(n&&!r)return t&&!n.includes(nr)?n.concat(nr):n.slice();let i=n;if(!i)if(Array.isArray(r))i=[];else{let s=Array.from(K0.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)i=i.concat(s);else typeof r=="function"&&(i=r(i.slice()));return t&&(i=i.concat(nr)),i.reduce((s,o)=>{let a=typeof o=="string"?W0[o]:o;if(!a){let c=JSON.stringify(o),l=Object.keys(W0).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 kN=(r,e)=>r.keye.key?1:0,Bo=class r{constructor({compat:e,customTags:t,merge:n,resolveKnownTags:i,schema:s,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?vl(e,"compat"):e?vl(null,e):null,this.name=typeof s=="string"&&s||"core",this.knownTags=i?G0:{},this.tags=vl(t,this.name,n),this.toStringOptions=a??null,Object.defineProperty(this,Zt,{value:ir}),Object.defineProperty(this,At,{value:xn}),Object.defineProperty(this,Hr,{value:sr}),this.sortMapEntries=typeof o=="function"?o:o===!0?kN:null}clone(){let e=Object.create(r.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};function J0(r,e){let t=[],n=e.directives===!0;if(e.directives!==!1&&r.directives){let c=r.directives.toString(r);c?(t.push(c),n=!0):r.directives.docStart&&(n=!0)}n&&t.push("---");let i=tl(r,e),{commentString:s}=i.options;if(r.commentBefore){t.length!==1&&t.unshift("");let c=s(r.commentBefore);t.unshift(Vt(c,""))}let o=!1,a=null;if(r.contents){if(ne(r.contents)){if(r.contents.spaceBefore&&n&&t.push(""),r.contents.commentBefore){let u=s(r.contents.commentBefore);t.push(Vt(u,""))}i.forceBlockIndent=!!r.comment,a=r.contents.comment}let c=a?void 0:()=>o=!0,l=Wr(r.contents,i,()=>a=null,c);a&&(l+=kr(l,"",s(a))),(l[0]==="|"||l[0]===">")&&t[t.length-1]==="---"?t[t.length-1]=`--- ${l}`:t.push(l)}else t.push(Wr(r.contents,i));if(r.directives?.docEnd)if(r.comment){let c=s(r.comment);c.includes(` `)?(t.push("..."),t.push(Vt(c,""))):t.push(`... ${c}`)}else t.push("...");else{let c=r.comment;c&&o&&(c=c.replace(/^\n+/,"")),c&&((!o||a)&&t[t.length-1]!==""&&t.push(""),t.push(Vt(s(c),"")))}return t.join(` `)+` -`}var En=class r{constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,nt,{value:zc});let i=null;typeof t=="function"||Array.isArray(t)?i=t:n===void 0&&t&&(n=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"},n);this.options=s;let{version:o}=s;n?._directives?(this.directives=n._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new Ar({version:o}),this.setSchema(o,n),this.contents=e===void 0?null:this.createNode(e,i,n)}clone(){let e=Object.create(r.prototype,{[nt]:{value:zc}});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=ne(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){ys(this.contents)&&this.contents.add(e)}addIn(e,t){ys(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){let n=mh(this);e.anchor=!t||n.has(t)?yh(t||"a",n):t}return new zr(e.anchor)}createNode(e,t,n){let i;if(typeof t=="function")e=t.call({"":e},"",e),i=t;else if(Array.isArray(t)){let y=b=>typeof b=="number"||b instanceof String||b instanceof Number,g=t.filter(y).map(String);g.length>0&&(t=t.concat(g)),i=t}else n===void 0&&t&&(n=t,t=void 0);let{aliasDuplicateObjects:s,anchorPrefix:o,flow:a,keepUndefined:c,onTagObj:l,tag:u}=n??{},{onAnchor:d,setAnchors:f,sourceObjects:p}=k0(this,o||"a"),h={aliasDuplicateObjects:s??!0,keepUndefined:c??!1,onAnchor:d,onTagObj:l,replacer:i,schema:this.schema,sourceObjects:p},m=Kr(e,u,h);return a&&ae(m)&&(m.flow=!0),f(),m}createPair(e,t,n={}){let i=this.createNode(e,null,n),s=this.createNode(t,null,n);return new _e(i,s)}delete(e){return ys(this.contents)?this.contents.delete(e):!1}deleteIn(e){return ds(e)?this.contents==null?!1:(this.contents=null,!0):ys(this.contents)?this.contents.deleteIn(e):!1}get(e,t){return ae(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return ds(e)?!t&&G(this.contents)?this.contents.value:this.contents:ae(this.contents)?this.contents.getIn(e,t):void 0}has(e){return ae(this.contents)?this.contents.has(e):!1}hasIn(e){return ds(e)?this.contents!==void 0:ae(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=To(this.schema,[e],t):ys(this.contents)&&this.contents.set(e,t)}setIn(e,t){ds(e)?this.contents=t:this.contents==null?this.contents=To(this.schema,Array.from(e),t):ys(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 Ar({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 Ar({version:e}),n={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,n=null;break;default:{let i=JSON.stringify(e);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${i}`)}}if(t.schema instanceof Object)this.schema=t.schema;else if(n)this.schema=new Bo(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:i,onAnchor:s,reviver:o}={}){let a={anchors:new Map,doc:this,keep:!e,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof i=="number"?i:100},c=Re(this.contents,t??"",a);if(typeof s=="function")for(let{count:l,res:u}of a.anchors.values())s(u,l);return typeof o=="function"?_n(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 J0(this,e)}};function ys(r){if(ae(r))return!0;throw new Error("Expected a YAML collection as document contents")}var Uo=class extends Error{constructor(e,t,n,i){super(),this.name=e,this.code=n,this.message=i,this.pos=t}},or=class extends Uo{constructor(e,t,n){super("YAMLParseError",e,t,n)}},Vo=class extends Uo{constructor(e,t,n){super("YAMLWarning",e,t,n)}},Mh=(r,e)=>t=>{if(t.pos[0]===-1)return;t.linePos=t.pos.map(a=>e.linePos(a));let{line:n,col:i}=t.linePos[0];t.message+=` at line ${n}, column ${i}`;let s=i-1,o=r.substring(e.lineStarts[n-1],e.lineStarts[n]).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"),n>1&&/^ *$/.test(o.substring(0,s))){let a=r.substring(e.lineStarts[n-2],e.lineStarts[n-1]);a.length>80&&(a=a.substring(0,79)+`\u2026 +`}var En=class r{constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,nt,{value:zc});let i=null;typeof t=="function"||Array.isArray(t)?i=t:n===void 0&&t&&(n=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"},n);this.options=s;let{version:o}=s;n?._directives?(this.directives=n._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new Ar({version:o}),this.setSchema(o,n),this.contents=e===void 0?null:this.createNode(e,i,n)}clone(){let e=Object.create(r.prototype,{[nt]:{value:zc}});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=ne(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){ys(this.contents)&&this.contents.add(e)}addIn(e,t){ys(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){let n=hh(this);e.anchor=!t||n.has(t)?mh(t||"a",n):t}return new zr(e.anchor)}createNode(e,t,n){let i;if(typeof t=="function")e=t.call({"":e},"",e),i=t;else if(Array.isArray(t)){let y=b=>typeof b=="number"||b instanceof String||b instanceof Number,g=t.filter(y).map(String);g.length>0&&(t=t.concat(g)),i=t}else n===void 0&&t&&(n=t,t=void 0);let{aliasDuplicateObjects:s,anchorPrefix:o,flow:a,keepUndefined:c,onTagObj:l,tag:u}=n??{},{onAnchor:d,setAnchors:f,sourceObjects:p}=k0(this,o||"a"),m={aliasDuplicateObjects:s??!0,keepUndefined:c??!1,onAnchor:d,onTagObj:l,replacer:i,schema:this.schema,sourceObjects:p},h=Kr(e,u,m);return a&&ae(h)&&(h.flow=!0),f(),h}createPair(e,t,n={}){let i=this.createNode(e,null,n),s=this.createNode(t,null,n);return new _e(i,s)}delete(e){return ys(this.contents)?this.contents.delete(e):!1}deleteIn(e){return ds(e)?this.contents==null?!1:(this.contents=null,!0):ys(this.contents)?this.contents.deleteIn(e):!1}get(e,t){return ae(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return ds(e)?!t&&G(this.contents)?this.contents.value:this.contents:ae(this.contents)?this.contents.getIn(e,t):void 0}has(e){return ae(this.contents)?this.contents.has(e):!1}hasIn(e){return ds(e)?this.contents!==void 0:ae(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=To(this.schema,[e],t):ys(this.contents)&&this.contents.set(e,t)}setIn(e,t){ds(e)?this.contents=t:this.contents==null?this.contents=To(this.schema,Array.from(e),t):ys(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 Ar({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 Ar({version:e}),n={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,n=null;break;default:{let i=JSON.stringify(e);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${i}`)}}if(t.schema instanceof Object)this.schema=t.schema;else if(n)this.schema=new Bo(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:i,onAnchor:s,reviver:o}={}){let a={anchors:new Map,doc:this,keep:!e,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof i=="number"?i:100},c=Re(this.contents,t??"",a);if(typeof s=="function")for(let{count:l,res:u}of a.anchors.values())s(u,l);return typeof o=="function"?_n(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 J0(this,e)}};function ys(r){if(ae(r))return!0;throw new Error("Expected a YAML collection as document contents")}var Uo=class extends Error{constructor(e,t,n,i){super(),this.name=e,this.code=n,this.message=i,this.pos=t}},or=class extends Uo{constructor(e,t,n){super("YAMLParseError",e,t,n)}},Vo=class extends Uo{constructor(e,t,n){super("YAMLWarning",e,t,n)}},Ch=(r,e)=>t=>{if(t.pos[0]===-1)return;t.linePos=t.pos.map(a=>e.linePos(a));let{line:n,col:i}=t.linePos[0];t.message+=` at line ${n}, column ${i}`;let s=i-1,o=r.substring(e.lineStarts[n-1],e.lineStarts[n]).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"),n>1&&/^ *$/.test(o.substring(0,s))){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?.line===n&&c.col>i&&(a=Math.max(1,Math.min(c.col-i,80-s)));let l=" ".repeat(s)+"^".repeat(a);t.message+=`: ${o} ${l} -`}};function Pr(r,{flow:e,indicator:t,next:n,offset:i,onError:s,parentIndent:o,startOnNewline:a}){let c=!1,l=a,u=a,d="",f="",p=!1,h=!1,m=null,y=null,g=null,b=null,v=null,S=null,_=null;for(let $ of r)switch(h&&($.type!=="space"&&$.type!=="newline"&&$.type!=="comma"&&s($.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),h=!1),m&&(l&&$.type!=="comment"&&$.type!=="newline"&&s(m,"TAB_AS_INDENT","Tabs are not allowed as indentation"),m=null),$.type){case"space":!e&&(t!=="doc-start"||n?.type!=="flow-collection")&&$.source.includes(" ")&&(m=$),u=!0;break;case"comment":{u||s($,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let M=$.source.substring(1)||" ";d?d+=f+M:d=M,f="",l=!1;break}case"newline":l?d?d+=$.source:(!S||t!=="seq-item-ind")&&(c=!0):f+=$.source,l=!0,p=!0,(y||g)&&(b=$),u=!0;break;case"anchor":y&&s($,"MULTIPLE_ANCHORS","A node can have at most one anchor"),$.source.endsWith(":")&&s($.offset+$.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),y=$,_??(_=$.offset),l=!1,u=!1,h=!0;break;case"tag":{g&&s($,"MULTIPLE_TAGS","A node can have at most one tag"),g=$,_??(_=$.offset),l=!1,u=!1,h=!0;break}case t:(y||g)&&s($,"BAD_PROP_ORDER",`Anchors and tags must be after the ${$.source} indicator`),S&&s($,"UNEXPECTED_TOKEN",`Unexpected ${$.source} in ${e??"collection"}`),S=$,l=t==="seq-item-ind"||t==="explicit-key-ind",u=!1;break;case"comma":if(e){v&&s($,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),v=$,l=!1,u=!1;break}default:s($,"UNEXPECTED_TOKEN",`Unexpected ${$.type} token`),l=!1,u=!1}let E=r[r.length-1],k=E?E.offset+E.source.length:i;return h&&n&&n.type!=="space"&&n.type!=="newline"&&n.type!=="comma"&&(n.type!=="scalar"||n.source!=="")&&s(n.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),m&&(l&&m.indent<=o||n?.type==="block-map"||n?.type==="block-seq")&&s(m,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:v,found:S,spaceBefore:c,comment:d,hasNewline:p,anchor:y,tag:g,newlineAfterProp:b,end:k,start:_??k}}function An(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(An(e.key)||An(e.value))return!0}return!1;default:return!0}}function Ho(r,e,t){if(e?.type==="flow-collection"){let n=e.end[0];n.indent===r&&(n.source==="]"||n.source==="}")&&An(e)&&t(n,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}function wl(r,e,t){let{uniqueKeys:n}=r.options;if(n===!1)return!1;let i=typeof n=="function"?n:(s,o)=>s===o||G(s)&&G(o)&&s.value===o.value;return e.some(s=>i(s.key,t))}var Y0="All mapping items must start at the same column";function X0({composeNode:r,composeEmptyNode:e},t,n,i,s){let o=s?.nodeClass??Ee,a=new o(t.schema);t.atRoot&&(t.atRoot=!1);let c=n.offset,l=null;for(let u of n.items){let{start:d,key:f,sep:p,value:h}=u,m=Pr(d,{indicator:"explicit-key-ind",next:f??p?.[0],offset:c,onError:i,parentIndent:n.indent,startOnNewline:!0}),y=!m.found;if(y){if(f&&(f.type==="block-seq"?i(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in f&&f.indent!==n.indent&&i(c,"BAD_INDENT",Y0)),!m.anchor&&!m.tag&&!p){l=m.end,m.comment&&(a.comment?a.comment+=` -`+m.comment:a.comment=m.comment);continue}(m.newlineAfterProp||An(f))&&i(f??d[d.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else m.found?.indent!==n.indent&&i(c,"BAD_INDENT",Y0);t.atKey=!0;let g=m.end,b=f?r(t,f,m,i):e(t,g,d,null,m,i);t.schema.compat&&Ho(n.indent,f,i),t.atKey=!1,wl(t,a.items,b)&&i(g,"DUPLICATE_KEY","Map keys must be unique");let v=Pr(p??[],{indicator:"map-value-ind",next:h,offset:b.range[2],onError:i,parentIndent:n.indent,startOnNewline:!f||f.type==="block-scalar"});if(c=v.end,v.found){y&&(h?.type==="block-map"&&!v.hasNewline&&i(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),t.options.strict&&m.startr&&(r.type==="block-map"||r.type==="block-seq");function Z0({composeNode:r,composeEmptyNode:e},t,n,i,s){let o=n.start.source==="{",a=o?"flow map":"flow sequence",c=s?.nodeClass??(o?Ee:We),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 y=0;ys===o||G(s)&&G(o)&&s.value===o.value;return e.some(s=>i(s.key,t))}var Y0="All mapping items must start at the same column";function X0({composeNode:r,composeEmptyNode:e},t,n,i,s){let o=s?.nodeClass??Ee,a=new o(t.schema);t.atRoot&&(t.atRoot=!1);let c=n.offset,l=null;for(let u of n.items){let{start:d,key:f,sep:p,value:m}=u,h=Pr(d,{indicator:"explicit-key-ind",next:f??p?.[0],offset:c,onError:i,parentIndent:n.indent,startOnNewline:!0}),y=!h.found;if(y){if(f&&(f.type==="block-seq"?i(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in f&&f.indent!==n.indent&&i(c,"BAD_INDENT",Y0)),!h.anchor&&!h.tag&&!p){l=h.end,h.comment&&(a.comment?a.comment+=` +`+h.comment:a.comment=h.comment);continue}(h.newlineAfterProp||An(f))&&i(f??d[d.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else h.found?.indent!==n.indent&&i(c,"BAD_INDENT",Y0);t.atKey=!0;let g=h.end,b=f?r(t,f,h,i):e(t,g,d,null,h,i);t.schema.compat&&Ho(n.indent,f,i),t.atKey=!1,wl(t,a.items,b)&&i(g,"DUPLICATE_KEY","Map keys must be unique");let v=Pr(p??[],{indicator:"map-value-ind",next:m,offset:b.range[2],onError:i,parentIndent:n.indent,startOnNewline:!f||f.type==="block-scalar"});if(c=v.end,v.found){y&&(m?.type==="block-map"&&!v.hasNewline&&i(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),t.options.strict&&h.startr&&(r.type==="block-map"||r.type==="block-seq");function Z0({composeNode:r,composeEmptyNode:e},t,n,i,s){let o=n.start.source==="{",a=o?"flow map":"flow sequence",c=s?.nodeClass??(o?Ee:We),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 y=0;y0){let y=Cr(h,m,t.options.strict,i);y.comment&&(l.comment?l.comment+=` -`+y.comment:l.comment=y.comment),l.range=[n.offset,m,y.offset]}else l.range=[n.offset,m,m];return l}function Ih(r,e,t,n,i,s){let o=t.type==="block-map"?X0(r,e,t,n,s):t.type==="block-seq"?Q0(r,e,t,n,s):Z0(r,e,t,n,s),a=o.constructor;return i==="!"||i===a.tagName?(o.tag=a.tagName,o):(i&&(o.tag=i),o)}function eS(r,e,t,n,i){let s=n.tag,o=s?e.directives.tagName(s.source,f=>i(s,"TAG_RESOLVE_FAILED",f)):null;if(t.type==="block-seq"){let{anchor:f,newlineAfterProp:p}=n,h=f&&s?f.offset>s.offset?f:s:f??s;h&&(!p||p.offsetf.tag===o&&f.collection===a);if(!c){let f=e.schema.knownTags[o];if(f?.collection===a)e.schema.tags.push(Object.assign({},f,{default:!1})),c=f;else return f?i(s,"BAD_COLLECTION_TYPE",`${f.tag} used for ${a} collection, but expects ${f.collection??"scalar"}`,!0):i(s,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),Ih(r,e,t,i,o)}let l=Ih(r,e,t,i,o,c),u=c.resolve?.(l,f=>i(s,"TAG_RESOLVE_FAILED",f),e.options)??l,d=ne(u)?u:new F(u);return d.range=l.range,d.tag=o,c?.format&&(d.format=c.format),d}function Oh(r,e,t){let n=e.offset,i=kN(e,r.options.strict,t);if(!i)return{value:"",type:null,comment:"",range:[n,n,n]};let s=i.mode===">"?F.BLOCK_FOLDED:F.BLOCK_LITERAL,o=e.source?PN(e.source):[],a=o.length;for(let m=o.length-1;m>=0;--m){let y=o[m][1];if(y===""||y==="\r")a=m;else break}if(a===0){let m=i.chomp==="+"&&o.length>0?` -`.repeat(Math.max(1,o.length-1)):"",y=n+i.length;return e.source&&(y+=e.source.length),{value:m,type:s,comment:i.comment,range:[n,y,y]}}let c=e.indent+i.indent,l=e.offset+i.length,u=0;for(let m=0;mc&&(c=y.length);else{y.length=a;--m)o[m][0].length>c&&(a=m+1);let d="",f="",p=!1;for(let m=0;m0){let y=Cr(m,h,t.options.strict,i);y.comment&&(l.comment?l.comment+=` +`+y.comment:l.comment=y.comment),l.range=[n.offset,h,y.offset]}else l.range=[n.offset,h,h];return l}function Rh(r,e,t,n,i,s){let o=t.type==="block-map"?X0(r,e,t,n,s):t.type==="block-seq"?Q0(r,e,t,n,s):Z0(r,e,t,n,s),a=o.constructor;return i==="!"||i===a.tagName?(o.tag=a.tagName,o):(i&&(o.tag=i),o)}function eS(r,e,t,n,i){let s=n.tag,o=s?e.directives.tagName(s.source,f=>i(s,"TAG_RESOLVE_FAILED",f)):null;if(t.type==="block-seq"){let{anchor:f,newlineAfterProp:p}=n,m=f&&s?f.offset>s.offset?f:s:f??s;m&&(!p||p.offsetf.tag===o&&f.collection===a);if(!c){let f=e.schema.knownTags[o];if(f?.collection===a)e.schema.tags.push(Object.assign({},f,{default:!1})),c=f;else return f?i(s,"BAD_COLLECTION_TYPE",`${f.tag} used for ${a} collection, but expects ${f.collection??"scalar"}`,!0):i(s,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),Rh(r,e,t,i,o)}let l=Rh(r,e,t,i,o,c),u=c.resolve?.(l,f=>i(s,"TAG_RESOLVE_FAILED",f),e.options)??l,d=ne(u)?u:new F(u);return d.range=l.range,d.tag=o,c?.format&&(d.format=c.format),d}function Ih(r,e,t){let n=e.offset,i=PN(e,r.options.strict,t);if(!i)return{value:"",type:null,comment:"",range:[n,n,n]};let s=i.mode===">"?F.BLOCK_FOLDED:F.BLOCK_LITERAL,o=e.source?CN(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=i.chomp==="+"&&o.length>0?` +`.repeat(Math.max(1,o.length-1)):"",y=n+i.length;return e.source&&(y+=e.source.length),{value:h,type:s,comment:i.comment,range:[n,y,y]}}let c=e.indent+i.indent,l=e.offset+i.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||g[0]===" "?(f===" "?f=` `:!p&&f===` `&&(f=` @@ -105,40 +105,40 @@ ${l} `,p=!0):g===""?f===` `?d+=` `:f=` -`:(d+=f+g,f=" ",p=!1)}switch(i.chomp){case"-":break;case"+":for(let m=a;mt(n+f,p,h);switch(i){case"scalar":a=F.PLAIN,c=CN(s,l);break;case"single-quoted-scalar":a=F.QUOTE_SINGLE,c=MN(s,l);break;case"double-quoted-scalar":a=F.QUOTE_DOUBLE,c=TN(s,l);break;default:return t(r,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${i}`),{value:"",type:null,comment:"",range:[n,n+s.length,n+s.length]}}let u=n+s.length,d=Cr(o,u,e,t);return{value:c,type:a,comment:d.comment,range:[n,u,d.offset]}}function CN(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}`),tS(r)}function MN(r,e){return(r[r.length-1]!=="'"||r.length===1)&&e(r.length,"MISSING_CHAR","Missing closing 'quote"),tS(r.slice(1,-1)).replace(/''/g,"'")}function tS(r){let e=/(.*?)\r?\n/sy,t=e.exec(r);if(!t)return r;let n,i;try{n=new RegExp("(?t(n+f,p,m);switch(i){case"scalar":a=F.PLAIN,c=MN(s,l);break;case"single-quoted-scalar":a=F.QUOTE_SINGLE,c=TN(s,l);break;case"double-quoted-scalar":a=F.QUOTE_DOUBLE,c=RN(s,l);break;default:return t(r,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${i}`),{value:"",type:null,comment:"",range:[n,n+s.length,n+s.length]}}let u=n+s.length,d=Cr(o,u,e,t);return{value:c,type:a,comment:d.comment,range:[n,u,d.offset]}}function MN(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}`),tS(r)}function TN(r,e){return(r[r.length-1]!=="'"||r.length===1)&&e(r.length,"MISSING_CHAR","Missing closing 'quote"),tS(r.slice(1,-1)).replace(/''/g,"'")}function tS(r){let e=/(.*?)\r?\n/sy,t=e.exec(r);if(!t)return r;let n,i;try{n=new RegExp("(?s?r.slice(s,n+1):i)}else t+=i}return(r[r.length-1]!=='"'||r.length===1)&&e(r.length,"MISSING_CHAR",'Missing closing "quote'),t}function RN(r,e){let t="",n=r[e+1];for(;(n===" "||n===" "||n===` +`)&&(t+=n>s?r.slice(s,n+1):i)}else t+=i}return(r[r.length-1]!=='"'||r.length===1)&&e(r.length,"MISSING_CHAR",'Missing closing "quote'),t}function IN(r,e){let t="",n=r[e+1];for(;(n===" "||n===" "||n===` `||n==="\r")&&!(n==="\r"&&r[e+2]!==` `);)n===` `&&(t+=` -`),e+=1,n=r[e+1];return t||(t=" "),{fold:t,offset:e}}var IN={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:` -`,r:"\r",t:" ",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function ON(r,e,t,n){let i=r.substr(e,t),o=i.length===t&&/^[0-9a-fA-F]+$/.test(i)?parseInt(i,16):NaN;try{return String.fromCodePoint(o)}catch{let a=r.substr(e-2,t+2);return n(e-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),a}}function Nh(r,e,t,n){let{value:i,type:s,comment:o,range:a}=e.type==="block-scalar"?Oh(r,e,n):Dh(e,r.options.strict,n),c=t?r.directives.tagName(t.source,d=>n(t,"TAG_RESOLVE_FAILED",d)):null,l;r.options.stringKeys&&r.atKey?l=r.schema[At]:c?l=DN(r.schema,i,c,t,n):e.type==="scalar"?l=NN(r,i,e,n):l=r.schema[At];let u;try{let d=l.resolve(i,f=>n(t??e,"TAG_RESOLVE_FAILED",f),r.options);u=G(d)?d:new F(d)}catch(d){let f=d instanceof Error?d.message:String(d);n(t??e,"TAG_RESOLVE_FAILED",f),u=new F(i)}return u.range=a,u.source=i,s&&(u.type=s),c&&(u.tag=c),l.format&&(u.format=l.format),o&&(u.comment=o),u}function DN(r,e,t,n,i){if(t==="!")return r[At];let s=[];for(let a of r.tags)if(!a.collection&&a.tag===t)if(a.default&&a.test)s.push(a);else return a;for(let a of s)if(a.test?.test(e))return a;let o=r.knownTags[t];return o&&!o.collection?(r.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(i(n,"TAG_RESOLVE_FAILED",`Unresolved tag: ${t}`,t!=="tag:yaml.org,2002:str"),r[At])}function NN({atKey:r,directives:e,schema:t},n,i,s){let o=t.tags.find(a=>(a.default===!0||r&&a.default==="key")&&a.test?.test(n))||t[At];if(t.compat){let a=t.compat.find(c=>c.default&&c.test?.test(n))??t[At];if(o.tag!==a.tag){let c=e.tagString(o.tag),l=e.tagString(a.tag),u=`Value may be parsed as either ${c} or ${l}`;s(i,"TAG_RESOLVE_FAILED",u,!0)}}return o}function rS(r,e,t){if(e){t??(t=e.length);for(let n=t-1;n>=0;--n){let i=e[n];switch(i.type){case"space":case"comment":case"newline":r-=i.source.length;continue}for(i=e[++n];i?.type==="space";)r+=i.source.length,i=e[++n];break}}return r}var LN={composeNode:Lh,composeEmptyNode:_l};function Lh(r,e,t,n){let i=r.atKey,{spaceBefore:s,comment:o,anchor:a,tag:c}=t,l,u=!0;switch(e.type){case"alias":l=FN(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=Nh(r,e,c,n),a&&(l.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=eS(LN,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??(l=_l(r,e.offset,void 0,null,t,n)),a&&l.anchor===""&&n(a,"BAD_ALIAS","Anchor cannot be an empty string"),i&&r.options.stringKeys&&(!G(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&n(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 _l(r,e,t,n,{spaceBefore:i,comment:s,anchor:o,tag:a,end:c},l){let u={type:"scalar",offset:rS(e,t,n),indent:-1,source:""},d=Nh(r,u,a,l);return o&&(d.anchor=o.source.substring(1),d.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),i&&(d.spaceBefore=!0),s&&(d.comment=s,d.range[2]=c),d}function FN({options:r},{offset:e,source:t,end:n},i){let s=new zr(t.substring(1));s.source===""&&i(e,"BAD_ALIAS","Alias cannot be an empty string"),s.source.endsWith(":")&&i(e+t.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=e+t.length,a=Cr(n,o,r.strict,i);return s.range=[e,o,a.offset],a.comment&&(s.comment=a.comment),s}function nS(r,e,{offset:t,start:n,value:i,end:s},o){let a=Object.assign({_directives:e},r),c=new En(void 0,a),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=Pr(n,{indicator:"doc-start",next:i??s?.[0],offset:t,onError:o,parentIndent:0,startOnNewline:!0});u.found&&(c.directives.docStart=!0,i&&(i.type==="block-map"||i.type==="block-seq")&&!u.hasNewline&&o(u.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=i?Lh(l,i,u,o):_l(l,u.end,n,null,u,o);let d=c.contents.range[2],f=Cr(s,d,!1,o);return f.comment&&(c.comment=f.comment),c.range=[t,d,f.offset],c}function zo(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 iS(r){let e="",t=!1,n=!1;for(let i=0;in(t,"TAG_RESOLVE_FAILED",d)):null,l;r.options.stringKeys&&r.atKey?l=r.schema[At]:c?l=NN(r.schema,i,c,t,n):e.type==="scalar"?l=LN(r,i,e,n):l=r.schema[At];let u;try{let d=l.resolve(i,f=>n(t??e,"TAG_RESOLVE_FAILED",f),r.options);u=G(d)?d:new F(d)}catch(d){let f=d instanceof Error?d.message:String(d);n(t??e,"TAG_RESOLVE_FAILED",f),u=new F(i)}return u.range=a,u.source=i,s&&(u.type=s),c&&(u.tag=c),l.format&&(u.format=l.format),o&&(u.comment=o),u}function NN(r,e,t,n,i){if(t==="!")return r[At];let s=[];for(let a of r.tags)if(!a.collection&&a.tag===t)if(a.default&&a.test)s.push(a);else return a;for(let a of s)if(a.test?.test(e))return a;let o=r.knownTags[t];return o&&!o.collection?(r.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(i(n,"TAG_RESOLVE_FAILED",`Unresolved tag: ${t}`,t!=="tag:yaml.org,2002:str"),r[At])}function LN({atKey:r,directives:e,schema:t},n,i,s){let o=t.tags.find(a=>(a.default===!0||r&&a.default==="key")&&a.test?.test(n))||t[At];if(t.compat){let a=t.compat.find(c=>c.default&&c.test?.test(n))??t[At];if(o.tag!==a.tag){let c=e.tagString(o.tag),l=e.tagString(a.tag),u=`Value may be parsed as either ${c} or ${l}`;s(i,"TAG_RESOLVE_FAILED",u,!0)}}return o}function rS(r,e,t){if(e){t??(t=e.length);for(let n=t-1;n>=0;--n){let i=e[n];switch(i.type){case"space":case"comment":case"newline":r-=i.source.length;continue}for(i=e[++n];i?.type==="space";)r+=i.source.length,i=e[++n];break}}return r}var FN={composeNode:Nh,composeEmptyNode:_l};function Nh(r,e,t,n){let i=r.atKey,{spaceBefore:s,comment:o,anchor:a,tag:c}=t,l,u=!0;switch(e.type){case"alias":l=jN(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=Dh(r,e,c,n),a&&(l.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=eS(FN,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??(l=_l(r,e.offset,void 0,null,t,n)),a&&l.anchor===""&&n(a,"BAD_ALIAS","Anchor cannot be an empty string"),i&&r.options.stringKeys&&(!G(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&n(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 _l(r,e,t,n,{spaceBefore:i,comment:s,anchor:o,tag:a,end:c},l){let u={type:"scalar",offset:rS(e,t,n),indent:-1,source:""},d=Dh(r,u,a,l);return o&&(d.anchor=o.source.substring(1),d.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),i&&(d.spaceBefore=!0),s&&(d.comment=s,d.range[2]=c),d}function jN({options:r},{offset:e,source:t,end:n},i){let s=new zr(t.substring(1));s.source===""&&i(e,"BAD_ALIAS","Alias cannot be an empty string"),s.source.endsWith(":")&&i(e+t.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=e+t.length,a=Cr(n,o,r.strict,i);return s.range=[e,o,a.offset],a.comment&&(s.comment=a.comment),s}function nS(r,e,{offset:t,start:n,value:i,end:s},o){let a=Object.assign({_directives:e},r),c=new En(void 0,a),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=Pr(n,{indicator:"doc-start",next:i??s?.[0],offset:t,onError:o,parentIndent:0,startOnNewline:!0});u.found&&(c.directives.docStart=!0,i&&(i.type==="block-map"||i.type==="block-seq")&&!u.hasNewline&&o(u.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=i?Nh(l,i,u,o):_l(l,u.end,n,null,u,o);let d=c.contents.range[2],f=Cr(s,d,!1,o);return f.comment&&(c.comment=f.comment),c.range=[t,d,f.offset],c}function zo(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 iS(r){let e="",t=!1,n=!1;for(let i=0;i{let o=zo(t);s?this.warnings.push(new Vo(o,n,i)):this.errors.push(new or(o,n,i))},this.directives=new Ar({version:e.version||"1.2"}),this.options=e}decorate(e,t){let{comment:n,afterEmptyLine:i}=iS(this.prelude);if(n){let s=e.contents;if(t)e.comment=e.comment?`${e.comment} ${n}`:n;else if(i||e.directives.docStart||!s)e.commentBefore=n;else if(ae(s)&&!s.flow&&s.items.length>0){let o=s.items[0];te(o)&&(o=o.key);let a=o.commentBefore;o.commentBefore=a?`${n} ${a}`:n}else{let o=s.commentBefore;s.commentBefore=o?`${n} ${o}`:n}}if(t){for(let s=0;s{let s=zo(e);s[0]+=t,this.onError(s,"BAD_DIRECTIVE",n,i)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{let t=nS(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 or(zo(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 or(zo(e),"UNEXPECTED_TOKEN",n));break}this.doc.directives.docEnd=!0;let t=Cr(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 or(zo(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),i=new En(void 0,n);this.atDirectives&&this.onError(t,"MISSING_CHAR","Missing directives-end indicator line"),i.range=[0,t,t],this.decorate(i,!1),yield i}}};var Fh=Symbol("break visit"),jN=Symbol("skip children"),sS=Symbol("remove item");function di(r,e){"type"in r&&r.type==="document"&&(r={start:r.start,value:r.value}),oS(Object.freeze([]),r,e)}di.BREAK=Fh;di.SKIP=jN;di.REMOVE=sS;di.itemAtPath=(r,e)=>{let t=r;for(let[n,i]of e){let s=t?.[n];if(s&&"items"in s)t=s.items[i];else return}return t};di.parentCollection=(r,e)=>{let t=di.itemAtPath(r,e.slice(0,-1)),n=e[e.length-1][0],i=t?.[n];if(i&&"items"in i)return i;throw new Error("Parent collection not found")};function oS(r,e,t){let n=t(e,r);if(typeof n=="symbol")return n;for(let i of["key","value"]){let s=e[i];if(s&&"items"in s){for(let o=0;o{let t=r;for(let[n,i]of e){let s=t?.[n];if(s&&"items"in s)t=s.items[i];else return}return t};di.parentCollection=(r,e)=>{let t=di.itemAtPath(r,e.slice(0,-1)),n=e[e.length-1][0],i=t?.[n];if(i&&"items"in i)return i;throw new Error("Parent collection not found")};function oS(r,e,t){let n=t(e,r);if(typeof n=="symbol")return n;for(let i of["key","value"]){let s=e[i];if(s&&"items"in s){for(let o=0;o":return"block-scalar-header"}return null}function ar(r){switch(r){case void 0:case" ":case` -`:case"\r":case" ":return!0;default:return!1}}var cS=new Set("0123456789ABCDEFabcdef"),BN=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),$l=new Set(",[]{}"),UN=new Set(` ,[]{} -\r `),Uh=r=>!r||UN.has(r),Wo=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){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=this.next??"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===` +`:case"\r":case" ":return!0;default:return!1}}var cS=new Set("0123456789ABCDEFabcdef"),UN=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),$l=new Set(",[]{}"),VN=new Set(` ,[]{} +\r `),Bh=r=>!r||VN.has(r),Wo=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){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=this.next??"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 n=0;for(;t===" ";)t=this.buffer[++n+e];if(t==="\r"){let i=this.buffer[n+e+1];if(i===` `||!i&&!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==="...")&&ar(this.buffer[e+3]))return-1}return e}getLine(){let e=this.lineEndPos;return(typeof e!="number"||e!==-1&&ethis.indentValue&&!ar(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===":")&&ar(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(Uh),"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 i=this.getLine();if(i===null)return this.setNext("flow");if((n!==-1&&nthis.indentValue&&!ar(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===":")&&ar(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(Bh),"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 i=this.getLine();if(i===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=>ar(t)||t==="#")}*parseBlockScalar(){let e=this.pos-1,t=0,n;e:for(let s=this.pos;n=this.buffer[s];++s)switch(n){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===` @@ -148,15 +148,15 @@ ${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.pus `&&s>=this.pos&&s+1+t>a)e=s;else break}while(!0);return yield Sl,yield*this.pushToIndex(e+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let e=this.flowLevel>0,t=this.pos-1,n=this.pos-1,i;for(;i=this.buffer[++n];)if(i===":"){let s=this.buffer[n+1];if(ar(s)||e&&$l.has(s))break;t=n}else if(ar(i)){let s=this.buffer[n+1];if(i==="\r"&&(s===` `?(n+=1,i=` `,s=this.buffer[n+1]):t=n),s==="#"||e&&$l.has(s))break;if(i===` -`){let o=this.continueScalar(n+1);if(o===-1)break;n=Math.max(n,o-2)}}else{if(e&&$l.has(i))break;t=n}return!i&&!this.atEnd?this.setNext("plain-scalar"):(yield Sl,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(Uh),e+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let t=this.flowLevel>0,n=this.charAt(1);if(ar(n)||t&&$l.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(;!ar(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(BN.has(t))t=this.buffer[++e];else if(t==="%"&&cS.has(this.buffer[e+1])&&cS.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===` +`){let o=this.continueScalar(n+1);if(o===-1)break;n=Math.max(n,o-2)}}else{if(e&&$l.has(i))break;t=n}return!i&&!this.atEnd?this.setNext("plain-scalar"):(yield Sl,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(Bh),e+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let t=this.flowLevel>0,n=this.charAt(1);if(ar(n)||t&&$l.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(;!ar(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(UN.has(t))t=this.buffer[++e];else if(t==="%"&&cS.has(this.buffer[e+1])&&cS.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,n;do n=this.buffer[++t];while(n===" "||e&&n===" ");let i=t-this.pos;return i>0&&(yield this.buffer.substr(this.pos,i),this.pos=t),i}*pushUntil(e){let t=this.pos,n=this.buffer[t];for(;!e(n);)n=this.buffer[++t];return yield*this.pushToIndex(t,!1)}};var Go=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[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(;r[++e]?.type==="space";);return r.splice(e,r.length)}function El(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?.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??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"&&dS(t),n.type){case"document":n.value=t;break;case"block-scalar":n.props.push(t);break;case"block-map":{let i=n.items[n.items.length-1];if(i.value){n.items.push({start:[],key:t,sep:[]}),this.onKeyLine=!0;return}else if(i.sep)i.value=t;else{Object.assign(i,{key:t,sep:[]}),this.onKeyLine=!i.explicitKey;return}break}case"block-seq":{let i=n.items[n.items.length-1];i.value?n.items.push({start:[],value:t}):i.value=t;break}case"flow-collection":{let i=n.items[n.items.length-1];!i||i.value?n.items.push({start:[],key:t,sep:[]}):i.sep?i.value=t:Object.assign(i,{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 i=t.items[t.items.length-1];i&&!i.sep&&!i.value&&i.start.length>0&&lS(i.start)===-1&&(t.indent===0||i.start.every(s=>s.type!=="comment"||s.indent=e.indent){let n=!this.onKeyLine&&this.indent===e.indent,i=n&&(t.sep||t.explicitKey)&&this.type!=="seq-item-ind",s=[];if(i&&t.sep&&!t.value){let o=[];for(let a=0;ae.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(s=t.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":i||t.value?(s.push(this.sourceToken),e.items.push({start:s}),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?(s.push(this.sourceToken),e.items.push({start:s,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(kn(t.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:s,key:null,sep:[this.sourceToken]}]});else if(uS(t.key)&&!kn(t.sep,"newline")){let o=gs(t.start),a=t.key,c=t.sep;c.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:a,sep:c}]})}else s.length>0?t.sep=t.sep.concat(s,this.sourceToken):t.sep.push(this.sourceToken);else if(kn(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{let o=gs(t.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else t.sep?t.value||i?e.items.push({start:s,key:null,sep:[this.sourceToken]}):kn(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 o=this.flowScalar(this.type);i||t.value?(e.items.push({start:s,key:o,sep:[]}),this.onKeyLine=!0):t.sep?this.stack.push(o):(Object.assign(t,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{let o=this.startBlockValue(e);if(o){if(o.type==="block-seq"){if(!t.explicitKey&&t.sep&&!kn(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:s});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){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;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?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 i=e.items[e.items.length-2]?.value?.end;if(Array.isArray(i)){El(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||kn(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 n;do yield*this.pop(),n=this.peek(1);while(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 i=this.flowScalar(this.type);!t||t.value?e.items.push({start:[],key:i,sep:[]}):t.sep?this.stack.push(i):Object.assign(t,{key:i,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 i=xl(n),s=gs(i);dS(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(` `)+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=xl(e),n=gs(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=xl(e),n=gs(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 VN(r){let e=r.prettyErrors!==!1;return{lineCounter:r.lineCounter||e&&new Go||null,prettyErrors:e}}function fS(r,e={}){let{lineCounter:t,prettyErrors:n}=VN(e),i=new Jo(t?.addNewLine),s=new Ko(e),o=null;for(let a of s.compose(i.parse(r),!0,r.length))if(!o)o=a;else if(o.options.logLevel!=="silent"){o.errors.push(new or(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&t&&(o.errors.forEach(Mh(r,t)),o.warnings.forEach(Mh(r,t))),o}function ui(r,e,t){let n;typeof e=="function"?n=e:t===void 0&&e&&typeof e=="object"&&(t=e);let i=fS(r,t);if(!i)return null;if(i.warnings.forEach(s=>rl(i.options.logLevel,s)),i.errors.length>0){if(i.options.logLevel!=="silent")throw i.errors[0];i.errors=[]}return i.toJS(Object.assign({reviver:n},t))}var KN=r=>r/2**32|0,WN=r=>r>>>0;function pS(r,e,t,n){let i=KN(t),s=WN(t);r.setUint32(e,n?s:i,n),r.setUint32(e+4,n?i:s,n)}function hS(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in r&&r.BYTES_PER_ELEMENT===1}var Vh=r=>r?`"${r}" `:"";function GN(r,e=""){if(typeof r!="number")throw new TypeError(Vh(e)+"expected number, got "+typeof r);if(!Number.isSafeInteger(r)||r<0)throw new RangeError(Vh(e)+"expected integer >= 0, got "+r);return r}function Al(r,e,t=""){if(hS(r)&&(e===void 0||r.length===e))return r;e!==void 0&&GN(e,"length");let n=hS(r),i=e!==void 0?` of length ${e}`:"",s=n?`length=${r.length}`:`type=${typeof r}`,o=Vh(t)+"expected Uint8Array"+i+", got "+s;throw n?new RangeError(o):new TypeError(o)}var JN=(r,e)=>{if(r===null||typeof r!="object"||Array.isArray(r))throw new TypeError((e==="object"?"":`"${e}" `)+"expected object, got type="+typeof r)},mS=(r,e)=>{JN(r,e);let t=Object.getPrototypeOf(r);if(t!==Object.prototype&&t!==null)throw new TypeError(`"${e}" expected plain object`);if(Object.hasOwn(r,"__proto__"))throw new TypeError(`"${e}.__proto__" is not allowed`)};function Hh(r,e=!0){if(r.destroyed)throw new Error("hash was destroyed");if(e&&r.finished)throw new Error("digest() was already called")}function yS(r,e){Al(r,void 0,"output");let t=e.outputLen;if(!(r.length>=t))throw new RangeError('"output" expected length >= '+t)}function bs(...r){for(let e=0;e>>e}function Pl(r,e){return r<>>32-e>>>0}var YN=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",XN=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function De(r){if(Al(r),YN)return r.toHex();let e="";for(let t=0;t= '+t)}function bs(...r){for(let e=0;e>>e}function Pl(r,e){return r<>>32-e>>>0}var XN=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",QN=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function De(r){if(Al(r),XN)return r.toHex();let e="";for(let t=0;t!Im.includes(s))||new Set(e).size!==e.length)throw new w("invalid_file_materialization","Selected file media classes must be valid and unique.");let t=[...e].sort((s,o)=>Im.indexOf(s)-Im.indexOf(o)),n=r?.excluded_folders??[];if(n.some(s=>typeof s!="string"||!s.trim()))throw new w("invalid_file_materialization","Excluded folders cannot be empty.");let i=n.map(s=>yn(s.trim())).sort((s,o)=>s.toLocaleLowerCase().localeCompare(o.toLocaleLowerCase()));if(i.length>100)throw new w("invalid_file_materialization","File sync supports at most 100 excluded folders.");if(new Set(i.map(s=>s.toLocaleLowerCase())).size!==i.length)throw new w("invalid_file_materialization","Excluded folders must be unique on portable filesystems.");for(let s of i)da(s,!0);return{file_classes:t,excluded_folders:i}}function ix(r){let e=r.includes(".")?r.slice(r.lastIndexOf(".")+1).toLowerCase():"";return["avif","bmp","gif","jpeg","jpg","png","svg","webp"].includes(e)?"image":["flac","m4a","mp3","oga","ogg","opus","wav"].includes(e)?"audio":["3gp","mkv","mov","mp4","webm"].includes(e)?"video":e==="pdf"?"pdf":"other"}function Z$(r){if(r.conflicts.length)throw new w("authority_import_path_conflict",`${r.conflicts.length} filename conflicts prevent uploading. Review the paths in Sync and rename the conflicting files before retrying. Nothing was renamed or excluded.`)}function aF(r,e,t=ix(e)){if(!r.file_classes.includes(t))return!1;let n=(0,z.normalizePath)(e);return!r.excluded_folders.some(i=>n===i||n.startsWith(`${i}/`))}var cF=/\.(?:md|base)$/,sx=/\.(?:md|base)$/i;function da(r,e=!1){let t=yn(r),n=t.split("/");if(t.length>1024||!e&&sx.test(t)||n.some(i=>i.startsWith(".")||oF.has(i.toLowerCase())||/[<>"|?*]/u.test(i)||/^(?:CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\.|$)/iu.test(i)))throw new w("invalid_file_path",`Collection file path ${t} is hidden, reserved, or non-portable.`);return t}async function ud(r){let e=new Uint8Array(await crypto.subtle.digest("SHA-256",r));return{size:r.byteLength,content_digest:`sha256:${Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}`}}async function Dm(r){let e=[],t=0;for await(let s of r){if(!(s instanceof Uint8Array))throw new w("file_integrity_failed","A binary stream returned an invalid chunk.");s.byteLength&&(t+=s.byteLength,xi(t),e.push(Uint8Array.from(s)))}let n=new Uint8Array(t),i=0;for(let s of e)n.set(s,i),i+=s.byteLength;return n.buffer}function ex(r){let e=r.includes(".")?r.slice(r.lastIndexOf(".")+1).toLowerCase():"";return{avif:"image/avif",gif:"image/gif",jpeg:"image/jpeg",jpg:"image/jpeg",png:"image/png",svg:"image/svg+xml",webp:"image/webp",flac:"audio/flac",m4a:"audio/mp4",mp3:"audio/mpeg",ogg:"audio/ogg",opus:"audio/opus",wav:"audio/wav",mov:"video/quicktime",mp4:"video/mp4",webm:"video/webm",pdf:"application/pdf"}[e]}async function lF(r,e){if(r!==void 0){if(!e)return JSON.stringify(r);if(r instanceof ArrayBuffer)return r;if(ArrayBuffer.isView(r))return Uint8Array.from(new Uint8Array(r.buffer,r.byteOffset,r.byteLength)).buffer;if(r instanceof Blob)return r.arrayBuffer();throw new w("invalid_file_upload","The adoption upload body was not binary data.")}}function fd(r,e){if(e!=null)return e;if(!r.trim())return{};try{return JSON.parse(r)}catch{return{}}}var md=L$(F$());function dF(){return async r=>{if(r.signal?.aborted)throw new DOMException("Enrollment cancelled.","AbortError");let e=await md({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,signal:r.signal});if(r.signal?.aborted)throw new DOMException("Enrollment cancelled.","AbortError");return{status:e.status,body:fd(e.text,e.json),retryAfterMs:aa(e.headers)}}}function uF(){return async r=>{if(r.signal?.aborted)throw new DOMException("Collection adoption cancelled.","AbortError");let e=await lF(r.body,r.rawBody),t=await md({url:r.url,method:r.method,headers:r.headers,body:e,contentType:e===void 0||r.rawBody?void 0:"application/json",throw:!1,signal:r.signal});if(r.signal?.aborted)throw new DOMException("Collection adoption cancelled.","AbortError");return{status:t.status,body:fd(t.text,t.json),retryAfterMs:aa(t.headers),headers:t.headers}}}var Nm=class{constructor(e,t,n=md,i,s){this.send=n;this.onFileProgress=i;this.signal=s;this.credentials=typeof t=="string"?{token:()=>Promise.resolve(t)}:t;let o;try{o=new URL(e)}catch{throw new w("invalid_sync_url","Sync URL must be an absolute authority endpoint.")}if(!(o.protocol==="https:"||o.protocol==="http:"&&["localhost","127.0.0.1","[::1]","::1"].includes(o.hostname))||o.username||o.password||o.search||o.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(o.pathname))throw new w("invalid_sync_url","Sync URL must identify one authority sync endpoint.");this.syncUrl=o.href.replace(/\/$/,""),this.filesUrl=this.syncUrl.replace(/\/sync$/u,"/files")}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()}`)}fileSnapshot(e,t){let n=new URLSearchParams({snapshot_id:e});return t&&n.set("page",t),this.request("GET",`files/snapshot?${n.toString()}`)}async*downloadFile(e){xi(e.size);let t=crypto.randomUUID();try{let n=0;this.onFileProgress?.({direction:"download",path:e.path,transferredBytes:n,totalBytes:e.size});let i=await this.fileRequest("POST","downloads",{protocol_version:1,type:"open_file_download",transfer_id:t,file_id:e.file_id,revision:e.revision});if(i.protocol_version!==1||i.type!=="file_transfer"||i.transfer_id!==t||i.direction!=="download"||i.protection!=="transport_tls"||i.total_size!==e.size||i.strategy.kind!=="object_ranges"||!Number.isSafeInteger(i.strategy.part_size)||i.strategy.part_size<=0)throw new w("invalid_sync_response","The authority returned an incompatible file download session.");let s=Math.ceil(e.size/i.strategy.part_size);for(let o=0;o=300)throw this.responseError(c,"file_download_failed");let l=tx(c.headers,"content-length");if(l!==void 0&&Number(l)!==a||c.arrayBuffer.byteLength!==a)throw new w("file_integrity_failed","Hosted authority returned a file part with the wrong length.");n+=a,this.onFileProgress?.({direction:"download",path:e.path,transferredBytes:n,totalBytes:e.size}),a&&(yield new Uint8Array(c.arrayBuffer))}}finally{await this.fileRequest("DELETE",`transfers/${encodeURIComponent(t)}`).catch(()=>{})}}async uploadFile(e,t){xi(e.size);let n=await this.fileRequest("POST","uploads",e);if(n.protocol_version!==1||n.type!=="file_transfer"||n.transfer_id!==e.transfer_id||n.direction!=="upload"||n.protection!=="transport_tls"||n.total_size!==e.size||!["object_put","object_multipart"].includes(n.strategy.kind))throw new w("invalid_sync_response","Authority returned an incompatible file upload session.");let i=n.strategy.kind==="object_multipart"?n.strategy.part_size:Math.max(1,e.size);if(!Number.isSafeInteger(i)||i<=0)throw new w("invalid_sync_response","Authority returned an invalid upload part size.");let s=new Lm(t),o=Math.max(1,Math.ceil(e.size/i));if(n.received.some(d=>!Number.isSafeInteger(d)||d<0||d>=o)||new Set(n.received).size!==n.received.length)throw new w("invalid_sync_response","Authority returned invalid upload progress.");let a=n.uploaded_parts??[];if(a.some((d,f)=>!Number.isSafeInteger(d.part_number)||d.part_number<1||d.part_number>o||!d.etag||d.etag.length>255||f>0&&a[f-1].part_number>=d.part_number)||(n.strategy.kind==="object_multipart"?a.length!==n.received.length||a.some((d,f)=>d.part_number-1!==n.received[f]):a.length!==0))throw new w("invalid_sync_response","Authority returned invalid uploaded part receipts.");let c=n.received.reduce((d,f)=>{let p=f*i;return d+Math.min(i,Math.max(0,e.size-p))},0);if(this.onFileProgress?.({direction:"upload",path:e.path,transferredBytes:c,totalBytes:e.size}),n.received.length===o)return this.commitUpload(e.transfer_id,a);let l=new Set(n.received),u=Array.from({length:o},()=>{});for(let d of a)u[d.part_number-1]=d;for(let d=0;d=300)throw new In(y.status===429||y.status>=500?"authority_unavailable":"file_upload_failed",`Object storage returned HTTP ${y.status}.`,y.status);if(c+=p,this.onFileProgress?.({direction:"upload",path:e.path,transferredBytes:c,totalBytes:e.size}),n.strategy.kind==="object_multipart"){let g=tx(y.headers,"etag");if(!g)throw new w("invalid_sync_response","Object storage omitted a multipart ETag.");u[d]={part_number:d+1,etag:g}}}return await s.expectEnd(),this.commitUpload(e.transfer_id,u.filter(d=>d!==void 0))}async commitUpload(e,t){let n=await this.fileRequest("POST",`uploads/${encodeURIComponent(e)}/commit`,{protocol_version:1,type:"commit_file_upload",transfer_id:e,parts:t});if(n.protocol_version!==1||n.type!=="file_upload_committed"||n.transfer_id!==e)throw new w("invalid_sync_response","Authority returned an invalid file upload receipt.");return n}async moveFile(e){let t=await this.fileRequest("POST",`${encodeURIComponent(e.file_id)}/move`,e);if(t.protocol_version!==1||t.type!=="file_moved"||t.mutation_id!==e.mutation_id)throw new w("invalid_sync_response","Authority returned an invalid file move receipt.");return t}async deleteFile(e){let t=await this.fileRequest("POST",`${encodeURIComponent(e.file_id)}/delete`,e);if(t.protocol_version!==1||t.type!=="file_deleted"||t.mutation_id!==e.mutation_id||t.file_id!==e.file_id)throw new w("invalid_sync_response","Authority returned an invalid file delete receipt.");return t}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){return this.requestAt(this.syncUrl,e,t,n)}async fileRequest(e,t,n){return this.requestAt(this.filesUrl,e,t,n)}async requestAt(e,t,n,i){let s=await this.authorized({url:`${e}/${n}`,method:t,body:i===void 0?void 0:JSON.stringify(i),contentType:i===void 0?void 0:"application/json",throw:!1}),o=fd(s.text,s.json);if(s.status<200||s.status>=300)throw this.responseError(s,"sync_failed");return o}async authorized(e){let t=s=>this.send({...e,headers:{authorization:`Bearer ${s}`},signal:this.signal}),n=await this.credentials.token(),i=await t(n);return i.status!==401||!this.credentials.renew?i:t(await this.credentials.renew(n))}responseError(e,t){let n=fd(e.text,e.json),i=at(n)&&at(n.error)?n.error:{},s=typeof i.code=="string"?i.code:e.status===401?"mirror_access_rejected":e.status===429||e.status>=500?"authority_unavailable":t;return new In(s,typeof i.message=="string"?i.message:`Sync request failed (${e.status}).`,e.status,aa(e.headers))}},Lm=class{constructor(e){this.remainder=new Uint8Array;this.iterator=e[Symbol.asyncIterator]()}async read(e){let t=new Uint8Array(new ArrayBuffer(e)),n=0;for(;n!["authorization","cookie","host","proxy-authorization","content-length"].includes(e.toLowerCase())))}function tx(r,e){return Object.entries(r).find(([n])=>n.toLowerCase()===e.toLowerCase())?.[1]}function ox(r){return[r.configDir||".obsidian",...sF].map(t=>(0,z.normalizePath)(t).replace(/\/+$/,""))}function Or(r,e){let t=yn(e);if(ox(r).some(n=>t===n||t.startsWith(`${n}/`)))throw new w("unsafe_mirror_path",`The collection authority attempted to write a reserved path: ${t}`);return t}function fe(r){if(r?.aborted)throw new DOMException("Synchronization cancelled.","AbortError")}function St(r,e){return r??new Error(`IndexedDB ${e} failed without an error detail.`)}function mF(r,e){let t=async a=>{fe(e);let c=await a();return fe(e),c},n=async function*(a){fe(e);for await(let c of a)fe(e),yield c,fe(e);fe(e)},i=r.uploadFile?.bind(r),s=r.moveFile?.bind(r),o=r.deleteFile?.bind(r);return{openSession:()=>t(()=>r.openSession()),snapshot:(a,c)=>t(()=>r.snapshot(a,c)),fileSnapshot:(a,c)=>t(()=>r.fileSnapshot(a,c)),downloadFile:a=>n(r.downloadFile(a)),...i?{uploadFile:(a,c)=>t(()=>i(a,n(c)))}:{},...s?{moveFile:a=>t(()=>s(a))}:{},...o?{deleteFile:a=>t(()=>o(a))}:{},changes:(a,c)=>t(()=>r.changes(a,c)),mutate:a=>t(()=>r.mutate(a))}}async function Ps(r,e){let t=(0,z.normalizePath)(e).replace(/\/+$/,"");if(!t)return;let n="";for(let i of t.split("/")){n=n?`${n}/${i}`:i;let s=r.getAbstractFileByPath(n);if(!(s instanceof z.TFolder)){if(s)throw new w("mirror_path_collision",`A file blocks the mirror folder ${n}.`);await r.adapter.exists(n)||await r.createFolder(n)}}}var Fm=class{constructor(e,t=s=>e.delete(s,!0),n=()=>{},i=()=>{}){this.vault=e;this.trashFile=t;this.assertActive=n;this.observeWrite=i}async exists(e){let t=Or(this.vault,e);return this.vault.getAbstractFileByPath(t)!==null||await this.vault.adapter.exists(t)}async read(e){let t=await this.readText(e);if(t===null||typeof t=="string")return t;throw new w(t.code,t.reason)}async readText(e){let t=Or(this.vault,e);if(this.vault.getAbstractFileByPath(t)instanceof z.TFolder)throw new w("mirror_path_collision",`Expected a file at ${t}.`);let i;try{i=await this.vault.adapter.readBinary(t)}catch{try{if(!await this.vault.adapter.exists(t))return null}catch{}throw new w("file_read_failed",`Could not read ${t}.`)}try{return new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}).decode(i)}catch{return{kind:"invalid",code:"invalid_utf8",reason:"File is not valid UTF-8.",revision:(await ud(i)).content_digest}}}async pathKind(e){let t=Or(this.vault,e);return(await this.vault.adapter.stat(t))?.type??null}async write(e,t,n){let i=Or(this.vault,e),s=n;if(s===void 0){let l=await this.readText(i);s=typeof l=="string"||l===null?l:void 0}let o=()=>new w("sync_plan_stale",`${i} changed before it could be written. Review sync again.`),a=i.lastIndexOf("/");a>=0&&await Ps(this.vault,i.slice(0,a));let c=this.vault.getAbstractFileByPath(i);if(c instanceof z.TFolder)throw new w("mirror_path_collision",`A folder blocks the mirror file ${i}.`);if(this.assertActive(),this.observeWrite(i),c instanceof z.TFile&&s===void 0)await this.vault.modify(c,t);else if(c instanceof z.TFile)await this.vault.process(c,l=>{if(this.assertActive(),l!==s&&l!==t)throw o();return t});else{if(s!==null)throw o();await this.vault.create(i,t)}}async move(e,t){let n=Or(this.vault,e),i=Or(this.vault,t),s=this.vault.getAbstractFileByPath(n);if(!(s instanceof z.TFile))throw new w("mirror_path_collision",`Expected a file at ${n}.`);if(this.vault.getAbstractFileByPath(i)!==null||await this.vault.adapter.exists(i))throw new w("mirror_path_collision",`A file or folder blocks the mirror path ${i}.`);let o=i.lastIndexOf("/");o>=0&&await Ps(this.vault,i.slice(0,o)),this.assertActive(),this.observeWrite(n),this.observeWrite(i),await this.vault.rename(s,i)}async remove(e){let t=Or(this.vault,e),n=this.vault.getAbstractFileByPath(t);if(n!=null){if(!(n instanceof z.TFile))throw new w("mirror_path_collision",`Expected a file at ${t}.`);this.assertActive(),this.observeWrite(t),await this.trashFile(n)}}async listMarkdown(e){return hd(this.vault).map(t=>(0,z.normalizePath)(t.path)).filter(t=>cF.test(t)&&!e.has(t)).filter(t=>!ox(this.vault).some(n=>t===n||t.startsWith(`${n}/`))).sort()}async inspectBinary(e){let t=da(e),n=this.vault.getAbstractFileByPath(t);if(n==null)return null;if(!(n instanceof z.TFile))throw new w("mirror_path_collision",`Expected a file at ${t}.`);xi(n.stat.size);let i=await this.vault.readBinary(n);return xi(i.byteLength),ud(i)}async writeBinary(e,t){let n=da(e),i=await Dm(t),s=n.lastIndexOf("/");s>=0&&await Ps(this.vault,n.slice(0,s));let o=this.vault.getAbstractFileByPath(n);if(o instanceof z.TFolder)throw new w("mirror_path_collision",`A folder blocks the mirror file ${n}.`);this.assertActive(),this.observeWrite(n),o instanceof z.TFile?await this.vault.modifyBinary(o,i):await this.vault.createBinary(n,i)}async listBinary(e){return hd(this.vault).map(t=>(0,z.normalizePath)(t.path)).filter(t=>!sx.test(t)&&!e.has(t)).filter(t=>{try{return da(t),!0}catch{return!1}}).sort()}async readBinary(e){let t=da(e),n=this.vault.getAbstractFileByPath(t);if(n==null)return null;if(!(n instanceof z.TFile))throw new w("mirror_path_collision",`Expected a file at ${t}.`);xi(n.stat.size);let i=new Uint8Array(await this.vault.readBinary(n));return xi(i.byteLength),(async function*(){for(let s=0;s{}),a}n&&n.stage!==i&&await this.removeStage(n.stage,n.chunks).catch(()=>{})}async remove(e){let t=await this.manifest(e);await this.delete(Nn,this.manifestKey(e)),t&&await this.removeStage(t.stage,t.chunks)}async prune(e){let t=await this.open(),n=await new Promise((o,a)=>{let c=[],l=t.transaction(Nn,"readonly").objectStore(Nn).openCursor();l.onsuccess=()=>{let u=l.result;if(!u)return o(c);c.push([u.key,u.value]),u.continue()},l.onerror=()=>a(St(l.error,"manifest cursor"))}),i=new Set;for(let[o,a]of n)!Array.isArray(o)||o[0]!==this.namespace||typeof o[1]=="string"&&e.has(o[1])||(await this.delete(Nn,o),await this.removeStage(a.stage,a.chunks));for(let[o,a]of n)Array.isArray(o)&&o[0]===this.namespace&&typeof o[1]=="string"&&e.has(o[1])&&i.add(a.stage);let s=await new Promise((o,a)=>{let c=[],l=t.transaction(Ln,"readonly").objectStore(Ln).openKeyCursor();l.onsuccess=()=>{let u=l.result;if(!u)return o(c);let d=u.key,f=Array.isArray(d)&&typeof d[1]=="string"?d[1]:null;Array.isArray(d)&&d[0]===this.namespace&&(f===null||!i.has(f))&&c.push(d),u.continue()},l.onerror=()=>a(St(l.error,"chunk cursor"))});for(let o of s)await this.delete(Ln,o)}manifest(e){return this.get(Nn,this.manifestKey(e))}manifestKey(e){return[this.namespace,e]}chunkKey(e,t){return[this.namespace,e,t]}async removeStage(e,t){for(let n=0;n{let o=n.transaction(e,"readonly").objectStore(e).get(t);o.onsuccess=()=>i(o.result??null),o.onerror=()=>s(St(o.error,`read from ${e}`))})}async put(e,t,n){let i=await this.open();await new Promise((s,o)=>{let a=i.transaction(e,"readwrite");a.objectStore(e).put(n,t),a.oncomplete=()=>s(),a.onerror=()=>o(St(a.error,`write to ${e}`)),a.onabort=()=>o(St(a.error,`write to ${e}`))})}async delete(e,t){let n=await this.open();await new Promise((i,s)=>{let o=n.transaction(e,"readwrite");o.objectStore(e).delete(t),o.oncomplete=()=>i(),o.onerror=()=>s(St(o.error,`delete from ${e}`)),o.onabort=()=>s(St(o.error,`delete from ${e}`))})}close(){this.database?.then(e=>e.close(),()=>{}),this.database=null}open(){if(typeof indexedDB>"u")throw new w("storage_unavailable","IndexedDB is required for binary file sync.");return this.database??=new Promise((e,t)=>{let n=indexedDB.open(Z2,1);n.onupgradeneeded=()=>{n.result.objectStoreNames.contains(Nn)||n.result.createObjectStore(Nn),n.result.objectStoreNames.contains(Ln)||n.result.createObjectStore(Ln)},n.onerror=()=>t(St(n.error,"binary store open")),n.onsuccess=()=>e(n.result)}),this.database}},qm=class{constructor(e){this.key=e;this.database=null}async read(){let e=await this.open();return new Promise((t,n)=>{let i=e.transaction(Dn,"readonly").objectStore(Dn).get(this.key);i.onsuccess=()=>t(i.result??null),i.onerror=()=>n(St(i.error,"mirror state read"))})}async write(e){let t=await this.open();await new Promise((n,i)=>{let s=t.transaction(Dn,"readwrite");s.objectStore(Dn).put(e,this.key),s.oncomplete=()=>n(),s.onerror=()=>i(St(s.error,"mirror state write")),s.onabort=()=>i(St(s.error,"mirror state write"))})}async clear(){let e=await this.open();await new Promise((t,n)=>{let i=e.transaction(Dn,"readwrite");i.objectStore(Dn).delete(this.key),i.oncomplete=()=>t(),i.onerror=()=>n(St(i.error,"mirror state clear")),i.onabort=()=>n(St(i.error,"mirror state clear"))})}close(){this.database?.then(e=>e.close(),()=>{}),this.database=null}open(){if(typeof indexedDB>"u")throw new w("storage_unavailable","IndexedDB is required for persistent mirror state.");return this.database??=new Promise((e,t)=>{let n=indexedDB.open(Q2,1);n.onupgradeneeded=()=>{n.result.objectStoreNames.contains(Dn)||n.result.createObjectStore(Dn)},n.onerror=()=>t(St(n.error,"mirror state store open")),n.onsuccess=()=>e(n.result)}),this.database}},Bm=class r{constructor(e){this.key=e}static{this.active=new Set}async runExclusive(e){if(r.active.has(this.key))throw new w("mirror_busy","A mirror operation is already running for this vault.");r.active.add(this.key);try{return await e()}finally{r.active.delete(this.key)}}},pd=class{constructor(e,t,n={}){this.app=e;this.settingsHost=t;this.options=n;this.disposed=!1;this.lifetime=new AbortController;this.stateStores=new Map;this.blobStores=new Map;this.progress=null;this.fileProgress=null;this.syncAbort=null;this.statusRequest=null;this.mirrorOperationTail=Promise.resolve();this.adoptionMarker=null;this.adoptionBusy=!1;this.engineWrites=new Map;this.renewal=null;this.fileSystem=n.fileSystem??new Fm(e.vault,i=>e.fileManager.trashFile(i),()=>this.assertActive(),i=>this.noteEngineWrite(i)),this.enrollmentClient=n.enrollmentClient??new Fl({request:dF()}),this.adoptionClient=n.adoptionClient??new zl({request:uF()})}dispose(){this.disposed=!0,this.lifetime.abort(),this.cancelSync();for(let e of this.stateStores.values())e.close();for(let e of this.blobStores.values())e.close();this.stateStores.clear(),this.blobStores.clear()}async withLifetime(e,t){this.assertActive();let n=new AbortController,i=()=>n.abort();this.lifetime.signal.addEventListener("abort",i,{once:!0}),e?.addEventListener("abort",i,{once:!0}),e?.aborted&&n.abort();try{return fe(n.signal),await t(n.signal)}finally{this.lifetime.signal.removeEventListener("abort",i),e?.removeEventListener("abort",i)}}assertActive(){if(this.disposed)throw new DOMException("Plugin unloaded.","AbortError")}async withAdoptionOperation(e,t){if(this.adoptionBusy)throw new w("authority_adoption_busy","Stop the current move before changing its setup.");this.adoptionBusy=!0;try{return await this.withLifetime(e,t)}finally{this.adoptionBusy=!1}}async initialize(){this.adoptionMarker=await this.readAdoptionMarker();let e=this.settingsHost.getMirrorProfile();if(this.adoptionMarker&&e){if(this.adoptionMarker.phase==="adopted"&&this.adoptionMarker.session.requested.collectionId===e.collectionId){await this.assertMirror(e.collectionId),await this.clearAdoptionCheckpoint(this.adoptionMarker.session.adoptionId);return}throw new w("authority_adoption_state_conflict","This vault contains both an authority-adoption checkpoint and a mirror profile.")}}getProgress(){return this.progress?{...this.progress}:null}getFileProgress(){return this.fileProgress?{...this.fileProgress}:null}getAdoptionMarker(){return this.adoptionMarker?JSON.parse(JSON.stringify(this.adoptionMarker)):null}getAdoptionRecovery(){let e=this.adoptionMarker;if(!e)return null;try{if(this.app.secretStorage.getSecret(this.adoptionSecretId(e.session.adoptionId)))return null}catch{}let t=["waiting_for_approval","uploading"].includes(e.phase);return{canReset:t&&Date.parse(e.session.expiresAt)<=Date.now(),canReconnect:!t}}async resetExpiredAdoption(){return this.withAdoptionOperation(void 0,async()=>{let e=await this.readAdoptionMarker();if(e?.session.adoptionId!==this.adoptionMarker?.session.adoptionId)throw new w("authority_adoption_state_conflict","Move setup changed. Reopen Sync before recovering it.");if(this.adoptionMarker=e,!e||this.settingsHost.getMirrorProfile()||await this.app.vault.adapter.exists(On)||!this.getAdoptionRecovery()?.canReset)throw new w("authority_adoption_reset_unsafe","Only an expired move that never froze this vault can be reset locally.");await this.clearAdoptionCheckpoint(e.session.adoptionId)})}async reconnectAdoption(e){return this.withAdoptionOperation(e.signal,async t=>{let n=this.adoptionMarker;if(!n||!this.getAdoptionRecovery()?.canReconnect||this.settingsHost.getMirrorProfile())throw new w("authority_adoption_reconnect_unsafe","This move does not require hosted recovery.");let i=await this.enrollmentClient.enroll({controlUrl:n.session.controlUrl,collectionId:n.session.requested.collectionId,mirrorName:n.session.requested.mirrorName??n.session.requested.sourceName,mode:"read_write"},{...e,signal:t});if(i.collectionId!==n.session.requested.collectionId||i.mode!=="read_write")throw new w("authority_adoption_state_conflict","Connect approved a different collection or access mode; this vault remains protected.");return fe(t),await this.updateAdoptionPhase("adopted"),this.persistAdoptedMirror(n.session,i)})}getSelectiveSync(){return fr(this.settingsHost.getMirrorProfile()?.selectiveSync??this.adoptionMarker?.selective_sync)}async configureSelectiveSync(e){let t=this.requireProfile();await this.settingsHost.saveMirrorProfile({...t,selectiveSync:fr(e)})}assertLocalAuthorityWritable(){if(this.assertActive(),this.adoptionMarker&&["fenced","activating","adopted"].includes(this.adoptionMarker.phase))throw new w("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){return this.withAdoptionOperation(t.signal,n=>this.adoptLocalCollectionActive(e,{...t,signal:n}))}async adoptLocalCollectionActive(e,t){if(this.settingsHost.getMirrorProfile())throw new w("mirror_already_configured","This vault already mirrors a collection authority.");if(this.adoptionMarker)return this.resumeAdoptionActive(t);t.onProgress?.({stage:"checking"}),Z$(await this.previewAdoption(e.selectiveSync,t.signal));let n=await this.ensurePortableCollectionIdentity(),i=await this.adoptionClient.begin({controlUrl:e.controlUrl,collectionId:n.collectionId,displayName:n.displayName,sourceName:e.mirrorName,retainMirror:!0,mirrorName:e.mirrorName},t);try{await this.storeAdoptionSecret(i)}catch(s){throw await this.adoptionClient.cancel(i,t).catch(()=>{}),s}return await this.writeAdoptionMarker({version:1,phase:"waiting_for_approval",session:Om(i),selective_sync:fr(e.selectiveSync),manifest_digest:null,source_revision:null,source_head:null}),await t.onVerification(Om(i)),this.runAdoptionWithRecovery(i,t)}async resumeAdoption(e={}){return this.withAdoptionOperation(e.signal,t=>this.resumeAdoptionActive({...e,signal:t}))}async resumeAdoptionActive(e){let t=this.adoptionMarker??await this.readAdoptionMarker();if(!t)throw new w("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 w("authority_adoption_credentials_missing","The collection-adoption credential is missing from Obsidian's secret store.");let i={...t.session,credential:n};return t.phase==="waiting_for_approval"&&await e.onVerification?.(Om(i)),this.runAdoptionWithRecovery(i,{...e,onVerification:s=>e.onVerification?.(s)})}async cancelAdoption(e){return this.withAdoptionOperation(e,t=>this.cancelAdoptionActive(t))}async cancelAdoptionActive(e){let t=this.adoptionMarker??await this.readAdoptionMarker();if(!t)return;if(["activating","adopted"].includes(t.phase))throw new w("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 w("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){return this.withLifetime(t.signal,n=>this.enrollActive(e,{...t,signal:n}))}async enrollActive(e,t){let n=await this.assertCanBecomeMirror(e.collectionId),i=await this.enrollmentClient.enroll({controlUrl:e.controlUrl,mirrorName:e.mirrorName,mode:e.mode,...n?{collectionId:n}:{}},t),s=await this.markMirror(i.collectionId);try{await this.persistEnrollment(i,e.selectiveSync)}catch(o){if(s)try{await this.app.vault.adapter.remove(On)}catch{throw new w("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 inspect(){return this.withMirrorOperation(async()=>{let e=this.requireProfile();await this.assertMirror(e.collectionId);let t=await this.createMirror(),{plan:n,status:i}=await t.review();return{preview:Sm(n),status:i}})}async preview(){return this.withMirrorOperation(async()=>{let e=this.requireProfile();await this.assertMirror(e.collectionId);let t=await this.createMirror();return Sm(await t.inspect())})}async status(){if(this.statusRequest)return this.statusRequest;let e=this.readStatus();this.statusRequest=e;try{return await e}finally{this.statusRequest===e&&(this.statusRequest=null)}}async readStatus(){return this.withMirrorOperation(async()=>{let e=this.settingsHost.getMirrorProfile();return e?(await this.assertMirror(e.collectionId),(await this.createMirror()).status()):null})}async remoteChangesWaiting(){let e=this.requireProfile(),t=await this.stateStoreFor(e).read();if(!t||t.batch)return!0;let i=await(await this.transportFor(e)).changes(t.cursor,1);return i.reset_required||i.scope_epoch!==t.scope_epoch||i.head>t.cursor}async checkpointSummary(){let e=this.settingsHost.getMirrorProfile();if(!e)return null;let t=await this.stateStoreFor(e).read();return t?{cursor:t.cursor,generation:t.generation??0,batch:t.batch?`${t.batch.phase} at action ${t.batch.next_action}/${t.batch.plan.actions.length}`:null,failure:t.batch?.failure?`${t.batch.failure.code}: ${t.batch.failure.message}`:null}:null}async reconnect(){let e=this.requireProfile();this.assertThisDevice(e),await this.renewAccessToken(e);let t=await this.status();if(!t)throw new w("mirror_not_configured","The renewed mirror profile could not be loaded.");return t}async reauthorize(e){return this.withLifetime(e.signal,t=>this.reauthorizeActive({...e,signal:t}))}async reauthorizeActive(e){let t=this.requireProfile(),n=this.isOtherDevice(t),i=this.stateStoreFor(t),s=n?null:await i.read();if(s?.batch)throw new w("mirror_recovery_required","Resume the durable synchronization checkpoint before approving this vault again.");let o=await this.enrollmentClient.enroll({controlUrl:t.controlUrl,mirrorName:t.name,mode:t.mode,collectionId:t.collectionId},e);if(o.collectionId!==t.collectionId)throw new w("mirror_identity_conflict","Connect approved a different collection. The existing mirror was not changed.");let a=rx(o,t.selectiveSync);s&&o.replicaId!==t.replicaId&&await this.stateStoreFor(a).write({...s,replica_id:o.replicaId}),await this.persistEnrollment(o,t.selectiveSync),!n&&o.replicaId!==t.replicaId&&(this.clearCredentials(t),"clear"in i&&typeof i.clear=="function"&&await i.clear());let c=await this.status();if(!c)throw new w("mirror_not_configured","The reauthorized mirror profile could not be loaded.");return c}async conflictComparison(e){let t=this.requireProfile(),n=await this.transportFor(t),i=await n.openSession(),s={state:"absent"};if(e.entity==="record"){let l;do{let u=await n.snapshot(i.snapshot_id,l),d=u.records.find(f=>f.record_id===e.object_id);if(d){s={state:"exact",path:d.path,revision:d.revision,size:new TextEncoder().encode(d.document).byteLength,document:d.document};break}l=u.next_page}while(l)}else{let l;do{let u=await n.fileSnapshot(i.snapshot_id,l),d=u.files.find(f=>f.file_id===e.object_id);if(d){s={state:"exact",path:d.path,revision:d.content_digest,size:d.size,modifiedAt:d.modified_at};break}l=u.next_page}while(l)}let o=e.path??s.path,a={state:"absent"};if(o){let l=this.app.vault.getAbstractFileByPath(o);if(l instanceof z.TFile)if(e.entity==="record"){let u=await this.app.vault.cachedRead(l);a={state:"exact",path:o,size:new TextEncoder().encode(u).byteLength,modifiedAt:l.stat?.mtime?new Date(l.stat.mtime).toISOString():void 0,document:u}}else{let u=await this.fileSystem.inspectBinary(o);u&&(a={state:"exact",path:o,revision:u.content_digest,size:u.size,modifiedAt:l.stat?.mtime?new Date(l.stat.mtime).toISOString():void 0,resourceUrl:this.app.vault.getResourcePath(l)})}}if(!(await this.status())?.conflicts.some(l=>l.object_id===e.object_id&&l.decision_id===e.decision_id))throw new w("conflict_decision_stale","This file changed again while its versions were loading.");return{entity:e.entity,objectId:e.object_id,decisionId:e.decision_id,local:a,remote:s}}async recordComparison(e,t){let n=this.requireProfile(),i=await this.transportFor(n),s=await i.openSession(),o={state:"absent"},a;do{let u=await i.snapshot(s.snapshot_id,a),d=u.records.find(f=>f.record_id===e);if(d){o={state:"exact",path:d.path,revision:d.revision,size:new TextEncoder().encode(d.document).byteLength,document:d.document};break}a=u.next_page}while(a);let c={state:"absent"},l=this.app.vault.getAbstractFileByPath(Or(this.app.vault,t));if(l instanceof z.TFile){let u=await this.app.vault.cachedRead(l);c={state:"exact",path:l.path,size:new TextEncoder().encode(u).byteLength,document:u}}return{entity:"record",objectId:e,decisionId:"",local:c,remote:o}}async autoResolveConflicts(){let e=await this.status();if(!e?.conflicts.length||e.recovery_required)return[];let t=this.requireProfile(),n=await this.stateStoreFor(t).read();if(!n||n.batch)return[];let i=e.conflicts.filter(a=>a.entity==="record"&&n.planned_conflicts?.[a.object_id]?.conflict_kind==="both_changed").map(a=>a.object_id),s=i.length?await this.remoteRecords(new Set(i)):new Map,o=[];for(let a of e.conflicts){let c=n.planned_conflicts?.[a.object_id];if(c)try{o.push(await this.autoResolve(a,c,s.get(a.object_id)))}catch(l){if(l instanceof w&&["conflict_decision_stale","sync_plan_stale"].includes(l.code))continue;o.push({path:a.path??a.object_id,outcome:"unresolved",reason:l instanceof Error?l.message:String(l)})}}return o}async autoResolve(e,t,n){let{object_id:i,decision_id:s}=e,o=t.local.state==="exact"?t.local.object.path:null,a=t.remote.state==="exact"?t.remote.object.path:null,c=e.path??o??a??i;if(t.conflict_kind==="rejected")return{path:c,outcome:"unresolved",reason:e.message};if(o===null)return await this.resolveConflict(i,s,"remote"),{path:c,outcome:a?"restored":"took_hosted"};if(a===null)return await this.resolveConflict(i,s,"local"),{path:c,outcome:"kept_local"};if(e.entity==="record"&&t.conflict_kind==="both_changed"&&n&&n.path===o&&t.remote.state==="exact"&&n.revision===t.remote.object.revision){let u=t.ancestor_document,d=await this.fileSystem.read(o);if(u!==void 0&&d!==null){let f=Y$(u,d,n.document,X2);if(f.clean){await this.resolveConflict(i,s,"local");try{await this.fileSystem.write(o,f.text,d)}catch(p){let h=await this.writeConflictCopy(o,n.document,"hosted conflict copy");return{path:c,outcome:"kept_both",copyPath:h,reason:p instanceof Error?p.message:String(p)}}return{path:c,outcome:"merged"}}}}let l=await this.preserveConflictCopy(o);return await this.resolveConflict(i,s,"remote"),{path:c,outcome:"kept_both",copyPath:l}}async remoteRecords(e){let t=await this.transportFor(this.requireProfile()),n=await t.openSession(),i=new Map,s;do{let o=await t.snapshot(n.snapshot_id,s);for(let a of o.records)e.has(a.record_id)&&i.set(a.record_id,{path:a.path,revision:a.revision,document:a.document});s=i.size===e.size?void 0:o.next_page}while(s);return i}async writeConflictCopy(e,t,n){let i=Or(this.app.vault,e),s=await this.conflictCopyPath(i,n);return await this.app.vault.create(s,t),s}async conflictCopyPath(e,t){let n=e.lastIndexOf("/"),i=e.lastIndexOf("."),s=i>n?e.slice(i):"",o=s?e.slice(0,-s.length):e,a=`${o} (${t})${s}`,c=2;for(;this.app.vault.getAbstractFileByPath(a)||await this.app.vault.adapter.exists(a);)a=`${o} (${t} ${c})${s}`,c+=1;return a}async preserveConflictCopy(e){let t=Or(this.app.vault,e);if(!(this.app.vault.getAbstractFileByPath(t)instanceof z.TFile))throw new w("mirror_conflict_copy_missing",`No local file exists at ${t}.`);let i=await this.conflictCopyPath(t,"local conflict copy");return await this.app.vault.adapter.copy(t,i),i}async disconnect(e){if(this.isSyncing())throw new w("mirror_busy","Stop the current synchronization before disconnecting.");return this.withMirrorOperation(()=>this.disconnectActive(e))}async disconnectActive(e){if(this.isSyncing())throw new w("mirror_busy","Stop the current synchronization before disconnecting.");let t=this.requireProfile(),n=this.stateStoreFor(t),i=await n.read();if(i?.batch)throw new w("mirror_recovery_required","Resume the durable synchronization checkpoint before disconnecting.");let s={removed:[],preserved:[]},o=await this.readMarker();o&&await this.app.vault.adapter.remove(On);try{await this.settingsHost.saveMirrorProfile(null)}catch(a){throw o&&await this.markMirror(t.collectionId),a}return this.isOtherDevice(t)||(this.clearCredentials(t),"clear"in n&&typeof n.clear=="function"&&await n.clear(),await this.blobStoreFor(t).prune(new Set)),e&&i&&await this.removeExactMirrorFiles(i,s),s}async sync(e,t,n,i){if(this.syncAbort)throw new w("mirror_busy","Synchronization is already running for this vault.");let s=new AbortController;this.syncAbort=s;try{return await this.withMirrorOperation(async()=>{let a=await(await this.createMirror(c=>{fe(s.signal),this.progress=c,t?.({...c})},s.signal,c=>{fe(s.signal),this.fileProgress=c,n?.({...c})},i)).apply(e.plan,{signal:s.signal});return fe(s.signal),a})}finally{this.progress=null,this.fileProgress=null,this.syncAbort=null}}cancelSync(){this.syncAbort?.abort()}noteEngineWrite(e){let t=Date.now();for(let[n,i]of this.engineWrites)t-i>Q$&&this.engineWrites.delete(n);this.engineWrites.set((0,z.normalizePath)(e),t)}isEngineWrite(e){let t=this.engineWrites.get((0,z.normalizePath)(e));return t!==void 0&&Date.now()-t<=Q$}isSyncing(){return this.syncAbort!==null}async resolveConflict(e,t,n){return this.withMirrorOperation(async()=>{let i=await this.createMirror();return await i.resolveConflict(e,t,n),i.status()})}async withMirrorOperation(e){let t=this.mirrorOperationTail,n;this.mirrorOperationTail=new Promise(i=>{n=i}),await t;try{return this.assertActive(),await e()}finally{n()}}async runAdoption(e,t){let n=this.requireAdoptionMarker(e.adoptionId),i=null;if(n.phase==="adopted"){let s=await this.adoptionClient.exchange(e,t);if(s.status!=="completed")throw new w("authority_adoption_state_conflict","The local checkpoint says adoption completed, but Connect does not.");i=s}else if(n.phase==="activating"){t.onProgress?.({stage:"activating"});let s=await this.readAdoptionSnapshot(n),o=await this.adoptionClient.exchange(e,t);i=o.status==="completed"?o:await this.adoptionClient.complete(e,s,t)}else if(n.phase==="fenced"){let s=await this.readAdoptionSnapshot(n),o=await this.adoptionClient.exchange(e,t);o.status==="completed"?i=o:(o.status==="ready"&&(t.onProgress?.({stage:"uploading",records:s.records.length}),await this.adoptionClient.uploadSnapshot(e,o,s,this.adoptionUploadOptions(e,t))),await this.updateAdoptionPhase("activating",s),t.onProgress?.({stage:"activating"}),i=await this.adoptionClient.complete(e,s,t))}else{let s=n.phase==="waiting_for_approval"?await this.adoptionClient.waitForApproval(e,t):await this.requirePreparedAdoption(e,t);await this.updateAdoptionPhase("uploading",void 0,s.adoption.expires_at),t.onProgress?.({stage:"checking"});let o=await this.captureAuthoritySnapshot(e.requested.collectionId,t.signal);t.onProgress?.({stage:"uploading",records:o.records.length}),await this.adoptionClient.uploadSnapshot(e,s,o,this.adoptionUploadOptions(e,t)),t.onProgress?.({stage:"checking"});let a=await this.captureAuthoritySnapshot(e.requested.collectionId,t.signal);await this.writeAdoptionSnapshot(a),await this.updateAdoptionPhase("fenced",a);let c=await this.requirePreparedAdoption(e,t);t.onProgress?.({stage:"uploading",records:a.records.length}),await this.adoptionClient.uploadSnapshot(e,c,a,this.adoptionUploadOptions(e,t)),await this.updateAdoptionPhase("activating",a),t.onProgress?.({stage:"activating"}),i=await this.adoptionClient.complete(e,a,t)}return await this.updateAdoptionPhase("adopted"),t.onProgress?.({stage:"connecting"}),this.finishRetainedMirror(e,i,t)}async runAdoptionWithRecovery(e,t){try{return await this.runAdoption(e,t)}catch(n){throw t.signal?.aborted?new DOMException("Adoption paused.","AbortError"):yF(n)?(await this.adoptionClient.cancel(e,{signal:t.signal}).catch(()=>{}),await this.clearAdoptionCheckpoint(e.adoptionId),new w(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 Yr("Hosted authority activation has already started. Resume using the saved fenced snapshot."):new w("authority_adoption_already_completed","Hosted authority has already adopted this collection.")}async finishRetainedMirror(e,t,n){let i,s=this.adoptionClient.mirrorEnrollmentSession(e,t);if(!s)throw new w("authority_adoption_mirror_missing","Hosted authority activated without retaining this vault as a mirror.");try{i=await this.enrollmentClient.waitForApproval(s,{signal:n.signal,onStatus:o=>n.onStatus?.({...o,state:o.state})})}catch(o){if(n.signal?.aborted)throw o;i=await this.enrollmentClient.enroll({controlUrl:e.controlUrl,collectionId:e.requested.collectionId,mirrorName:e.requested.mirrorName??e.requested.sourceName,mode:"read_write"},{signal:n.signal,onVerification:a=>n.onVerification(a)})}return this.persistAdoptedMirror(e,i)}async persistAdoptedMirror(e,t){let n=await this.markMirror(t.collectionId);try{await this.persistEnrollment(t,this.adoptionMarker?.selective_sync)}catch(i){throw n&&await this.app.vault.adapter.remove(On),i}return await this.clearAdoptionCheckpoint(e.adoptionId),this.requireProfile()}async adoptionSources(e,t){fe(t);let n=await ai(this.app.vault);if(fe(t),!n)throw new w("invalid_collection_configuration","A valid mdbase.yaml is required.");let i=await this.app.vault.adapter.read("mdbase.yaml");fe(t);let s=(0,z.parseYaml)(i),o=`${(0,z.normalizePath)(n.settings.types_folder)}/`,a=this.app.vault.getMarkdownFiles().filter(h=>(0,z.normalizePath)(h.path).startsWith(o)).sort((h,m)=>h.path.localeCompare(m.path)),c=gF(s).map(h=>(0,nx.default)(h,{dot:!0})),l=hd(this.app.vault).filter(h=>h.extension==="base"&&c.some(m=>m((0,z.normalizePath)(h.path)))).sort((h,m)=>h.path.localeCompare(m.path)),u=this.app.vault.getMarkdownFiles().filter(h=>!yt((0,z.normalizePath)(h.path),n)).sort((h,m)=>h.path.localeCompare(m.path)),d=["mdbase.yaml",...a.map(h=>h.path),...l.map(h=>h.path)],f=e.file_classes.length?(await this.fileSystem.listBinary?.(new Set(d))??[]).filter(h=>aF(e,h)&&!yt(h,n)):[];fe(t);let p={records:u.length,resources:d.length,files:f.length,conflicts:Rm([...d,...u.map(h=>h.path),...f])};return{config:n,configuration:i,typeFiles:a,baseFiles:l,recordFiles:u,binaryPaths:f,resourcePaths:d,preview:p}}renameNamespace(){return this.app.vault.getAllLoadedFiles?.()??hd(this.app.vault)}async planAdoptionRenames(e=this.getSelectiveSync()){this.assertActive();let{preview:t,resourcePaths:n}=await this.adoptionSources(fr(e)),i=this.renameNamespace().map(c=>c.path).sort(),s=X$(t.conflicts,i,new Set(n)),o=s.renames.map(({from:c})=>{let l=this.app.vault.getAbstractFileByPath(c);return[c,l instanceof z.TFile?l.stat:null]}),a=(await ud(new TextEncoder().encode(JSON.stringify({paths:i,sources:o,proposed:s,policy:e})).buffer)).content_digest;return{...s,revision:a}}async applyAdoptionRenames(e,t=this.getSelectiveSync(),n){return this.withAdoptionOperation(void 0,async i=>{if(this.assertLocalAuthorityWritable(),this.settingsHost.getMirrorProfile()||await this.app.vault.adapter.exists(On))throw new w("adoption_rename_unsafe","Automatic rename review is only available before this vault becomes a mirror.");let s=await this.planAdoptionRenames(t);if(JSON.stringify(s)!==JSON.stringify(e))throw new w("adoption_rename_stale","Files changed since the rename review. Review the new suggestions before renaming.");let o=e.renames.map(c=>this.app.vault.getAbstractFileByPath(c.from)),a=0;n?.(0,e.renames.length);for(let[c,l]of e.renames.entries()){let u=o[c];try{if(fe(i),this.assertLocalAuthorityWritable(),!(u instanceof z.TFile)||u.path!==l.from||this.app.vault.getAbstractFileByPath(l.from)!==u)throw new Error("The source file changed. Review again.");if(this.renameNamespace().some(d=>$i(d.path)===$i(l.to))||await this.app.vault.adapter.exists(l.to))throw new Error("The destination is now occupied. Review again.");fe(i),await this.app.fileManager.renameFile(u,l.to),a++}catch(d){throw u?.path===l.to&&a++,new w("adoption_rename_failed",`Rename stopped after ${a} of ${e.renames.length} files. Check filenames and links before retrying. ${d instanceof Error?d.message:String(d)}`)}n?.(a,e.renames.length)}return a})}async previewAdoption(e=this.getSelectiveSync(),t){return this.assertActive(),(await this.adoptionSources(fr(e),t)).preview}async captureAuthoritySnapshot(e,t){let{config:n,configuration:i,typeFiles:s,baseFiles:o,recordFiles:a,binaryPaths:c,preview:l}=await this.adoptionSources(this.getSelectiveSync(),t);Z$(l);let u=[{path:"mdbase.yaml",kind:"configuration",document:i}];for(let[p,h]of[["type",s],["view",o]])for(let m of h)fe(t),u.push({path:(0,z.normalizePath)(m.path),kind:p,document:await this.app.vault.cachedRead(m)});let d=[];for(let p of a){fe(t);let h=(0,z.normalizePath)(p.path),m=await this.app.vault.cachedRead(p);fe(t),d.push({path:h,document:m})}let f=[];if(c.length){let p=this.adoptionBlobStore(e);for(let h of c){fe(t);let m=await this.fileSystem.readBinary?.(h);if(fe(t),!m)continue;let y=await Dm(m);fe(t);let g=await ud(y);fe(t),await p.write(g.content_digest,(async function*(){yield new Uint8Array(y)})()),fe(t);let b=this.app.vault.getAbstractFileByPath(h);f.push({file_id:Hl(e,`file:${h}`),path:h,revision:g.content_digest,...g,...ex(h)?{media_type:ex(h)}:{},media_class:ix(h),modified_at:new Date(b instanceof z.TFile&&b.stat?.mtime?b.stat.mtime:Date.now()).toISOString()})}}return fe(t),nm({collectionId:e,sourceHead:0,specVersion:n.spec_version,resources:u,records:d,files:f})}adoptionBlobStore(e){return this.options.adoptionBlobStoreFactory?.(e)??this.cachedBlobStore(`adoption:${e}`)}adoptionUploadOptions(e,t){let n=this.adoptionBlobStore(e.requested.collectionId);return{signal:t.signal,fileSource:async i=>Dm(n.read(i.content_digest)),onFileProgress:({file:i,transferredBytes:s,totalBytes:o})=>t.onFileProgress?.(i.path,s,o)}}async ensurePortableCollectionIdentity(){if(!await this.app.vault.adapter.exists("mdbase.yaml"))throw new w("collection_not_initialized","Initialize an mdbase collection before hosting it.");let e=await this.app.vault.adapter.read("mdbase.yaml"),t;try{t=(0,z.parseYaml)(e)}catch{throw new w("invalid_collection_configuration","mdbase.yaml must contain valid YAML.")}if(!at(t))throw new w("invalid_collection_configuration","mdbase.yaml must contain a YAML mapping.");let n=at(t["x-mdbase-connect"])?t["x-mdbase-connect"].collection_id:void 0,i;if(n===void 0){i=crypto.randomUUID();let o=at(t["x-mdbase-connect"])?t["x-mdbase-connect"]:{};t["x-mdbase-connect"]={...o,collection_id:i},this.assertActive(),await this.app.vault.adapter.write("mdbase.yaml",(0,z.stringifyYaml)(t))}else if(typeof n=="string"&&ua.test(n))i=n;else throw new w("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:i,displayName:s}}stateStoreFor(e){if(this.assertActive(),this.options.stateStoreFactory)return this.options.stateStoreFactory(e);let t=`${e.collectionId}:${e.replicaId}`,n=this.stateStores.get(t);return n||(n=new qm(t),this.stateStores.set(t,n)),n}cachedBlobStore(e){this.assertActive();let t=this.blobStores.get(e);return t||(t=new jm(e),this.blobStores.set(e,t)),t}blobStoreFor(e){return this.options.blobStoreFactory?.(e)??this.cachedBlobStore(`${e.collectionId}:${e.replicaId}`)}async transportFor(e,t,n){this.assertActive(),this.assertThisDevice(e),await this.claimLegacyProfile(e);let i=await this.freshAccessToken(e);this.assertActive();let s=this.options.transportFactory?.(e,i)??new Nm(e.syncUrl,this.transportCredentials(e),md,n,t);return mF(s,t)}async createMirror(e,t,n,i){let s=this.requireProfile();await this.assertMirror(s.collectionId);let o=await this.transportFor(s,t,n),a=this.stateStoreFor(s),c={stateStore:i?new od(a,i):a,fileSystem:this.fileSystem,blobStore:this.blobStoreFor(s),selectiveSync:fr(s.selectiveSync),lease:this.options.leaseFactory?.(s)??new Bm(`${s.collectionId}:${s.replicaId}`),onProgress:e};return s.mode==="read_write"?new ia(s.replicaId,o,c):new Si(s.replicaId,o,c)}requireProfile(){this.assertActive();let e=this.settingsHost.getMirrorProfile();if(!e)throw new w("mirror_not_configured","This vault is not connected to a collection authority.");return e}secretIds(e,t){let n=e==="access"?tF:rF;return{current:`${n}${t.replicaId.toLowerCase()}`,legacy:`${n}${t.collectionId.toLowerCase()}`}}readSecret(e,t){let n=this.secretIds(e,t),i=this.app.secretStorage.getSecret(n.current);if(i)return i;let s=this.app.secretStorage.getSecret(n.legacy);if(!s)return null;try{this.app.secretStorage.setSecret(n.current,s)}catch{}return s}clearCredentials(e){for(let t of["access","refresh"]){let n=this.secretIds(t,e),i=this.app.secretStorage.getSecret(n.current);i&&this.app.secretStorage.getSecret(n.legacy)===i&&this.app.secretStorage.setSecret(n.legacy,""),this.app.secretStorage.setSecret(n.current,"")}}currentDeviceId(){return this.settingsHost.deviceId?.()}isOtherDevice(e=this.settingsHost.getMirrorProfile()){let t=this.currentDeviceId();return!!(e?.deviceId&&t&&e.deviceId!==t)}async claimLegacyProfile(e){let t=this.currentDeviceId();e.deviceId||!t||await this.settingsHost.saveMirrorProfile({...e,deviceId:t})}assertThisDevice(e){if(this.isOtherDevice(e))throw new w("mirror_other_device","This vault's sync settings were copied from another device or vault. Set up sync here to give this copy its own connection.")}adoptionSecretId(e){return`${nF}${e.toLowerCase()}`}async storeAdoptionSecret(e){try{let t=this.adoptionSecretId(e.adoptionId);if(this.app.secretStorage.setSecret(t,e.credential),this.app.secretStorage.getSecret(t)!==e.credential)throw new Error("Secret was not retained")}catch{throw new w("authority_adoption_credentials_unavailable","Obsidian could not save this device's authorization. Unlock or repair Obsidian's secret storage before starting the move. Nothing was uploaded.")}}async persistEnrollment(e,t){this.assertActive();try{let n=this.secretIds("access",e).current,i=this.secretIds("refresh",e).current;if(this.app.secretStorage.setSecret(n,e.accessToken),this.app.secretStorage.setSecret(i,e.refreshCredential),this.app.secretStorage.getSecret(n)!==e.accessToken||this.app.secretStorage.getSecret(i)!==e.refreshCredential)throw new Error("Secret was not retained")}catch{throw new w("mirror_credentials_unavailable","Obsidian could not save this device's authorization. Unlock or repair Obsidian's secret storage, then reconnect. Your files were not changed.")}await this.settingsHost.saveMirrorProfile(rx(e,t??this.settingsHost.getMirrorProfile()?.selectiveSync,this.currentDeviceId()))}async removeExactMirrorFiles(e,t){let n=new Map;for(let[i,s]of Object.entries(e.records)){let o=e.local_bindings?.[i]?.path??s.path;n.set(o,{entity:"document",document:s.record?.document,revision:s.revision})}for(let[i,s]of Object.entries(e.resources??{})){let o=e.local_bindings?.[i]?.path??s.path;n.set(o,{entity:"document",document:s.record?.document,revision:s.revision})}for(let[i,s]of Object.entries(e.files??{})){let o=e.local_bindings?.[i]?.path??s.file.path;n.set(o,{entity:"file",digest:s.file.content_digest,size:s.file.size})}for(let[i,s]of[...n.entries()].sort(([o],[a])=>a.localeCompare(o))){let o=!1;if(s.entity==="document"){let a=await this.fileSystem.read(i);o=a!==null&&(s.document!==void 0?a===s.document:await wF(a,s.revision))}else if(s.entity==="file"){let a=await this.fileSystem.inspectBinary(i);o=a!==null&&a.content_digest===s.digest&&a.size===s.size}if(!o){await this.fileSystem.exists(i)&&t.preserved.push(i);continue}try{await this.fileSystem.remove(i),t.removed.push(i)}catch{t.preserved.push(i)}}}async freshAccessToken(e){if(this.renewal)return this.renewal;let t=this.readSecret("access",e),n=Date.parse(e.accessTokenExpiresAt);return t&&Number.isFinite(n)&&n-Date.now()>iF?t:this.renewAccessToken(e)}renewAccessToken(e){return this.renewal??=this.renewAccessTokenOnce(e).finally(()=>{this.renewal=null}),this.renewal}async renewAccessTokenOnce(e){let t=this.readSecret("refresh",e);if(!t)throw new w("mirror_credentials_missing","The mirror refresh credential is missing. Approve this vault again.");let n=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:this.readSecret("access",e)??"",refreshCredential:t,accessTokenExpiresAt:e.accessTokenExpiresAt});return await this.persistEnrollment(n,e.selectiveSync),n.accessToken}transportCredentials(e){return{token:()=>this.freshAccessToken(this.requireProfile()),renew:async t=>{let n=this.readSecret("access",e);return n&&n!==t?n:this.renewAccessToken(this.requireProfile())}}}async assertCanBecomeMirror(e){let t=await this.readMarker(),n=await this.readPortableCollectionId();if(n&&!t)throw new w("local_authority_requires_transfer","This vault has a local Connect identity. Transfer authority explicitly before using it as a mirror.");if(n&&t?.collection_id!==n)throw new w("mirror_identity_conflict","The vault identity and mirror role marker identify different collections.");let i=this.settingsHost.getMirrorProfile(),s=i?.collectionId??e;if(t&&s&&t.collection_id!==s)throw new w("mirror_identity_conflict","This vault is already marked as a different mirror.");if(!t&&!i&&await this.app.vault.adapter.exists("mdbase.yaml"))throw new w("existing_collection_requires_transfer","This vault already contains an mdbase collection. Connect an empty vault, or transfer collection authority explicitly.");return s??t?.collection_id}async readPortableCollectionId(){if(!await this.app.vault.adapter.exists("mdbase.yaml"))return null;let e;try{e=(0,z.parseYaml)(await this.app.vault.adapter.read("mdbase.yaml"))}catch{throw new w("invalid_collection_configuration","mdbase.yaml must contain valid YAML.")}if(!at(e))throw new w("invalid_collection_configuration","mdbase.yaml must contain a YAML mapping.");let t=e["x-mdbase-connect"];if(t===void 0)return null;if(!at(t))throw new w("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"||!ua.test(n))throw new w("invalid_collection_configuration","x-mdbase-connect.collection_id must be a UUID string.");return n}async markMirror(e){this.assertActive();let t=await this.readMarker();if(t){if(t.collection_id!==e)throw new w("mirror_identity_conflict","This vault already mirrors a different collection authority.");return!1}return await Ps(this.app.vault,".mdbase"),this.assertActive(),await this.app.vault.adapter.write(On,`${JSON.stringify({version:1,role:"mirror",collection_id:e},null,2)} +`)??null;let a=new Map;for(let l of new Set([...i.order,...s.order,...n.order])){let u=X$(n.blocks.get(l),i.blocks.get(l),s.blocks.get(l));if(u===null)return null;u!==void 0&&a.set(l,u)}let c=i.order.filter(l=>a.has(l));for(let[l,u]of s.order.entries()){if(!a.has(u)||c.includes(u))continue;let d=s.order.slice(0,l).reverse().find(f=>c.includes(f));c.splice(d===void 0?0:c.indexOf(d)+1,0,u)}return c.flatMap(l=>(a.get(l)??"").split(` +`))}function X$(r,e,t){return e===t?e:e===r?t:t===r?e:null}function $i(r){return[...r.normalize("NFC")].map(e=>e.toLowerCase()).join("").normalize("NFC")}function Rm(r){let e=new Map;for(let t of r){let n=$i(t),i=e.get(n)??[];i.push(t),e.set(n,i)}return[...e.values()].filter(t=>t.length>1)}function Q$(r,e,t){let n=new Set([...e].map($i)),i=[],s=[];for(let o of[...r].sort((a,c)=>a[0]c[0]?1:0)){let a=[...o].sort();if(a.some(c=>t.has(c))||new Set(a).size!==a.length){s.push(a);continue}for(let c of a.slice(1)){let l=c.lastIndexOf("/"),u=c.lastIndexOf("."),d=u>l+1?c.slice(u):"",f=d?c.slice(0,-d.length):c,p=2,m;do m=`${f} (${p++})${d}`;while(n.has($i(m)));n.add($i(m)),i.push({from:c,to:m})}}return{renames:i,manual:s}}function X2(r){try{let e=(0,z.parseYaml)(r);return e===null||typeof e=="object"&&!Array.isArray(e)}catch{return!1}}var On=".mdbase/connect-role.json",ca=".mdbase/authority-adoption.json",la=".mdbase/authority-adoption-snapshot.json",Q2="mdbase-obsidian-connect",Dn="mirrors",Z2="mdbase-obsidian-connect-blobs",Nn="manifests",Ln="chunks",ld=1024*1024,eF=32*1024*1024,Z$=2e3;function xi(r){if(!Number.isSafeInteger(r)||r<0||r>eF)throw new w("file_too_large","Binary sync supports files up to 32 MiB on this device. Exclude this file's folder to continue.")}var tF="mdbase-connect-access-",rF="mdbase-connect-refresh-",nF="mdbase-connect-adoption-",iF=300*1e3,sF=[".git",".trash",".mdbase"],oF=new Set([".git",".mdbase",".trash","node_modules","_contracts","_schemas","_types","_views"]),Im=["image","audio","video","pdf","other"],ua=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function at(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function fr(r){let e=r?.file_classes??[];if(e.some(s=>!Im.includes(s))||new Set(e).size!==e.length)throw new w("invalid_file_materialization","Selected file media classes must be valid and unique.");let t=[...e].sort((s,o)=>Im.indexOf(s)-Im.indexOf(o)),n=r?.excluded_folders??[];if(n.some(s=>typeof s!="string"||!s.trim()))throw new w("invalid_file_materialization","Excluded folders cannot be empty.");let i=n.map(s=>yn(s.trim())).sort((s,o)=>s.toLocaleLowerCase().localeCompare(o.toLocaleLowerCase()));if(i.length>100)throw new w("invalid_file_materialization","File sync supports at most 100 excluded folders.");if(new Set(i.map(s=>s.toLocaleLowerCase())).size!==i.length)throw new w("invalid_file_materialization","Excluded folders must be unique on portable filesystems.");for(let s of i)da(s,!0);return{file_classes:t,excluded_folders:i}}function sx(r){let e=r.includes(".")?r.slice(r.lastIndexOf(".")+1).toLowerCase():"";return["avif","bmp","gif","jpeg","jpg","png","svg","webp"].includes(e)?"image":["flac","m4a","mp3","oga","ogg","opus","wav"].includes(e)?"audio":["3gp","mkv","mov","mp4","webm"].includes(e)?"video":e==="pdf"?"pdf":"other"}function ex(r){if(r.conflicts.length)throw new w("authority_import_path_conflict",`${r.conflicts.length} filename conflicts prevent uploading. Review the paths in Sync and rename the conflicting files before retrying. Nothing was renamed or excluded.`)}function aF(r,e,t=sx(e)){if(!r.file_classes.includes(t))return!1;let n=(0,z.normalizePath)(e);return!r.excluded_folders.some(i=>n===i||n.startsWith(`${i}/`))}var cF=/\.(?:md|base)$/,ox=/\.(?:md|base)$/i;function da(r,e=!1){let t=yn(r),n=t.split("/");if(t.length>1024||!e&&ox.test(t)||n.some(i=>i.startsWith(".")||oF.has(i.toLowerCase())||/[<>"|?*]/u.test(i)||/^(?:CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\.|$)/iu.test(i)))throw new w("invalid_file_path",`Collection file path ${t} is hidden, reserved, or non-portable.`);return t}async function dd(r){let e=new Uint8Array(await crypto.subtle.digest("SHA-256",r));return{size:r.byteLength,content_digest:`sha256:${Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}`}}async function Dm(r){let e=[],t=0;for await(let s of r){if(!(s instanceof Uint8Array))throw new w("file_integrity_failed","A binary stream returned an invalid chunk.");s.byteLength&&(t+=s.byteLength,xi(t),e.push(Uint8Array.from(s)))}let n=new Uint8Array(t),i=0;for(let s of e)n.set(s,i),i+=s.byteLength;return n.buffer}function tx(r){let e=r.includes(".")?r.slice(r.lastIndexOf(".")+1).toLowerCase():"";return{avif:"image/avif",gif:"image/gif",jpeg:"image/jpeg",jpg:"image/jpeg",png:"image/png",svg:"image/svg+xml",webp:"image/webp",flac:"audio/flac",m4a:"audio/mp4",mp3:"audio/mpeg",ogg:"audio/ogg",opus:"audio/opus",wav:"audio/wav",mov:"video/quicktime",mp4:"video/mp4",webm:"video/webm",pdf:"application/pdf"}[e]}async function lF(r,e){if(r!==void 0){if(!e)return JSON.stringify(r);if(r instanceof ArrayBuffer)return r;if(ArrayBuffer.isView(r))return Uint8Array.from(new Uint8Array(r.buffer,r.byteOffset,r.byteLength)).buffer;if(r instanceof Blob)return r.arrayBuffer();throw new w("invalid_file_upload","The adoption upload body was not binary data.")}}function ud(r,e){if(e!=null)return e;if(!r.trim())return{};try{return JSON.parse(r)}catch{return{}}}var hd=L$(F$());function dF(){return async r=>{if(r.signal?.aborted)throw new DOMException("Enrollment cancelled.","AbortError");let e=await hd({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,signal:r.signal});if(r.signal?.aborted)throw new DOMException("Enrollment cancelled.","AbortError");return{status:e.status,body:ud(e.text,e.json),retryAfterMs:aa(e.headers)}}}function uF(){return async r=>{if(r.signal?.aborted)throw new DOMException("Collection adoption cancelled.","AbortError");let e=await lF(r.body,r.rawBody),t=await hd({url:r.url,method:r.method,headers:r.headers,body:e,contentType:e===void 0||r.rawBody?void 0:"application/json",throw:!1,signal:r.signal});if(r.signal?.aborted)throw new DOMException("Collection adoption cancelled.","AbortError");return{status:t.status,body:ud(t.text,t.json),retryAfterMs:aa(t.headers),headers:t.headers}}}var Nm=class{constructor(e,t,n=hd,i,s){this.send=n;this.onFileProgress=i;this.signal=s;this.credentials=typeof t=="string"?{token:()=>Promise.resolve(t)}:t;let o;try{o=new URL(e)}catch{throw new w("invalid_sync_url","Sync URL must be an absolute authority endpoint.")}if(!(o.protocol==="https:"||o.protocol==="http:"&&["localhost","127.0.0.1","[::1]","::1"].includes(o.hostname))||o.username||o.password||o.search||o.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(o.pathname))throw new w("invalid_sync_url","Sync URL must identify one authority sync endpoint.");this.syncUrl=o.href.replace(/\/$/,""),this.filesUrl=this.syncUrl.replace(/\/sync$/u,"/files")}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()}`)}fileSnapshot(e,t){let n=new URLSearchParams({snapshot_id:e});return t&&n.set("page",t),this.request("GET",`files/snapshot?${n.toString()}`)}async*downloadFile(e){xi(e.size);let t=crypto.randomUUID();try{let n=0;this.onFileProgress?.({direction:"download",path:e.path,transferredBytes:n,totalBytes:e.size});let i=await this.fileRequest("POST","downloads",{protocol_version:1,type:"open_file_download",transfer_id:t,file_id:e.file_id,revision:e.revision});if(i.protocol_version!==1||i.type!=="file_transfer"||i.transfer_id!==t||i.direction!=="download"||i.protection!=="transport_tls"||i.total_size!==e.size||i.strategy.kind!=="object_ranges"||!Number.isSafeInteger(i.strategy.part_size)||i.strategy.part_size<=0)throw new w("invalid_sync_response","The authority returned an incompatible file download session.");let s=Math.ceil(e.size/i.strategy.part_size);for(let o=0;o=300)throw this.responseError(c,"file_download_failed");let l=rx(c.headers,"content-length");if(l!==void 0&&Number(l)!==a||c.arrayBuffer.byteLength!==a)throw new w("file_integrity_failed","Hosted authority returned a file part with the wrong length.");n+=a,this.onFileProgress?.({direction:"download",path:e.path,transferredBytes:n,totalBytes:e.size}),a&&(yield new Uint8Array(c.arrayBuffer))}}finally{await this.fileRequest("DELETE",`transfers/${encodeURIComponent(t)}`).catch(()=>{})}}async uploadFile(e,t){xi(e.size);let n=await this.fileRequest("POST","uploads",e);if(n.protocol_version!==1||n.type!=="file_transfer"||n.transfer_id!==e.transfer_id||n.direction!=="upload"||n.protection!=="transport_tls"||n.total_size!==e.size||!["object_put","object_multipart"].includes(n.strategy.kind))throw new w("invalid_sync_response","Authority returned an incompatible file upload session.");let i=n.strategy.kind==="object_multipart"?n.strategy.part_size:Math.max(1,e.size);if(!Number.isSafeInteger(i)||i<=0)throw new w("invalid_sync_response","Authority returned an invalid upload part size.");let s=new Lm(t),o=Math.max(1,Math.ceil(e.size/i));if(n.received.some(d=>!Number.isSafeInteger(d)||d<0||d>=o)||new Set(n.received).size!==n.received.length)throw new w("invalid_sync_response","Authority returned invalid upload progress.");let a=n.uploaded_parts??[];if(a.some((d,f)=>!Number.isSafeInteger(d.part_number)||d.part_number<1||d.part_number>o||!d.etag||d.etag.length>255||f>0&&a[f-1].part_number>=d.part_number)||(n.strategy.kind==="object_multipart"?a.length!==n.received.length||a.some((d,f)=>d.part_number-1!==n.received[f]):a.length!==0))throw new w("invalid_sync_response","Authority returned invalid uploaded part receipts.");let c=n.received.reduce((d,f)=>{let p=f*i;return d+Math.min(i,Math.max(0,e.size-p))},0);if(this.onFileProgress?.({direction:"upload",path:e.path,transferredBytes:c,totalBytes:e.size}),n.received.length===o)return this.commitUpload(e.transfer_id,a);let l=new Set(n.received),u=Array.from({length:o},()=>{});for(let d of a)u[d.part_number-1]=d;for(let d=0;d=300)throw new In(y.status===429||y.status>=500?"authority_unavailable":"file_upload_failed",`Object storage returned HTTP ${y.status}.`,y.status);if(c+=p,this.onFileProgress?.({direction:"upload",path:e.path,transferredBytes:c,totalBytes:e.size}),n.strategy.kind==="object_multipart"){let g=rx(y.headers,"etag");if(!g)throw new w("invalid_sync_response","Object storage omitted a multipart ETag.");u[d]={part_number:d+1,etag:g}}}return await s.expectEnd(),this.commitUpload(e.transfer_id,u.filter(d=>d!==void 0))}async commitUpload(e,t){let n=await this.fileRequest("POST",`uploads/${encodeURIComponent(e)}/commit`,{protocol_version:1,type:"commit_file_upload",transfer_id:e,parts:t});if(n.protocol_version!==1||n.type!=="file_upload_committed"||n.transfer_id!==e)throw new w("invalid_sync_response","Authority returned an invalid file upload receipt.");return n}async moveFile(e){let t=await this.fileRequest("POST",`${encodeURIComponent(e.file_id)}/move`,e);if(t.protocol_version!==1||t.type!=="file_moved"||t.mutation_id!==e.mutation_id)throw new w("invalid_sync_response","Authority returned an invalid file move receipt.");return t}async deleteFile(e){let t=await this.fileRequest("POST",`${encodeURIComponent(e.file_id)}/delete`,e);if(t.protocol_version!==1||t.type!=="file_deleted"||t.mutation_id!==e.mutation_id||t.file_id!==e.file_id)throw new w("invalid_sync_response","Authority returned an invalid file delete receipt.");return t}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){return this.requestAt(this.syncUrl,e,t,n)}async fileRequest(e,t,n){return this.requestAt(this.filesUrl,e,t,n)}async requestAt(e,t,n,i){let s=await this.authorized({url:`${e}/${n}`,method:t,body:i===void 0?void 0:JSON.stringify(i),contentType:i===void 0?void 0:"application/json",throw:!1}),o=ud(s.text,s.json);if(s.status<200||s.status>=300)throw this.responseError(s,"sync_failed");return o}async authorized(e){let t=s=>this.send({...e,headers:{authorization:`Bearer ${s}`},signal:this.signal}),n=await this.credentials.token(),i=await t(n);return i.status!==401||!this.credentials.renew?i:t(await this.credentials.renew(n))}responseError(e,t){let n=ud(e.text,e.json),i=at(n)&&at(n.error)?n.error:{},s=typeof i.code=="string"?i.code:e.status===401?"mirror_access_rejected":e.status===429||e.status>=500?"authority_unavailable":t;return new In(s,typeof i.message=="string"?i.message:`Sync request failed (${e.status}).`,e.status,aa(e.headers))}},Lm=class{constructor(e){this.remainder=new Uint8Array;this.iterator=e[Symbol.asyncIterator]()}async read(e){let t=new Uint8Array(new ArrayBuffer(e)),n=0;for(;n!["authorization","cookie","host","proxy-authorization","content-length"].includes(e.toLowerCase())))}function rx(r,e){return Object.entries(r).find(([n])=>n.toLowerCase()===e.toLowerCase())?.[1]}function ax(r){return[r.configDir||".obsidian",...sF].map(t=>(0,z.normalizePath)(t).replace(/\/+$/,""))}function Or(r,e){let t=yn(e);if(ax(r).some(n=>t===n||t.startsWith(`${n}/`)))throw new w("unsafe_mirror_path",`The collection authority attempted to write a reserved path: ${t}`);return t}function fe(r){if(r?.aborted)throw new DOMException("Synchronization cancelled.","AbortError")}function St(r,e){return r??new Error(`IndexedDB ${e} failed without an error detail.`)}function mF(r,e){let t=async a=>{fe(e);let c=await a();return fe(e),c},n=async function*(a){fe(e);for await(let c of a)fe(e),yield c,fe(e);fe(e)},i=r.uploadFile?.bind(r),s=r.moveFile?.bind(r),o=r.deleteFile?.bind(r);return{openSession:()=>t(()=>r.openSession()),snapshot:(a,c)=>t(()=>r.snapshot(a,c)),fileSnapshot:(a,c)=>t(()=>r.fileSnapshot(a,c)),downloadFile:a=>n(r.downloadFile(a)),...i?{uploadFile:(a,c)=>t(()=>i(a,n(c)))}:{},...s?{moveFile:a=>t(()=>s(a))}:{},...o?{deleteFile:a=>t(()=>o(a))}:{},changes:(a,c)=>t(()=>r.changes(a,c)),mutate:a=>t(()=>r.mutate(a))}}async function Ps(r,e){let t=(0,z.normalizePath)(e).replace(/\/+$/,"");if(!t)return;let n="";for(let i of t.split("/")){n=n?`${n}/${i}`:i;let s=r.getAbstractFileByPath(n);if(!(s instanceof z.TFolder)){if(s)throw new w("mirror_path_collision",`A file blocks the mirror folder ${n}.`);await r.adapter.exists(n)||await r.createFolder(n)}}}var Fm=class{constructor(e,t=s=>e.delete(s,!0),n=()=>{},i=()=>{}){this.vault=e;this.trashFile=t;this.assertActive=n;this.observeWrite=i}async exists(e){let t=Or(this.vault,e);return this.vault.getAbstractFileByPath(t)!==null||await this.vault.adapter.exists(t)}async read(e){let t=await this.readText(e);if(t===null||typeof t=="string")return t;throw new w(t.code,t.reason)}async readText(e){let t=Or(this.vault,e);if(this.vault.getAbstractFileByPath(t)instanceof z.TFolder)throw new w("mirror_path_collision",`Expected a file at ${t}.`);let i;try{i=await this.vault.adapter.readBinary(t)}catch{try{if(!await this.vault.adapter.exists(t))return null}catch{}throw new w("file_read_failed",`Could not read ${t}.`)}try{return new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}).decode(i)}catch{return{kind:"invalid",code:"invalid_utf8",reason:"File is not valid UTF-8.",revision:(await dd(i)).content_digest}}}async pathKind(e){let t=Or(this.vault,e);return(await this.vault.adapter.stat(t))?.type??null}async write(e,t,n){let i=Or(this.vault,e),s=n;if(s===void 0){let l=await this.readText(i);s=typeof l=="string"||l===null?l:void 0}let o=()=>new w("sync_plan_stale",`${i} changed before it could be written. Review sync again.`),a=i.lastIndexOf("/");a>=0&&await Ps(this.vault,i.slice(0,a));let c=this.vault.getAbstractFileByPath(i);if(c instanceof z.TFolder)throw new w("mirror_path_collision",`A folder blocks the mirror file ${i}.`);if(this.assertActive(),this.observeWrite(i),c instanceof z.TFile&&s===void 0)await this.vault.modify(c,t);else if(c instanceof z.TFile)await this.vault.process(c,l=>{if(this.assertActive(),l!==s&&l!==t)throw o();return t});else{if(s!==null)throw o();await this.vault.create(i,t)}}async move(e,t){let n=Or(this.vault,e),i=Or(this.vault,t),s=this.vault.getAbstractFileByPath(n);if(!(s instanceof z.TFile))throw new w("mirror_path_collision",`Expected a file at ${n}.`);if(this.vault.getAbstractFileByPath(i)!==null||await this.vault.adapter.exists(i))throw new w("mirror_path_collision",`A file or folder blocks the mirror path ${i}.`);let o=i.lastIndexOf("/");o>=0&&await Ps(this.vault,i.slice(0,o)),this.assertActive(),this.observeWrite(n),this.observeWrite(i),await this.vault.rename(s,i)}async remove(e){let t=Or(this.vault,e),n=this.vault.getAbstractFileByPath(t);if(n!=null){if(!(n instanceof z.TFile))throw new w("mirror_path_collision",`Expected a file at ${t}.`);this.assertActive(),this.observeWrite(t),await this.trashFile(n)}}async listMarkdown(e){return pd(this.vault).map(t=>(0,z.normalizePath)(t.path)).filter(t=>cF.test(t)&&!e.has(t)).filter(t=>!ax(this.vault).some(n=>t===n||t.startsWith(`${n}/`))).sort()}async inspectBinary(e){let t=da(e),n=this.vault.getAbstractFileByPath(t);if(n==null)return null;if(!(n instanceof z.TFile))throw new w("mirror_path_collision",`Expected a file at ${t}.`);xi(n.stat.size);let i=await this.vault.readBinary(n);return xi(i.byteLength),dd(i)}async writeBinary(e,t,n){let i=da(e),s=n===void 0?await this.inspectBinary(i):n,o=await Dm(t),a=i.lastIndexOf("/");a>=0&&await Ps(this.vault,i.slice(0,a));let c=await this.inspectBinary(i);if(c?.content_digest!==s?.content_digest||c?.size!==s?.size)throw new w("sync_plan_stale",`${i} changed before it could be written. Review sync again.`);let l=this.vault.getAbstractFileByPath(i);if(l instanceof z.TFolder)throw new w("mirror_path_collision",`A folder blocks the mirror file ${i}.`);this.assertActive(),this.observeWrite(i),l instanceof z.TFile?await this.vault.modifyBinary(l,o):await this.vault.createBinary(i,o)}async listBinary(e){return pd(this.vault).map(t=>(0,z.normalizePath)(t.path)).filter(t=>!ox.test(t)&&!e.has(t)).filter(t=>{try{return da(t),!0}catch{return!1}}).sort()}async readBinary(e){let t=da(e),n=this.vault.getAbstractFileByPath(t);if(n==null)return null;if(!(n instanceof z.TFile))throw new w("mirror_path_collision",`Expected a file at ${t}.`);xi(n.stat.size);let i=new Uint8Array(await this.vault.readBinary(n));return xi(i.byteLength),(async function*(){for(let s=0;s{}),a}n&&n.stage!==i&&await this.removeStage(n.stage,n.chunks).catch(()=>{})}async remove(e){let t=await this.manifest(e);await this.delete(Nn,this.manifestKey(e)),t&&await this.removeStage(t.stage,t.chunks)}async prune(e){let t=await this.open(),n=await new Promise((o,a)=>{let c=[],l=t.transaction(Nn,"readonly").objectStore(Nn).openCursor();l.onsuccess=()=>{let u=l.result;if(!u)return o(c);c.push([u.key,u.value]),u.continue()},l.onerror=()=>a(St(l.error,"manifest cursor"))}),i=new Set;for(let[o,a]of n)!Array.isArray(o)||o[0]!==this.namespace||typeof o[1]=="string"&&e.has(o[1])||(await this.delete(Nn,o),await this.removeStage(a.stage,a.chunks));for(let[o,a]of n)Array.isArray(o)&&o[0]===this.namespace&&typeof o[1]=="string"&&e.has(o[1])&&i.add(a.stage);let s=await new Promise((o,a)=>{let c=[],l=t.transaction(Ln,"readonly").objectStore(Ln).openKeyCursor();l.onsuccess=()=>{let u=l.result;if(!u)return o(c);let d=u.key,f=Array.isArray(d)&&typeof d[1]=="string"?d[1]:null;Array.isArray(d)&&d[0]===this.namespace&&(f===null||!i.has(f))&&c.push(d),u.continue()},l.onerror=()=>a(St(l.error,"chunk cursor"))});for(let o of s)await this.delete(Ln,o)}manifest(e){return this.get(Nn,this.manifestKey(e))}manifestKey(e){return[this.namespace,e]}chunkKey(e,t){return[this.namespace,e,t]}async removeStage(e,t){for(let n=0;n{let o=n.transaction(e,"readonly").objectStore(e).get(t);o.onsuccess=()=>i(o.result??null),o.onerror=()=>s(St(o.error,`read from ${e}`))})}async put(e,t,n){let i=await this.open();await new Promise((s,o)=>{let a=i.transaction(e,"readwrite");a.objectStore(e).put(n,t),a.oncomplete=()=>s(),a.onerror=()=>o(St(a.error,`write to ${e}`)),a.onabort=()=>o(St(a.error,`write to ${e}`))})}async delete(e,t){let n=await this.open();await new Promise((i,s)=>{let o=n.transaction(e,"readwrite");o.objectStore(e).delete(t),o.oncomplete=()=>i(),o.onerror=()=>s(St(o.error,`delete from ${e}`)),o.onabort=()=>s(St(o.error,`delete from ${e}`))})}close(){this.database?.then(e=>e.close(),()=>{}),this.database=null}open(){if(typeof indexedDB>"u")throw new w("storage_unavailable","IndexedDB is required for binary file sync.");return this.database??=new Promise((e,t)=>{let n=indexedDB.open(Z2,1);n.onupgradeneeded=()=>{n.result.objectStoreNames.contains(Nn)||n.result.createObjectStore(Nn),n.result.objectStoreNames.contains(Ln)||n.result.createObjectStore(Ln)},n.onerror=()=>t(St(n.error,"binary store open")),n.onsuccess=()=>e(n.result)}),this.database}},qm=class{constructor(e){this.key=e;this.database=null}async read(){let e=await this.open();return new Promise((t,n)=>{let i=e.transaction(Dn,"readonly").objectStore(Dn).get(this.key);i.onsuccess=()=>t(i.result??null),i.onerror=()=>n(St(i.error,"mirror state read"))})}async write(e){let t=await this.open();await new Promise((n,i)=>{let s=t.transaction(Dn,"readwrite");s.objectStore(Dn).put(e,this.key),s.oncomplete=()=>n(),s.onerror=()=>i(St(s.error,"mirror state write")),s.onabort=()=>i(St(s.error,"mirror state write"))})}async clear(){let e=await this.open();await new Promise((t,n)=>{let i=e.transaction(Dn,"readwrite");i.objectStore(Dn).delete(this.key),i.oncomplete=()=>t(),i.onerror=()=>n(St(i.error,"mirror state clear")),i.onabort=()=>n(St(i.error,"mirror state clear"))})}close(){this.database?.then(e=>e.close(),()=>{}),this.database=null}open(){if(typeof indexedDB>"u")throw new w("storage_unavailable","IndexedDB is required for persistent mirror state.");return this.database??=new Promise((e,t)=>{let n=indexedDB.open(Q2,1);n.onupgradeneeded=()=>{n.result.objectStoreNames.contains(Dn)||n.result.createObjectStore(Dn)},n.onerror=()=>t(St(n.error,"mirror state store open")),n.onsuccess=()=>e(n.result)}),this.database}},Bm=class r{constructor(e){this.key=e}static{this.active=new Set}async runExclusive(e){if(r.active.has(this.key))throw new w("mirror_busy","A mirror operation is already running for this vault.");r.active.add(this.key);try{return await e()}finally{r.active.delete(this.key)}}},fd=class{constructor(e,t,n={}){this.app=e;this.settingsHost=t;this.options=n;this.disposed=!1;this.lifetime=new AbortController;this.stateStores=new Map;this.blobStores=new Map;this.progress=null;this.fileProgress=null;this.syncAbort=null;this.statusRequest=null;this.mirrorOperationTail=Promise.resolve();this.adoptionMarker=null;this.adoptionBusy=!1;this.engineWrites=new Map;this.renewal=null;this.fileSystem=n.fileSystem??new Fm(e.vault,i=>e.fileManager.trashFile(i),()=>this.assertActive(),i=>this.noteEngineWrite(i)),this.enrollmentClient=n.enrollmentClient??new Fl({request:dF()}),this.adoptionClient=n.adoptionClient??new zl({request:uF()})}dispose(){this.disposed=!0,this.lifetime.abort(),this.cancelSync();for(let e of this.stateStores.values())e.close();for(let e of this.blobStores.values())e.close();this.stateStores.clear(),this.blobStores.clear()}async withLifetime(e,t){this.assertActive();let n=new AbortController,i=()=>n.abort();this.lifetime.signal.addEventListener("abort",i,{once:!0}),e?.addEventListener("abort",i,{once:!0}),e?.aborted&&n.abort();try{return fe(n.signal),await t(n.signal)}finally{this.lifetime.signal.removeEventListener("abort",i),e?.removeEventListener("abort",i)}}assertActive(){if(this.disposed)throw new DOMException("Plugin unloaded.","AbortError")}async withAdoptionOperation(e,t){if(this.adoptionBusy)throw new w("authority_adoption_busy","Stop the current move before changing its setup.");this.adoptionBusy=!0;try{return await this.withLifetime(e,t)}finally{this.adoptionBusy=!1}}async initialize(){this.adoptionMarker=await this.readAdoptionMarker();let e=this.settingsHost.getMirrorProfile();if(this.adoptionMarker&&e){if(this.adoptionMarker.phase==="adopted"&&this.adoptionMarker.session.requested.collectionId===e.collectionId){await this.assertMirror(e.collectionId),await this.clearAdoptionCheckpoint(this.adoptionMarker.session.adoptionId);return}throw new w("authority_adoption_state_conflict","This vault contains both an authority-adoption checkpoint and a mirror profile.")}}getProgress(){return this.progress?{...this.progress}:null}getFileProgress(){return this.fileProgress?{...this.fileProgress}:null}getAdoptionMarker(){return this.adoptionMarker?JSON.parse(JSON.stringify(this.adoptionMarker)):null}getAdoptionRecovery(){let e=this.adoptionMarker;if(!e)return null;try{if(this.app.secretStorage.getSecret(this.adoptionSecretId(e.session.adoptionId)))return null}catch{}let t=["waiting_for_approval","uploading"].includes(e.phase);return{canReset:t&&Date.parse(e.session.expiresAt)<=Date.now(),canReconnect:!t}}async resetExpiredAdoption(){return this.withAdoptionOperation(void 0,async()=>{let e=await this.readAdoptionMarker();if(e?.session.adoptionId!==this.adoptionMarker?.session.adoptionId)throw new w("authority_adoption_state_conflict","Move setup changed. Reopen Sync before recovering it.");if(this.adoptionMarker=e,!e||this.settingsHost.getMirrorProfile()||await this.app.vault.adapter.exists(On)||!this.getAdoptionRecovery()?.canReset)throw new w("authority_adoption_reset_unsafe","Only an expired move that never froze this vault can be reset locally.");await this.clearAdoptionCheckpoint(e.session.adoptionId)})}async reconnectAdoption(e){return this.withAdoptionOperation(e.signal,async t=>{let n=this.adoptionMarker;if(!n||!this.getAdoptionRecovery()?.canReconnect||this.settingsHost.getMirrorProfile())throw new w("authority_adoption_reconnect_unsafe","This move does not require hosted recovery.");let i=await this.enrollmentClient.enroll({controlUrl:n.session.controlUrl,collectionId:n.session.requested.collectionId,mirrorName:n.session.requested.mirrorName??n.session.requested.sourceName,mode:"read_write"},{...e,signal:t});if(i.collectionId!==n.session.requested.collectionId||i.mode!=="read_write")throw new w("authority_adoption_state_conflict","Connect approved a different collection or access mode; this vault remains protected.");return fe(t),await this.updateAdoptionPhase("adopted"),this.persistAdoptedMirror(n.session,i)})}getSelectiveSync(){return fr(this.settingsHost.getMirrorProfile()?.selectiveSync??this.adoptionMarker?.selective_sync)}async configureSelectiveSync(e){let t=this.requireProfile();await this.settingsHost.saveMirrorProfile({...t,selectiveSync:fr(e)})}assertLocalAuthorityWritable(){if(this.assertActive(),this.adoptionMarker&&["fenced","activating","adopted"].includes(this.adoptionMarker.phase))throw new w("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){return this.withAdoptionOperation(t.signal,n=>this.adoptLocalCollectionActive(e,{...t,signal:n}))}async adoptLocalCollectionActive(e,t){if(this.settingsHost.getMirrorProfile())throw new w("mirror_already_configured","This vault already mirrors a collection authority.");if(this.adoptionMarker)return this.resumeAdoptionActive(t);t.onProgress?.({stage:"checking"}),ex(await this.previewAdoption(e.selectiveSync,t.signal));let n=await this.ensurePortableCollectionIdentity(),i=await this.adoptionClient.begin({controlUrl:e.controlUrl,collectionId:n.collectionId,displayName:n.displayName,sourceName:e.mirrorName,retainMirror:!0,mirrorName:e.mirrorName},t);try{await this.storeAdoptionSecret(i)}catch(s){throw await this.adoptionClient.cancel(i,t).catch(()=>{}),s}return await this.writeAdoptionMarker({version:1,phase:"waiting_for_approval",session:Om(i),selective_sync:fr(e.selectiveSync),manifest_digest:null,source_revision:null,source_head:null}),await t.onVerification(Om(i)),this.runAdoptionWithRecovery(i,t)}async resumeAdoption(e={}){return this.withAdoptionOperation(e.signal,t=>this.resumeAdoptionActive({...e,signal:t}))}async resumeAdoptionActive(e){let t=this.adoptionMarker??await this.readAdoptionMarker();if(!t)throw new w("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 w("authority_adoption_credentials_missing","The collection-adoption credential is missing from Obsidian's secret store.");let i={...t.session,credential:n};return t.phase==="waiting_for_approval"&&await e.onVerification?.(Om(i)),this.runAdoptionWithRecovery(i,{...e,onVerification:s=>e.onVerification?.(s)})}async cancelAdoption(e){return this.withAdoptionOperation(e,t=>this.cancelAdoptionActive(t))}async cancelAdoptionActive(e){let t=this.adoptionMarker??await this.readAdoptionMarker();if(!t)return;if(["activating","adopted"].includes(t.phase))throw new w("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 w("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){return this.withLifetime(t.signal,n=>this.enrollActive(e,{...t,signal:n}))}async enrollActive(e,t){let n=await this.assertCanBecomeMirror(e.collectionId),i=await this.enrollmentClient.enroll({controlUrl:e.controlUrl,mirrorName:e.mirrorName,mode:e.mode,...n?{collectionId:n}:{}},t),s=await this.markMirror(i.collectionId);try{await this.persistEnrollment(i,e.selectiveSync)}catch(o){if(s)try{await this.app.vault.adapter.remove(On)}catch{throw new w("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 inspect(){return this.withMirrorOperation(async()=>{let e=this.requireProfile();await this.assertMirror(e.collectionId);let t=await this.createMirror(),{plan:n,status:i}=await t.review();return{preview:_m(n),status:i}})}async preview(){return this.withMirrorOperation(async()=>{let e=this.requireProfile();await this.assertMirror(e.collectionId);let t=await this.createMirror();return _m(await t.inspect())})}async status(){if(this.statusRequest)return this.statusRequest;let e=this.readStatus();this.statusRequest=e;try{return await e}finally{this.statusRequest===e&&(this.statusRequest=null)}}async readStatus(){return this.withMirrorOperation(async()=>{let e=this.settingsHost.getMirrorProfile();return e?(await this.assertMirror(e.collectionId),(await this.createMirror()).status()):null})}async remoteChangesWaiting(){let e=this.requireProfile(),t=await this.stateStoreFor(e).read();if(!t||t.batch)return!0;let i=await(await this.transportFor(e)).changes(t.cursor,1);return i.reset_required||i.scope_epoch!==t.scope_epoch||i.head>t.cursor}async checkpointSummary(){let e=this.settingsHost.getMirrorProfile();if(!e)return null;let t=await this.stateStoreFor(e).read();return t?{cursor:t.cursor,generation:t.generation??0,batch:t.batch?`${t.batch.phase} at action ${t.batch.next_action}/${t.batch.plan.actions.length}`:null,failure:t.batch?.failure?`${t.batch.failure.code}: ${t.batch.failure.message}`:null}:null}async reconnect(){let e=this.requireProfile();this.assertThisDevice(e),await this.renewAccessToken(e);let t=await this.status();if(!t)throw new w("mirror_not_configured","The renewed mirror profile could not be loaded.");return t}async reauthorize(e){return this.withLifetime(e.signal,t=>this.reauthorizeActive({...e,signal:t}))}async reauthorizeActive(e){let t=this.requireProfile(),n=this.isOtherDevice(t),i=this.stateStoreFor(t);if((n?null:await i.read())?.batch)throw new w("mirror_recovery_required","Resume the durable synchronization checkpoint before approving this vault again.");let o=await this.enrollmentClient.enroll({controlUrl:t.controlUrl,mirrorName:t.name,mode:t.mode,collectionId:t.collectionId},e);if(o.collectionId!==t.collectionId)throw new w("mirror_identity_conflict","Connect approved a different collection. The existing mirror was not changed.");return this.withMirrorOperation(async()=>{let a=this.requireProfile();if(a.collectionId!==t.collectionId||a.replicaId!==t.replicaId||a.enrollmentId!==t.enrollmentId)throw new w("mirror_identity_conflict","The connection changed during approval. The current mirror was not changed.");let c=n?null:await i.read();if(c?.batch)throw new w("mirror_recovery_required","Resume the durable synchronization checkpoint before approving this vault again.");let l=nx(o,a.selectiveSync);return c&&o.replicaId!==t.replicaId&&await this.stateStoreFor(l).write({...c,replica_id:o.replicaId}),await this.persistEnrollment(o,a.selectiveSync),!n&&o.replicaId!==t.replicaId&&(this.clearCredentials(t),"clear"in i&&typeof i.clear=="function"&&await i.clear()),(await this.createMirror()).status()})}async conflictComparison(e){let t=this.requireProfile(),n=await this.transportFor(t),i=await n.openSession(),s={state:"absent"};if(e.entity==="record"){let l;do{let u=await n.snapshot(i.snapshot_id,l),d=u.records.find(f=>f.record_id===e.object_id);if(d){s={state:"exact",path:d.path,revision:d.revision,size:new TextEncoder().encode(d.document).byteLength,document:d.document};break}l=u.next_page}while(l)}else{let l;do{let u=await n.fileSnapshot(i.snapshot_id,l),d=u.files.find(f=>f.file_id===e.object_id);if(d){s={state:"exact",path:d.path,revision:d.content_digest,size:d.size,modifiedAt:d.modified_at};break}l=u.next_page}while(l)}let o=e.path??s.path,a={state:"absent"};if(o){let l=this.app.vault.getAbstractFileByPath(o);if(l instanceof z.TFile)if(e.entity==="record"){let u=await this.app.vault.cachedRead(l);a={state:"exact",path:o,size:new TextEncoder().encode(u).byteLength,modifiedAt:l.stat?.mtime?new Date(l.stat.mtime).toISOString():void 0,document:u}}else{let u=await this.fileSystem.inspectBinary(o);u&&(a={state:"exact",path:o,revision:u.content_digest,size:u.size,modifiedAt:l.stat?.mtime?new Date(l.stat.mtime).toISOString():void 0,resourceUrl:this.app.vault.getResourcePath(l)})}}if(!(await this.status())?.conflicts.some(l=>l.object_id===e.object_id&&l.decision_id===e.decision_id))throw new w("conflict_decision_stale","This file changed again while its versions were loading.");return{entity:e.entity,objectId:e.object_id,decisionId:e.decision_id,local:a,remote:s}}async recordComparison(e,t){let n=this.requireProfile(),i=await this.transportFor(n),s=await i.openSession(),o={state:"absent"},a;do{let u=await i.snapshot(s.snapshot_id,a),d=u.records.find(f=>f.record_id===e);if(d){o={state:"exact",path:d.path,revision:d.revision,size:new TextEncoder().encode(d.document).byteLength,document:d.document};break}a=u.next_page}while(a);let c={state:"absent"},l=this.app.vault.getAbstractFileByPath(Or(this.app.vault,t));if(l instanceof z.TFile){let u=await this.app.vault.cachedRead(l);c={state:"exact",path:l.path,size:new TextEncoder().encode(u).byteLength,document:u}}return{entity:"record",objectId:e,decisionId:"",local:c,remote:o}}async autoResolveConflicts(){let e=await this.status();if(!e?.conflicts.length||e.recovery_required)return[];let t=this.requireProfile(),n=await this.stateStoreFor(t).read();if(!n||n.batch)return[];let i=e.conflicts.filter(a=>a.entity==="record"&&n.planned_conflicts?.[a.object_id]?.conflict_kind==="both_changed").map(a=>a.object_id),s=i.length?await this.remoteRecords(new Set(i)):new Map,o=[];for(let a of e.conflicts){let c=n.planned_conflicts?.[a.object_id];if(c)try{o.push(await this.autoResolve(a,c,s.get(a.object_id)))}catch(l){if(l instanceof w&&["conflict_decision_stale","sync_plan_stale"].includes(l.code))continue;o.push({path:a.path??a.object_id,outcome:"unresolved",reason:l instanceof Error?l.message:String(l)})}}return o}async autoResolve(e,t,n){let{object_id:i,decision_id:s}=e,o=t.local.state==="exact"?t.local.object.path:null,a=t.remote.state==="exact"?t.remote.object.path:null,c=e.path??o??a??i;if(t.conflict_kind==="rejected")return{path:c,outcome:"unresolved",reason:e.message};if(o===null)return await this.resolveConflict(i,s,"remote"),{path:c,outcome:a?"restored":"took_hosted"};if(a===null)return await this.resolveConflict(i,s,"local"),{path:c,outcome:"kept_local"};if(e.entity==="record"&&t.conflict_kind==="both_changed"&&n&&n.path===o&&t.remote.state==="exact"&&n.revision===t.remote.object.revision){let u=t.ancestor_document,d=await this.fileSystem.read(o);if(u!==void 0&&d!==null){let f=Y$(u,d,n.document,X2);if(f.clean){await this.resolveConflict(i,s,"local");try{await this.fileSystem.write(o,f.text,d)}catch(p){let m=await this.writeConflictCopy(o,n.document,"hosted conflict copy");return{path:c,outcome:"kept_both",copyPath:m,reason:p instanceof Error?p.message:String(p)}}return{path:c,outcome:"merged"}}}}let l=await this.preserveConflictCopy(o);return await this.resolveConflict(i,s,"remote"),{path:c,outcome:"kept_both",copyPath:l}}async remoteRecords(e){let t=await this.transportFor(this.requireProfile()),n=await t.openSession(),i=new Map,s;do{let o=await t.snapshot(n.snapshot_id,s);for(let a of o.records)e.has(a.record_id)&&i.set(a.record_id,{path:a.path,revision:a.revision,document:a.document});s=i.size===e.size?void 0:o.next_page}while(s);return i}async writeConflictCopy(e,t,n){let i=Or(this.app.vault,e);return this.createConflictCopy(i,new TextEncoder().encode(t).buffer,n)}async createConflictCopy(e,t,n){let i=e.lastIndexOf("/"),s=e.lastIndexOf("."),o=s>i?e.slice(s):"",c=(o?e.slice(0,-o.length):e).replace(/(?: \((?:local|hosted) conflict copy(?: \d+)?\))+$/,""),l=new Uint8Array(t),u=1;for(;;){let d=`${c} (${n}${u===1?"":` ${u}`})${o}`;if(d===e){u+=1;continue}if(this.app.vault.getAbstractFileByPath(d)||await this.app.vault.adapter.exists(d)){try{let f=new Uint8Array(await this.app.vault.adapter.readBinary(d));if(f.length===l.length&&f.every((p,m)=>p===l[m]))return d}catch{}u+=1;continue}try{return await this.app.vault.createBinary(d,t),d}catch(f){if(!await this.app.vault.adapter.exists(d))throw f}}}async preserveConflictCopy(e){let t=Or(this.app.vault,e);if(!(this.app.vault.getAbstractFileByPath(t)instanceof z.TFile))throw new w("mirror_conflict_copy_missing",`No local file exists at ${t}.`);let i=await this.app.vault.adapter.readBinary(t);return this.createConflictCopy(t,i,"local conflict copy")}async disconnect(e){if(this.isSyncing())throw new w("mirror_busy","Stop the current synchronization before disconnecting.");return this.withMirrorOperation(()=>this.disconnectActive(e))}async disconnectActive(e){if(this.isSyncing())throw new w("mirror_busy","Stop the current synchronization before disconnecting.");let t=this.requireProfile(),n=this.stateStoreFor(t),i=await n.read();if(i?.batch)throw new w("mirror_recovery_required","Resume the durable synchronization checkpoint before disconnecting.");let s={removed:[],preserved:[]},o=await this.readMarker();o&&await this.app.vault.adapter.remove(On);try{await this.settingsHost.saveMirrorProfile(null)}catch(a){throw o&&await this.markMirror(t.collectionId),a}return this.isOtherDevice(t)||(this.clearCredentials(t),"clear"in n&&typeof n.clear=="function"&&await n.clear(),await this.blobStoreFor(t).prune(new Set)),e&&i&&await this.removeExactMirrorFiles(i,s),s}async sync(e,t,n,i){if(this.syncAbort)throw new w("mirror_busy","Synchronization is already running for this vault.");let s=new AbortController;this.syncAbort=s;try{return await this.withMirrorOperation(async()=>{let a=await(await this.createMirror(c=>{fe(s.signal),this.progress=c,t?.({...c})},s.signal,c=>{fe(s.signal),this.fileProgress=c,n?.({...c})},i)).apply(e.plan,{signal:s.signal});return fe(s.signal),a})}finally{this.progress=null,this.fileProgress=null,this.syncAbort=null}}cancelSync(){this.syncAbort?.abort()}noteEngineWrite(e){let t=Date.now();for(let[n,i]of this.engineWrites)t-i>Z$&&this.engineWrites.delete(n);this.engineWrites.set((0,z.normalizePath)(e),t)}isEngineWrite(e){let t=this.engineWrites.get((0,z.normalizePath)(e));return t!==void 0&&Date.now()-t<=Z$}isSyncing(){return this.syncAbort!==null}async resolveConflict(e,t,n){return this.withMirrorOperation(async()=>{let i=await this.createMirror();return await i.resolveConflict(e,t,n),i.status()})}async withMirrorOperation(e){let t=this.mirrorOperationTail,n;this.mirrorOperationTail=new Promise(i=>{n=i}),await t;try{return this.assertActive(),await e()}finally{n()}}async runAdoption(e,t){let n=this.requireAdoptionMarker(e.adoptionId),i=null;if(n.phase==="adopted"){let s=await this.adoptionClient.exchange(e,t);if(s.status!=="completed")throw new w("authority_adoption_state_conflict","The local checkpoint says adoption completed, but Connect does not.");i=s}else if(n.phase==="activating"){t.onProgress?.({stage:"activating"});let s=await this.readAdoptionSnapshot(n),o=await this.adoptionClient.exchange(e,t);i=o.status==="completed"?o:await this.adoptionClient.complete(e,s,t)}else if(n.phase==="fenced"){let s=await this.readAdoptionSnapshot(n),o=await this.adoptionClient.exchange(e,t);o.status==="completed"?i=o:(o.status==="ready"&&(t.onProgress?.({stage:"uploading",records:s.records.length}),await this.adoptionClient.uploadSnapshot(e,o,s,this.adoptionUploadOptions(e,t))),await this.updateAdoptionPhase("activating",s),t.onProgress?.({stage:"activating"}),i=await this.adoptionClient.complete(e,s,t))}else{let s=n.phase==="waiting_for_approval"?await this.adoptionClient.waitForApproval(e,t):await this.requirePreparedAdoption(e,t);await this.updateAdoptionPhase("uploading",void 0,s.adoption.expires_at),t.onProgress?.({stage:"checking"});let o=await this.captureAuthoritySnapshot(e.requested.collectionId,t.signal);t.onProgress?.({stage:"uploading",records:o.records.length}),await this.adoptionClient.uploadSnapshot(e,s,o,this.adoptionUploadOptions(e,t)),t.onProgress?.({stage:"checking"});let a=await this.captureAuthoritySnapshot(e.requested.collectionId,t.signal);await this.writeAdoptionSnapshot(a),await this.updateAdoptionPhase("fenced",a);let c=await this.requirePreparedAdoption(e,t);t.onProgress?.({stage:"uploading",records:a.records.length}),await this.adoptionClient.uploadSnapshot(e,c,a,this.adoptionUploadOptions(e,t)),await this.updateAdoptionPhase("activating",a),t.onProgress?.({stage:"activating"}),i=await this.adoptionClient.complete(e,a,t)}return await this.updateAdoptionPhase("adopted"),t.onProgress?.({stage:"connecting"}),this.finishRetainedMirror(e,i,t)}async runAdoptionWithRecovery(e,t){try{return await this.runAdoption(e,t)}catch(n){throw t.signal?.aborted?new DOMException("Adoption paused.","AbortError"):yF(n)?(await this.adoptionClient.cancel(e,{signal:t.signal}).catch(()=>{}),await this.clearAdoptionCheckpoint(e.adoptionId),new w(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 Yr("Hosted authority activation has already started. Resume using the saved fenced snapshot."):new w("authority_adoption_already_completed","Hosted authority has already adopted this collection.")}async finishRetainedMirror(e,t,n){let i,s=this.adoptionClient.mirrorEnrollmentSession(e,t);if(!s)throw new w("authority_adoption_mirror_missing","Hosted authority activated without retaining this vault as a mirror.");try{i=await this.enrollmentClient.waitForApproval(s,{signal:n.signal,onStatus:o=>n.onStatus?.({...o,state:o.state})})}catch(o){if(n.signal?.aborted)throw o;i=await this.enrollmentClient.enroll({controlUrl:e.controlUrl,collectionId:e.requested.collectionId,mirrorName:e.requested.mirrorName??e.requested.sourceName,mode:"read_write"},{signal:n.signal,onVerification:a=>n.onVerification(a)})}return this.persistAdoptedMirror(e,i)}async persistAdoptedMirror(e,t){let n=await this.markMirror(t.collectionId);try{await this.persistEnrollment(t,this.adoptionMarker?.selective_sync)}catch(i){throw n&&await this.app.vault.adapter.remove(On),i}return await this.clearAdoptionCheckpoint(e.adoptionId),this.requireProfile()}async adoptionSources(e,t){fe(t);let n=await ai(this.app.vault);if(fe(t),!n)throw new w("invalid_collection_configuration","A valid mdbase.yaml is required.");let i=await this.app.vault.adapter.read("mdbase.yaml");fe(t);let s=(0,z.parseYaml)(i),o=`${(0,z.normalizePath)(n.settings.types_folder)}/`,a=this.app.vault.getMarkdownFiles().filter(m=>(0,z.normalizePath)(m.path).startsWith(o)).sort((m,h)=>m.path.localeCompare(h.path)),c=gF(s).map(m=>(0,ix.default)(m,{dot:!0})),l=pd(this.app.vault).filter(m=>m.extension==="base"&&c.some(h=>h((0,z.normalizePath)(m.path)))).sort((m,h)=>m.path.localeCompare(h.path)),u=this.app.vault.getMarkdownFiles().filter(m=>!yt((0,z.normalizePath)(m.path),n)).sort((m,h)=>m.path.localeCompare(h.path)),d=["mdbase.yaml",...a.map(m=>m.path),...l.map(m=>m.path)],f=e.file_classes.length?(await this.fileSystem.listBinary?.(new Set(d))??[]).filter(m=>aF(e,m)&&!yt(m,n)):[];fe(t);let p={records:u.length,resources:d.length,files:f.length,conflicts:Rm([...d,...u.map(m=>m.path),...f])};return{config:n,configuration:i,typeFiles:a,baseFiles:l,recordFiles:u,binaryPaths:f,resourcePaths:d,preview:p}}renameNamespace(){return this.app.vault.getAllLoadedFiles?.()??pd(this.app.vault)}async planAdoptionRenames(e=this.getSelectiveSync()){this.assertActive();let{preview:t,resourcePaths:n}=await this.adoptionSources(fr(e)),i=this.renameNamespace().map(c=>c.path).sort(),s=Q$(t.conflicts,i,new Set(n)),o=s.renames.map(({from:c})=>{let l=this.app.vault.getAbstractFileByPath(c);return[c,l instanceof z.TFile?l.stat:null]}),a=(await dd(new TextEncoder().encode(JSON.stringify({paths:i,sources:o,proposed:s,policy:e})).buffer)).content_digest;return{...s,revision:a}}async applyAdoptionRenames(e,t=this.getSelectiveSync(),n){return this.withAdoptionOperation(void 0,async i=>{if(this.assertLocalAuthorityWritable(),this.settingsHost.getMirrorProfile()||await this.app.vault.adapter.exists(On))throw new w("adoption_rename_unsafe","Automatic rename review is only available before this vault becomes a mirror.");let s=await this.planAdoptionRenames(t);if(JSON.stringify(s)!==JSON.stringify(e))throw new w("adoption_rename_stale","Files changed since the rename review. Review the new suggestions before renaming.");let o=e.renames.map(c=>this.app.vault.getAbstractFileByPath(c.from)),a=0;n?.(0,e.renames.length);for(let[c,l]of e.renames.entries()){let u=o[c];try{if(fe(i),this.assertLocalAuthorityWritable(),!(u instanceof z.TFile)||u.path!==l.from||this.app.vault.getAbstractFileByPath(l.from)!==u)throw new Error("The source file changed. Review again.");if(this.renameNamespace().some(d=>$i(d.path)===$i(l.to))||await this.app.vault.adapter.exists(l.to))throw new Error("The destination is now occupied. Review again.");fe(i),await this.app.fileManager.renameFile(u,l.to),a++}catch(d){throw u?.path===l.to&&a++,new w("adoption_rename_failed",`Rename stopped after ${a} of ${e.renames.length} files. Check filenames and links before retrying. ${d instanceof Error?d.message:String(d)}`)}n?.(a,e.renames.length)}return a})}async previewAdoption(e=this.getSelectiveSync(),t){return this.assertActive(),(await this.adoptionSources(fr(e),t)).preview}async captureAuthoritySnapshot(e,t){let{config:n,configuration:i,typeFiles:s,baseFiles:o,recordFiles:a,binaryPaths:c,preview:l}=await this.adoptionSources(this.getSelectiveSync(),t);ex(l);let u=[{path:"mdbase.yaml",kind:"configuration",document:i}];for(let[p,m]of[["type",s],["view",o]])for(let h of m)fe(t),u.push({path:(0,z.normalizePath)(h.path),kind:p,document:await this.app.vault.cachedRead(h)});let d=[];for(let p of a){fe(t);let m=(0,z.normalizePath)(p.path),h=await this.app.vault.cachedRead(p);fe(t),d.push({path:m,document:h})}let f=[];if(c.length){let p=this.adoptionBlobStore(e);for(let m of c){fe(t);let h=await this.fileSystem.readBinary?.(m);if(fe(t),!h)continue;let y=await Dm(h);fe(t);let g=await dd(y);fe(t),await p.write(g.content_digest,(async function*(){yield new Uint8Array(y)})()),fe(t);let b=this.app.vault.getAbstractFileByPath(m);f.push({file_id:Hl(e,`file:${m}`),path:m,revision:g.content_digest,...g,...tx(m)?{media_type:tx(m)}:{},media_class:sx(m),modified_at:new Date(b instanceof z.TFile&&b.stat?.mtime?b.stat.mtime:Date.now()).toISOString()})}}return fe(t),rm({collectionId:e,sourceHead:0,specVersion:n.spec_version,resources:u,records:d,files:f})}adoptionBlobStore(e){return this.options.adoptionBlobStoreFactory?.(e)??this.cachedBlobStore(`adoption:${e}`)}adoptionUploadOptions(e,t){let n=this.adoptionBlobStore(e.requested.collectionId);return{signal:t.signal,fileSource:async i=>Dm(n.read(i.content_digest)),onFileProgress:({file:i,transferredBytes:s,totalBytes:o})=>t.onFileProgress?.(i.path,s,o)}}async ensurePortableCollectionIdentity(){if(!await this.app.vault.adapter.exists("mdbase.yaml"))throw new w("collection_not_initialized","Initialize an mdbase collection before hosting it.");let e=await this.app.vault.adapter.read("mdbase.yaml"),t;try{t=(0,z.parseYaml)(e)}catch{throw new w("invalid_collection_configuration","mdbase.yaml must contain valid YAML.")}if(!at(t))throw new w("invalid_collection_configuration","mdbase.yaml must contain a YAML mapping.");let n=at(t["x-mdbase-connect"])?t["x-mdbase-connect"].collection_id:void 0,i;if(n===void 0){i=crypto.randomUUID();let o=at(t["x-mdbase-connect"])?t["x-mdbase-connect"]:{};t["x-mdbase-connect"]={...o,collection_id:i},this.assertActive(),await this.app.vault.adapter.write("mdbase.yaml",(0,z.stringifyYaml)(t))}else if(typeof n=="string"&&ua.test(n))i=n;else throw new w("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:i,displayName:s}}stateStoreFor(e){if(this.assertActive(),this.options.stateStoreFactory)return this.options.stateStoreFactory(e);let t=`${e.collectionId}:${e.replicaId}`,n=this.stateStores.get(t);return n||(n=new qm(t),this.stateStores.set(t,n)),n}cachedBlobStore(e){this.assertActive();let t=this.blobStores.get(e);return t||(t=new jm(e),this.blobStores.set(e,t)),t}blobStoreFor(e){return this.options.blobStoreFactory?.(e)??this.cachedBlobStore(`${e.collectionId}:${e.replicaId}`)}async transportFor(e,t,n){this.assertActive(),this.assertThisDevice(e),await this.claimLegacyProfile(e);let i=await this.freshAccessToken(e);this.assertActive();let s=this.options.transportFactory?.(e,i)??new Nm(e.syncUrl,this.transportCredentials(e),hd,n,t);return mF(s,t)}async createMirror(e,t,n,i){let s=this.requireProfile();await this.assertMirror(s.collectionId);let o=await this.transportFor(s,t,n),a=this.stateStoreFor(s),c={stateStore:i?new od(a,i):a,fileSystem:this.fileSystem,blobStore:this.blobStoreFor(s),selectiveSync:fr(s.selectiveSync),lease:this.options.leaseFactory?.(s)??new Bm(`${s.collectionId}:${s.replicaId}`),onProgress:e};return s.mode==="read_write"?new ia(s.replicaId,o,c):new Si(s.replicaId,o,c)}requireProfile(){this.assertActive();let e=this.settingsHost.getMirrorProfile();if(!e)throw new w("mirror_not_configured","This vault is not connected to a collection authority.");return e}secretIds(e,t){let n=e==="access"?tF:rF;return{current:`${n}${t.replicaId.toLowerCase()}`,legacy:`${n}${t.collectionId.toLowerCase()}`}}readSecret(e,t){let n=this.secretIds(e,t),i=this.app.secretStorage.getSecret(n.current);if(i)return i;let s=this.app.secretStorage.getSecret(n.legacy);if(!s)return null;try{this.app.secretStorage.setSecret(n.current,s)}catch{}return s}clearCredentials(e){for(let t of["access","refresh"]){let n=this.secretIds(t,e),i=this.app.secretStorage.getSecret(n.current);i&&this.app.secretStorage.getSecret(n.legacy)===i&&this.app.secretStorage.setSecret(n.legacy,""),this.app.secretStorage.setSecret(n.current,"")}}currentDeviceId(){return this.settingsHost.deviceId?.()}isOtherDevice(e=this.settingsHost.getMirrorProfile()){let t=this.currentDeviceId();return!!(e?.deviceId&&t&&e.deviceId!==t)}async claimLegacyProfile(e){let t=this.currentDeviceId();e.deviceId||!t||await this.settingsHost.saveMirrorProfile({...e,deviceId:t})}assertThisDevice(e){if(this.isOtherDevice(e))throw new w("mirror_other_device","This vault's sync settings were copied from another device or vault. Set up sync here to give this copy its own connection.")}adoptionSecretId(e){return`${nF}${e.toLowerCase()}`}async storeAdoptionSecret(e){try{let t=this.adoptionSecretId(e.adoptionId);if(this.app.secretStorage.setSecret(t,e.credential),this.app.secretStorage.getSecret(t)!==e.credential)throw new Error("Secret was not retained")}catch{throw new w("authority_adoption_credentials_unavailable","Obsidian could not save this device's authorization. Unlock or repair Obsidian's secret storage before starting the move. Nothing was uploaded.")}}async persistEnrollment(e,t){this.assertActive();try{let n=this.secretIds("access",e).current,i=this.secretIds("refresh",e).current;if(this.app.secretStorage.setSecret(n,e.accessToken),this.app.secretStorage.setSecret(i,e.refreshCredential),this.app.secretStorage.getSecret(n)!==e.accessToken||this.app.secretStorage.getSecret(i)!==e.refreshCredential)throw new Error("Secret was not retained")}catch{throw new w("mirror_credentials_unavailable","Obsidian could not save this device's authorization. Unlock or repair Obsidian's secret storage, then reconnect. Your files were not changed.")}await this.settingsHost.saveMirrorProfile(nx(e,t??this.settingsHost.getMirrorProfile()?.selectiveSync,this.currentDeviceId()))}async removeExactMirrorFiles(e,t){let n=new Map;for(let[i,s]of Object.entries(e.records)){let o=e.local_bindings?.[i]?.path??s.path;n.set(o,{entity:"document",document:s.record?.document,revision:s.revision})}for(let[i,s]of Object.entries(e.resources??{})){let o=e.local_bindings?.[i]?.path??s.path;n.set(o,{entity:"document",document:s.record?.document,revision:s.revision})}for(let[i,s]of Object.entries(e.files??{})){let o=e.local_bindings?.[i]?.path??s.file.path;n.set(o,{entity:"file",digest:s.file.content_digest,size:s.file.size})}for(let[i,s]of[...n.entries()].sort(([o],[a])=>a.localeCompare(o))){let o=!1;if(s.entity==="document"){let a=await this.fileSystem.read(i);o=a!==null&&(s.document!==void 0?a===s.document:await wF(a,s.revision))}else if(s.entity==="file"){let a=await this.fileSystem.inspectBinary(i);o=a!==null&&a.content_digest===s.digest&&a.size===s.size}if(!o){await this.fileSystem.exists(i)&&t.preserved.push(i);continue}try{await this.fileSystem.remove(i),t.removed.push(i)}catch{t.preserved.push(i)}}}async freshAccessToken(e){if(this.renewal)return this.renewal;let t=this.readSecret("access",e),n=Date.parse(e.accessTokenExpiresAt);return t&&Number.isFinite(n)&&n-Date.now()>iF?t:this.renewAccessToken(e)}renewAccessToken(e){return this.renewal??=this.renewAccessTokenOnce(e).finally(()=>{this.renewal=null}),this.renewal}async renewAccessTokenOnce(e){let t=this.readSecret("refresh",e);if(!t)throw new w("mirror_credentials_missing","The mirror refresh credential is missing. Approve this vault again.");let n=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:this.readSecret("access",e)??"",refreshCredential:t,accessTokenExpiresAt:e.accessTokenExpiresAt},{signal:this.lifetime.signal}),i=this.requireProfile();if(i.collectionId!==e.collectionId||i.replicaId!==e.replicaId||i.enrollmentId!==e.enrollmentId)throw new w("mirror_identity_conflict","The connection changed while credentials were renewing. Retry with the current connection.");return await this.persistEnrollment(n,i.selectiveSync),n.accessToken}transportCredentials(e){return{token:()=>this.freshAccessToken(this.requireProfile()),renew:async t=>{let n=this.readSecret("access",e);return n&&n!==t?n:this.renewAccessToken(this.requireProfile())}}}async assertCanBecomeMirror(e){let t=await this.readMarker(),n=await this.readPortableCollectionId();if(n&&!t)throw new w("local_authority_requires_transfer","This vault has a local Connect identity. Transfer authority explicitly before using it as a mirror.");if(n&&t?.collection_id!==n)throw new w("mirror_identity_conflict","The vault identity and mirror role marker identify different collections.");let i=this.settingsHost.getMirrorProfile(),s=i?.collectionId??e;if(t&&s&&t.collection_id!==s)throw new w("mirror_identity_conflict","This vault is already marked as a different mirror.");if(!t&&!i&&await this.app.vault.adapter.exists("mdbase.yaml"))throw new w("existing_collection_requires_transfer","This vault already contains an mdbase collection. Connect an empty vault, or transfer collection authority explicitly.");return s??t?.collection_id}async readPortableCollectionId(){if(!await this.app.vault.adapter.exists("mdbase.yaml"))return null;let e;try{e=(0,z.parseYaml)(await this.app.vault.adapter.read("mdbase.yaml"))}catch{throw new w("invalid_collection_configuration","mdbase.yaml must contain valid YAML.")}if(!at(e))throw new w("invalid_collection_configuration","mdbase.yaml must contain a YAML mapping.");let t=e["x-mdbase-connect"];if(t===void 0)return null;if(!at(t))throw new w("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"||!ua.test(n))throw new w("invalid_collection_configuration","x-mdbase-connect.collection_id must be a UUID string.");return n}async markMirror(e){this.assertActive();let t=await this.readMarker();if(t){if(t.collection_id!==e)throw new w("mirror_identity_conflict","This vault already mirrors a different collection authority.");return!1}return await Ps(this.app.vault,".mdbase"),this.assertActive(),await this.app.vault.adapter.write(On,`${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 w("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(On))return null;let e;try{e=JSON.parse(await this.app.vault.adapter.read(On))}catch{throw new w("invalid_mirror_marker","The mirror role marker is corrupt.")}if(!at(e)||e.version!==1||e.role!=="mirror"||typeof e.collection_id!="string"||!ua.test(e.collection_id))throw new w("invalid_mirror_marker","The mirror role marker is invalid.");return e}requireAdoptionMarker(e){if(!this.adoptionMarker||this.adoptionMarker.session.adoptionId!==e)throw new w("authority_adoption_state_conflict","The collection-adoption checkpoint does not match this approval.");return this.adoptionMarker}async updateAdoptionPhase(e,t,n){if(!this.adoptionMarker)throw new w("authority_adoption_not_found","Collection-adoption checkpoint is missing.");await this.writeAdoptionMarker({...this.adoptionMarker,phase:e,...n?{session:{...this.adoptionMarker.session,expiresAt:n}}:{},...t?{manifest_digest:t.manifest_digest,source_revision:t.source_revision,source_head:t.source_head}:{}})}async writeAdoptionMarker(e){await Ps(this.app.vault,".mdbase"),this.assertActive(),await this.app.vault.adapter.write(ca,`${JSON.stringify(e,null,2)} -`),this.adoptionMarker=e}async readAdoptionMarker(){if(!await this.app.vault.adapter.exists(ca))return null;let e;try{e=JSON.parse(await this.app.vault.adapter.read(ca))}catch{throw new w("invalid_authority_adoption_checkpoint","The collection-adoption checkpoint is corrupt.")}if(!bF(e))throw new w("invalid_authority_adoption_checkpoint","The collection-adoption checkpoint is invalid.");return e}async writeAdoptionSnapshot(e){this.assertActive(),await Ps(this.app.vault,".mdbase"),this.assertActive(),await this.app.vault.adapter.write(la,JSON.stringify(e))}async readAdoptionSnapshot(e){if(!await this.app.vault.adapter.exists(la))throw new w("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(la))}catch{throw new w("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 w("authority_adoption_snapshot_mismatch","The fenced authority snapshot does not match its durable checkpoint.");return t}async clearAdoptionCheckpoint(e){let t=this.adoptionMarker?.session.requested.collectionId;await this.app.vault.adapter.exists(la)&&await this.app.vault.adapter.remove(la),await this.app.vault.adapter.exists(ca)&&await this.app.vault.adapter.remove(ca),this.adoptionMarker=null;try{this.app.secretStorage.setSecret(this.adoptionSecretId(e),"")}catch{}t&&await this.adoptionBlobStore(t).prune(new Set).catch(()=>{})}};function Om(r){let{credential:e,...t}=r;return t}function yF(r){return r instanceof J&&["authority_adoption_expired","authority_adoption_cancelled"].includes(r.code)}function gF(r){if(!at(r))return[];let e=r["x-obsidian"];return!at(e)||!at(e.bases)||!Array.isArray(e.bases.include)?[]:e.bases.include.filter(t=>typeof t=="string")}function hd(r){let e=r.getFiles?.();if(e)return e;let t=[],n=i=>{for(let s of i.children)s instanceof z.TFile?t.push(s):s instanceof z.TFolder&&n(s)};return n(r.getRoot()),t}function bF(r){if(!at(r)||r.version!==1||!["waiting_for_approval","uploading","fenced","activating","adopted"].includes(String(r.phase))||!at(r.session))return!1;let e=r.session;return typeof e.controlUrl=="string"&&typeof e.adoptionId=="string"&&ua.test(e.adoptionId)&&typeof e.verificationUri=="string"&&typeof e.expiresAt=="string"&&at(e.requested)&&typeof e.requested.collectionId=="string"&&ua.test(e.requested.collectionId)&&typeof e.requested.displayName=="string"&&typeof e.requested.sourceName=="string"&&e.requested.retainMirror===!0&&(r.selective_sync===void 0||vF(r.selective_sync))&&(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))}function vF(r){if(!at(r)||!Array.isArray(r.file_classes)||!Array.isArray(r.excluded_folders))return!1;try{let e=fr(r);return e.file_classes.length===r.file_classes.length&&e.excluded_folders.length===r.excluded_folders.length}catch{return!1}}function rx(r,e,t){return{version:1,syncUrl:r.syncUrl,controlUrl:r.controlUrl,collectionId:r.collectionId,replicaId:r.replicaId,mode:r.mode,name:r.name,enrollmentId:r.enrollmentId,accessTokenExpiresAt:r.accessTokenExpiresAt,selectiveSync:fr(e),...t?{deviceId:t}:{}}}async function wF(r,e){if(!e?.startsWith("sha256:"))return!1;let t=new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(r)));return`sha256:${Array.from(t,i=>i.toString(16).padStart(2,"0")).join("")}`===e}var Xe=require("obsidian");qt();var ma="0.3.0",_F=new Set(["name","description","display_name_key","strict","path_pattern","filename_pattern","match","fields","extends"]),SF=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 pe(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function Ae(r){return r===void 0?r:JSON.parse(JSON.stringify(r))}function rn(r){return Zo.digest(r)}function Ei(r){return Array.isArray(r)?`[${r.map(Ei).join(",")}]`:pe(r)?`{${Object.keys(r).sort().map(e=>`${JSON.stringify(e)}:${Ei(r[e])}`).join(",")}}`:JSON.stringify(r)}function Um(r){if(Array.isArray(r))return r.map(Um);if(!pe(r))return r;let e={};for(let[t,n]of Object.entries(r)){let i=Um(n);i!=null&&(Array.isArray(i)&&i.length===0||pe(i)&&Object.keys(i).length===0||(e[t]=i))}return e}function Cs(r){return[...new Set(r)]}function $F(r){return pe(r.fields)?Object.values(r.fields).some(e=>pe(e)&&(typeof e.tn_role=="string"||Array.isArray(e.tn_completed_values))):!1}function Vm(r,e,t){let n=pe(e)?e:{},i={},s={},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)?Ae(n.values):[]};break;case"link":a={type:"string"},i[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=Vm(`${r}[]`,n.items,t);a={type:"array",items:c.schema},Object.assign(i,c.links),Object.assign(s,c.legacy),o.push(...c.unsupported);break}case"object":{let c={},l=[];for(let[u,d]of Object.entries(pe(n.fields)?n.fields:{})){let f=Vm(`${r}.${u}`,d,t);c[u]=f.schema,Object.assign(i,f.links),Object.assign(s,f.legacy),o.push(...f.unsupported),pe(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:Cs(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"&&(n.type==="list"?a.minItems=n.min_length:a.minLength=n.min_length),typeof n.max_length=="number"&&(n.type==="list"?a.maxItems=n.max_length: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=Ae(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");(!SF.has(c)||(c==="tn_role"||c==="tn_completed_values")&&!u)&&(s[`${r}.${c}`]=Ae(l))}return{schema:a,links:i,legacy:s,unsupported:o}}function fa(r,e,t,n){let i=pe(r[e])?r[e]:{},s=pe(i.set)?i.set:{};s[t]=n,i.set=s,r[e]=i}function xF(r,e,t){if(t==="now")fa(r,"on_create",e,{now:!0});else if(t==="now_on_write")fa(r,"on_update",e,{now:!0});else if(t==="uuid")fa(r,"on_create",e,{uuid:!0});else if(t==="ulid")fa(r,"on_create",e,{ulid:!0});else if(pe(t)&&t.transform==="slugify"&&typeof t.from=="string")fa(r,"on_create",e,{slugify:t.from});else return!1;return!0}function EF(r){let e=r.match(/^(.*\/)?\{title\}\.md$/);return e?{runtime:"tasknotes",template:"{{title}}",folder:(e[1]??"").replace(/\/$/,""),generated_by:"tasknotes.filename.create"}:{runtime:"tasknotes",template:r,generated_by:"tasknotes.filename.create"}}function AF(r,e,t){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"||!pe(t.fields))throw new Error(`${r} is not a v0.2 type with a name and fields.`);let n=$F(t),i=t.name.trim().toLowerCase(),s={type:{const:i}},o=[],a={},c={},l=[],u={},d={},f=[],p=[],h={},m={},y={};for(let[E,k]of Object.entries(t.fields)){let $=pe(k)?k:{},M=Vm(E,$,n);s[E]=M.schema,Object.assign(c,M.links),Object.assign(d,M.legacy),f.push(...M.unsupported),$.required===!0&&o.push(E),$.default!==void 0&&(a[E]=Ae($.default)),$.unique===!0&&l.push({field:E,scope:"collection"}),$.generated!==void 0&&(xF(u,E,$.generated)?p.push(E):(d[`${E}.generated`]=Ae($.generated),f.push(`${E}.generated`))),typeof $.tn_role=="string"&&(h[$.tn_role]=E),Array.isArray($.tn_completed_values)&&(m.completed_values=Ae($.tn_completed_values))}a.status!==void 0&&(m.default=Ae(a.status)),a.priority!==void 0&&(y.default=Ae(a.priority));let g=typeof t.display_name_key=="string"&&Object.prototype.hasOwnProperty.call(t.fields,t.display_name_key)?t.display_name_key:void 0,b={...g?{display:{name_field:g}}:{},read_defaults:a,links:c,unique:l};typeof t.path_pattern=="string"&&(b.path=n?EF(t.path_pattern):{pattern:t.path_pattern});let v={};for(let[E,k]of Object.entries(t))_F.has(E)||(v[E]=Ae(k));Object.keys(d).length&&(v.fields=d);let S=Um({kind:"mdbase.type",name:i,version:1,description:typeof t.description=="string"?t.description:void 0,match:pe(t.match)?Ae(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:Cs(o)}:{}}},collection:b,lifecycle:u,...n?{"x-tasknotes":{contract:"tasknotes.task",version:1,field_roles:h,status:m,priority:y,archive:{tags_field:h.tags??"tags",archived_tag:"archived"}}}:{},...Object.keys(v).length?{"x-legacy-v0.2":v}:{}}),_=[];t.extends!==void 0&&f.push("extends");for(let E of Cs(f).sort())_.push({path:r,code:"migration_lossy",message:`${E} 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"&&!g&&_.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:i,fieldsConverted:Object.keys(t.fields).length,requiredFields:Cs(o),defaultsMoved:Object.keys(a),generatedFieldsMoved:Cs(p),linksMoved:Object.keys(c),taskNotes:n},diagnostics:_}}var kF=["default_strict","write_nulls","write_empty_lists","write_defaults","rename_update_refs","cache_folder","migrations_folder","extensions"];function PF(r,e){let t=Ae(r);t.spec_version=ma;let n=pe(t.settings)?t.settings:{};if(t.settings=n,!Array.isArray(n.record_extensions)){let a=Array.isArray(n.extensions)?n.extensions.map(String).map(c=>c.replace(/^\./,"")):[];n.record_extensions=Cs(["md",...a])}Array.isArray(n.explicit_type_keys)||(n.explicit_type_keys=["type","types"]),n.validation===void 0&&typeof n.default_validation=="string"&&(n.validation=n.default_validation),n.validation===void 0&&typeof t.default_validation=="string"&&(n.validation=t.default_validation),n.validation??="warn",n.id_field===void 0&&(n.id_field=typeof t.id_field=="string"?t.id_field:"id");let i=typeof n.types_folder=="string"?(0,Xe.normalizePath)(n.types_folder):"_types",s=(Array.isArray(n.exclude)?n.exclude:[]).map(String).flatMap(a=>CF(a,i)??[]);for(let a of s)MF(a)||e.push({path:"mdbase.yaml",code:"non_portable_exclude",message:`Exclude pattern "${a}" is not a portable v0.3 glob; review it.`,severity:"warning"});n.include_subfolders===!1&&s.push("*/**"),s.length>0?n.exclude=s:delete n.exclude;let o={};for(let a of kF)n[a]!==void 0&&(o[a]=n[a]),delete n[a];if(Object.keys(o).length>0){let a=pe(t["x-legacy-v0.2"])?t["x-legacy-v0.2"]:{};t["x-legacy-v0.2"]={...a,settings:o}}return delete n.include_subfolders,delete n.default_validation,delete t.default_validation,delete t.id_field,t}function CF(r,e){return/[/*?[]/.test(r)?r.includes("/")?r:`**/${r}`:r.startsWith(".")||r==="node_modules"||r===e?null:`${r}/**`}function MF(r){return r!==""&&!r.startsWith("/")&&!/[{}\\]/.test(r)&&r.split("/").every(e=>e==="**"||!e.includes("**"))}function ax(r,e){let t=pe(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 TF(r,e){let t={};for(let[n,i]of Object.entries(pe(e.fields)?e.fields:{}))pe(i)&&(t[n]=Ae(i));return{name:typeof e.name=="string"?e.name:r.split("/").pop()?.replace(/\.md$/,"")??"type",fields:t,match:pe(e.match)?Ae(e.match):void 0,filePath:r,specProfile:"v0.2"}}function RF(r,e){let t=pe(e.schema)?e.schema:{},n=pe(t.value)?t.value:{};return{name:typeof e.name=="string"?e.name:r.split("/").pop()?.replace(/\.md$/,"")??"type",fields:gn(n),match:pe(e.match)?Ae(e.match):void 0,collection:pe(e.collection)?Ae(e.collection):void 0,schema:Ae(n),filePath:r,specProfile:"v0.3"}}function IF(r,e,t){let n=Ae(r);for(let i of e){let s=t.get(i);if(s)for(let[o,a]of Object.entries(s.fields))!(o in n)&&a.default!==void 0&&(n[o]=Ae(a.default))}return n}function OF(r,e,t){let n=Ae(r);for(let i of e){let s=t.get(i);if(s)for(let[o,a]of Object.entries(s.collection?.read_defaults??{}))o in n||(n[o]=Ae(a))}return n}async function DF(r,e){let t=(0,Xe.normalizePath)(e).replace(/\/+$/,"");if(!t)return;let n="";for(let i of t.split("/")){n=n?`${n}/${i}`:i;let s=r.getAbstractFileByPath(n);if(!(s instanceof Xe.TFolder)){if(s)throw new Error(`A file blocks folder ${n}.`);await r.adapter.exists(n)||await r.createFolder(n)}}}async function yd(r,e,t){let n=(0,Xe.normalizePath)(e),i=n.lastIndexOf("/");if(i>=0&&await DF(r,n.slice(0,i)),n.startsWith(".mdbase/")){await r.adapter.write(n,t);return}let s=r.getAbstractFileByPath(n);if(s instanceof Xe.TFolder)throw new Error(`A folder blocks file ${n}.`);s instanceof Xe.TFile?await r.modify(s,t):await r.create(n,t)}async function ha(r,e){let t=(0,Xe.normalizePath)(e),n=r.getAbstractFileByPath(t);if(n instanceof Xe.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 cx(r){let e=await ha(r,"mdbase.yaml"),t=(0,Xe.parseYaml)(e);if(!pe(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===ma?"This collection is already mdbase v0.3.":`Expected an mdbase v0.2.x collection, found ${JSON.stringify(n)}.`);let i=pe(t.settings)?t.settings:{},s=typeof i.types_folder=="string"?(0,Xe.normalizePath)(i.types_folder):"_types",o=`${s}/`,a=[],c=[],l=[],u=PF(t,l),d=`${(0,Xe.stringifyYaml)(u).trimEnd()} +`),this.adoptionMarker=e}async readAdoptionMarker(){if(!await this.app.vault.adapter.exists(ca))return null;let e;try{e=JSON.parse(await this.app.vault.adapter.read(ca))}catch{throw new w("invalid_authority_adoption_checkpoint","The collection-adoption checkpoint is corrupt.")}if(!bF(e))throw new w("invalid_authority_adoption_checkpoint","The collection-adoption checkpoint is invalid.");return e}async writeAdoptionSnapshot(e){this.assertActive(),await Ps(this.app.vault,".mdbase"),this.assertActive(),await this.app.vault.adapter.write(la,JSON.stringify(e))}async readAdoptionSnapshot(e){if(!await this.app.vault.adapter.exists(la))throw new w("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(la))}catch{throw new w("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 w("authority_adoption_snapshot_mismatch","The fenced authority snapshot does not match its durable checkpoint.");return t}async clearAdoptionCheckpoint(e){let t=this.adoptionMarker?.session.requested.collectionId;await this.app.vault.adapter.exists(la)&&await this.app.vault.adapter.remove(la),await this.app.vault.adapter.exists(ca)&&await this.app.vault.adapter.remove(ca),this.adoptionMarker=null;try{this.app.secretStorage.setSecret(this.adoptionSecretId(e),"")}catch{}t&&await this.adoptionBlobStore(t).prune(new Set).catch(()=>{})}};function Om(r){let{credential:e,...t}=r;return t}function yF(r){return r instanceof J&&["authority_adoption_expired","authority_adoption_cancelled"].includes(r.code)}function gF(r){if(!at(r))return[];let e=r["x-obsidian"];return!at(e)||!at(e.bases)||!Array.isArray(e.bases.include)?[]:e.bases.include.filter(t=>typeof t=="string")}function pd(r){let e=r.getFiles?.();if(e)return e;let t=[],n=i=>{for(let s of i.children)s instanceof z.TFile?t.push(s):s instanceof z.TFolder&&n(s)};return n(r.getRoot()),t}function bF(r){if(!at(r)||r.version!==1||!["waiting_for_approval","uploading","fenced","activating","adopted"].includes(String(r.phase))||!at(r.session))return!1;let e=r.session;return typeof e.controlUrl=="string"&&typeof e.adoptionId=="string"&&ua.test(e.adoptionId)&&typeof e.verificationUri=="string"&&typeof e.expiresAt=="string"&&at(e.requested)&&typeof e.requested.collectionId=="string"&&ua.test(e.requested.collectionId)&&typeof e.requested.displayName=="string"&&typeof e.requested.sourceName=="string"&&e.requested.retainMirror===!0&&(r.selective_sync===void 0||vF(r.selective_sync))&&(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))}function vF(r){if(!at(r)||!Array.isArray(r.file_classes)||!Array.isArray(r.excluded_folders))return!1;try{let e=fr(r);return e.file_classes.length===r.file_classes.length&&e.excluded_folders.length===r.excluded_folders.length}catch{return!1}}function nx(r,e,t){return{version:1,syncUrl:r.syncUrl,controlUrl:r.controlUrl,collectionId:r.collectionId,replicaId:r.replicaId,mode:r.mode,name:r.name,enrollmentId:r.enrollmentId,accessTokenExpiresAt:r.accessTokenExpiresAt,selectiveSync:fr(e),...t?{deviceId:t}:{}}}async function wF(r,e){if(!e?.startsWith("sha256:"))return!1;let t=new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(r)));return`sha256:${Array.from(t,i=>i.toString(16).padStart(2,"0")).join("")}`===e}var Xe=require("obsidian");qt();var ma="0.3.0",_F=new Set(["name","description","display_name_key","strict","path_pattern","filename_pattern","match","fields","extends"]),SF=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 pe(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function Ae(r){return r===void 0?r:JSON.parse(JSON.stringify(r))}function rn(r){return Zo.digest(r)}function Ei(r){return Array.isArray(r)?`[${r.map(Ei).join(",")}]`:pe(r)?`{${Object.keys(r).sort().map(e=>`${JSON.stringify(e)}:${Ei(r[e])}`).join(",")}}`:JSON.stringify(r)}function Um(r){if(Array.isArray(r))return r.map(Um);if(!pe(r))return r;let e={};for(let[t,n]of Object.entries(r)){let i=Um(n);i!=null&&(Array.isArray(i)&&i.length===0||pe(i)&&Object.keys(i).length===0||(e[t]=i))}return e}function Cs(r){return[...new Set(r)]}function $F(r){return pe(r.fields)?Object.values(r.fields).some(e=>pe(e)&&(typeof e.tn_role=="string"||Array.isArray(e.tn_completed_values))):!1}function Vm(r,e,t){let n=pe(e)?e:{},i={},s={},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)?Ae(n.values):[]};break;case"link":a={type:"string"},i[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=Vm(`${r}[]`,n.items,t);a={type:"array",items:c.schema},Object.assign(i,c.links),Object.assign(s,c.legacy),o.push(...c.unsupported);break}case"object":{let c={},l=[];for(let[u,d]of Object.entries(pe(n.fields)?n.fields:{})){let f=Vm(`${r}.${u}`,d,t);c[u]=f.schema,Object.assign(i,f.links),Object.assign(s,f.legacy),o.push(...f.unsupported),pe(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:Cs(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"&&(n.type==="list"?a.minItems=n.min_length:a.minLength=n.min_length),typeof n.max_length=="number"&&(n.type==="list"?a.maxItems=n.max_length: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=Ae(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");(!SF.has(c)||(c==="tn_role"||c==="tn_completed_values")&&!u)&&(s[`${r}.${c}`]=Ae(l))}return{schema:a,links:i,legacy:s,unsupported:o}}function fa(r,e,t,n){let i=pe(r[e])?r[e]:{},s=pe(i.set)?i.set:{};s[t]=n,i.set=s,r[e]=i}function xF(r,e,t){if(t==="now")fa(r,"on_create",e,{now:!0});else if(t==="now_on_write")fa(r,"on_update",e,{now:!0});else if(t==="uuid")fa(r,"on_create",e,{uuid:!0});else if(t==="ulid")fa(r,"on_create",e,{ulid:!0});else if(pe(t)&&t.transform==="slugify"&&typeof t.from=="string")fa(r,"on_create",e,{slugify:t.from});else return!1;return!0}function EF(r){let e=r.match(/^(.*\/)?\{title\}\.md$/);return e?{runtime:"tasknotes",template:"{{title}}",folder:(e[1]??"").replace(/\/$/,""),generated_by:"tasknotes.filename.create"}:{runtime:"tasknotes",template:r,generated_by:"tasknotes.filename.create"}}function AF(r,e,t){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"||!pe(t.fields))throw new Error(`${r} is not a v0.2 type with a name and fields.`);let n=$F(t),i=t.name.trim().toLowerCase(),s={type:{const:i}},o=[],a={},c={},l=[],u={},d={},f=[],p=[],m={},h={},y={};for(let[E,k]of Object.entries(t.fields)){let $=pe(k)?k:{},M=Vm(E,$,n);s[E]=M.schema,Object.assign(c,M.links),Object.assign(d,M.legacy),f.push(...M.unsupported),$.required===!0&&o.push(E),$.default!==void 0&&(a[E]=Ae($.default)),$.unique===!0&&l.push({field:E,scope:"collection"}),$.generated!==void 0&&(xF(u,E,$.generated)?p.push(E):(d[`${E}.generated`]=Ae($.generated),f.push(`${E}.generated`))),typeof $.tn_role=="string"&&(m[$.tn_role]=E),Array.isArray($.tn_completed_values)&&(h.completed_values=Ae($.tn_completed_values))}a.status!==void 0&&(h.default=Ae(a.status)),a.priority!==void 0&&(y.default=Ae(a.priority));let g=typeof t.display_name_key=="string"&&Object.prototype.hasOwnProperty.call(t.fields,t.display_name_key)?t.display_name_key:void 0,b={...g?{display:{name_field:g}}:{},read_defaults:a,links:c,unique:l};typeof t.path_pattern=="string"&&(b.path=n?EF(t.path_pattern):{pattern:t.path_pattern});let v={};for(let[E,k]of Object.entries(t))_F.has(E)||(v[E]=Ae(k));Object.keys(d).length&&(v.fields=d);let S=Um({kind:"mdbase.type",name:i,version:1,description:typeof t.description=="string"?t.description:void 0,match:pe(t.match)?Ae(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:Cs(o)}:{}}},collection:b,lifecycle:u,...n?{"x-tasknotes":{contract:"tasknotes.task",version:1,field_roles:m,status:h,priority:y,archive:{tags_field:m.tags??"tags",archived_tag:"archived"}}}:{},...Object.keys(v).length?{"x-legacy-v0.2":v}:{}}),_=[];t.extends!==void 0&&f.push("extends");for(let E of Cs(f).sort())_.push({path:r,code:"migration_lossy",message:`${E} 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"&&!g&&_.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:i,fieldsConverted:Object.keys(t.fields).length,requiredFields:Cs(o),defaultsMoved:Object.keys(a),generatedFieldsMoved:Cs(p),linksMoved:Object.keys(c),taskNotes:n},diagnostics:_}}var kF=["default_strict","write_nulls","write_empty_lists","write_defaults","rename_update_refs","cache_folder","migrations_folder","extensions"];function PF(r,e){let t=Ae(r);t.spec_version=ma;let n=pe(t.settings)?t.settings:{};if(t.settings=n,!Array.isArray(n.record_extensions)){let a=Array.isArray(n.extensions)?n.extensions.map(String).map(c=>c.replace(/^\./,"")):[];n.record_extensions=Cs(["md",...a])}Array.isArray(n.explicit_type_keys)||(n.explicit_type_keys=["type","types"]),n.validation===void 0&&typeof n.default_validation=="string"&&(n.validation=n.default_validation),n.validation===void 0&&typeof t.default_validation=="string"&&(n.validation=t.default_validation),n.validation??="warn",n.id_field===void 0&&(n.id_field=typeof t.id_field=="string"?t.id_field:"id");let i=typeof n.types_folder=="string"?(0,Xe.normalizePath)(n.types_folder):"_types",s=(Array.isArray(n.exclude)?n.exclude:[]).map(String).flatMap(a=>CF(a,i)??[]);for(let a of s)MF(a)||e.push({path:"mdbase.yaml",code:"non_portable_exclude",message:`Exclude pattern "${a}" is not a portable v0.3 glob; review it.`,severity:"warning"});n.include_subfolders===!1&&s.push("*/**"),s.length>0?n.exclude=s:delete n.exclude;let o={};for(let a of kF)n[a]!==void 0&&(o[a]=n[a]),delete n[a];if(Object.keys(o).length>0){let a=pe(t["x-legacy-v0.2"])?t["x-legacy-v0.2"]:{};t["x-legacy-v0.2"]={...a,settings:o}}return delete n.include_subfolders,delete n.default_validation,delete t.default_validation,delete t.id_field,t}function CF(r,e){return/[/*?[]/.test(r)?r.includes("/")?r:`**/${r}`:r.startsWith(".")||r==="node_modules"||r===e?null:`${r}/**`}function MF(r){return r!==""&&!r.startsWith("/")&&!/[{}\\]/.test(r)&&r.split("/").every(e=>e==="**"||!e.includes("**"))}function cx(r,e){let t=pe(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 TF(r,e){let t={};for(let[n,i]of Object.entries(pe(e.fields)?e.fields:{}))pe(i)&&(t[n]=Ae(i));return{name:typeof e.name=="string"?e.name:r.split("/").pop()?.replace(/\.md$/,"")??"type",fields:t,match:pe(e.match)?Ae(e.match):void 0,filePath:r,specProfile:"v0.2"}}function RF(r,e){let t=pe(e.schema)?e.schema:{},n=pe(t.value)?t.value:{};return{name:typeof e.name=="string"?e.name:r.split("/").pop()?.replace(/\.md$/,"")??"type",fields:gn(n),match:pe(e.match)?Ae(e.match):void 0,collection:pe(e.collection)?Ae(e.collection):void 0,schema:Ae(n),filePath:r,specProfile:"v0.3"}}function IF(r,e,t){let n=Ae(r);for(let i of e){let s=t.get(i);if(s)for(let[o,a]of Object.entries(s.fields))!(o in n)&&a.default!==void 0&&(n[o]=Ae(a.default))}return n}function OF(r,e,t){let n=Ae(r);for(let i of e){let s=t.get(i);if(s)for(let[o,a]of Object.entries(s.collection?.read_defaults??{}))o in n||(n[o]=Ae(a))}return n}async function DF(r,e){let t=(0,Xe.normalizePath)(e).replace(/\/+$/,"");if(!t)return;let n="";for(let i of t.split("/")){n=n?`${n}/${i}`:i;let s=r.getAbstractFileByPath(n);if(!(s instanceof Xe.TFolder)){if(s)throw new Error(`A file blocks folder ${n}.`);await r.adapter.exists(n)||await r.createFolder(n)}}}async function md(r,e,t){let n=(0,Xe.normalizePath)(e),i=n.lastIndexOf("/");if(i>=0&&await DF(r,n.slice(0,i)),n.startsWith(".mdbase/")){await r.adapter.write(n,t);return}let s=r.getAbstractFileByPath(n);if(s instanceof Xe.TFolder)throw new Error(`A folder blocks file ${n}.`);s instanceof Xe.TFile?await r.modify(s,t):await r.create(n,t)}async function ha(r,e){let t=(0,Xe.normalizePath)(e),n=r.getAbstractFileByPath(t);if(n instanceof Xe.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 lx(r){let e=await ha(r,"mdbase.yaml"),t=(0,Xe.parseYaml)(e);if(!pe(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===ma?"This collection is already mdbase v0.3.":`Expected an mdbase v0.2.x collection, found ${JSON.stringify(n)}.`);let i=pe(t.settings)?t.settings:{},s=typeof i.types_folder=="string"?(0,Xe.normalizePath)(i.types_folder):"_types",o=`${s}/`,a=[],c=[],l=[],u=PF(t,l),d=`${(0,Xe.stringifyYaml)(u).trimEnd()} `;a.push({path:"mdbase.yaml",sourceDigest:rn(e),targetDigest:rn(d),source:e,target:d});let f=new Map,p=new Map;for(let S of r.getMarkdownFiles().filter(_=>_.path.startsWith(o)).sort((_,E)=>_.path.localeCompare(E.path))){let _=await r.cachedRead(S),E=Me(_);if(!E.hasFrontmatter||E.error)throw new Error(`Cannot migrate ${S.path}: ${E.error??"frontmatter is missing"}.`);let k=AF(S.path,n,E.frontmatter),$=TF(S.path,E.frontmatter),M=RF(S.path,k.target);f.set($.name,$),p.set(M.name,M);let x=`${mt(k.target,E.body)} -`;a.push({path:S.path,sourceDigest:rn(_),targetDigest:rn(x),source:_,target:x}),c.push(k.summary),l.push(...k.diagnostics)}if(!c.length)throw new Error(`No v0.2 type files were found in ${s}.`);let h=0,m=0,y=ax(t,n),g=ax(u,ma),b=r.getMarkdownFiles().filter(S=>!S.path.startsWith(o)).filter(S=>!S.path.startsWith(".mdbase/")).sort((S,_)=>S.path.localeCompare(_.path));for(let[S,_]of b.entries()){let E=Me(await r.cachedRead(_));if(E.error){m+=1;continue}let k=Ke(_.path,E.frontmatter,y,f),$=Ke(_.path,E.frontmatter,g,p),M=IF(E.frontmatter,k,f),x=OF(E.frontmatter,$,p);(Ei(k.slice().sort())!==Ei($.slice().sort())||Ei(M)!==Ei(x))&&l.push({path:_.path,code:"effective_read_changed",message:"The proposed v0.3 types would change this record's resolved types or effective default values.",severity:"lossy"}),h+=1,S>0&&S%250===0&&await new Promise(q=>window.setTimeout(q,0))}let v=rn(Ei({sourceVersion:n,operations:a.map(({path:S,sourceDigest:_,targetDigest:E})=>({path:S,sourceDigest:_,targetDigest:E})),diagnostics:l}));return{planVersion:1,analysisId:v,sourceVersion:n,targetVersion:ma,createdAt:new Date().toISOString(),backupLocation:`.mdbase/migrations/v02-to-v03-${v.slice(0,12)}`,operations:a,typeSummaries:c,diagnostics:l,applicable:!l.some(S=>S.severity==="lossy"),recordFilesRewritten:0,recordsVerified:h,recordsSkipped:m}}async function pa(r,e,t){await yd(r,e,`${JSON.stringify(t,null,2)} -`)}async function lx(r,e,t={}){if(e.planVersion!==1||e.targetVersion!==ma)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 ha(r,s.path);if(rn(o)!==s.sourceDigest)throw new Error(`${s.path} changed after migration analysis. Run the review again.`)}let n=`${e.backupLocation}/manifest.json`,i={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 yd(r,`${e.backupLocation}/files/${s.path}`,s.source);await pa(r,n,i),i.status="applying",await pa(r,n,i);try{for(let s of e.operations){let o=await ha(r,s.path);if(rn(o)!==s.sourceDigest)throw new Error(`${s.path} changed during migration.`);i.written.push(s.path),await pa(r,n,i),await yd(r,s.path,s.target);let a=await ha(r,s.path);if(rn(a)!==s.targetDigest)throw new Error(`${s.path} did not verify after write.`)}return i.status="applied",i.completed_at=new Date().toISOString(),await pa(r,n,i),{applied:!0,restored:!1,manifestPath:n,written:[...i.written]}}catch(s){let o=[];for(let a of[...i.written].reverse()){let c=e.operations.find(l=>l.path===a);if(!c){o.push(a);continue}try{await yd(r,a,c.source),rn(await ha(r,a))!==c.sourceDigest&&o.push(a)}catch{o.push(a)}}i.status=o.length?"recovery_required":"rolled_back",i.error=s instanceof Error?s.message:String(s),i.manual_recovery_paths=o.length?o:void 0,i.completed_at=new Date().toISOString();try{await pa(r,n,i)}catch{}return{applied:!1,restored:o.length===0,manifestPath:n,written:[...i.written],error:i.error}}}var gd=require("obsidian");qt();function we(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function Mt(r){return JSON.parse(JSON.stringify(r))}var NF=new Set(["file","formula","this"]);function LF(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(NF.has(e.toLowerCase()))throw new Error(`Type name '${e}' is reserved.`);return e}function Hm(){return{specProfile:"v0.3",originalFrontmatter:{},name:"",description:"",extendsType:"",displayNameKey:"",strictMode:!1,pathPattern:"",filenamePattern:"",matchPathGlob:"",matchFieldsPresent:"",matchWhere:"",fields:[{name:"title",definition:{type:"string",required:!0}}],implementations:[],body:`# Type +`;a.push({path:S.path,sourceDigest:rn(_),targetDigest:rn(x),source:_,target:x}),c.push(k.summary),l.push(...k.diagnostics)}if(!c.length)throw new Error(`No v0.2 type files were found in ${s}.`);let m=0,h=0,y=cx(t,n),g=cx(u,ma),b=r.getMarkdownFiles().filter(S=>!S.path.startsWith(o)).filter(S=>!S.path.startsWith(".mdbase/")).sort((S,_)=>S.path.localeCompare(_.path));for(let[S,_]of b.entries()){let E=Me(await r.cachedRead(_));if(E.error){h+=1;continue}let k=Ke(_.path,E.frontmatter,y,f),$=Ke(_.path,E.frontmatter,g,p),M=IF(E.frontmatter,k,f),x=OF(E.frontmatter,$,p);(Ei(k.slice().sort())!==Ei($.slice().sort())||Ei(M)!==Ei(x))&&l.push({path:_.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,S>0&&S%250===0&&await new Promise(q=>window.setTimeout(q,0))}let v=rn(Ei({sourceVersion:n,operations:a.map(({path:S,sourceDigest:_,targetDigest:E})=>({path:S,sourceDigest:_,targetDigest:E})),diagnostics:l}));return{planVersion:1,analysisId:v,sourceVersion:n,targetVersion:ma,createdAt:new Date().toISOString(),backupLocation:`.mdbase/migrations/v02-to-v03-${v.slice(0,12)}`,operations:a,typeSummaries:c,diagnostics:l,applicable:!l.some(S=>S.severity==="lossy"),recordFilesRewritten:0,recordsVerified:m,recordsSkipped:h}}async function pa(r,e,t){await md(r,e,`${JSON.stringify(t,null,2)} +`)}async function dx(r,e,t={}){if(e.planVersion!==1||e.targetVersion!==ma)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 ha(r,s.path);if(rn(o)!==s.sourceDigest)throw new Error(`${s.path} changed after migration analysis. Run the review again.`)}let n=`${e.backupLocation}/manifest.json`,i={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 md(r,`${e.backupLocation}/files/${s.path}`,s.source);await pa(r,n,i),i.status="applying",await pa(r,n,i);try{for(let s of e.operations){let o=await ha(r,s.path);if(rn(o)!==s.sourceDigest)throw new Error(`${s.path} changed during migration.`);i.written.push(s.path),await pa(r,n,i),await md(r,s.path,s.target);let a=await ha(r,s.path);if(rn(a)!==s.targetDigest)throw new Error(`${s.path} did not verify after write.`)}return i.status="applied",i.completed_at=new Date().toISOString(),await pa(r,n,i),{applied:!0,restored:!1,manifestPath:n,written:[...i.written]}}catch(s){let o=[];for(let a of[...i.written].reverse()){let c=e.operations.find(l=>l.path===a);if(!c){o.push(a);continue}try{await md(r,a,c.source),rn(await ha(r,a))!==c.sourceDigest&&o.push(a)}catch{o.push(a)}}i.status=o.length?"recovery_required":"rolled_back",i.error=s instanceof Error?s.message:String(s),i.manual_recovery_paths=o.length?o:void 0,i.completed_at=new Date().toISOString();try{await pa(r,n,i)}catch{}return{applied:!1,restored:o.length===0,manifestPath:n,written:[...i.written],error:i.error}}}var yd=require("obsidian");qt();function we(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function Mt(r){return JSON.parse(JSON.stringify(r))}var NF=new Set(["file","formula","this"]);function LF(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(NF.has(e.toLowerCase()))throw new Error(`Type name '${e}' is reserved.`);return e}function Hm(){return{specProfile:"v0.3",originalFrontmatter:{},name:"",description:"",extendsType:"",displayNameKey:"",strictMode:!1,pathPattern:"",filenamePattern:"",matchPathGlob:"",matchFieldsPresent:"",matchWhere:"",fields:[{name:"title",definition:{type:"string",required:!0}}],implementations:[],body:`# Type -Describe the type and intended usage.`,extraFrontmatter:{}}}function FF(r){return we(r)?Object.entries(r).filter(e=>we(e[1])).map(([e,t])=>({name:e,definition:Mt(t)})):[]}function jF(r){return Array.isArray(r)?r.flatMap(e=>{if(!we(e)||typeof e.contract!="string"||typeof e.version!="string")return[];let t=we(e.fields)?Object.fromEntries(Object.entries(e.fields).filter(([,i])=>typeof i=="string")):{},n=we(e.binding)?Mt(e.binding):void 0;return[{contract:e.contract,version:e.version,fields:t,...n?{binding:n}:{}}]}):[]}function qF(r){return Object.fromEntries(r.map(e=>[e.name,e.definition]))}function BF(r,e){let t=e.split("."),n=r,i;for(let[s,o]of t.entries()){let a=o.match(/^([^[]+)((?:\[\])*)$/);if(!a||(i=n[a[1]],!i))return null;let c=a[2].length/2;for(let l=0;l{if(e.selectors.add(i),n.type==="link"&&e.links.set(i,{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,`${i}[]`),n.type==="object"&&n.fields)for(let[s,o]of Object.entries(n.fields))t(o,`${i}.${s}`)};for(let[n,i]of Object.entries(r))t(i,n);return e}function bd(r,e,t){let n=r.kind==="mdbase.type",i=n&&we(r.schema)?r.schema:{},s=we(i.value)?i.value:{},o=typeof i.ref=="string"?i.ref:"",a=n&&we(r.collection)?r.collection:{},c=we(a.display)?a.display:{},l=we(a.path)?a.path:{},u=FF(n?gn(s):r.fields);n&&UF(u,a.links);let d=we(r.match)?r.match:{},f=n?s.additionalProperties===!1:r.strict,p=new Set(["name","description","extends","display_name_key","strict","path_pattern","filename_pattern","match","fields"]),h={};for(let[y,g]of Object.entries(r))p.has(y)||(h[y]=Mt(g));let m="";if(d.where!==void 0)try{m=(0,gd.stringifyYaml)(d.where).trim()}catch{m=""}return{specProfile:n?"v0.3":"v0.2",originalFrontmatter:Mt(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:m,fields:u.length||o?u:Hm().fields,implementations:jF(r.implements),body:e.trim()||`# ${t} +Describe the type and intended usage.`,extraFrontmatter:{}}}function FF(r){return we(r)?Object.entries(r).filter(e=>we(e[1])).map(([e,t])=>({name:e,definition:Mt(t)})):[]}function jF(r){return Array.isArray(r)?r.flatMap(e=>{if(!we(e)||typeof e.contract!="string"||typeof e.version!="string")return[];let t=we(e.fields)?Object.fromEntries(Object.entries(e.fields).filter(([,i])=>typeof i=="string")):{},n=we(e.binding)?Mt(e.binding):void 0;return[{contract:e.contract,version:e.version,fields:t,...n?{binding:n}:{}}]}):[]}function qF(r){return Object.fromEntries(r.map(e=>[e.name,e.definition]))}function BF(r,e){let t=e.split("."),n=r,i;for(let[s,o]of t.entries()){let a=o.match(/^([^[]+)((?:\[\])*)$/);if(!a||(i=n[a[1]],!i))return null;let c=a[2].length/2;for(let l=0;l{if(e.selectors.add(i),n.type==="link"&&e.links.set(i,{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,`${i}[]`),n.type==="object"&&n.fields)for(let[s,o]of Object.entries(n.fields))t(o,`${i}.${s}`)};for(let[n,i]of Object.entries(r))t(i,n);return e}function gd(r,e,t){let n=r.kind==="mdbase.type",i=n&&we(r.schema)?r.schema:{},s=we(i.value)?i.value:{},o=typeof i.ref=="string"?i.ref:"",a=n&&we(r.collection)?r.collection:{},c=we(a.display)?a.display:{},l=we(a.path)?a.path:{},u=FF(n?gn(s):r.fields);n&&UF(u,a.links);let d=we(r.match)?r.match:{},f=n?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,g]of Object.entries(r))p.has(y)||(m[y]=Mt(g));let h="";if(d.where!==void 0)try{h=(0,yd.stringifyYaml)(d.where).trim()}catch{h=""}return{specProfile:n?"v0.3":"v0.2",originalFrontmatter:Mt(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:Hm().fields,implementations:jF(r.implements),body:e.trim()||`# ${t} -Type definition for ${t}.`,extraFrontmatter:h,...o?{readOnlyReason:`This type uses schema.ref (${o}). Edit the referenced JSON Schema file directly.`}:{}}}function Fn(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?Mt(r.originalFrontmatter):{},t=we(e.schema)?e.schema:{},n=we(t.value)?t.value:{},i=Object.create(null);for(let m of r.fields){let y=m.name.trim();if(!y)throw new Error("Every field needs a name.");if(Object.prototype.hasOwnProperty.call(i,y))throw new Error(`Duplicate field name: ${y}`);i[y]=Mt(m.definition)}let s=LF(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:es(i,n,r.strictMode===!0)}};delete o.schema.ref,r.description.trim()?o.description=r.description.trim():delete o.description;let a=we(o.match)?Mt(o.match):{};r.matchPathGlob.trim()?a.path_glob=r.matchPathGlob.trim():delete a.path_glob;let c=r.matchFieldsPresent.split(",").map(m=>m.trim()).filter(Boolean);if(c.length?a.fields_present=c:delete a.fields_present,r.matchWhere.trim()){let m=(0,gd.parseYaml)(r.matchWhere);if(!we(m))throw new Error("Match where must be a YAML mapping.");a.where=m}else delete a.where;Object.keys(a).length?o.match=a:delete o.match;let l=we(o.collection)?Mt(o.collection):{},u=we(l.display)?Mt(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 m=we(l.path)?l.path:{};l.path={...m,pattern:r.pathPattern.trim()}}else if(we(l.path)&&typeof l.path.pattern=="string"){let m={...l.path};delete m.pattern,Object.keys(m).length?l.path=m:delete l.path}let d=we(l.links)?Mt(l.links):{},f=Mt(d),p=dx(i),h=dx(gn(n));for(let m of new Set([...h.selectors,...p.selectors]))delete f[m];for(let[m,y]of p.links)f[m]={...we(d[m])?d[m]:{},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,r.implementations.length?o.implements=r.implementations.map(m=>({contract:m.contract,version:m.version,fields:Mt(m.fields),...m.binding&&Object.keys(m.binding).length?{binding:Mt(m.binding)}:{}})):delete o.implements;for(let m of["fields","strict","extends","display_name_key","path_pattern","filename_pattern"])delete o[m];return o}qt();function nn(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function ux(r){return JSON.parse(JSON.stringify(r))}function Ms(r){return`${r.id}@${r.version}`}function ya(r){let e=nn(r.schema)?r.schema:{},t=nn(e.properties)?e.properties:{},n=new Set(Array.isArray(e.required)?e.required.map(String):[]);return Object.entries(t).filter(i=>nn(i[1])).map(([i,s])=>({name:i,reference:i,required:n.has(i),schema:s,...typeof s.description=="string"?{description:s.description}:{}}))}function ga(r){let e=Object.fromEntries(r.fields.map(s=>[s.name,s.definition])),t=es(e),n=nn(t.properties)?t.properties:{},i=new Set(Array.isArray(t.required)?t.required.map(String):[]);return Object.entries(n).filter(s=>nn(s[1])).map(([s,o])=>({label:s,reference:s,required:i.has(s),type:jn(o),schema:o}))}function Ts(r,e){return r.fields[e.reference]??r.fields[e.name]??""}function ba(r,e){if(!e)return r.required?{level:"error",label:"Required",message:`Map required contract field ${r.reference}.`}:{level:"unmapped",label:"Not exposed",message:"This optional contract field is not exposed."};let t=jn(r.schema);return yx(t,e.type)?r.required&&!e.required?{level:"warning",label:"Review",message:`${e.reference} is optional in this type, so the contract value may be absent.`}:{level:"valid",label:"Ready",message:"This field satisfies the contract shape."}:{level:"error",label:"Incompatible",message:`${e.reference} is ${e.type}, but the contract expects ${t}.`}}function fx(r,e){if(r.implementations.some(i=>i.contract===e.id&&i.version===e.version))throw new Error(`${e.id} ${e.version} is already implemented.`);let t=ga(r),n=Object.fromEntries(ya(e).flatMap(i=>{let s=t.find(o=>o.reference.toLowerCase()===i.reference.toLowerCase()&&yx(jn(i.schema),o.type));return s?[[i.reference,s.reference]]:[]}));r.implementations.push({contract:e.id,version:e.version,fields:n})}function px(r,e,t){r.implementations=r.implementations.filter(n=>n.contract!==e||n.version!==t)}function hx(r,e,t){t?r.fields[e]=t:delete r.fields[e]}function zm(r,e){r.binding=Object.keys(e).length?ux(e):void 0}function va(r){if(!r)return"";if(Array.isArray(r.enum)&&r.enum.length)return ux(r.enum[0]);let e=jn(r);if(e==="object"){let t={},n=nn(r.properties)?r.properties:{},i=new Set(Array.isArray(r.required)?r.required.map(String):[]);for(let[s,o]of Object.entries(n))i.has(s)&&nn(o)&&(t[s]=va(o));return t}return e==="array"?[]:e==="boolean"?!1:e==="number"||e==="integer"?0:""}function jn(r){return"const"in r?typeof r.const:Array.isArray(r.type)?String(r.type.find(e=>e!=="null")??r.type[0]??"string"):typeof r.type=="string"?r.type:Array.isArray(r.enum)?"string":nn(r.properties)||nn(r.additionalProperties)?"object":"any"}function mx(r){let e=jn(r);return e==="array"?"List":e==="boolean"?"Boolean":e==="integer"?"Integer":e==="number"?"Number":e==="object"?"Object":e==="any"?"Any value":"Text"}function yx(r,e){return r==="any"||e==="any"||r===e?!0:r==="number"&&e==="integer"}function Km(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function VF(r){return JSON.parse(JSON.stringify(r))}function Jm(r){let e=2166136261,t=2654435769;for(let n=0;n>>0).toString(36)}-${(t>>>0).toString(36)}`}function gx(r){let e=VF(r);return delete e.sourceRevision,e}function vd(r,e){return r===null||e===null?r===e:JSON.stringify(gx(r))===JSON.stringify(gx(e))}function bx(r){return new Map(r.fields.map(e=>[e.name,e]))}function Wm(r){return typeof r.type=="string"?r.type:"any"}function Gm(r,e,t,n){let i=Wm(r);if(i==="enum"&&(!Array.isArray(r.values)||r.values.length===0)&&t.push({code:"enum_without_values",severity:"warning",path:e,message:"Add at least one allowed value, or use String for an unrestricted value."}),i==="enum"&&Array.isArray(r.values)){let s=r.values.map(o=>JSON.stringify(o));new Set(s).size!==s.length&&t.push({code:"enum_duplicate_values",severity:"error",path:e,message:"Allowed values must be unique."}),r.default!==void 0&&!s.includes(JSON.stringify(r.default))&&t.push({code:"default_not_allowed",severity:"error",path:e,message:"The default is not one of the allowed values."})}for(let[s,o,a]of[["min","max","Minimum"],["min_length","max_length","Minimum length"]]){let c=r[s],l=r[o];typeof c=="number"&&typeof l=="number"&&c>l&&t.push({code:"constraint_range_inverted",severity:"error",path:e,message:`${a} is greater than the maximum.`})}if(typeof r.pattern=="string")try{new RegExp(r.pattern)}catch(s){t.push({code:"invalid_pattern",severity:"error",path:e,message:`The pattern is not a valid regular expression: ${s instanceof Error?s.message:String(s)}`})}if(i==="link"){let s=typeof r.target=="string"?r.target.trim():"";s&&s!=="any"&&n.size&&!n.has(s)&&t.push({code:"unknown_link_target",severity:"error",path:e,message:`The target type '${s}' is not installed in this collection.`})}if(i==="list"&&(Km(r.items)?Gm(r.items,`${e}[]`,t,n):t.push({code:"list_items_missing",severity:"error",path:e,message:"Choose the shape of each list item."})),i==="object"){if(!Km(r.fields)){t.push({code:"object_fields_missing",severity:"error",path:e,message:"Add an object field or change this field's type."});return}let s=new Set;for(let[o,a]of Object.entries(r.fields)){let c=`${e}.${o||"unnamed"}`;o.trim()?s.has(o)&&t.push({code:"duplicate_field_name",severity:"error",path:c,message:`The nested field '${o}' is declared more than once.`}):t.push({code:"field_name_required",severity:"error",path:c,message:"Every nested field needs a name."}),s.add(o),Km(a)&&Gm(a,c,t,n)}}}function wa(r,e={}){let t=[],n=new Set(e.knownTypes??[]);try{Fn(r)}catch(a){t.push({code:"invalid_type_document",severity:"error",path:"type",message:a instanceof Error?a.message:String(a)})}let i=new Set;for(let a of r.fields){let c=a.name.trim(),l=`fields.${c||"unnamed"}`;c?i.has(c)&&t.push({code:"duplicate_field_name",severity:"error",path:l,message:`The field '${c}' is declared more than once.`}):t.push({code:"field_name_required",severity:"error",path:l,message:"Every field needs a name."}),i.add(c),Gm(a.definition,l,t,n)}r.displayNameKey.trim()&&!i.has(r.displayNameKey.trim())&&t.push({code:"display_field_missing",severity:"error",path:"identity.displayNameKey",message:`The display field '${r.displayNameKey.trim()}' is not declared.`});let s=new Map([...e.contracts??[]].map(a=>[Ms(a),a])),o=ga(r);for(let a of r.implementations){let c=`${a.contract}@${a.version}`,l=s.get(c);if(!l){t.push({code:"contract_unavailable",severity:"error",path:`applications.${c}`,message:"This exact application contract is not installed."});continue}for(let u of ya(l)){let d=Ts(a,u),f=o.find(h=>h.reference===d),p=ba(u,f);p.level!=="valid"&&t.push({code:p.level==="error"?"invalid_contract_mapping":"review_contract_mapping",severity:p.level==="error"?"error":"warning",path:`applications.${c}.${u.reference}`,message:p.message})}}return t.filter((a,c,l)=>l.findIndex(u=>u.code===a.code&&u.path===a.path&&u.message===a.message)===c)}function _a(r,e){if(!r)return[{code:"create_type",risk:"safe",summary:`Create the type '${e.name||"Untitled type"}'.`}];let t=[];r.name!==e.name&&t.push({code:"rename_type",risk:"high",summary:`Rename the type from '${r.name}' to '${e.name}'. Existing type references may need review.`}),(r.description!==e.description||r.displayNameKey!==e.displayNameKey)&&t.push({code:"identity",risk:"safe",summary:"Update the type's identity and display metadata."}),(r.matchPathGlob!==e.matchPathGlob||r.matchFieldsPresent!==e.matchFieldsPresent||r.matchWhere!==e.matchWhere)&&t.push({code:"membership",risk:"high",summary:"Change which records belong to this type."}),r.pathPattern!==e.pathPattern&&t.push({code:"placement",risk:"review",summary:"Change the suggested path for new records."}),r.strictMode!==e.strictMode&&t.push({code:"strictness",risk:e.strictMode===!0?"high":"review",summary:e.strictMode===!0?"Reject fields that are not declared by this type.":"Allow fields that are not declared by this type."});let n=bx(r),i=bx(e),s=[...i.keys()].filter(l=>!n.has(l)),o=[...n.keys()].filter(l=>!i.has(l));s.length&&t.push({code:"add_fields",risk:s.some(l=>i.get(l)?.definition.required===!0)?"high":"safe",summary:`Add ${s.length===1?"field":"fields"}: ${s.join(", ")}.`}),o.length&&t.push({code:"remove_fields",risk:"high",summary:`Remove ${o.length===1?"field":"fields"}: ${o.join(", ")}.`});for(let[l,u]of i){let d=n.get(l);if(!d)continue;let f=Wm(d.definition),p=Wm(u.definition);f!==p&&t.push({code:"change_field_type",risk:"high",summary:`Change '${l}' from ${f} to ${p}.`}),d.definition.required!==!0&&u.definition.required===!0&&t.push({code:"require_field",risk:"high",summary:`Make '${l}' required. Existing records may become invalid.`}),f===p&&JSON.stringify(d.definition)!==JSON.stringify(u.definition)&&d.definition.required===u.definition.required&&t.push({code:"field_rules",risk:"review",summary:`Update validation or documentation for '${l}'.`})}let a=[...n.keys()].filter(l=>i.has(l)),c=[...i.keys()].filter(l=>n.has(l));return a.join("\0")!==c.join("\0")&&t.push({code:"reorder_fields",risk:"safe",summary:"Reorder fields."}),JSON.stringify(r.implementations)!==JSON.stringify(e.implementations)&&t.push({code:"application_compatibility",risk:"review",summary:"Update application contract mappings or settings."}),!t.length&&!vd(r,e)&&t.push({code:"type_document",risk:"review",summary:"Update advanced type metadata or documentation."}),t}var Ds=require("obsidian");var Sa="mdbase-frontmatter",vx=` +Type definition for ${t}.`,extraFrontmatter:m,...o?{readOnlyReason:`This type uses schema.ref (${o}). Edit the referenced JSON Schema file directly.`}:{}}}function Fn(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?Mt(r.originalFrontmatter):{},t=we(e.schema)?e.schema:{},n=we(t.value)?t.value:{},i=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(i,y))throw new Error(`Duplicate field name: ${y}`);i[y]=Mt(h.definition)}let s=LF(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:es(i,n,r.strictMode===!0)}};delete o.schema.ref,r.description.trim()?o.description=r.description.trim():delete o.description;let a=we(o.match)?Mt(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,yd.parseYaml)(r.matchWhere);if(!we(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=we(o.collection)?Mt(o.collection):{},u=we(l.display)?Mt(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=we(l.path)?l.path:{};l.path={...h,pattern:r.pathPattern.trim()}}else if(we(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=we(l.links)?Mt(l.links):{},f=Mt(d),p=ux(i),m=ux(gn(n));for(let h of new Set([...m.selectors,...p.selectors]))delete f[h];for(let[h,y]of p.links)f[h]={...we(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,r.implementations.length?o.implements=r.implementations.map(h=>({contract:h.contract,version:h.version,fields:Mt(h.fields),...h.binding&&Object.keys(h.binding).length?{binding:Mt(h.binding)}:{}})):delete o.implements;for(let h of["fields","strict","extends","display_name_key","path_pattern","filename_pattern"])delete o[h];return o}qt();function nn(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function fx(r){return JSON.parse(JSON.stringify(r))}function Ms(r){return`${r.id}@${r.version}`}function ya(r){let e=nn(r.schema)?r.schema:{},t=nn(e.properties)?e.properties:{},n=new Set(Array.isArray(e.required)?e.required.map(String):[]);return Object.entries(t).filter(i=>nn(i[1])).map(([i,s])=>({name:i,reference:i,required:n.has(i),schema:s,...typeof s.description=="string"?{description:s.description}:{}}))}function ga(r){let e=Object.fromEntries(r.fields.map(s=>[s.name,s.definition])),t=es(e),n=nn(t.properties)?t.properties:{},i=new Set(Array.isArray(t.required)?t.required.map(String):[]);return Object.entries(n).filter(s=>nn(s[1])).map(([s,o])=>({label:s,reference:s,required:i.has(s),type:jn(o),schema:o}))}function Ts(r,e){return r.fields[e.reference]??r.fields[e.name]??""}function ba(r,e){if(!e)return r.required?{level:"error",label:"Required",message:`Map required contract field ${r.reference}.`}:{level:"unmapped",label:"Not exposed",message:"This optional contract field is not exposed."};let t=jn(r.schema);return gx(t,e.type)?r.required&&!e.required?{level:"warning",label:"Review",message:`${e.reference} is optional in this type, so the contract value may be absent.`}:{level:"valid",label:"Ready",message:"This field satisfies the contract shape."}:{level:"error",label:"Incompatible",message:`${e.reference} is ${e.type}, but the contract expects ${t}.`}}function px(r,e){if(r.implementations.some(i=>i.contract===e.id&&i.version===e.version))throw new Error(`${e.id} ${e.version} is already implemented.`);let t=ga(r),n=Object.fromEntries(ya(e).flatMap(i=>{let s=t.find(o=>o.reference.toLowerCase()===i.reference.toLowerCase()&&gx(jn(i.schema),o.type));return s?[[i.reference,s.reference]]:[]}));r.implementations.push({contract:e.id,version:e.version,fields:n})}function hx(r,e,t){r.implementations=r.implementations.filter(n=>n.contract!==e||n.version!==t)}function mx(r,e,t){t?r.fields[e]=t:delete r.fields[e]}function zm(r,e){r.binding=Object.keys(e).length?fx(e):void 0}function va(r){if(!r)return"";if(Array.isArray(r.enum)&&r.enum.length)return fx(r.enum[0]);let e=jn(r);if(e==="object"){let t={},n=nn(r.properties)?r.properties:{},i=new Set(Array.isArray(r.required)?r.required.map(String):[]);for(let[s,o]of Object.entries(n))i.has(s)&&nn(o)&&(t[s]=va(o));return t}return e==="array"?[]:e==="boolean"?!1:e==="number"||e==="integer"?0:""}function jn(r){return"const"in r?typeof r.const:Array.isArray(r.type)?String(r.type.find(e=>e!=="null")??r.type[0]??"string"):typeof r.type=="string"?r.type:Array.isArray(r.enum)?"string":nn(r.properties)||nn(r.additionalProperties)?"object":"any"}function yx(r){let e=jn(r);return e==="array"?"List":e==="boolean"?"Boolean":e==="integer"?"Integer":e==="number"?"Number":e==="object"?"Object":e==="any"?"Any value":"Text"}function gx(r,e){return r==="any"||e==="any"||r===e?!0:r==="number"&&e==="integer"}function Km(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function VF(r){return JSON.parse(JSON.stringify(r))}function Jm(r){let e=2166136261,t=2654435769;for(let n=0;n>>0).toString(36)}-${(t>>>0).toString(36)}`}function bx(r){let e=VF(r);return delete e.sourceRevision,e}function bd(r,e){return r===null||e===null?r===e:JSON.stringify(bx(r))===JSON.stringify(bx(e))}function vx(r){return new Map(r.fields.map(e=>[e.name,e]))}function Wm(r){return typeof r.type=="string"?r.type:"any"}function Gm(r,e,t,n){let i=Wm(r);if(i==="enum"&&(!Array.isArray(r.values)||r.values.length===0)&&t.push({code:"enum_without_values",severity:"warning",path:e,message:"Add at least one allowed value, or use String for an unrestricted value."}),i==="enum"&&Array.isArray(r.values)){let s=r.values.map(o=>JSON.stringify(o));new Set(s).size!==s.length&&t.push({code:"enum_duplicate_values",severity:"error",path:e,message:"Allowed values must be unique."}),r.default!==void 0&&!s.includes(JSON.stringify(r.default))&&t.push({code:"default_not_allowed",severity:"error",path:e,message:"The default is not one of the allowed values."})}for(let[s,o,a]of[["min","max","Minimum"],["min_length","max_length","Minimum length"]]){let c=r[s],l=r[o];typeof c=="number"&&typeof l=="number"&&c>l&&t.push({code:"constraint_range_inverted",severity:"error",path:e,message:`${a} is greater than the maximum.`})}if(typeof r.pattern=="string")try{new RegExp(r.pattern)}catch(s){t.push({code:"invalid_pattern",severity:"error",path:e,message:`The pattern is not a valid regular expression: ${s instanceof Error?s.message:String(s)}`})}if(i==="link"){let s=typeof r.target=="string"?r.target.trim():"";s&&s!=="any"&&n.size&&!n.has(s)&&t.push({code:"unknown_link_target",severity:"error",path:e,message:`The target type '${s}' is not installed in this collection.`})}if(i==="list"&&(Km(r.items)?Gm(r.items,`${e}[]`,t,n):t.push({code:"list_items_missing",severity:"error",path:e,message:"Choose the shape of each list item."})),i==="object"){if(!Km(r.fields)){t.push({code:"object_fields_missing",severity:"error",path:e,message:"Add an object field or change this field's type."});return}let s=new Set;for(let[o,a]of Object.entries(r.fields)){let c=`${e}.${o||"unnamed"}`;o.trim()?s.has(o)&&t.push({code:"duplicate_field_name",severity:"error",path:c,message:`The nested field '${o}' is declared more than once.`}):t.push({code:"field_name_required",severity:"error",path:c,message:"Every nested field needs a name."}),s.add(o),Km(a)&&Gm(a,c,t,n)}}}function wa(r,e={}){let t=[],n=new Set(e.knownTypes??[]);try{Fn(r)}catch(a){t.push({code:"invalid_type_document",severity:"error",path:"type",message:a instanceof Error?a.message:String(a)})}let i=new Set;for(let a of r.fields){let c=a.name.trim(),l=`fields.${c||"unnamed"}`;c?i.has(c)&&t.push({code:"duplicate_field_name",severity:"error",path:l,message:`The field '${c}' is declared more than once.`}):t.push({code:"field_name_required",severity:"error",path:l,message:"Every field needs a name."}),i.add(c),Gm(a.definition,l,t,n)}r.displayNameKey.trim()&&!i.has(r.displayNameKey.trim())&&t.push({code:"display_field_missing",severity:"error",path:"identity.displayNameKey",message:`The display field '${r.displayNameKey.trim()}' is not declared.`});let s=new Map([...e.contracts??[]].map(a=>[Ms(a),a])),o=ga(r);for(let a of r.implementations){let c=`${a.contract}@${a.version}`,l=s.get(c);if(!l){t.push({code:"contract_unavailable",severity:"error",path:`applications.${c}`,message:"This exact application contract is not installed."});continue}for(let u of ya(l)){let d=Ts(a,u),f=o.find(m=>m.reference===d),p=ba(u,f);p.level!=="valid"&&t.push({code:p.level==="error"?"invalid_contract_mapping":"review_contract_mapping",severity:p.level==="error"?"error":"warning",path:`applications.${c}.${u.reference}`,message:p.message})}}return t.filter((a,c,l)=>l.findIndex(u=>u.code===a.code&&u.path===a.path&&u.message===a.message)===c)}function _a(r,e){if(!r)return[{code:"create_type",risk:"safe",summary:`Create the type '${e.name||"Untitled type"}'.`}];let t=[];r.name!==e.name&&t.push({code:"rename_type",risk:"high",summary:`Rename the type from '${r.name}' to '${e.name}'. Existing type references may need review.`}),(r.description!==e.description||r.displayNameKey!==e.displayNameKey)&&t.push({code:"identity",risk:"safe",summary:"Update the type's identity and display metadata."}),(r.matchPathGlob!==e.matchPathGlob||r.matchFieldsPresent!==e.matchFieldsPresent||r.matchWhere!==e.matchWhere)&&t.push({code:"membership",risk:"high",summary:"Change which records belong to this type."}),r.pathPattern!==e.pathPattern&&t.push({code:"placement",risk:"review",summary:"Change the suggested path for new records."}),r.strictMode!==e.strictMode&&t.push({code:"strictness",risk:e.strictMode===!0?"high":"review",summary:e.strictMode===!0?"Reject fields that are not declared by this type.":"Allow fields that are not declared by this type."});let n=vx(r),i=vx(e),s=[...i.keys()].filter(l=>!n.has(l)),o=[...n.keys()].filter(l=>!i.has(l));s.length&&t.push({code:"add_fields",risk:s.some(l=>i.get(l)?.definition.required===!0)?"high":"safe",summary:`Add ${s.length===1?"field":"fields"}: ${s.join(", ")}.`}),o.length&&t.push({code:"remove_fields",risk:"high",summary:`Remove ${o.length===1?"field":"fields"}: ${o.join(", ")}.`});for(let[l,u]of i){let d=n.get(l);if(!d)continue;let f=Wm(d.definition),p=Wm(u.definition);f!==p&&t.push({code:"change_field_type",risk:"high",summary:`Change '${l}' from ${f} to ${p}.`}),d.definition.required!==!0&&u.definition.required===!0&&t.push({code:"require_field",risk:"high",summary:`Make '${l}' required. Existing records may become invalid.`}),f===p&&JSON.stringify(d.definition)!==JSON.stringify(u.definition)&&d.definition.required===u.definition.required&&t.push({code:"field_rules",risk:"review",summary:`Update validation or documentation for '${l}'.`})}let a=[...n.keys()].filter(l=>i.has(l)),c=[...i.keys()].filter(l=>n.has(l));return a.join("\0")!==c.join("\0")&&t.push({code:"reorder_fields",risk:"safe",summary:"Reorder fields."}),JSON.stringify(r.implementations)!==JSON.stringify(e.implementations)&&t.push({code:"application_compatibility",risk:"review",summary:"Update application contract mappings or settings."}),!t.length&&!bd(r,e)&&t.push({code:"type_document",risk:"review",summary:"Update advanced type metadata or documentation."}),t}var Ds=require("obsidian");var Sa="mdbase-frontmatter",wx=` @@ -206,17 +209,17 @@ Type definition for ${t}.`,extraFrontmatter:h,...o?{readOnlyReason:`This type us -`;var Ex=require("obsidian");var HF={schema_required:"missing",missing_required:"missing",schema_additional_properties:"not declared",unknown_field:"not declared",schema_type:"wrong type",invalid_type:"wrong type",schema_enum:"not an allowed value",invalid_enum:"not an allowed value",schema_maximum:"above maximum",above_max:"above maximum",schema_minimum:"below minimum",below_min:"below minimum",schema_max_length:"too long",above_max_length:"too long",schema_min_length:"too short",below_min_length:"too short",schema_max_items:"too many items",schema_min_items:"too few items",schema_pattern:"pattern mismatch",pattern_mismatch:"pattern mismatch",format_invalid:"invalid format",duplicate_value:"duplicate value",duplicate_unique:"duplicate value",link_not_found:"missing link target",missing_link_target:"missing link target",link_wrong_type:"link to wrong type",no_matching_type:"no matching type",unknown_type:"unknown type",invalid_frontmatter:"invalid frontmatter"};function zF(r){return HF[r]??r.replace(/^schema_/,"").replace(/_/g," ")}function KF(r){return[r.type??"",r.field??"",r.code].join("\0")}function Ym(r){return[r.type,r.field,zF(r.code)].filter(Boolean).join(" \xB7 ")}function wx(r){let e=new Map;for(let t of r){let n=KF(t),i=e.get(n);i||(i={key:n,label:Ym(t),issues:[]},e.set(n,i)),i.issues.push(t)}return[...e.values()].sort((t,n)=>n.issues.length-t.issues.length||t.label.localeCompare(n.label))}qt();function _x(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function Sx(r,e,t){let n=new Map;for(let i of r){let s=Ke(i.path,i.frontmatter,e,t);s.length&&n.set(i.path,s)}return n}function $x(r,e){let t=new Map,n=i=>{let s=t.get(i);return s||(s={notes:0,issues:0},t.set(i,s)),s};for(let i of r.values())for(let s of i)n(s).notes+=1;for(let i of e)for(let s of Xm(i,r))n(s).issues+=1;return t}function Xm(r,e){return r.type?[r.type]:e.get(r.path)??[]}function WF(r,e){let t=Fn(r),n=_x(t.schema)?t.schema:{},i=_x(n.value)?n.value:{};return wc(t,e??`${r.name||"new"}.md`,i)}function GF(){return new Promise(r=>window.setTimeout(r,0))}async function xx(r){let e;try{e=WF(r.draft,r.filePath)}catch(s){return{error:s instanceof Error?s.message:String(s)}}let t=r.savedName?r.types.get(r.savedName)??null:null,n=new Map(r.types);r.savedName&&n.delete(r.savedName),n.set(e.name,e);let i={matched:[],added:[],removed:[],failing:[],fixed:0};for(let[s,o]of r.records.entries()){if(s>0&&s%400===0&&(await GF(),r.isCurrent&&!r.isCurrent()))return null;let a=t!==null&&Ke(o.path,o.frontmatter,r.config,r.types).includes(t.name),c=Ke(o.path,o.frontmatter,r.config,n).includes(e.name);if(c&&i.matched.push(o.path),c&&!a&&i.added.push(o.path),a&&!c&&i.removed.push(o.path),!c&&!a)continue;let l=a&&t?ts(o.path,o.frontmatter,t).length:0,u=c?ts(o.path,o.frontmatter,e):[];u.length?i.failing.push({path:o.path,issues:u,isNew:l===0}):l>0&&c&&(i.fixed+=1)}return{impact:i}}var wd=class{constructor(e){this.ctx=e;this.issueQuery="";this.issueSeverity="all";this.issueLimit=250;this.issueGroupBy="file"}getState(){return{issueQuery:this.issueQuery,issueSeverity:this.issueSeverity,issueGroupBy:this.issueGroupBy}}setState(e){typeof e.issueQuery=="string"&&(this.issueQuery=e.issueQuery.slice(0,2e3)),["all","error","warn"].includes(String(e.issueSeverity))&&(this.issueSeverity=e.issueSeverity),(e.issueGroupBy==="rule"||e.issueGroupBy==="file")&&(this.issueGroupBy=e.issueGroupBy)}updateValidationProgress(){let e=this.ctx.containerEl.querySelector("[data-validation-summary]");e&&(e.textContent=this.ctx.host.getValidationSummary())}filterToPath(e){this.issueQuery=e,this.issueLimit=250}render(e){let t=e.createDiv({cls:"mdbase-issues-document"}),n=this.ctx.host.getIssues(),i=new Set(n.map(b=>b.path)).size,s=t.createDiv({cls:"mdbase-document-header"}),o=s.createDiv(),a=this.ctx.host.getValidationSummary();o.createEl("h2",{text:n.length?`${n.length.toLocaleString()} ${n.length===1?"issue":"issues"} \xB7 ${i.toLocaleString()} ${i===1?"file":"files"}`:a==="Not checked yet"?"Validation":"No known issues"});let c=o.createDiv({cls:"mdbase-muted",text:a});if(c.setAttr("role","status"),c.setAttr("data-validation-summary","true"),this.ctx.host.isValidating()){let b=s.createEl("button",{text:"Stop validation"});b.onclick=()=>this.ctx.host.cancelValidation()}let l=s.createEl("button",{text:"Validate"});if(l.disabled=this.ctx.busy||this.ctx.host.isValidating(),l.onclick=()=>void this.ctx.perform(async()=>{await this.ctx.host.validateCollection(),this.ctx.render()}),!n.length)return;let u=t.createDiv({cls:"mdbase-issue-controls"}),d=u.createEl("select");d.setAttr("aria-label","Issue severity"),d.createEl("option",{value:"all",text:"All severities"}),d.createEl("option",{value:"error",text:"Errors"}),d.createEl("option",{value:"warn",text:"Warnings"}),d.value=this.issueSeverity,d.onchange=()=>{this.issueSeverity=d.value==="error"||d.value==="warn"?d.value:"all",this.issueLimit=250,this.ctx.render()};let f=u.createEl("select");f.setAttr("aria-label","Group issues"),f.createEl("option",{value:"file",text:"By file"}),f.createEl("option",{value:"rule",text:"By rule"}),f.value=this.issueGroupBy,f.onchange=()=>{this.issueGroupBy=f.value==="rule"?"rule":"file",this.ctx.render()};let p=u.createEl("input",{type:"search"});p.setAttr("aria-label","Filter issues"),p.setAttr("data-focus-key","issue-search"),p.placeholder="Filter issues",p.value=this.issueQuery,p.oninput=()=>{this.issueQuery=p.value,this.issueLimit=250,this.ctx.render();let b=this.ctx.containerEl.querySelector(".mdbase-issue-controls input[type='search']");b?.focus(),b?.setSelectionRange(b.value.length,b.value.length)};let h=this.issueQuery.trim().toLowerCase(),m=n.filter(b=>this.issueSeverity!=="all"&&b.severity!==this.issueSeverity?!1:h?`${b.path} ${b.code} ${b.type??""} ${b.field??""} ${b.message}`.toLowerCase().includes(h):!0),y=new Set(m.map(b=>b.path)).size;if((m.length!==n.length||m.length>this.issueLimit)&&t.createDiv({cls:"mdbase-issues-summary",text:`${Math.min(m.length,this.issueLimit).toLocaleString()} of ${m.length.toLocaleString()} issues \xB7 ${y.toLocaleString()} files`}),!m.length){t.createDiv({cls:"mdbase-empty-state",text:"No issues match these filters."});return}let g=m.slice(0,this.issueLimit);if(this.issueGroupBy==="rule"?this.renderIssuesByRule(t,g):this.renderIssuesByFile(t,g),m.length>g.length){let b=t.createEl("button",{cls:"mdbase-load-more",text:`Load ${Math.min(250,m.length-g.length)} more`});b.onclick=()=>{this.issueLimit+=250,this.ctx.render()}}}renderIssuesByFile(e,t){let n=new Map;for(let i of t)n.set(i.path,[...n.get(i.path)??[],i]);for(let[i,s]of n){let o=e.createEl("section",{cls:"mdbase-issue-group"}),a=o.createDiv({cls:"mdbase-issue-group-header"}),c=a.createEl("button",{cls:"mdbase-issue-file-button"});(0,Ex.setIcon)(c.createSpan({cls:"mdbase-issue-file-icon"}),"file-text"),c.createSpan({cls:"mdbase-issue-file-path",text:i}),c.setAttr("title",`Open ${i}`),c.onclick=()=>void this.ctx.host.openFileByPath(i),a.createSpan({cls:"mdbase-issue-file-count",text:`${s.length} ${s.length===1?"issue":"issues"}`});for(let l of s){let u=o.createDiv({cls:"mdbase-issue-row"});this.fillIssueRow(u,l,`${l.severity==="warn"?"Warning":"Error"}${l.field?` \xB7 ${l.field}`:""}`)}}}renderIssuesByRule(e,t){for(let n of wx(t)){let i=n.issues[0],s=e.createEl("section",{cls:"mdbase-issue-group"}),o=s.createDiv({cls:"mdbase-issue-group-header"}),a=o.createDiv({cls:"mdbase-issue-rule-title"});a.createSpan({cls:"mdbase-issue-indicator",attr:{"data-severity":i.severity,"aria-hidden":"true"}}),a.createSpan({cls:"mdbase-issue-file-path",text:Ym(i)});let c=new Set(n.issues.map(p=>p.path)).size;o.createSpan({cls:"mdbase-issue-file-count",text:`${c.toLocaleString()} ${c===1?"note":"notes"}`});let l=o.createDiv({cls:"mdbase-issue-row-actions"});this.renderEditRuleButton(l,i);let u=this.ctx.host.getQuickFixLabel(i),d=u?n.issues.filter(p=>this.ctx.host.getQuickFixLabel(p)===u):[],f=new Set(d.map(p=>p.path)).size;if(u&&f>1){let p=l.createEl("button",{text:`${u} \xB7 ${f} notes`});p.disabled=this.ctx.busy,p.onclick=()=>void this.applyBulkQuickFix(u,d)}for(let p of n.issues){let h=s.createDiv({cls:"mdbase-issue-row"});this.fillIssueRow(h,p,p.path,!0)}}}fillIssueRow(e,t,n,i=!1){e.setAttr("data-severity",t.severity),e.createSpan({cls:"mdbase-issue-indicator"}).setAttr("aria-hidden","true");let s=typeof t.details?.technical_message=="string"?t.details.technical_message:"";e.setAttr("title",s?`${t.code}: ${s}`:t.code);let o=e.createDiv({cls:"mdbase-issue-metadata"});if(i){let l=o.createEl("button",{cls:"mdbase-link-button mdbase-issue-context",text:n});l.setAttr("title",`Open ${t.path}${t.field?` at ${t.field}`:""}`),l.onclick=()=>void this.ctx.host.openFileByPath(t.path,t.field)}else o.createDiv({cls:"mdbase-issue-context",text:n});e.createDiv({cls:"mdbase-issue-row-message",text:t.message});let a=e.createDiv({cls:"mdbase-issue-row-actions"});if(!i&&t.field){let l=this.ctx.iconButton(a,"arrow-up-right",`Open ${t.path} at ${t.field}`);l.onclick=()=>void this.ctx.host.openFileByPath(t.path,t.field)}i||this.renderEditRuleButton(a,t);let c=this.ctx.host.getQuickFixLabel(t);if(c){let l=a.createEl("button",{text:c});l.disabled=this.ctx.busy,l.onclick=()=>void this.ctx.perform(async()=>{await this.ctx.host.applyQuickFix(t)})}}renderEditRuleButton(e,t){let n=Xm(t,this.ctx.recordTypes())[0],i=n?this.ctx.schema?.types.get(n):void 0;if(!i)return;let s=this.ctx.iconButton(e,"pencil",t.field?`Edit ${t.field} in ${i.name}`:`Edit type ${i.name}`);s.onclick=()=>void this.ctx.openTypeField(i.filePath,t.field)}async applyBulkQuickFix(e,t){let n=new Set(t.map(s=>s.path)).size;await new Ec(this.ctx.app).confirm(e,t)&&await this.ctx.perform(async()=>{let s=await this.ctx.host.applyQuickFixes(t);this.ctx.message=s.skipped?`${e}: updated ${s.changed} of ${n} ${n===1?"note":"notes"}. ${s.skipped} changed since validation and were left as they are.`:`${e}: updated ${s.changed} ${s.changed===1?"note":"notes"}.`})}};var Rs=require("obsidian"),_d="https://connect.mdbase.dev",Ax=["string","integer","number","boolean","date","datetime","time","enum","link","list","object","any"];function Se(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function qn(r){return JSON.parse(JSON.stringify(r))}function kx(r){let e=Rs.Platform.isIosApp?"iOS":Rs.Platform.isAndroidApp?"Android":Rs.Platform.isMacOS?"Mac":Rs.Platform.isWin?"Windows":Rs.Platform.isLinux?"Linux":"Obsidian";return`${r} \xB7 ${e}`}function Qm(r){return r==="any"?"Any value":r==="datetime"?"Date and time":r&&r[0].toUpperCase()+r.slice(1)}function $a(r){return typeof r.type=="string"?r.type:"any"}function Px(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 Sd(r,e,t){Object.defineProperty(r,e,{configurable:!0,enumerable:!0,writable:!0,value:t})}function Tt(r,e,t,n,i={}){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,i.description&&s.createDiv({cls:"mdbase-form-description",text:i.description});let c=i.multiline?s.createEl("textarea"):s.createEl("input",{type:"text"});return c.id=a,c.setAttr("data-focus-key",`form-${e.toLowerCase().replace(/[^a-z0-9]+/g,"-")}`),c.value=t,c.placeholder=i.placeholder??"",c.addEventListener("input",()=>n(c.value)),c}function zt(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 Zm(r){if(r<1e3)return String(r);let e=r<1e4?1:0;return`${(r/1e3).toFixed(e)}k`}var xa=10,Cx={cancelled:"Paused",stale:"Stopped: changes detected",attention:"Needs attention",blocked:"Stopped",failed:"Failed"};function ey(r){return r.charAt(0).toUpperCase()+r.slice(1)}function Mx(r){if(!r)return"Never synced";let e=Date.parse(r);if(!Number.isFinite(e))return r;let t=Math.round((e-Date.now())/1e3),n=Math.abs(t),i=new Intl.RelativeTimeFormat(void 0,{numeric:"auto"});if(n<60)return i.format(t,"second");let s=Math.round(t/60);if(Math.abs(s)<60)return i.format(s,"minute");let o=Math.round(s/60);return Math.abs(o)<24?i.format(o,"hour"):i.format(Math.round(o/24),"day")}function Tx(r){return r?r.state==="up_to_date"?"Up to date":r.state==="changes_waiting"?"Changes waiting":["attention","blocked","failed","stale"].includes(r.state)||r.recovery_required?"Needs attention":r.state==="cancelled"?"Paused safely":r.state==="applying"?"Synchronizing":r.state==="planned"?"Review ready":"Ready for first sync":"Checking connection"}function ty(r){return r instanceof Error&&r.name==="AbortError"}var Rx=require("obsidian"),$d="Attachments are limited to 32 MiB per file on desktop and mobile. Exclusions apply to both notes and attachments. Previously synced files remain in this vault; excluded paths no longer transfer. Excluding a folder does not delete hosted copies.";function xd(r,e,t,n){let i=[...t],s=e.createDiv({cls:"mdbase-folder-exclusions"}),o=s.createDiv({cls:"mdbase-folder-chips"}),a=s.createEl("input",{type:"text",placeholder:"Choose or enter a folder"});a.id="mdbase-excluded-folder",a.setAttr("aria-label","Excluded folder"),a.setAttr("data-focus-key","excluded-folder-input");let c=s.createEl("datalist");c.id="mdbase-folder-options",a.setAttr("list",c.id);for(let f of r.vault.getAllLoadedFiles())f instanceof Rx.TFolder&&f.path&&f.path!=="/"&&c.createEl("option",{value:f.path});let l=s.createDiv({cls:"mdbase-inline-error",attr:{role:"alert"}}),u=()=>{o.empty();for(let f of i){let p=o.createEl("button",{text:`${f} \xD7`});p.setAttr("aria-label",`Remove exclusion ${f}`),p.onclick=()=>{i.splice(i.indexOf(f),1),n([...i]),u()}}},d=()=>{let f=a.value.trim().replace(/\/+$/,"");if(!f||f.startsWith("/")||f.includes("\\")||f.split("/").some(p=>!p||p==="."||p==="..")){l.textContent="Choose a vault-relative folder without parent traversal or empty segments.";return}l.textContent="",i.includes(f)||(i.push(f),n([...i]),u()),a.value="",a.focus()};s.createEl("button",{text:"Exclude folder"}).onclick=d,a.onkeydown=f=>{f.key==="Enter"&&(f.preventDefault(),d())},u()}var Is=require("obsidian");function Ix(r,e){let t=r.split(` +`;var Ax=require("obsidian");var HF={schema_required:"missing",missing_required:"missing",schema_additional_properties:"not declared",unknown_field:"not declared",schema_type:"wrong type",invalid_type:"wrong type",schema_enum:"not an allowed value",invalid_enum:"not an allowed value",schema_maximum:"above maximum",above_max:"above maximum",schema_minimum:"below minimum",below_min:"below minimum",schema_max_length:"too long",above_max_length:"too long",schema_min_length:"too short",below_min_length:"too short",schema_max_items:"too many items",schema_min_items:"too few items",schema_pattern:"pattern mismatch",pattern_mismatch:"pattern mismatch",format_invalid:"invalid format",duplicate_value:"duplicate value",duplicate_unique:"duplicate value",link_not_found:"missing link target",missing_link_target:"missing link target",link_wrong_type:"link to wrong type",no_matching_type:"no matching type",unknown_type:"unknown type",invalid_frontmatter:"invalid frontmatter"};function zF(r){return HF[r]??r.replace(/^schema_/,"").replace(/_/g," ")}function KF(r){return[r.type??"",r.field??"",r.code].join("\0")}function Ym(r){return[r.type,r.field,zF(r.code)].filter(Boolean).join(" \xB7 ")}function _x(r){let e=new Map;for(let t of r){let n=KF(t),i=e.get(n);i||(i={key:n,label:Ym(t),issues:[]},e.set(n,i)),i.issues.push(t)}return[...e.values()].sort((t,n)=>n.issues.length-t.issues.length||t.label.localeCompare(n.label))}qt();function Sx(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function $x(r,e,t){let n=new Map;for(let i of r){let s=Ke(i.path,i.frontmatter,e,t);s.length&&n.set(i.path,s)}return n}function xx(r,e){let t=new Map,n=i=>{let s=t.get(i);return s||(s={notes:0,issues:0},t.set(i,s)),s};for(let i of r.values())for(let s of i)n(s).notes+=1;for(let i of e)for(let s of Xm(i,r))n(s).issues+=1;return t}function Xm(r,e){return r.type?[r.type]:e.get(r.path)??[]}function WF(r,e){let t=Fn(r),n=Sx(t.schema)?t.schema:{},i=Sx(n.value)?n.value:{};return wc(t,e??`${r.name||"new"}.md`,i)}function GF(){return new Promise(r=>window.setTimeout(r,0))}async function Ex(r){let e;try{e=WF(r.draft,r.filePath)}catch(s){return{error:s instanceof Error?s.message:String(s)}}let t=r.savedName?r.types.get(r.savedName)??null:null,n=new Map(r.types);r.savedName&&n.delete(r.savedName),n.set(e.name,e);let i={matched:[],added:[],removed:[],failing:[],fixed:0};for(let[s,o]of r.records.entries()){if(s>0&&s%400===0&&(await GF(),r.isCurrent&&!r.isCurrent()))return null;let a=t!==null&&Ke(o.path,o.frontmatter,r.config,r.types).includes(t.name),c=Ke(o.path,o.frontmatter,r.config,n).includes(e.name);if(c&&i.matched.push(o.path),c&&!a&&i.added.push(o.path),a&&!c&&i.removed.push(o.path),!c&&!a)continue;let l=a&&t?ts(o.path,o.frontmatter,t).length:0,u=c?ts(o.path,o.frontmatter,e):[];u.length?i.failing.push({path:o.path,issues:u,isNew:l===0}):l>0&&c&&(i.fixed+=1)}return{impact:i}}var vd=class{constructor(e){this.ctx=e;this.issueQuery="";this.issueSeverity="all";this.issueLimit=250;this.issueGroupBy="file"}getState(){return{issueQuery:this.issueQuery,issueSeverity:this.issueSeverity,issueGroupBy:this.issueGroupBy}}setState(e){typeof e.issueQuery=="string"&&(this.issueQuery=e.issueQuery.slice(0,2e3)),["all","error","warn"].includes(String(e.issueSeverity))&&(this.issueSeverity=e.issueSeverity),(e.issueGroupBy==="rule"||e.issueGroupBy==="file")&&(this.issueGroupBy=e.issueGroupBy)}updateValidationProgress(){let e=this.ctx.containerEl.querySelector("[data-validation-summary]");e&&(e.textContent=this.ctx.host.getValidationSummary())}filterToPath(e){this.issueQuery=e,this.issueLimit=250}render(e){let t=e.createDiv({cls:"mdbase-issues-document"}),n=this.ctx.host.getIssues(),i=new Set(n.map(b=>b.path)).size,s=t.createDiv({cls:"mdbase-document-header"}),o=s.createDiv(),a=this.ctx.host.getValidationSummary();o.createEl("h2",{text:n.length?`${n.length.toLocaleString()} ${n.length===1?"issue":"issues"} \xB7 ${i.toLocaleString()} ${i===1?"file":"files"}`:a==="Not checked yet"?"Validation":"No known issues"});let c=o.createDiv({cls:"mdbase-muted",text:a});if(c.setAttr("role","status"),c.setAttr("data-validation-summary","true"),this.ctx.host.isValidating()){let b=s.createEl("button",{text:"Stop validation"});b.onclick=()=>this.ctx.host.cancelValidation()}let l=s.createEl("button",{text:"Validate"});if(l.disabled=this.ctx.busy||this.ctx.host.isValidating(),l.onclick=()=>void this.ctx.perform(async()=>{await this.ctx.host.validateCollection(),this.ctx.render()}),!n.length)return;let u=t.createDiv({cls:"mdbase-issue-controls"}),d=u.createEl("select");d.setAttr("aria-label","Issue severity"),d.createEl("option",{value:"all",text:"All severities"}),d.createEl("option",{value:"error",text:"Errors"}),d.createEl("option",{value:"warn",text:"Warnings"}),d.value=this.issueSeverity,d.onchange=()=>{this.issueSeverity=d.value==="error"||d.value==="warn"?d.value:"all",this.issueLimit=250,this.ctx.render()};let f=u.createEl("select");f.setAttr("aria-label","Group issues"),f.createEl("option",{value:"file",text:"By file"}),f.createEl("option",{value:"rule",text:"By rule"}),f.value=this.issueGroupBy,f.onchange=()=>{this.issueGroupBy=f.value==="rule"?"rule":"file",this.ctx.render()};let p=u.createEl("input",{type:"search"});p.setAttr("aria-label","Filter issues"),p.setAttr("data-focus-key","issue-search"),p.placeholder="Filter issues",p.value=this.issueQuery,p.oninput=()=>{this.issueQuery=p.value,this.issueLimit=250,this.ctx.render();let b=this.ctx.containerEl.querySelector(".mdbase-issue-controls input[type='search']");b?.focus(),b?.setSelectionRange(b.value.length,b.value.length)};let m=this.issueQuery.trim().toLowerCase(),h=n.filter(b=>this.issueSeverity!=="all"&&b.severity!==this.issueSeverity?!1:m?`${b.path} ${b.code} ${b.type??""} ${b.field??""} ${b.message}`.toLowerCase().includes(m):!0),y=new Set(h.map(b=>b.path)).size;if((h.length!==n.length||h.length>this.issueLimit)&&t.createDiv({cls:"mdbase-issues-summary",text:`${Math.min(h.length,this.issueLimit).toLocaleString()} of ${h.length.toLocaleString()} issues \xB7 ${y.toLocaleString()} files`}),!h.length){t.createDiv({cls:"mdbase-empty-state",text:"No issues match these filters."});return}let g=h.slice(0,this.issueLimit);if(this.issueGroupBy==="rule"?this.renderIssuesByRule(t,g):this.renderIssuesByFile(t,g),h.length>g.length){let b=t.createEl("button",{cls:"mdbase-load-more",text:`Load ${Math.min(250,h.length-g.length)} more`});b.onclick=()=>{this.issueLimit+=250,this.ctx.render()}}}renderIssuesByFile(e,t){let n=new Map;for(let i of t)n.set(i.path,[...n.get(i.path)??[],i]);for(let[i,s]of n){let o=e.createEl("section",{cls:"mdbase-issue-group"}),a=o.createDiv({cls:"mdbase-issue-group-header"}),c=a.createEl("button",{cls:"mdbase-issue-file-button"});(0,Ax.setIcon)(c.createSpan({cls:"mdbase-issue-file-icon"}),"file-text"),c.createSpan({cls:"mdbase-issue-file-path",text:i}),c.setAttr("title",`Open ${i}`),c.onclick=()=>void this.ctx.host.openFileByPath(i),a.createSpan({cls:"mdbase-issue-file-count",text:`${s.length} ${s.length===1?"issue":"issues"}`});for(let l of s){let u=o.createDiv({cls:"mdbase-issue-row"});this.fillIssueRow(u,l,`${l.severity==="warn"?"Warning":"Error"}${l.field?` \xB7 ${l.field}`:""}`)}}}renderIssuesByRule(e,t){for(let n of _x(t)){let i=n.issues[0],s=e.createEl("section",{cls:"mdbase-issue-group"}),o=s.createDiv({cls:"mdbase-issue-group-header"}),a=o.createDiv({cls:"mdbase-issue-rule-title"});a.createSpan({cls:"mdbase-issue-indicator",attr:{"data-severity":i.severity,"aria-hidden":"true"}}),a.createSpan({cls:"mdbase-issue-file-path",text:Ym(i)});let c=new Set(n.issues.map(p=>p.path)).size;o.createSpan({cls:"mdbase-issue-file-count",text:`${c.toLocaleString()} ${c===1?"note":"notes"}`});let l=o.createDiv({cls:"mdbase-issue-row-actions"});this.renderEditRuleButton(l,i);let u=this.ctx.host.getQuickFixLabel(i),d=u?n.issues.filter(p=>this.ctx.host.getQuickFixLabel(p)===u):[],f=new Set(d.map(p=>p.path)).size;if(u&&f>1){let p=l.createEl("button",{text:`${u} \xB7 ${f} notes`});p.disabled=this.ctx.busy,p.onclick=()=>void this.applyBulkQuickFix(u,d)}for(let p of n.issues){let m=s.createDiv({cls:"mdbase-issue-row"});this.fillIssueRow(m,p,p.path,!0)}}}fillIssueRow(e,t,n,i=!1){e.setAttr("data-severity",t.severity),e.createSpan({cls:"mdbase-issue-indicator"}).setAttr("aria-hidden","true");let s=typeof t.details?.technical_message=="string"?t.details.technical_message:"";e.setAttr("title",s?`${t.code}: ${s}`:t.code);let o=e.createDiv({cls:"mdbase-issue-metadata"});if(i){let l=o.createEl("button",{cls:"mdbase-link-button mdbase-issue-context",text:n});l.setAttr("title",`Open ${t.path}${t.field?` at ${t.field}`:""}`),l.onclick=()=>void this.ctx.host.openFileByPath(t.path,t.field)}else o.createDiv({cls:"mdbase-issue-context",text:n});e.createDiv({cls:"mdbase-issue-row-message",text:t.message});let a=e.createDiv({cls:"mdbase-issue-row-actions"});if(!i&&t.field){let l=this.ctx.iconButton(a,"arrow-up-right",`Open ${t.path} at ${t.field}`);l.onclick=()=>void this.ctx.host.openFileByPath(t.path,t.field)}i||this.renderEditRuleButton(a,t);let c=this.ctx.host.getQuickFixLabel(t);if(c){let l=a.createEl("button",{text:c});l.disabled=this.ctx.busy,l.onclick=()=>void this.ctx.perform(async()=>{await this.ctx.host.applyQuickFix(t)})}}renderEditRuleButton(e,t){let n=Xm(t,this.ctx.recordTypes())[0],i=n?this.ctx.schema?.types.get(n):void 0;if(!i)return;let s=this.ctx.iconButton(e,"pencil",t.field?`Edit ${t.field} in ${i.name}`:`Edit type ${i.name}`);s.onclick=()=>void this.ctx.openTypeField(i.filePath,t.field)}async applyBulkQuickFix(e,t){let n=new Set(t.map(s=>s.path)).size;await new Ec(this.ctx.app).confirm(e,t)&&await this.ctx.perform(async()=>{let s=await this.ctx.host.applyQuickFixes(t);this.ctx.message=s.skipped?`${e}: updated ${s.changed} of ${n} ${n===1?"note":"notes"}. ${s.skipped} changed since validation and were left as they are.`:`${e}: updated ${s.changed} ${s.changed===1?"note":"notes"}.`})}};var Rs=require("obsidian"),wd="https://connect.mdbase.dev",kx=["string","integer","number","boolean","date","datetime","time","enum","link","list","object","any"];function Se(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function qn(r){return JSON.parse(JSON.stringify(r))}function Px(r){let e=Rs.Platform.isIosApp?"iOS":Rs.Platform.isAndroidApp?"Android":Rs.Platform.isMacOS?"Mac":Rs.Platform.isWin?"Windows":Rs.Platform.isLinux?"Linux":"Obsidian";return`${r} \xB7 ${e}`}function Qm(r){return r==="any"?"Any value":r==="datetime"?"Date and time":r&&r[0].toUpperCase()+r.slice(1)}function $a(r){return typeof r.type=="string"?r.type:"any"}function Cx(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 _d(r,e,t){Object.defineProperty(r,e,{configurable:!0,enumerable:!0,writable:!0,value:t})}function Tt(r,e,t,n,i={}){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,i.description&&s.createDiv({cls:"mdbase-form-description",text:i.description});let c=i.multiline?s.createEl("textarea"):s.createEl("input",{type:"text"});return c.id=a,c.setAttr("data-focus-key",`form-${e.toLowerCase().replace(/[^a-z0-9]+/g,"-")}`),c.value=t,c.placeholder=i.placeholder??"",c.addEventListener("input",()=>n(c.value)),c}function zt(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 Zm(r){if(r<1e3)return String(r);let e=r<1e4?1:0;return`${(r/1e3).toFixed(e)}k`}var xa=10,Mx={cancelled:"Paused",stale:"Stopped: changes detected",attention:"Needs attention",blocked:"Stopped",failed:"Failed"};function ey(r){return r.charAt(0).toUpperCase()+r.slice(1)}function Tx(r){if(!r)return"Never synced";let e=Date.parse(r);if(!Number.isFinite(e))return r;let t=Math.round((e-Date.now())/1e3),n=Math.abs(t),i=new Intl.RelativeTimeFormat(void 0,{numeric:"auto"});if(n<60)return i.format(t,"second");let s=Math.round(t/60);if(Math.abs(s)<60)return i.format(s,"minute");let o=Math.round(s/60);return Math.abs(o)<24?i.format(o,"hour"):i.format(Math.round(o/24),"day")}function Rx(r){return r?r.state==="up_to_date"?"Up to date":r.state==="changes_waiting"?"Changes waiting":["attention","blocked","failed","stale"].includes(r.state)||r.recovery_required?"Needs attention":r.state==="cancelled"?"Paused safely":r.state==="applying"?"Synchronizing":r.state==="planned"?"Review ready":"Ready for first sync":"Checking connection"}function ty(r){return r instanceof Error&&r.name==="AbortError"}var Ix=require("obsidian"),Sd="Attachments are limited to 32 MiB per file on desktop and mobile. Exclusions apply to both notes and attachments. Previously synced files remain in this vault; excluded paths no longer transfer. Excluding a folder does not delete hosted copies.";function $d(r,e,t,n){let i=[...t],s=e.createDiv({cls:"mdbase-folder-exclusions"}),o=s.createDiv({cls:"mdbase-folder-chips"}),a=s.createEl("input",{type:"text",placeholder:"Choose or enter a folder"});a.id="mdbase-excluded-folder",a.setAttr("aria-label","Excluded folder"),a.setAttr("data-focus-key","excluded-folder-input");let c=s.createEl("datalist");c.id="mdbase-folder-options",a.setAttr("list",c.id);for(let f of r.vault.getAllLoadedFiles())f instanceof Ix.TFolder&&f.path&&f.path!=="/"&&c.createEl("option",{value:f.path});let l=s.createDiv({cls:"mdbase-inline-error",attr:{role:"alert"}}),u=()=>{o.empty();for(let f of i){let p=o.createEl("button",{text:`${f} \xD7`});p.setAttr("aria-label",`Remove exclusion ${f}`),p.onclick=()=>{i.splice(i.indexOf(f),1),n([...i]),u()}}},d=()=>{let f=a.value.trim().replace(/\/+$/,"");if(!f||f.startsWith("/")||f.includes("\\")||f.split("/").some(p=>!p||p==="."||p==="..")){l.textContent="Choose a vault-relative folder without parent traversal or empty segments.";return}l.textContent="",i.includes(f)||(i.push(f),n([...i]),u()),a.value="",a.focus()};s.createEl("button",{text:"Exclude folder"}).onclick=d,a.onkeydown=f=>{f.key==="Enter"&&(f.preventDefault(),d())},u()}var Is=require("obsidian");function Ox(r,e){let t=r.split(` `),n=e.split(` -`),i=t.length>200||n.length>200,s=t.slice(0,200),o=n.slice(0,200),a=Array.from({length:s.length+1},()=>new Uint16Array(o.length+1));for(let d=s.length-1;d>=0;d-=1)for(let f=o.length-1;f>=0;f-=1)a[d][f]=s[d]===o[f]?a[d+1][f+1]+1:Math.max(a[d+1][f],a[d][f+1]);let c=[],l=0,u=0;for(;(l=300);)l=o.length||l=a[l][u+1]?(c.push({kind:"local",value:s[l]}),l+=1):(c.push({kind:"remote",value:o[u]}),u+=1);return{lines:c,truncated:i||l0&&!r.actions.some(o=>o.command!=="advance_checkpoint"))return{actionLabel:"Resolve issues",actionDisabled:!0,message:"Synchronization is paused. Resolve the blocking issues, then refresh the review."};let n=r.actions.filter(o=>o.command!=="advance_checkpoint").length,i=r.actions.some(o=>o.command==="advance_checkpoint"),s=r.issues.some(o=>o.code==="invalid_frontmatter"&&!o.blocking);return{actionLabel:n?`Sync ${n}${r.summary.blocking_issues?" available":""} ${n===1?"change":"changes"}`:i?"Confirm sync":"Up to date",actionDisabled:t||r.actions.length===0,message:r.summary.blocking_issues>0?"Sync available changes. Unresolved items are isolated and remain for the next review; they do not stop independent transfers.":s?"Frontmatter warnings do not block this sync. Document bytes are preserved; synchronization does not repair YAML.":e?"Review each transfer below, then sync when ready.":"This vault and the hosted collection are already aligned."}}function pr(r){return r<1024?`${r} B`:r<1024*1024?`${(r/1024).toFixed(r<10*1024?1:0)} KB`:r<1024*1024*1024?`${(r/(1024*1024)).toFixed(r<10*1024*1024?1:0)} MB`:`${(r/(1024*1024*1024)).toFixed(1)} GB`}function Ox(r){let{connected:e,status:t,progress:n,fileProgress:i,problem:s,validationIssues:o,localChangeObserved:a}=r,c=r.reviewChanges??0;if(!e)return o?{state:"attention",label:`mdbase: ${o} ${o===1?"issue":"issues"}`,detail:"Open validation issues",destination:"issues"}:{state:"local",label:"mdbase: Local",detail:"This vault is not connected",destination:"sync"};if(i){let u=i.totalBytes>0?Math.min(100,Math.round(i.transferredBytes/i.totalBytes*100)):100;return{state:"syncing",label:`mdbase: ${i.direction==="upload"?"Uploading":"Downloading"} ${u}%`,detail:`${i.path} \xB7 ${pr(i.transferredBytes)} of ${pr(i.totalBytes)}`,destination:"sync"}}if(n)return{state:"syncing",label:`mdbase: Syncing${n.total==null?"":` ${n.completed}/${n.total}`}`,detail:"Open synchronization progress",destination:"sync"};if(s&&s.kind!=="busy")return{state:s.kind==="paused"?"paused":s.kind==="offline"?"offline":"attention",label:s.kind==="paused"?"mdbase: Paused":s.kind==="offline"?"mdbase: Offline":s.kind==="device"?"mdbase: Set up sync":"mdbase: Needs attention",detail:s.kind==="offline"?`${s.title}. Changes will sync when it's back.`:s.title,destination:"sync"};if(c>0)return{state:"attention",label:`mdbase: Review ${c} ${c===1?"change":"changes"}`,detail:"Some changes need review before syncing",destination:"sync"};if(t?.recovery_required||t?.conflicts.length||t?.local_issues.length||["attention","blocked","failed","stale"].includes(t?.state??""))return{state:"attention",label:"mdbase: Needs attention",detail:"Review synchronization",destination:"sync"};if(t?.state==="cancelled")return{state:"paused",label:"mdbase: Paused",detail:"Review and resume synchronization",destination:"sync"};let l=t?.pending??0;return a||l>0||t?.state==="changes_waiting"||t?.state==="planned"?{state:"waiting",label:l>0?`mdbase: ${l} ${l===1?"change":"changes"}`:"mdbase: Changes waiting",detail:"Review local and hosted changes",destination:"sync"}:t?.state==="up_to_date"?{state:"synced",label:"mdbase: Synced",detail:"Local and hosted collections are aligned",destination:"sync"}:{state:"waiting",label:"mdbase: Ready to sync",detail:"Review the first synchronization",destination:"sync"}}var YF=new Set(["mirror_credentials_missing","invalid_mirror_enrollment","mirror_enrollment_expired","mirror_pairing_not_found","invalid_mirror_pairing","mirror_access_rejected","replica_revoked"]);function Rt(r){let e=QF(r);return e==="mirror_busy"?{code:e,kind:"busy",title:"Synchronization is already running",message:"The active transfer is still using this vault. Its progress is shown below.",action:"resume",actionLabel:"Show progress"}:e==="mirror_other_device"?{code:e,kind:"device",title:"Set up sync on this device",message:"This vault's sync settings came from another device or another copy of the vault, probably through a different sync service. Approve this copy to give it its own connection. Your files stay as they are.",action:"reauthorize",actionLabel:"Set up this device"}:YF.has(e)?{code:e,kind:"auth",title:"Connect approval is required again",message:"Your local files and mirror checkpoint are safe. Approve this vault again to restore access.",action:"reauthorize",actionLabel:"Sign in again"}:["operation_cancelled","cancelled","sync_cancelled","AbortError"].includes(e)?{code:e,kind:"paused",title:"Synchronization paused",message:"Completed changes are saved. Sync resumes from the same point when you continue.",action:"resume",actionLabel:"Resume sync"}:["stale","stale_mirror_plan","mirror_plan_stale","sync_plan_stale","conflict_decision_stale"].includes(e)?{code:e,kind:"decision",title:"The collection changed again",message:"No stale decision was applied. Review the newest local and hosted versions.",action:"review",actionLabel:"Review newest changes"}:["enrollment_recovery_required","mirror_recovery_required","pending_mirror_recovery"].includes(e)?{code:e,kind:"recovery",title:"Synchronization needs recovery",message:"Your original files are safe. Resume from the durable checkpoint before disconnecting this vault.",action:"resume",actionLabel:"Resume recovery"}:oa(r)?{code:e,kind:"offline",title:"Can't reach mdbase Connect",message:"Your changes are saved on this device and sync automatically when the connection returns.",action:"retry",actionLabel:"Retry now"}:{code:e,kind:"internal",title:"Sync stopped unexpectedly",message:`${ZF(r,"An unexpected error stopped synchronization.")} Your files are safe. Sync tries again automatically; if this keeps happening, copy the diagnostics and report it.`,action:"retry",actionLabel:"Try again"}}function Dx(r){return Rt(Object.assign(new Error(r.message),{code:r.code}))}function Nx(r){return Array.isArray(r)?r.filter(XF).slice(-JF):[]}function XF(r){if(!r||typeof r!="object"||Array.isArray(r))return!1;let e=r;return typeof e.id=="string"&&typeof e.occurredAt=="string"&&typeof e.summary=="string"&&(e.detail===void 0||typeof e.detail=="string")&&(e.path===void 0||typeof e.path=="string")&&["success","info","attention","error"].includes(e.tone??"")&&typeof e.requiresAcknowledgement=="boolean"}function QF(r){return r instanceof DOMException?r.name:r&&typeof r=="object"&&"code"in r&&typeof r.code=="string"?r.code:r instanceof Error&&r.name?r.name:"sync_failed"}function ZF(r,e){return r instanceof Error&&r.message?r.message:e}var Ed=class{constructor(e){this.ctx=e;this.conflictComparisons=new Map;this.loadingConflictComparisons=new Set;this.pendingSyncFocus=null;this.historyQuery="";this.transferQuery="";this.transferFilter="all";this.transferPages=new Map;this.historyLimit=xa;this.previewComparisons=new Map;this.comparedPreview=null;this.loadingPreviewComparisons=new Set;this.enrollmentVerification="";this.enrollmentAbort=null;this.enrollmentControlUrl=_d;this.enrollmentMirrorName=kx(this.ctx.app.vault.getName());this.enrollmentCollectionId="";this.enrollmentMode="read_write";this.filePolicyDraft=null;this.adoptionFileProgress="";this.adoptionPreview=null;this.adoptionRenamePlan=null;this.adoptionStage="";this.adoptionFailed=!1}getState(){return{historyQuery:this.historyQuery}}setState(e){typeof e.historyQuery=="string"&&(this.historyQuery=e.historyQuery.slice(0,2e3))}get session(){return this.ctx.host.sync}dispose(){this.enrollmentAbort?.abort(),this.enrollmentAbort=null}focusSection(e){this.ctx.destination="sync",this.pendingSyncFocus=e,this.ctx.render(),window.setTimeout(()=>this.focusPendingSyncSection(),0)}async reconnectCollection(){await this.session.reconnect()==="reauthorize"&&await this.ctx.perform(()=>this.reauthorizeCollection())}render(e){let t=e.createDiv({cls:"mdbase-sync-document"}),n=this.ctx.host.getMirrorProfile();if(!n){this.renderEnrollment(t);return}let i=this.session.state,s=!!(i.fileProgress||i.progress),o=t.createEl("section",{cls:"mdbase-sync-status"});o.setAttr("data-state",i.status?.state??"checking");let a=o.createDiv({cls:"mdbase-sync-heading"});a.createEl("h2",{text:n.name}),a.createDiv({cls:"mdbase-muted",text:`${s?"Syncing":Tx(i.status)} \xB7 ${Mx(i.status?.last_synced_at)}`});let c=a.createDiv({cls:"mdbase-muted mdbase-sync-scope"});c.createSpan({text:this.syncScopeText(n.mode)});let l=c.createEl("button",{cls:"mdbase-link-button",text:"Settings"});if(l.setAttr("aria-label","Open sync settings"),l.onclick=()=>this.ctx.host.openSettings(),i.message&&!i.problem){let y=o.createDiv({cls:"mdbase-inline-message mdbase-notice"});y.createSpan({text:i.message}).setAttr("role","status");let g=this.ctx.iconButton(y,"x","Dismiss sync message");g.onclick=()=>this.session.clearMessage()}if(s){let y=o.createDiv({cls:"mdbase-sync-progress",attr:{"aria-live":"polite"}}),g=i.fileProgress?.totalBytes??i.progress?.total??null,b=i.fileProgress?.transferredBytes??i.progress?.completed??0,v=y.createEl("progress");v.max=g??1,v.value=g==null?0:b,g==null&&v.removeAttribute("value"),y.createDiv({cls:"mdbase-progress-label",text:i.fileProgress?`${i.fileProgress.direction==="upload"?"Uploading":"Downloading"} ${i.fileProgress.path} \xB7 ${pr(b)} of ${pr(g??0)}`:`${i.progress?.phase==="uploading"?"Uploading local changes":i.progress?.phase==="downloading"?"Downloading collection files":"Applying changes"} \xB7 ${b}${g==null?"":` of ${g}`}`});let S=y.createEl("button",{text:"Stop"});S.onclick=()=>this.session.cancel()}let u=this.ctx.host.otherSyncServices();u.length&&o.createDiv({cls:"mdbase-inline-message mdbase-sync-coexistence",text:`${u.join(" and ")} also ${u.length===1?"syncs":"sync"} this vault. Two services syncing the same notes can duplicate them or bring deleted ones back; let only one of them sync this vault's notes.`}),i.paused&&!i.problem&&!s?this.renderRecoveryCard(o,{code:"sync_paused",kind:"paused",title:"Sync is paused",message:"Changes on this device and in Connect wait until you resume.",action:"resume",actionLabel:"Resume sync"}):(i.problem||i.status?.recovery_required)&&this.renderRecoveryCard(o,i.problem??{code:"mirror_recovery_required",kind:"recovery",title:"Synchronization needs recovery",message:"Your original files are safe. Resume from the durable checkpoint before disconnecting this vault.",action:"resume",actionLabel:"Resume recovery"});let d=this.ctx.busy||i.busy||s,f=i.preview;f!==this.comparedPreview&&(this.previewComparisons.clear(),this.comparedPreview=f,this.transferPages.clear());let p=this.session.safety(),h=!!(f?.plan.actions.length||f?.entries.length),m=o.createDiv({cls:"mdbase-sync-actions"});if(!s&&!(i.problem&&i.problem.action!=="review"))if(h&&f){let y=ry(f.plan,f.entries.length,d);if(f.plan.actions.length&&!y.actionDisabled){let b=m.createEl("button",{text:y.actionLabel,cls:"mod-cta"});b.disabled=y.actionDisabled,b.onclick=()=>void this.session.apply()}let g=this.ctx.iconButton(m,"refresh-cw","Refresh review");g.disabled=d,g.onclick=()=>void this.session.review()}else{let y=m.createEl("button",{text:i.busy?"Checking\u2026":"Sync now",cls:"mod-cta"});y.disabled=d,y.onclick=()=>void this.session.syncNow()}h&&p&&!p.safe&&f?.plan.actions.length&&o.createDiv({cls:"mdbase-muted mdbase-review-reasons",text:`Review needed: ${p.reasons.join(", ").toLowerCase()}.`}),f&&h&&this.renderMirrorPreview(t,f),i.status?.conflicts.length&&this.renderConflicts(t,i.status),i.status?.local_issues.length&&!h&&this.renderLocalMirrorIssues(t,i.status),this.renderHistory(t),window.setTimeout(()=>this.focusPendingSyncSection(),0)}syncScopeText(e){let t=this.ctx.host.connectSync.getSelectiveSync().excluded_folders,n=t.length?`Whole vault except ${t.length>2?`${t.slice(0,2).join(", ")} +${t.length-2}`:t.join(", ")}`:"Whole vault";return`${e==="read_only"?"Read only":"Read and write"} \xB7 ${n}`}renderRecoveryCard(e,t){let n=e.createDiv({cls:"mdbase-recovery-card"});n.setAttr("data-kind",t.kind);let i=n.createDiv();i.createEl("strong",{text:t.title}),i.createDiv({text:t.message});let s=this.session.state.retryAt;if(s&&(t.kind==="offline"||t.kind==="internal")){let c=Math.max(0,Math.round((s-Date.now())/1e3));i.createDiv({cls:"mdbase-muted",text:c<=1?"Trying again now\u2026":c<60?`Trying again in ${c}s.`:`Trying again in ${Math.round(c/60)} min.`})}let o=n.createDiv({cls:"mdbase-recovery-actions"}),a=o.createEl("button",{text:t.actionLabel,cls:"mod-cta"});if(a.disabled=this.ctx.busy||this.session.state.busy,a.onclick=()=>{t.kind==="auth"?this.reconnectCollection():t.action==="reauthorize"?this.ctx.perform(()=>this.reauthorizeCollection()):t.action==="review"?this.session.review():this.session.syncNow()},t.kind==="internal"||t.kind==="recovery"){let c=o.createEl("button",{text:"Copy diagnostics"});c.onclick=()=>void this.ctx.host.copySyncDiagnostics()}}async reauthorizeCollection(){this.enrollmentAbort?.abort();let e=new AbortController;this.enrollmentAbort=e;try{await this.session.reauthorize({signal:e.signal,onVerification:t=>{this.enrollmentVerification=t.verificationUri,this.ctx.message="Approve this vault again in Connect. Its local files and checkpoint remain unchanged.",window.open(t.verificationUri,"_blank","noopener,noreferrer"),this.ctx.render()},onStatus:t=>{this.ctx.message=t.state==="waiting_for_approval"?"Waiting for approval in Connect\u2026":`Connect is retrying approval (attempt ${t.attempt}).`,this.ctx.render()}}),this.enrollmentVerification="",this.ctx.message=""}finally{this.enrollmentAbort===e&&(this.enrollmentAbort=null)}}renderHistory(e){let t=this.session.historyRuns();if(!t.length)return;let n=t.filter(l=>l.needsAcknowledgement),i=this.ctx.disclosure(e,"sync-activity","History",n.length>0);i.addClass("mdbase-activity"),i.id="mdbase-sync-activity";for(let l of[...n].reverse())this.renderEventRow(i,l);let s=i.createDiv({cls:"mdbase-section-header mdbase-history-controls"}),o=s.createEl("input",{type:"search"});if(o.setAttr("aria-label","Filter history by path"),o.setAttr("data-focus-key","history-search"),o.placeholder="Filter by path",o.value=this.historyQuery,o.oninput=()=>{this.historyQuery=o.value,this.historyLimit=xa,this.ctx.render()},t.length>n.length){let l=s.createEl("button",{text:"Clear history"});l.disabled=this.ctx.busy,l.onclick=()=>void this.session.clearHistory()}let a=this.historyQuery.trim().toLowerCase(),c=K$(t.filter(l=>!l.needsAcknowledgement),a).sort((l,u)=>u.finishedAt.localeCompare(l.finishedAt));if(!c.length){i.createDiv({cls:"mdbase-muted",text:a?"No synced files match.":"No completed syncs."});return}for(let l of c.slice(0,this.historyLimit))U$(l)?this.renderEventRow(i,l):this.renderHistoryRun(i,l,a!=="");if(c.length>this.historyLimit){let l=i.createEl("button",{cls:"mdbase-link-button",text:`Show ${Math.min(xa,c.length-this.historyLimit)} more`});l.setAttr("data-focus-key","history-more"),l.onclick=()=>{this.historyLimit+=xa,this.ctx.render()}}}renderHistoryRun(e,t,n){let i=e.createEl("details",{cls:"mdbase-history-run"}),s=`history-run-${t.id}`;n?i.open=!0:(i.dataset.disclosure=s,i.open=this.ctx.disclosures.get(s)??!1);let o=i.createEl("summary",{cls:"mdbase-activity-row"});o.setAttr("data-focus-key",`disclosure-${s}`);let a=t.outcome==="applied"?"success":t.outcome==="failed"?"error":"attention";o.setAttr("data-tone",a),(0,Is.setIcon)(o.createSpan(),a==="success"?"check":"circle-alert");let c=o.createDiv();c.createEl("strong",{text:H$(t)});let l=Cx[t.outcome];c.createSpan({cls:"mdbase-muted",text:l?`${ks(t.finishedAt)} \xB7 ${l}`:ks(t.finishedAt)}),t.message&&t.outcome!=="applied"&&c.createDiv({text:t.message}),(0,Is.setIcon)(o.createSpan({cls:"mdbase-history-chevron"}),"chevron-right");let u=i.createDiv({cls:"mdbase-transfer-ledger mdbase-history-files"});for(let d of t.files.slice(0,250)){let f=u.createDiv({cls:"mdbase-transfer-row"});f.setAttr("title",new Date(d.at).toLocaleString()),f.createSpan({cls:"mdbase-transfer-action",text:d.action}).setAttr("data-action",d.status==="completed"?d.action:"fix");let h=f.createDiv({cls:"mdbase-transfer-body"}),m=h.createDiv({cls:"mdbase-transfer-path"}),y=m.createSpan({cls:"mdbase-history-direction"}),g=d.direction==="download"?"Downloaded":d.direction==="upload"?"Uploaded":"Needs attention";if(y.setAttr("aria-label",g),y.setAttr("title",g),(0,Is.setIcon)(y,d.direction==="download"?"download":d.direction==="upload"?"upload":"circle-alert"),d.action!=="delete"&&this.ctx.app.vault.getAbstractFileByPath(d.path)){let b=m.createEl("button",{cls:"mdbase-link-button mdbase-transfer-open"});b.createEl("code",{text:d.path}),b.setAttr("title",`Open ${d.path}`),b.onclick=()=>void this.ctx.host.openFileByPath(d.path)}else m.createEl("code",{text:d.path});d.fromPath&&h.createDiv({cls:"mdbase-muted",text:`From ${d.fromPath}`}),d.status!=="completed"&&h.createDiv({text:d.message?`${ey(d.status)}: ${d.message}`:ey(d.status)})}t.files.length>250&&u.createDiv({cls:"mdbase-transfer-more",text:`${t.files.length-250} more files are recorded in this sync.`})}renderEventRow(e,t){let n=t.tone??"info",i=e.createDiv({cls:"mdbase-activity-row"});i.setAttr("data-tone",n),(0,Is.setIcon)(i.createSpan(),n==="success"?"check":n==="info"?"info":"circle-alert");let s=i.createDiv(),o=t.summary??"";if(t.message&&t.message!==o){let a=s.createEl("details");a.createEl("summary",{text:o}),a.createDiv({text:t.message})}else s.createEl("strong",{text:o});if(s.createSpan({cls:"mdbase-muted",text:ks(t.finishedAt)}),t.needsAcknowledgement){let a=i.createEl("button",{text:"Dismiss"});a.disabled=this.ctx.busy,a.onclick=()=>void this.session.dismissEvent(t.id)}}focusPendingSyncSection(){if(!this.pendingSyncFocus)return;let e=this.pendingSyncFocus==="activity"?"mdbase-sync-activity":"mdbase-sync-conflicts",t=this.ctx.containerEl.querySelector(`#${e}`);if(!t)return;this.pendingSyncFocus=null;let n=t.closest("details");n&&(n.open=!0),t.scrollIntoView({block:"nearest"})}filePolicy(){return this.filePolicyDraft??=JSON.parse(JSON.stringify(this.ctx.host.connectSync.getSelectiveSync())),this.filePolicyDraft}renderFilePolicyControls(e){let t=this.filePolicy(),n=e.createEl("section",{cls:"mdbase-editor-section mdbase-file-policy"});n.createEl("h3",{text:"Attachments"});let i=n.createDiv({cls:"mdbase-file-class-grid"}),s=[["image","Images"],["audio","Audio"],["video","Video"],["pdf","PDFs"],["other","Other files"]];for(let[o,a]of s){let c=i.createEl("label"),l=c.createEl("input",{type:"checkbox"});l.setAttr("data-focus-key",`file-class-${o}`),l.checked=t.file_classes.includes(o),l.onchange=()=>{t.file_classes=l.checked?[...new Set([...t.file_classes,o])]:t.file_classes.filter(u=>u!==o),this.ctx.render()},c.createSpan({text:a})}n.createDiv({cls:"mdbase-form-description",text:$d}),n.createEl("h4",{text:"Excluded folders"}),xd(this.ctx.app,n,t.excluded_folders,o=>{t.excluded_folders=o}),t.file_classes.includes("other")&&n.createDiv({cls:"mdbase-inline-message",text:"Other files includes all remaining visible file formats."})}renderEnrollment(e){if(this.ctx.schema||this.ctx.host.connectSync.getAdoptionMarker()){this.renderLocalAdoption(e);return}let t=e.createEl("section",{cls:"mdbase-editor-section mdbase-enrollment"});if(t.createEl("h3",{text:"Copy a collection from Connect"}),t.createEl("p",{cls:"mdbase-muted",text:"Connect holds the collection; this vault syncs a copy. Choose a collection in Connect, then review the first sync."}),this.enrollmentVerification){let p=t.createDiv({cls:"mdbase-approval-link"});p.createSpan({text:"Waiting for approval \xB7 "});let h=p.createEl("a",{text:"Open Connect",href:this.enrollmentVerification});h.setAttr("target","_blank"),h.setAttr("rel","noopener noreferrer")}if(this.enrollmentAbort&&this.enrollmentVerification){let p=t.createEl("button",{text:"Stop waiting"});p.onclick=()=>this.enrollmentAbort?.abort();return}Tt(t,"Device name",this.enrollmentMirrorName,p=>{this.enrollmentMirrorName=p});let n=t.createDiv({cls:"mdbase-form-row"}),i=n.createEl("label",{text:"Access"}),s=n.createEl("select");i.htmlFor=s.id="mdbase-enrollment-access",s.createEl("option",{value:"read_write",text:"Read and write"}),s.createEl("option",{value:"read_only",text:"Read only"}),s.value=this.enrollmentMode,s.onchange=()=>{this.enrollmentMode=s.value==="read_only"?"read_only":"read_write",this.ctx.render()};let o=t.createDiv({cls:"mdbase-form-row mdbase-sync-target"});o.createEl("label",{text:"Syncs"});let a=o.createDiv({cls:"mdbase-sync-target-value"}),c=this.filePolicy().excluded_folders;a.createSpan({text:`Whole vault \u201C${this.ctx.app.vault.getName()}\u201D${c.length?` except ${c.join(", ")}`:""}`});let l=a.createEl("button",{cls:"mdbase-link-button",text:"Exclude folders"});l.onclick=()=>{this.ctx.disclosures.set("enrollment-options",!0),this.ctx.render()},t.createEl("p",{cls:"mdbase-form-description",text:this.enrollmentMode==="read_write"?"Existing notes may upload. Nothing moves until you review and sync.":"Downloads only. Existing local changes must be resolved or excluded."});let u=this.ctx.disclosure(t,"enrollment-options","Advanced");Tt(u,"Connect URL",this.enrollmentControlUrl,p=>{this.enrollmentControlUrl=p},{placeholder:_d}),Tt(u,"Collection ID",this.enrollmentCollectionId,p=>{this.enrollmentCollectionId=p},{placeholder:"Choose during approval"}),this.renderFilePolicyControls(u);let d=t.createDiv({cls:"mdbase-actions mdbase-enrollment-actions"}),f=d.createEl("button",{text:this.enrollmentAbort?"Waiting for approval\u2026":"Connect"});if(f.setAttr("title","Opens Connect in your browser to choose a collection"),f.addClass("mod-cta"),f.disabled=this.ctx.busy,f.onclick=()=>void this.ctx.perform(async()=>{this.enrollmentAbort?.abort();let p=new AbortController;this.enrollmentAbort=p;try{await this.ctx.host.connectSync.enroll({controlUrl:this.enrollmentControlUrl,mirrorName:this.enrollmentMirrorName,mode:this.enrollmentMode,selectiveSync:this.filePolicy(),...this.enrollmentCollectionId.trim()?{collectionId:this.enrollmentCollectionId.trim()}:{}},{signal:p.signal,onVerification:g=>{this.enrollmentVerification=g.verificationUri,this.ctx.message="",window.open(g.verificationUri,"_blank","noopener,noreferrer"),this.ctx.render()},onStatus:g=>{this.ctx.message=g.state==="waiting_for_approval"?"Waiting for approval in Connect\u2026":`Connect is retrying enrollment (attempt ${g.attempt}).`,this.ctx.render()}}),this.enrollmentVerification="";let h=await this.session.review(),m=h?.entries.reduce((g,b)=>g+(b.estimatedBytes??0),0)??0,y=h?.entries.length??0;this.ctx.message=`Connected. Review ${y} ${y===1?"item":"items"}${m?` \xB7 ${pr(m)}`:""} before syncing.`,this.ctx.render()}catch(h){if(!ty(h))throw h;this.enrollmentVerification="",this.ctx.message="Cancelled. No files synced."}finally{this.enrollmentAbort===p&&(this.enrollmentAbort=null)}}),this.enrollmentAbort){let p=d.createEl("button",{text:"Stop waiting"});p.onclick=()=>{this.enrollmentAbort?.abort(),this.enrollmentVerification="",this.ctx.message="Cancelled. No files synced.",this.ctx.render()}}}renderLocalAdoption(e){let t=this.ctx.host.connectSync.getAdoptionMarker(),n=t?this.ctx.host.connectSync.getAdoptionRecovery():null,i=!t||["waiting_for_approval","uploading"].includes(t.phase),s=i?this.adoptionPreview?.conflicts??[]:[],o=e.createEl("section",{cls:"mdbase-editor-section mdbase-enrollment"});o.createEl("h3",{text:"Upload to Connect"}),o.createEl("p",{cls:"mdbase-muted",text:n?n.canReset?"This upload expired and its device authorization is missing. Reset setup to start again. Your files stay local.":n.canReconnect?"Device authorization is unavailable. Reconnect to the hosted collection through Connect. This vault stays protected until approval succeeds.":`Device authorization is unavailable. Restore Obsidian's secret storage, or reset setup after ${new Date(t?.session.expiresAt??"").toLocaleString()}.`:this.ctx.busy&&this.adoptionStage?this.adoptionStage:t?t.phase==="waiting_for_approval"?"Not connected yet. Approval is pending in Connect.":t.phase==="adopted"?"Collection is hosted. Finish connecting this device.":t.phase==="activating"?"Activation outcome is pending. Resume to check it safely.":s.length||this.adoptionFailed?"Approval received. Upload stopped; this vault is not connected yet.":"Approval received. Transfer is not running; resume to continue.":"This vault holds the collection. Upload it to Connect to sync it with other devices; Connect then holds the collection and this vault syncs a copy.",attr:{role:"status","aria-live":"polite"}});let a=this.enrollmentVerification||(!n&&t?.phase==="waiting_for_approval"?t.session.verificationUri:void 0);if(a){let u=o.createDiv({cls:"mdbase-approval-link"});u.createSpan({text:"Approval page: "});let d=u.createEl("a",{text:"Open Connect",href:a});d.setAttr("target","_blank"),d.setAttr("rel","noopener noreferrer")}if(t&&(this.enrollmentControlUrl=t.session.controlUrl,this.enrollmentMirrorName=t.session.requested.mirrorName??"Obsidian"),t){let u=this.ctx.disclosure(o,"adoption-details","Details");zt(u,"Collection",t.session.requested.collectionId),zt(u,"Phase",t.phase.replace(/_/g," ")),zt(u,"Connect",t.session.controlUrl);let d=this.ctx.host.connectSync.getSelectiveSync();zt(u,"Files",d.file_classes.length?d.file_classes.join(", "):"Markdown only")}else{Tt(o,"Device name",this.enrollmentMirrorName,d=>{this.enrollmentMirrorName=d});let u=this.ctx.disclosure(o,"adoption-options","Advanced");Tt(u,"Connect URL",this.enrollmentControlUrl,d=>{this.enrollmentControlUrl=d},{placeholder:_d}),this.renderFilePolicyControls(u)}!n&&i&&(this.adoptionPreview&&o.createEl("p",{cls:"mdbase-muted",text:`${this.adoptionPreview.records.toLocaleString()} notes \xB7 ${this.adoptionPreview.files.toLocaleString()} attachments`}),s.length&&(o.createEl("h4",{text:`${s.length} filename conflicts`}),this.renderAdoptionRenameReview(o,s))),n||o.createEl("p",{cls:"mdbase-form-description",text:"Sync starts only after the upload completes."});let c=o.createDiv({cls:"mdbase-actions mdbase-enrollment-actions"});if(!n&&i){let u=c.createEl("button",{text:"Check files"});u.disabled=this.ctx.busy,u.onclick=()=>void this.ctx.perform(async()=>{this.adoptionRenamePlan=null,this.adoptionPreview=await this.ctx.host.connectSync.previewAdoption(this.filePolicy()),this.ctx.message=this.adoptionPreview.conflicts.length?"Resolve the listed filename conflicts before continuing.":"Files checked. No filename conflicts."})}if(n&&!n.canReconnect){if(n.canReset){let u=c.createEl("button",{text:"Reset setup",cls:"mod-cta"});u.disabled=this.ctx.busy,u.onclick=()=>void this.ctx.perform(async()=>{this.filePolicyDraft=this.ctx.host.connectSync.getSelectiveSync(),await this.ctx.host.connectSync.resetExpiredAdoption(),this.enrollmentVerification="",this.ctx.message="Expired setup cleared. Your files and collection identity are unchanged. Start a new upload to approve this device again.",await this.ctx.refresh(!0)})}else{let u=c.createEl("button",{text:"Check again"});u.disabled=this.ctx.busy,u.onclick=()=>this.ctx.render()}return}if(t&&!n&&!["activating","adopted"].includes(t.phase)){let u=c.createEl("button",{text:"Cancel upload"});u.disabled=this.ctx.busy,u.onclick=()=>void this.ctx.perform(async()=>{await this.ctx.host.connectSync.cancelAdoption(),this.enrollmentVerification="",this.ctx.message="Upload cancelled. The collection is still local.",await this.ctx.refresh(!0)})}if(this.enrollmentAbort){let u=c.createEl("button",{text:t?.phase==="waiting_for_approval"?"Stop waiting":"Pause upload"});u.onclick=()=>{this.enrollmentAbort?.abort(),this.ctx.message="Upload paused. Resume when ready.",this.ctx.render()}}let l=c.createEl("button",{text:n?"Reconnect collection":t?"Resume upload":"Upload to Connect"});l.addClass("mod-cta"),l.disabled=this.ctx.busy||!n&&s.length>0,l.onclick=()=>void this.ctx.perform(async()=>{this.adoptionFailed=!1,this.adoptionStage="Checking files\u2026",this.enrollmentAbort?.abort();let u=new AbortController;this.enrollmentAbort=u;let d=y=>{this.enrollmentVerification=y.verificationUri,this.adoptionStage="Waiting for approval in Connect\u2026",this.ctx.message="Approve the upload in Connect.",this.ctx.render()},f=y=>{this.ctx.message=y.state==="waiting_for_approval"?"Waiting for upload approval in Connect\u2026":`Connect is retrying (attempt ${y.attempt}).`,this.ctx.render()},p=y=>{this.adoptionStage=y.stage==="checking"?"Checking files\u2026":y.stage==="uploading"?`Approval received. Uploading ${y.records?.toLocaleString()??""} notes\u2026`:y.stage==="activating"?"Activating hosted collection. Keep this vault open\u2026":"Finishing this device's connection\u2026",this.enrollmentVerification="",this.ctx.message="",this.ctx.render()},h=(y,g,b)=>{this.adoptionFileProgress=`${y} \xB7 ${pr(g)} of ${pr(b)}`,this.adoptionStage=`Uploading ${this.adoptionFileProgress}`,this.ctx.render()},m={signal:u.signal,onVerification:d,onStatus:f,onFileProgress:h,onProgress:p};try{n?await this.ctx.host.connectSync.reconnectAdoption(m):t?await this.ctx.host.connectSync.resumeAdoption(m):await this.ctx.host.connectSync.adoptLocalCollection({controlUrl:this.enrollmentControlUrl,mirrorName:this.enrollmentMirrorName,selectiveSync:this.filePolicy()},m),this.enrollmentVerification="",this.ctx.message="Collection hosted. This vault is now connected.",await this.ctx.refresh(!0)}catch(y){if(this.ctx.host.connectSync.getAdoptionMarker()?.phase!=="waiting_for_approval"&&(this.enrollmentVerification=""),!ty(y))throw this.adoptionFailed=!0,await this.ctx.host.connectSync.previewAdoption(this.filePolicy()).then(g=>{this.adoptionPreview=g}).catch(()=>{}),y;this.ctx.message="Upload paused. Resume when ready."}finally{this.adoptionStage="",this.enrollmentAbort===u&&(this.enrollmentAbort=null)}})}renderAdoptionRenameReview(e,t){let n=this.adoptionRenamePlan;e.createEl("p",{text:n?"Keep both files with distinct names. Nothing is merged or deleted. Link updates follow your Obsidian settings.":"Names must also be distinct on case-insensitive devices. Review suggested names, or rename the files yourself."});let i=e.createEl("ul",{cls:"mdbase-adoption-conflicts"}),s=n?n.renames.map(l=>[l.from,l.to]):t;for(let l of s){let u=i.createEl("li");l.forEach((d,f)=>{f&&u.appendText(n?" \u2192 ":" \u2194 "),u.createEl("code",{text:d})})}n?.manual.length&&e.createEl("p",{text:"Collection-resource conflicts need manual review: "+n.manual.map(l=>l.join(" \u2194 ")).join("; ")});let o=e.createDiv({cls:"mdbase-actions"});if(!n){let l=o.createEl("button",{text:"Review renames\u2026"});l.disabled=this.ctx.busy,l.onclick=()=>void this.ctx.perform(async()=>{this.adoptionRenamePlan=await this.ctx.host.connectSync.planAdoptionRenames(this.filePolicy())});return}let a=o.createEl("button",{text:`Rename ${n.renames.length} ${n.renames.length===1?"file":"files"}`,cls:"mod-cta"});a.disabled=this.ctx.busy||!n.renames.length,a.onclick=()=>void this.ctx.perform(async()=>{try{let l=await this.ctx.host.connectSync.applyAdoptionRenames(n,this.filePolicy(),(u,d)=>{this.adoptionStage=`Renaming ${u} of ${d} files\u2026`,this.ctx.render()});this.ctx.message=`Renamed ${l} ${l===1?"file":"files"}. Review the file check, then resume the upload.`}finally{this.adoptionStage="",this.adoptionRenamePlan=null,await this.ctx.host.connectSync.previewAdoption(this.filePolicy()).then(l=>{this.adoptionPreview=l}).catch(()=>{})}});let c=o.createEl("button",{text:"Cancel"});c.disabled=this.ctx.busy,c.onclick=()=>{this.adoptionRenamePlan=null,this.ctx.render()}}renderMirrorPreview(e,t){let n=e.createEl("section",{cls:"mdbase-transfer-review"}),i=n.createDiv({cls:"mdbase-transfer-heading"});i.createDiv().createEl("h3",{text:t.phase==="initial"?"First sync":"Changes"});let o=t.entries.reduce((p,h)=>p+(h.estimatedBytes??0),0);i.createSpan({cls:"mdbase-transfer-total",text:t.entries.length?`${t.entries.length} ${t.entries.length===1?"item":"items"}${o?` \xB7 ${pr(o)}`:""}`:"No changes"});let a=n.createDiv({cls:"mdbase-issue-controls"}),c=a.createEl("input",{type:"search",placeholder:"Search transfer paths"});c.setAttr("aria-label","Search transfer paths"),c.setAttr("data-focus-key","transfer-search"),c.value=this.transferQuery,c.oninput=()=>{this.transferQuery=c.value,this.transferPages.clear(),this.ctx.render()};let l=a.createEl("select");l.setAttr("aria-label","Filter transfers");for(let[p,h]of[["all","All changes"],["delete","Deletes"],["replace","Replacements"],["upload","Uploads"],["download","Downloads"],["attention","Needs attention"]])l.createEl("option",{value:p,text:h});l.value=this.transferFilter,l.onchange=()=>{this.transferFilter=l.value,this.transferPages.clear(),this.ctx.render()};let u=this.transferQuery.trim().toLowerCase(),d=t.entries.filter(p=>(!u||`${p.path} ${p.detail}`.toLowerCase().includes(u))&&(this.transferFilter==="all"||p.action===this.transferFilter||p.direction===this.transferFilter));d.length||n.createDiv({cls:"mdbase-muted",text:"No changes match these filters."}),n.createDiv({cls:"mdbase-muted",text:`Showing ${d.length} of ${t.entries.length} items. Approval always applies to the entire reviewed plan, not just these filters.`});let f=[{direction:"download",title:"Downloads"},{direction:"upload",title:"Uploads"},{direction:"attention",title:"Needs attention"}];for(let p of f){let h=d.filter(_=>_.direction===p.direction);if(!h.length)continue;let m=n.createEl("section",{cls:"mdbase-transfer-group"});m.setAttr("data-direction",p.direction);let y=m.createDiv({cls:"mdbase-transfer-group-heading"}),g=y.createSpan({cls:"mdbase-transfer-group-icon"});(0,Is.setIcon)(g,p.direction==="download"?"download":p.direction==="upload"?"upload":"circle-alert"),y.createEl("h4",{text:p.title}),y.createSpan({text:String(h.length),cls:"mdbase-transfer-count"});let b=m.createDiv({cls:"mdbase-transfer-ledger"}),v=Math.min(this.transferPages.get(p.direction)??0,Math.floor((h.length-1)/250)),S=v*250;for(let _ of h.slice(S,S+250)){let E=b.createDiv({cls:"mdbase-transfer-row"});E.createSpan({cls:"mdbase-transfer-action",text:_.action}).setAttr("data-action",_.action);let $=E.createDiv({cls:"mdbase-transfer-body"}),M=$.createDiv({cls:"mdbase-transfer-path"}),x=this.ctx.app.vault.getAbstractFileByPath(_.path)?_.path:null;if(x){let T=M.createEl("button",{cls:"mdbase-link-button mdbase-transfer-open"});T.createEl("code",{text:_.path}),T.setAttr("title",`Open ${_.path}`),T.onclick=()=>void this.ctx.host.openFileByPath(x)}else M.createEl("code",{text:_.path});_.estimatedBytes!==void 0&&M.createSpan({cls:"mdbase-transfer-size",text:pr(_.estimatedBytes)}),_.direction==="attention"||["rename","replace","delete"].includes(_.action)?$.createDiv({text:_.detail}):E.setAttr("title",_.detail);let q=_.recordId;if(q&&_.kind==="document"&&_.action==="update"&&x){let T=`${q}:${_.path}`,V=this.previewComparisons.get(T),P=E.createEl("button",{text:V?"Hide":this.loadingPreviewComparisons.has(T)?"Loading\u2026":"Compare"});P.setAttr("data-focus-key",`preview-compare-${T}`),P.disabled=this.loadingPreviewComparisons.has(T),P.onclick=()=>{V?(this.previewComparisons.delete(T),this.ctx.render()):this.loadPreviewComparison(T,q,_.path)},V&&this.renderConflictComparison($,V)}}if(h.length>250){let _=b.createDiv({cls:"mdbase-actions"});_.createSpan({cls:"mdbase-muted",text:`Showing ${S+1}\u2013${Math.min(S+250,h.length)} of ${h.length}`});let E=_.createEl("button",{text:`Previous ${p.title.toLowerCase()}`});E.disabled=v===0,E.setAttr("data-focus-key",`transfer-previous-${p.direction}`),E.onclick=()=>{this.transferPages.set(p.direction,v-1),this.ctx.render()};let k=_.createEl("button",{text:`Next ${p.title.toLowerCase()}`});k.disabled=S+250>=h.length,k.setAttr("data-focus-key",`transfer-next-${p.direction}`),k.onclick=()=>{this.transferPages.set(p.direction,v+1),this.ctx.render()}}}t.collisions.length?n.createDiv({cls:"mdbase-inline-error",text:"Colliding files and related moves are left unchanged. Independent files can still sync. Move or rename the obstruction, then review again."}):t.local_issues.length&&n.createDiv({cls:"mdbase-inline-message",text:t.plan.summary.blocking_issues>0?ry(t.plan,t.entries.length).message:"These diagnostics do not block synchronization. Document bytes are preserved unchanged."})}renderConflicts(e,t){let n=e.createEl("section",{cls:"mdbase-editor-section"});n.id="mdbase-sync-conflicts",n.createEl("h3",{text:"Conflicts"});for(let i of t.conflicts){let s=n.createDiv({cls:"mdbase-conflict-row"}),o=s.createDiv({cls:"mdbase-conflict-summary"});o.createEl("strong",{text:i.path??i.object_id}),o.createDiv({text:i.message});let a=s.createDiv({cls:"mdbase-actions"}),c=`${i.object_id}:${i.decision_id}`,l=this.conflictComparisons.get(c),u=a.createEl("button",{text:l?"Hide":this.loadingConflictComparisons.has(c)?"Loading\u2026":"Resolve\u2026"});if(u.setAttr("data-focus-key",`compare-${c}`),u.disabled=this.ctx.busy||this.loadingConflictComparisons.has(c),u.onclick=()=>{if(l){this.conflictComparisons.delete(c),this.ctx.render();return}this.loadConflictComparison(i,c)},l){for(let d of["local","remote"]){let f=a.createEl("button",{text:d==="local"?"Keep local":"Use hosted"});f.disabled=this.ctx.busy,f.onclick=()=>void this.resolveMirrorConflict(i,d,!1)}if(i.path){let d=a.createEl("button",{text:"Keep both"});d.disabled=this.ctx.busy,d.onclick=()=>void this.resolveMirrorConflict(i,"remote",!0)}this.renderConflictComparison(s,l)}}}async loadPreviewComparison(e,t,n){this.loadingPreviewComparisons.add(e),this.ctx.render();try{this.previewComparisons.set(e,await this.ctx.host.connectSync.recordComparison(t,n))}catch(i){this.ctx.message=Rt(i).message}finally{this.loadingPreviewComparisons.delete(e),this.ctx.render()}}async loadConflictComparison(e,t){this.loadingConflictComparisons.add(t),this.ctx.render();try{this.conflictComparisons.set(t,await this.ctx.host.connectSync.conflictComparison(e))}catch(n){this.session.reportProblem(n).code==="conflict_decision_stale"&&await this.session.refreshStatus()}finally{this.loadingConflictComparisons.delete(t),this.ctx.render()}}renderConflictComparison(e,t){let n=e.createDiv({cls:"mdbase-conflict-comparison"});if(t.entity==="record"){let s=Ix(t.local.document??"",t.remote.document??""),o=n.createDiv({cls:"mdbase-conflict-legend"});o.createSpan({text:"\u2212 Local only",cls:"is-local"}),o.createSpan({text:"+ Hosted only",cls:"is-remote"});let a=n.createEl("pre",{cls:"mdbase-conflict-diff"});for(let c of s.lines){let l=a.createEl("div",{cls:`is-${c.kind}`});l.createSpan({text:c.kind==="local"?"\u2212":c.kind==="remote"?"+":" "}),l.createSpan({text:c.value||" "})}s.truncated&&n.createDiv({cls:"mdbase-muted",text:"Diff shortened for a responsive review. Open the local note to inspect it in full."});return}let i=n.createDiv({cls:"mdbase-conflict-sides"});this.renderConflictSide(i,"Local",t.local),this.renderConflictSide(i,"Hosted",t.remote)}renderConflictSide(e,t,n){let i=e.createDiv({cls:"mdbase-conflict-side"});if(i.createEl("h4",{text:t}),n.state==="absent"){i.createDiv({cls:"mdbase-muted",text:"File is absent in this version."});return}if(n.path&&i.createEl("code",{text:n.path}),n.size!==void 0&&i.createDiv({text:`Size: ${pr(n.size)}`}),n.modifiedAt&&i.createDiv({text:`Modified: ${new Date(n.modifiedAt).toLocaleString()}`}),n.revision&&i.createDiv({cls:"mdbase-conflict-digest",text:`Digest: ${n.revision}`}),n.resourceUrl&&n.path&&/\.(?:avif|gif|jpe?g|png|svg|webp)$/i.test(n.path)){let s=i.createEl("img",{cls:"mdbase-conflict-image-preview"});s.src=n.resourceUrl,s.alt=`${t} preview of ${n.path}`}else t==="Hosted"&&i.createDiv({cls:"mdbase-muted",text:"Hosted binary preview is materialized only after you choose it."})}async resolveMirrorConflict(e,t,n){await this.ctx.perform(async()=>{await this.session.resolveConflict(e,t,n)&&this.conflictComparisons.delete(`${e.object_id}:${e.decision_id}`)})}renderLocalMirrorIssues(e,t){let n=e.createEl("section",{cls:"mdbase-editor-section"});n.createEl("h3",{text:"Local files needing attention"}),n.createEl("p",{text:"Review these file diagnostics. The sync preview identifies which issues block synchronization; a diagnostic alone does not mean syncing is paused."});for(let i of t.local_issues){let s=n.createDiv({cls:"mdbase-conflict-row"}),o=s.createDiv();o.createEl("strong",{text:i.path}),o.createDiv({text:i.message});let c=s.createDiv({cls:"mdbase-actions"}).createEl("button",{text:"Open file"});c.disabled=this.ctx.busy,c.onclick=()=>void this.ctx.host.openFileByPath(i.path)}}async refresh(){if(!this.session.isSyncing()){if(!this.ctx.host.getMirrorProfile()){if(!this.ctx.schema||this.enrollmentAbort)return;try{this.adoptionPreview=await this.ctx.host.connectSync.previewAdoption(this.filePolicy())}catch(e){this.ctx.message=Rt(e).message}return}await this.session.refreshStatus()}}};var Qe=require("obsidian");qt();function Lx(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function Os(r){return typeof r=="number"&&Number.isFinite(r)?r:null}function ny(r,e,t=""){let n=t?` ${t}`:"";return r!==null&&e!==null?r===e?`${r}${n}`:`${r}\u2013${e}${n}`:r!==null?`\u2265 ${r}${n}`:e!==null?`\u2264 ${e}${n}`:null}function sn(r){return typeof r=="string"?r:typeof r=="number"||typeof r=="boolean"||typeof r=="bigint"?String(r):JSON.stringify(r)??""}function iy(r){let e=sn(r);return e.length>24?`${e.slice(0,23)}\u2026`:e}function Fx(r){let e=typeof r.type=="string"?r.type:"any",t=[];if(e==="enum"&&Array.isArray(r.values)){let n=r.values.map(iy);t.push(n.length>3?`${n.slice(0,3).join(", ")}, +${n.length-3}`:n.join(", ")||"no values")}if(e==="integer"||e==="number"){let n=ny(Os(r.min),Os(r.max));n&&t.push(n)}if(e==="list"){let n=ny(Os(r.min_length),Os(r.max_length),"items");n&&t.push(n),Lx(r.items)&&typeof r.items.type=="string"&&t.push(`of ${r.items.type}`)}else{let n=ny(Os(r.min_length),Os(r.max_length),"chars");n&&t.push(n)}if(typeof r.pattern=="string"&&r.pattern&&t.push(`/${iy(r.pattern)}/`),e==="link"&&typeof r.target=="string"&&r.target&&t.push(`\u2192 ${r.target}`),e==="object"&&Lx(r.fields)){let n=Object.keys(r.fields).length;t.push(`${n} ${n===1?"field":"fields"}`)}return r.default!==void 0&&t.push(`default ${iy(r.default)}`),r.unique===!0&&t.push("unique"),r.deprecated===!0&&t.push("deprecated"),t}function jx(r,e,t){if(e!==void 0&&sn(e)===r)return e;let n=r.trim()!==""&&Number.isFinite(Number(r)),i=r==="true"||r==="false",s=o=>t.length>0&&t.every(a=>typeof a===o);return n&&(typeof e=="number"||typeof e!="boolean"&&s("number"))?Number(r):i&&(typeof e=="boolean"||typeof e!="number"&&s("boolean"))?r==="true":r}function qx(r,e){if(r==="")return{};if(e==="integer"||e==="number"){let t=Number(r);return Number.isFinite(t)?e==="integer"&&!Number.isInteger(t)?{error:"Default must be a whole number."}:{value:t}:{error:"Default must be a number."}}return e==="boolean"?r==="true"?{value:!0}:r==="false"?{value:!1}:{error:"Default must be true or false."}:{value:r}}var Un=require("@codemirror/commands"),Vn=require("@codemirror/language"),Kt=require("@codemirror/state"),$t=require("@codemirror/view"),Bn=require("@lezer/highlight"),ej=Vn.StreamLanguage.define({startState:()=>({section:"start"}),copyState:r=>({...r}),token(r,e){return r.sol()&&r.match(/^---\s*$/)?(e.section=e.section==="start"?"yaml":"body","meta"):e.section==="body"?(r.skipToEnd(),null):(e.section==="start"&&(e.section="yaml"),r.eatSpace()?null:r.match("#")?(r.skipToEnd(),"comment"):r.match(/^-(?=\s|$)/)?"punctuation":r.match(/^(?:[^\s:#'"[\]{},][^:#]*?|"[^"]*"|'[^']*')(?=\s*:(?:\s|$))/)?"propertyName":r.match(/^"(?:[^"\\]|\\.)*"?/)||r.match(/^'(?:[^']|'')*'?/)?"string":r.match(/^-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?(?=[\s,\]}]|$)/)?"number":r.match(/^(?:true|false|null|~)(?=[\s,\]}]|$)/)?"atom":r.match(/^[:[\]{},|>]/)?"punctuation":(r.eatWhile(/[^\s#:,[\]{}]/),r.current()===""&&r.next(),"string"))}}),tj=Vn.HighlightStyle.define([{tag:Bn.tags.propertyName,color:"var(--text-accent)"},{tag:Bn.tags.string,color:"var(--text-normal)"},{tag:Bn.tags.number,color:"var(--color-orange)"},{tag:Bn.tags.atom,color:"var(--color-purple)"},{tag:Bn.tags.comment,color:"var(--text-faint)",fontStyle:"italic"},{tag:Bn.tags.meta,color:"var(--text-faint)"},{tag:Bn.tags.punctuation,color:"var(--text-muted)"}]),Bx=Kt.StateEffect.define(),rj=Kt.StateField.define({create:()=>$t.Decoration.none,update(r,e){let t=r.map(e.changes);for(let n of e.effects){if(!n.is(Bx))continue;let i=new Kt.RangeSetBuilder,s=[...new Set(n.value.map(o=>o.line).filter(o=>o!==null&&o>=1&&o<=e.state.doc.lines))].sort((o,a)=>o-a);for(let o of s){let a=e.state.doc.line(o),c=n.value.find(l=>l.line===o)?.severity??"error";i.add(a.from,a.from,$t.Decoration.line({class:`mdbase-yaml-problem-line is-${c}`}))}t=i.finish()}return t},provide:r=>$t.EditorView.decorations.from(r)}),Ad=class{constructor(e){this.editable=new Kt.Compartment;this.applyingExternalChange=!1;this.view=new $t.EditorView({state:Kt.EditorState.create({doc:e.doc,extensions:[(0,$t.lineNumbers)(),(0,Un.history)(),Vn.indentUnit.of(" "),Kt.EditorState.tabSize.of(2),$t.keymap.of([...Un.defaultKeymap,...Un.historyKeymap,Un.indentWithTab]),ej,(0,Vn.syntaxHighlighting)(tj),rj,$t.EditorView.lineWrapping,this.editable.of(this.editability(e.readOnly)),$t.EditorView.contentAttributes.of({"aria-labelledby":e.labelledBy,"data-focus-key":"yaml-editor",spellcheck:"false"}),$t.EditorView.updateListener.of(t=>{t.docChanged&&!this.applyingExternalChange&&e.onChange(t.state.doc.toString())})]})}),this.dom=this.view.dom,this.dom.addClass("mdbase-yaml-editor")}get value(){return this.view.state.doc.toString()}setValue(e){if(e!==this.value){this.applyingExternalChange=!0;try{this.view.dispatch({changes:{from:0,to:this.view.state.doc.length,insert:e}})}finally{this.applyingExternalChange=!1}}}setReadOnly(e){this.view.dispatch({effects:this.editable.reconfigure(this.editability(e))})}setProblems(e){this.view.dispatch({effects:Bx.of(e)})}revealLine(e){if(e<1||e>this.view.state.doc.lines)return;let t=this.view.state.doc.line(e).from;this.view.dispatch({selection:{anchor:t},scrollIntoView:!0}),this.view.focus()}destroy(){this.view.destroy()}editability(e){return[Kt.EditorState.readOnly.of(e),$t.EditorView.editable.of(!e)]}};function Ux(r,e=2){let t=r.match(/line (\d+)/i)??r.match(/\((\d+):\d+\)/);return t?Number(t[1])+e-1:null}function sy(r,e){if(!e)return null;let t=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),n=new RegExp(`^\\s*(?:-\\s+)?["']?${t}["']?\\s*:`),s=r.split(` -`).findIndex(o=>n.test(o));return s===-1?null:s+1}var kd=class{constructor(e){this.ctx=e;this.editorMode="design";this.query="";this.selectedPath=null;this.model=null;this.originalModel=null;this.yamlDraft="";this.dirty=!1;this.migrationPlan=null;this.allowLossy=!1;this.statsCache=null;this.impact=null;this.impactVersion=0;this.impactTimer=null;this.showAllMatches=!1;this.pendingFieldReveal=null;this.sessionDrafts=new Set;this.yamlEditor=null;this.yamlProblemTimer=null;this.draftSaveTimer=null;this.fieldQuery="";this.expandedFields=new Set;this.fieldIds=new WeakMap;this.nextFieldId=1;this.typeSelectionVersion=0}async onSchemaLoaded(e,t){if(this.selectedPath&&!this.typeEntries().some(n=>n.filePath===this.selectedPath)&&(this.selectedPath=null,this.model=null,this.originalModel=null),!this.selectedPath&&this.typeEntries().length&&!Qe.Platform.isMobile&&(this.selectedPath=this.typeEntries()[0].filePath),this.selectedPath&&(!this.model||e)){if(this.dirty&&await this.flushTypeDraft(),!t())return;await this.selectType(this.selectedPath,!1)}}onRecordsLoaded(e){(e||!this.impact)&&this.scheduleImpact(0)}afterRender(e){if(!this.pendingFieldReveal)return;let t=e.querySelector(`[data-field-id="${this.pendingFieldReveal}"]`);t&&(t.scrollIntoView({block:"nearest"}),(!e.contains(e.ownerDocument.activeElement)||e.ownerDocument.activeElement===e.ownerDocument.body)&&t.querySelector("summary")?.focus({preventScroll:!0}),t.addClass("is-revealed")),this.pendingFieldReveal=null}getState(){return{selectedPath:this.selectedPath,editorMode:this.editorMode,query:this.query,fieldQuery:this.fieldQuery}}async setState(e){for(let t of["query","fieldQuery"])typeof e[t]=="string"&&(this[t]=e[t].slice(0,2e3));typeof e.selectedPath=="string"&&e.selectedPath!==this.selectedPath&&(await this.leaveCurrentType(),this.selectedPath=e.selectedPath,this.model=null,this.originalModel=null)}restoreEditorMode(e){e==="yaml"&&this.editorMode!=="yaml"&&this.switchEditorMode("yaml")}async dispose(){this.impactTimer!==null&&window.clearTimeout(this.impactTimer),this.yamlProblemTimer!==null&&window.clearTimeout(this.yamlProblemTimer),this.impactVersion++,await this.flushTypeDraft(),this.yamlEditor?.destroy(),this.yamlEditor=null}async openTypeField(e,t){this.ctx.destination="types",(e!==this.selectedPath||!this.model)&&await this.selectType(e),!(!this.model||this.selectedPath!==e)&&(t&&this.revealField(t),this.ctx.render())}revealField(e){if(!this.model)return;let t=e.split(".").filter(Boolean),n=t.shift()?.replace(/\[\]$/g,"")??"",i=this.model.fields.find(s=>s.name===n)?.definition;if(i){this.editorMode="design",this.fieldQuery="",this.expandedFields.add(this.fieldId(i));for(let s of t){let o=s.replace(/\[\]$/g,""),a=Se(i.items)?i.items:i,c=Se(a.fields)?a.fields[o]:void 0;if(!Se(c))break;a!==i&&this.expandedFields.add(this.fieldId(a)),i=c,this.expandedFields.add(this.fieldId(i))}this.pendingFieldReveal=this.fieldId(i)}}currentStats(){let e=this.ctx.host.getIssues(),t=this.ctx.schema?.types??null,n=this.statsCache;if(n&&n.records===this.ctx.records&&n.types===t&&n.issues===e)return n;let i=this.ctx.records&&this.ctx.schema?Sx(this.ctx.records,this.ctx.schema.config,this.ctx.schema.types):new Map;return this.statsCache={records:this.ctx.records,types:t,issues:e,recordTypes:i,stats:$x(i,e)},this.statsCache}scheduleImpact(e=400){this.impactTimer!==null&&window.clearTimeout(this.impactTimer),this.impactTimer=window.setTimeout(()=>{this.impactTimer=null,this.computeImpact().then(t=>{t!==void 0&&(this.impact=t,this.updateImpactRegions())})},e)}async computeImpact(){let e=++this.impactVersion,t=this.editorMode==="yaml"?this.modelFromYamlDraft():null;if(t&&"error"in t)return{error:t.error};let n=t?.model??this.model;if(!n||!this.ctx.schema||!this.ctx.records||n.specProfile!=="v0.3"||n.readOnlyReason)return null;let i=this.selectedPath?[...this.ctx.schema.types.values()].find(o=>o.filePath===this.selectedPath)?.name??null:null,s=await xx({records:this.ctx.records,config:this.ctx.schema.config,types:this.ctx.schema.types,draft:n,savedName:i,filePath:this.selectedPath,isCurrent:()=>e===this.impactVersion});return e===this.impactVersion&&s!==null?s:void 0}updateImpactRegions(){let e=this.ctx.containerEl.querySelector(".mdbase-match-preview");e&&(e.empty(),this.fillMatchPreview(e));let t=this.ctx.containerEl.querySelector("[data-disclosure='type-matching'] > summary");t&&(t.textContent=this.matchingLabel());let n=this.ctx.containerEl.querySelector(".mdbase-impact");n&&(n.empty(),this.fillImpact(n));let i=this.ctx.containerEl.querySelector(".mdbase-type-editor-pane"),s=i?.querySelector(".mdbase-draft-bar");i&&s&&this.model&&(s.remove(),this.renderDraftBar(i,this.model))}createNewType(){this.ctx.destination="types",this.createType()}async editType(e){this.ctx.destination="types",await this.selectType(e)}typeEntries(){return this.ctx.schema?[...this.ctx.schema.types.values()].sort((e,t)=>e.name.localeCompare(t.name)):[]}renderSetup(e){let t=e.createDiv({cls:"mdbase-empty-state mdbase-setup"});if(this.ctx.host.getMirrorProfile()){t.createEl("h2",{text:"Waiting for the first sync"}),t.createEl("p",{text:"Types appear here once the hosted collection has synced."});let s=t.createEl("button",{text:"Open sync",cls:"mod-cta"});s.onclick=()=>this.ctx.showDestination("sync");return}t.createEl("h2",{text:"Set up mdbase"});let n=t.createDiv({cls:"mdbase-setup-choices"}),i=(s,o,a,c)=>{let l=n.createDiv({cls:"mdbase-setup-choice"}),u=l.createDiv();u.createEl("strong",{text:s}),u.createDiv({cls:"mdbase-muted",text:o});let d=l.createEl("button",{text:s,cls:a?"mod-cta":""});d.disabled=this.ctx.busy,d.onclick=c};i("Start a collection","This vault holds the collection. You can upload it to Connect later.",!0,()=>{this.ctx.perform(async()=>{await this.ctx.host.initializeCollection(),await this.ctx.refresh(!0)})}),i("Copy from Connect","Connect holds the collection. This vault syncs a copy.",!1,()=>{this.ctx.showDestination("sync")})}render(e){if(!this.ctx.schema){this.renderSetup(e);return}if(this.ctx.schema.config.spec_version.startsWith("0.2.")&&this.renderLegacyBanner(e),!this.typeEntries().length&&!this.model){let n=e.createDiv({cls:"mdbase-empty-state"});n.createEl("h2",{text:"Add your first type"}),n.createEl("p",{text:"Install ready-made types and application contracts from mdbase-contracts, or design your own type."});let i=n.createDiv({cls:"mdbase-actions"}),s=i.createEl("button",{text:"Browse ready-made types",cls:"mod-cta"});s.disabled=this.ctx.busy||this.ctx.schema.config.spec_version.startsWith("0.2.")||this.ctx.host.getMirrorProfile()!==null,s.onclick=()=>void this.ctx.perform(()=>this.ctx.host.openContractCatalog());let o=i.createEl("button",{text:"Design a custom type"});o.disabled=this.ctx.schema.config.spec_version.startsWith("0.2.")||this.ctx.host.getMirrorProfile()?.mode==="read_only",o.onclick=()=>void this.createType();return}let t=e.createDiv({cls:"mdbase-types-layout"});this.model&&t.addClass("has-selection"),this.renderTypeList(t),this.renderTypeEditor(t)}renderLegacyBanner(e){let t=e.createDiv({cls:"mdbase-legacy-banner"}),n=t.createDiv();if(n.createEl("strong",{text:"Read-only \xB7 v0.2 collection"}),n.createEl("p",{text:"Migrate to edit types."}),!this.migrationPlan){let i=t.createEl("button",{text:"Review migration"});i.disabled=this.ctx.busy||this.ctx.host.getMirrorProfile()!==null,i.onclick=()=>void this.ctx.perform(async()=>{this.migrationPlan=await this.ctx.host.analyzeMigration(),this.ctx.render()})}this.ctx.host.getMirrorProfile()&&t.createDiv({cls:"mdbase-form-description",text:"Hosted resources must be migrated at the collection authority."}),this.migrationPlan&&this.renderMigrationReview(e,this.migrationPlan)}renderMigrationReview(e,t){let n=e.createDiv({cls:"mdbase-migration-review"}),i=n.createDiv({cls:"mdbase-section-header"});i.createEl("h3",{text:"Migration review"}),i.createSpan({cls:"mdbase-spec-badge",text:`${t.sourceVersion} \u2192 ${t.targetVersion}`});let s=n.createDiv({cls:"mdbase-status-list"});zt(s,"Files replaced",String(t.operations.length)),zt(s,"Type definitions",String(t.typeSummaries.length)),zt(s,"Record reads verified",String(t.recordsVerified)),t.recordsSkipped&&zt(s,"Records skipped",String(t.recordsSkipped)),zt(s,"Record files rewritten","0"),zt(s,"Recovery backup",t.backupLocation);let o=n.createDiv({cls:"mdbase-review-list"});t.diagnostics.length||o.createDiv({cls:"mdbase-review-ok",text:"No migration diagnostics."});for(let u of t.diagnostics.slice(0,250)){let d=o.createDiv({cls:"mdbase-review-item"});d.setAttr("data-severity",u.severity),d.createDiv({cls:"mdbase-review-code",text:`${u.severity} \xB7 ${u.path}`}),d.createDiv({text:u.message})}if(t.diagnostics.length>250&&o.createDiv({cls:"mdbase-form-description",text:`Showing 250 of ${t.diagnostics.length} diagnostics.`}),!t.applicable){let u=n.createEl("label",{cls:"mdbase-consent"}),d=u.createEl("input",{type:"checkbox"});d.checked=this.allowLossy,d.onchange=()=>{this.allowLossy=d.checked,this.ctx.render()},u.createSpan({text:"I reviewed the lossy diagnostics and want to apply this migration."})}let a=n.createDiv({cls:"mdbase-actions"}),c=a.createEl("button",{text:"Apply migration"});c.addClass("mod-warning"),c.disabled=this.ctx.busy||!t.applicable&&!this.allowLossy,c.onclick=()=>void this.ctx.perform(async()=>{await this.ctx.host.applyMigration(t,this.allowLossy),this.migrationPlan=null,this.allowLossy=!1,this.model=null,this.originalModel=null,await this.ctx.refresh(!0)});let l=a.createEl("button",{text:"Close review"});l.onclick=()=>{this.migrationPlan=null,this.ctx.render()}}renderTypeList(e){let t=e.createDiv({cls:"mdbase-type-list-pane"}),n=t.createDiv({cls:"mdbase-pane-header"});n.createEl("h2",{text:"Types"});let i=this.ctx.iconButton(n,"download","Browse ready-made types");i.disabled=this.ctx.busy||this.ctx.schema?.config.spec_version.startsWith("0.2.")===!0||this.ctx.host.getMirrorProfile()!==null,i.onclick=()=>void this.ctx.perform(()=>this.ctx.host.openContractCatalog());let s=this.ctx.schema?.config.spec_version.startsWith("0.2.")??!0?"Migrate to v0.3 to create types":this.ctx.host.getMirrorProfile()?.mode==="read_only"?"Read-only mirror":"",o=this.ctx.iconButton(n,"plus",s?`Create type \xB7 ${s}`:"Create type");o.disabled=!!s,o.onclick=()=>void this.createType();let a=t.createEl("input",{type:"search"});a.addClass("mdbase-type-search"),a.placeholder="Search types",a.setAttr("aria-label","Search types"),a.setAttr("data-focus-key","type-search"),a.value=this.query,a.oninput=()=>{this.query=a.value,this.ctx.render();let f=this.ctx.containerEl.querySelector(".mdbase-type-search");f?.focus(),f?.setSelectionRange(f.value.length,f.value.length)};let c=t.createDiv({cls:"mdbase-type-list"});c.setAttr("data-scroll-key","type-list");let l=this.query.trim().toLowerCase(),u=this.typeEntries().filter(f=>`${f.name} ${f.description??""} ${f.filePath}`.toLowerCase().includes(l));if(!u.length){c.createDiv({cls:"mdbase-empty-list",text:l?"No matching types.":"No type definitions."});return}let{stats:d}=this.currentStats();for(let f of u){let p=c.createEl("button",{cls:"mdbase-type-row"});f.filePath===this.selectedPath&&p.addClass("is-active"),p.setAttr("aria-current",f.filePath===this.selectedPath?"true":"false");let h=p.createDiv({cls:"mdbase-type-name-line"});if(h.createSpan({cls:"mdbase-type-name",text:f.name}),f.filePath===this.selectedPath?this.dirty:this.ctx.host.loadTypeDraft(f.filePath)!==null){let g=h.createSpan({cls:"mdbase-unsaved-dot"});g.setAttr("aria-label","Unsaved changes"),g.setAttr("title","Unsaved changes")}let y=d.get(f.name);if(this.ctx.records){let g=p.createDiv({cls:"mdbase-type-meta"}),b=y?.notes??0;g.createSpan({text:`${b.toLocaleString()} ${b===1?"note":"notes"}`}),y?.issues&&g.createSpan({cls:"mdbase-type-issues",text:`${y.issues.toLocaleString()} ${y.issues===1?"issue":"issues"}`})}p.onclick=()=>void this.selectType(f.filePath)}}renderTypeEditor(e){let t=e.createDiv({cls:"mdbase-type-editor-pane"});if(t.setAttr("data-scroll-key","type-editor"),!this.model){t.createDiv({cls:"mdbase-empty-state"}).createEl("p",{text:"Select a type"});return}let n=this.ctx.host.getMirrorProfile()?.mode==="read_only",i=this.model.specProfile==="v0.2"||n||!!this.model.readOnlyReason,s=this.model.readOnlyReason??(n?"Read-only mirror. Reconnect with write access to edit.":"Migrate this v0.2 collection to edit types."),o=t.createDiv({cls:"mdbase-editor-header"}),a=this.ctx.iconButton(o,"arrow-left","Back to type list");a.addClass("mdbase-mobile-back"),a.onclick=()=>void this.leaveCurrentType().then(()=>{this.selectedPath=null,this.model=null,this.originalModel=null,this.ctx.render()});let c=o.createDiv({cls:"mdbase-editor-heading"});c.createDiv({cls:"mdbase-editor-title-line"}).createEl("h2",{text:this.model.name||"Untitled type"}),c.createDiv({cls:"mdbase-editor-path",text:this.selectedPath??"New type"});let u=o.createDiv({cls:"mdbase-editor-actions"});if(this.selectedPath){let p=this.selectedPath,h=this.ctx.iconButton(u,"file-code","Open source");h.onclick=()=>void this.ctx.host.openFileByPath(p)}if(this.selectedPath){let p=this.model.name,h=u.createEl("button",{text:"New note"});h.disabled=i||this.ctx.busy,h.onclick=()=>void this.ctx.host.createNoteFromType(p),this.renderStaleDrafts(t)}i&&t.createDiv({cls:"mdbase-readonly-note",text:s});let d=t.createDiv({cls:"mdbase-mode-switch"});d.setAttr("role","tablist");for(let[p,h]of[["design","Design"],["yaml","YAML"]]){let m=d.createEl("button",{text:h});m.id=`mdbase-mode-${p}`,m.setAttr("role","tab"),m.setAttr("aria-selected",String(this.editorMode===p)),this.editorMode===p&&m.addClass("is-active"),m.onclick=()=>this.switchEditorMode(p)}let f=t.createDiv({cls:"mdbase-editor-document"});f.setAttr("data-scroll-key","type-document"),this.editorMode==="design"?this.renderDesignEditor(f,this.model,i):this.renderYamlEditor(f,i),this.dirty&&!i&&this.renderDraftBar(t,this.model)}renderStaleDrafts(e){if(!this.selectedPath||!this.originalModel)return;let t=this.selectedPath,n=this.ctx.host.loadTypeDraft(t),i=[...this.ctx.host.getArchivedTypeDrafts(t),...n&&n.sourceRevision!==(this.originalModel.sourceRevision??null)?[n]:[]];for(let s of i){let o=e.createDiv({cls:"mdbase-recovery-card"});o.createDiv({text:`An older draft from ${new Date(s.updatedAt).toLocaleString()} is available. The source changed; it will not be applied automatically.`});let a=o.createEl("button",{text:"Compare draft"});a.onclick=()=>{let u=new Qe.Modal(this.ctx.app);u.titleEl.setText("Current source and recovered draft");let d=s.yamlDraft;if(d===void 0)try{d=mt(Ea(s.model),s.model.body)}catch{d=JSON.stringify(s.model,null,2)}u.contentEl.createEl("h3",{text:"Current source"}),u.contentEl.createEl("pre",{text:this.originalModel?mt(Ea(this.originalModel),this.originalModel.body):this.yamlDraft}),u.contentEl.createEl("h3",{text:"Recovered draft (read-only)"}),u.contentEl.createEl("pre",{text:d}),u.contentEl.createEl("p",{text:"Copy the parts you want into the current definition, then review before saving."}),u.open()};let c=o.createEl("button",{text:"Export draft"});c.onclick=()=>void this.ctx.perform(async()=>{let u="mdbase-draft-recovery";this.ctx.app.vault.getAbstractFileByPath(u)||await this.ctx.app.vault.createFolder(u);let d=await this.ctx.app.vault.create(`${u}/draft-${crypto.randomUUID()}.txt`,s.yamlDraft??JSON.stringify(s.model,null,2));this.ctx.message=`Exported recovery draft to ${d.path}. The original draft is still retained.`});let l=o.createEl("button",{text:"Discard old draft"});l.onclick=()=>{let u=new Qe.Modal(this.ctx.app);u.titleEl.setText("Discard this recovered draft?"),u.contentEl.createEl("p",{text:"This removes the saved recovery copy, not the current source or your current edits. Export it first if you might need it."}),u.contentEl.createEl("button",{text:"Cancel"}).onclick=()=>u.close(),u.contentEl.createEl("button",{text:"Discard old draft",cls:"mod-warning"}).onclick=()=>{u.close(),this.ctx.perform(async()=>{s===n?await this.ctx.host.clearTypeDraft(t):await this.ctx.host.discardArchivedTypeDraft(s)})},u.open()}}}renderDraftBar(e,t){let n=_a(this.originalModel,t),s=wa(t,{knownTypes:this.typeEntries().map(m=>m.name),contracts:this.ctx.schema?.contracts.values()}).filter(m=>m.severity==="error").length,o=n.filter(m=>m.risk==="high").length,a=this.newlyFailing(),c=this.editorMode==="yaml"?this.yamlProblems().filter(m=>m.severity==="error").length:0,l=e.createDiv({cls:"mdbase-draft-bar"}),u=l.createDiv({cls:"mdbase-draft-summary"}),d=this.editorMode==="yaml"?c:s;u.setAttr("data-tone",d?"error":a||o?"warning":"normal"),u.createSpan({text:d?`${d} ${d===1?"error":"errors"}`:a?`${a} ${a===1?"note":"notes"} would fail`:o?`${o} high-impact ${o===1?"change":"changes"}`:"Unsaved changes"});let f=l.createDiv({cls:"mdbase-actions"});if(this.editorMode==="design"){let m=f.createEl("button",{text:"Review"});m.onclick=()=>{let g=this.ctx.containerEl.querySelector("#mdbase-section-review")?.closest("details");g&&(g.open=!0),this.ctx.render(),this.ctx.containerEl.querySelector("#mdbase-section-review")?.scrollIntoView({block:"nearest"})}}let p=f.createEl("button",{text:"Discard"});p.onclick=()=>void this.discardCurrentType();let h=f.createEl("button",{text:"Save"});h.addClass("mod-cta"),h.disabled=(this.editorMode==="design"?s>0:c>0)||this.ctx.busy,h.onclick=()=>void this.saveCurrentType()}newlyFailing(){return!this.dirty||!this.impact||"error"in this.impact?0:this.impact.impact.failing.filter(e=>e.isNew).length}matchingLabel(){let e=this.impact&&!("error"in this.impact)?this.impact.impact.matched.length:this.savedTypeName()?this.currentStats().stats.get(this.savedTypeName()??"")?.notes:void 0;return e===void 0||!this.ctx.records?"Matching":`Matching \xB7 ${e.toLocaleString()} ${e===1?"note":"notes"}`}savedTypeName(){return!this.selectedPath||!this.ctx.schema?null:[...this.ctx.schema.types.values()].find(e=>e.filePath===this.selectedPath)?.name??null}fillMatchPreview(e){let t=this.impact,n,i=[],s=[];if(t&&!("error"in t))({matched:n,added:i,removed:s}=t.impact);else{let d=this.savedTypeName();if(!this.ctx.records||!d||t&&"error"in t&&this.dirty){e.createDiv({cls:"mdbase-muted",text:this.ctx.records?t&&"error"in t?"Fix errors to preview matching notes.":"Save the type to preview matching notes.":"Counting notes\u2026"});return}n=[...this.currentStats().recordTypes].filter(([,f])=>f.includes(d)).map(([f])=>f)}let o=e.createDiv({cls:"mdbase-match-summary"});o.createSpan({text:`${n.length.toLocaleString()} ${n.length===1?"note matches":"notes match"}`}),i.length&&o.createSpan({cls:"mdbase-match-added",text:`${i.length} added`}),s.length&&o.createSpan({cls:"mdbase-match-removed",text:`${s.length} no longer match`});let a=new Set(i),c=[...i.map(d=>({path:d,change:"added"})),...s.map(d=>({path:d,change:"removed"})),...n.filter(d=>!a.has(d)).map(d=>({path:d,change:null}))];if(!c.length)return;let l=this.showAllMatches?200:5,u=e.createDiv({cls:"mdbase-match-list"});for(let d of c.slice(0,l)){let f=u.createEl("button",{cls:"mdbase-match-row"});d.change&&(f.setAttr("data-change",d.change),f.createSpan({cls:"mdbase-match-marker",text:d.change==="added"?"+":"\u2212",attr:{"aria-label":d.change==="added"?"Added":"No longer matches"}})),f.createSpan({text:d.path}),f.setAttr("title",`Open ${d.path}`),f.onclick=()=>void this.ctx.host.openFileByPath(d.path)}if(c.length>5){let d=e.createEl("button",{cls:"mdbase-link-button",text:this.showAllMatches?"Show fewer":c.length>200?`Show 200 of ${c.length.toLocaleString()}`:`Show all ${c.length.toLocaleString()}`});d.onclick=()=>{this.showAllMatches=!this.showAllMatches,e.empty(),this.fillMatchPreview(e)}}}fillImpact(e){let t=this.impact;if(!t){e.createDiv({cls:"mdbase-muted",text:this.ctx.records?"Checking notes\u2026":"Counting notes\u2026"});return}if("error"in t){e.createDiv({cls:"mdbase-muted",text:"Fix errors to check existing notes."});return}let{impact:n}=t,i=n.failing.filter(l=>l.isNew),s=n.failing.length-i.length,o=e.createDiv({cls:"mdbase-impact-heading"});o.setAttr("data-tone",i.length?"warning":"normal"),o.createEl("strong",{text:i.length?`${i.length} ${i.length===1?"note":"notes"} would fail`:"No notes newly fail"});let a=[`${n.matched.length.toLocaleString()} ${n.matched.length===1?"note":"notes"} checked`];if(n.fixed&&a.push(`${n.fixed} fixed`),s&&a.push(`${s} already failing`),o.createSpan({cls:"mdbase-muted",text:a.join(" \xB7 ")}),!i.length)return;let c=e.createDiv({cls:"mdbase-impact-list"});for(let l of i.slice(0,10)){let u=c.createDiv({cls:"mdbase-impact-row"}),d=u.createEl("button",{cls:"mdbase-link-button",text:l.path});d.onclick=()=>void this.ctx.host.openFileByPath(l.path,l.issues[0]?.field),u.createSpan({cls:"mdbase-muted",text:`${l.issues[0]?.message??""}${l.issues.length>1?` \xB7 +${l.issues.length-1} more`:""}`})}i.length>10&&c.createDiv({cls:"mdbase-muted",text:`${i.length-10} more notes`})}renderDesignEditor(e,t,n){let i=wa(t,{knownTypes:this.typeEntries().map(T=>T.name),contracts:this.ctx.schema?.contracts.values()}),s=e.createEl("section",{cls:"mdbase-editor-section"});s.id="mdbase-section-identity";let o=Tt(s,"Name",t.name,T=>{t.name=T,this.markDirty()});o.disabled=n;let a=Tt(s,"Description",t.description,T=>{t.description=T,this.markDirty()},{multiline:!0});a.disabled=n;let c=this.ctx.disclosure(e,"type-options","Options"),l=c.createDiv({cls:"mdbase-form-row"}),u=l.createEl("label",{text:"Display field"}),d=l.createEl("select");u.htmlFor=d.id="mdbase-display-field",d.createEl("option",{value:"",text:"Use the file name"});for(let T of t.fields)d.createEl("option",{value:T.name,text:T.name||"Unnamed field"});t.displayNameKey&&!t.fields.some(T=>T.name===t.displayNameKey)&&d.createEl("option",{value:t.displayNameKey,text:`${t.displayNameKey} \xB7 missing`}),d.value=t.displayNameKey,d.onchange=()=>{t.displayNameKey=d.value,this.markDirty()},d.disabled=n;let f=c.createEl("label",{cls:"mdbase-checkbox-row"}),p=f.createEl("input",{type:"checkbox"});p.checked=t.strictMode===!0,p.disabled=n,p.onchange=()=>{t.strictMode=p.checked,this.markDirty()},f.createSpan({text:"Reject undeclared fields"});let h=this.ctx.disclosure(e,"type-matching",this.matchingLabel());h.id="mdbase-section-membership",this.fillMatchPreview(h.createDiv({cls:"mdbase-match-preview"}));let m=Tt(h,"Path glob",t.matchPathGlob,T=>{t.matchPathGlob=T,this.markDirty()},{placeholder:"Projects/**/*.md"});m.disabled=n;let y=Tt(h,"Fields present",t.matchFieldsPresent,T=>{t.matchFieldsPresent=T,this.markDirty()},{description:"Comma-separated frontmatter keys."});y.disabled=n;let g=Tt(h,"Where",t.matchWhere,T=>{t.matchWhere=T,this.markDirty()},{multiline:!0,description:"YAML predicate, including contains and nested equality conditions.",placeholder:`tags: - contains: task`});g.disabled=n;let b=e.createEl("section",{cls:"mdbase-editor-section"});b.id="mdbase-section-fields";let v=b.createDiv({cls:"mdbase-section-header"});v.createEl("h3",{text:"Fields"});let S=v.createDiv({cls:"mdbase-section-actions"});if(this.expandedFields.size){let T=this.ctx.iconButton(S,"fold-vertical","Collapse all fields");T.onclick=()=>{this.expandedFields.clear(),this.ctx.render()}}let _=this.ctx.iconButton(S,"plus","Add field");if(_.disabled=n,_.onclick=()=>{let T={type:"string"};t.fields.push({name:"",definition:T}),this.expandedFields.add(this.fieldId(T)),this.markDirty(!0)},t.fields.length>6||this.fieldQuery){let P=b.createDiv({cls:"mdbase-field-toolbar"}).createDiv({cls:"mdbase-field-toolbar-actions"}).createEl("input",{type:"search"});P.placeholder="Filter fields",P.setAttr("aria-label","Filter fields"),P.setAttr("data-focus-key","field-search"),P.value=this.fieldQuery,P.oninput=()=>{this.fieldQuery=P.value,this.ctx.render()}}let E=b.createDiv({cls:"mdbase-fields"}),k=this.fieldQuery.trim().toLowerCase(),$=t.fields.filter(T=>!k||this.fieldMatches(T.name,T.definition,k));for(let T of $){let V=t.fields.indexOf(T);this.renderFieldRow(E,T,V,n)}$.length||E.createDiv({cls:"mdbase-empty-list",text:t.fields.length?"No fields match this filter.":"No fields declared."}),h.parentElement&&e.appendChild(h.parentElement),c.parentElement&&e.appendChild(c.parentElement);let x=Tt(c,"Path pattern",t.pathPattern,T=>{t.pathPattern=T,this.markDirty()},{placeholder:"Notes/{title}.md"});if(x.disabled=n,this.renderContractEditor(e,t,n),!this.dirty&&!i.length)return;let q=this.ctx.disclosure(e,"type-review","Changes",i.some(T=>T.severity==="error"));if(q.id="mdbase-section-review",this.dirty&&this.fillImpact(q.createDiv({cls:"mdbase-impact"})),i.length){let T=q.createDiv({cls:"mdbase-diagnostic-summary"}),V=i.filter(C=>C.severity==="error").length,P=i.length-V;T.createEl("strong",{text:`${V} ${V===1?"error":"errors"} \xB7 ${P} ${P===1?"warning":"warnings"}`});for(let C of i.slice(0,12)){let Be=T.createDiv({cls:"mdbase-diagnostic-item"});Be.setAttr("data-severity",C.severity),Be.createEl("code",{text:C.path}),Be.createSpan({text:C.message})}}if(this.dirty){let T=q.createEl("ul");for(let V of _a(this.originalModel,t))T.createEl("li",{text:V.summary}).setAttr("data-risk",V.risk)}}renderContractEditor(e,t,n){let i=this.ctx.disclosure(e,"type-applications","Applications");i.addClass("mdbase-contracts-section"),i.id="mdbase-section-applications";let s=[...this.ctx.schema?.contracts.values()??[]],o=new Set(t.implementations.map(c=>`${c.contract}@${c.version}`)),a=s.filter(c=>!o.has(Ms(c)));s.length||i.createDiv({cls:"mdbase-contract-empty",text:"No application contracts installed."});for(let c of t.implementations){let l=s.find(u=>u.id===c.contract&&u.version===c.version);this.renderContractImplementation(i,t,c,l,n)}if(a.length){let c=i.createDiv({cls:"mdbase-contract-add"}),l=c.createEl("label",{text:"Installed contract"}),u=c.createEl("select");l.htmlFor=u.id=`mdbase-contract-${Math.random().toString(36).slice(2)}`;for(let f of a)u.createEl("option",{value:Ms(f),text:`${f.id} \xB7 ${f.version}`});let d=c.createEl("button",{text:"Add contract"});d.disabled=n,d.onclick=()=>{let f=a.find(p=>Ms(p)===u.value);if(f)try{fx(t,f),this.markDirty(!0)}catch(p){new Qe.Notice(p instanceof Error?p.message:String(p))}}}}renderContractImplementation(e,t,n,i,s){let o=e.createEl("article",{cls:"mdbase-contract-implementation"}),a=o.createDiv({cls:"mdbase-contract-header"}),c=a.createDiv();c.createEl("strong",{text:n.contract}),c.createSpan({cls:"mdbase-contract-version",text:n.version});let l=a.createEl("button",{text:"Remove"});if(l.disabled=s,l.onclick=()=>{px(t,n.contract,n.version),this.markDirty(!0)},!i){o.createDiv({cls:"mdbase-contract-unavailable",text:"This exact contract is not installed in the collection. Restore it or remove this implementation before saving."});return}let u=ya(i),d=ga(t),f=u.filter(b=>Ts(n,b)),p=u.filter(b=>b.required),h=p.filter(b=>Ts(n,b)).length,m=o.createEl("details");m.open=hx.reference===v),_=ba(b,S),E=g.createDiv({cls:`mdbase-contract-mapping-row ${_.level}`}),k=E.createDiv({cls:"mdbase-contract-field-definition"});k.createEl("code",{text:b.reference}),k.createSpan({cls:b.required?"mdbase-contract-required":"mdbase-contract-optional",text:b.required?"Required":"Optional"}),k.createEl("small",{text:b.description||mx(b.schema)});let $=E.createEl("select");$.setAttr("aria-label",`${n.contract} ${b.reference} source field`),$.setAttr("aria-invalid",_.level==="error"?"true":"false"),$.disabled=s,$.createEl("option",{value:"",text:b.required?"Choose a source field":"Not exposed"});for(let x of d){let q=ba(b,x),T=$.createEl("option",{value:x.reference,text:`${x.reference} \xB7 ${x.type}${q.level==="warning"?" \xB7 review":""}`});T.disabled=q.level==="error"}$.value=v,$.onchange=()=>{hx(n,b.reference,$.value||void 0),this.markDirty(!0)};let M=E.createDiv({cls:"mdbase-contract-mapping-status"});M.createEl("strong",{text:_.label}),M.createEl("small",{text:_.message})}if(i.binding_schema){let b=o.createEl("details",{cls:"mdbase-contract-settings"});b.open=!!n.binding;let v=b.createEl("summary");v.createSpan({text:"Contract settings"}),v.createSpan({cls:"mdbase-contract-summary",text:n.binding?"Configured":"Optional"});let S=b.createDiv({cls:"mdbase-contract-settings-body"});if(S.createEl("p",{cls:"mdbase-form-description",text:"Control how compatible applications interpret this type. Values follow the contract's schema."}),n.binding)this.renderContractSchemaValue(S,i.binding_schema,n.binding,_=>{Se(_)&&(zm(n,_),this.markDirty())},"Settings",s);else{let _=S.createEl("button",{text:"Configure settings"});_.disabled=s,_.onclick=()=>{let E=va(i.binding_schema);Se(E)&&(zm(n,E),this.markDirty(!0))}}}}renderContractSchemaValue(e,t,n,i,s,o){if(jn(t)==="object"){let c=Se(n)?n:{},l=e.createEl("fieldset",{cls:"mdbase-contract-schema-object"});l.createEl("legend",{text:s});let u=Se(t.properties)?t.properties:{},d=new Set(Array.isArray(t.required)?t.required.map(String):[]),f=[...new Set([...d,...Object.keys(c).filter(h=>h in u)])];for(let h of f){let m=u[h];if(!Se(m))continue;let y=l.createDiv({cls:"mdbase-contract-schema-field"}),g=typeof m.description=="string"?m.description:void 0;y.createEl("label",{text:`${h}${d.has(h)?" \xB7 required":""}`}),g&&y.createEl("small",{text:g}),this.renderContractSchemaControl(y,m,c[h],b=>{i({...c,[h]:b})},h,o)}f.length||l.createDiv({cls:"mdbase-empty-list",text:"No settings declared."});let p=Object.keys(u).filter(h=>!f.includes(h));if(p.length){let h=l.createDiv({cls:"mdbase-contract-schema-add"}),m=h.createEl("select");for(let g of p)m.createEl("option",{value:g,text:g});let y=h.createEl("button",{text:"Add optional setting"});y.disabled=o,y.onclick=()=>{let g=m.value,b=u[g];Se(b)&&i({...c,[g]:va(b)})}}return}this.renderContractSchemaControl(e,t,n,i,s,o)}renderContractSchemaControl(e,t,n,i,s,o){let a=jn(t);if(Array.isArray(t.enum)){let l=e.createEl("select");l.setAttr("aria-label",s);for(let u of t.enum)l.createEl("option",{value:JSON.stringify(u),text:String(u)});l.value=JSON.stringify(n),l.disabled=o,l.onchange=()=>i(JSON.parse(l.value));return}if(a==="array"){let l=Se(t.items)?t.items:{type:"string"},u=Array.isArray(n)?n:[],d=e.createDiv({cls:"mdbase-contract-schema-array"});for(let[p,h]of u.entries()){let m=d.createDiv({cls:"mdbase-contract-schema-array-item"});m.createSpan({text:`${p+1}.`}),this.renderContractSchemaControl(m,l,h,g=>{i(u.map((b,v)=>v===p?g:b))},`${s} item ${p+1}`,o);let y=m.createEl("button",{text:"Remove"});y.disabled=o||u.length<=(typeof t.minItems=="number"?t.minItems:0),y.onclick=()=>i(u.filter((g,b)=>b!==p))}let f=e.createEl("button",{text:`Add ${s.toLowerCase()} item`});f.disabled=o||typeof t.maxItems=="number"&&u.length>=t.maxItems,f.onclick=()=>i([...u,va(l)]);return}if(a==="object"){this.renderContractSchemaValue(e,t,n,i,s,o);return}if(a==="boolean"){let l=e.createEl("input",{type:"checkbox"});l.checked=n===!0,l.disabled=o,l.setAttr("aria-label",s),l.onchange=()=>i(l.checked);return}let c=e.createEl("input",{type:a==="number"||a==="integer"?"number":"text"});c.setAttr("aria-label",s),c.value=n==null?"":typeof n=="string"?n:typeof n=="number"||typeof n=="boolean"?String(n):"",c.disabled=o,c.oninput=()=>i(a==="number"||a==="integer"?Number(c.value):c.value)}renderFieldRow(e,t,n,i){let s=this.model?.fields??[];this.renderFieldDefinition(e,t.definition,{name:t.name,nameLabel:`Field ${n+1} name`,onNameInput:o=>{t.name=o,this.markDirty()},required:t.definition.required===!0,onRequiredChange:o=>{t.definition.required=o,this.markDirty()},onRemove:()=>{this.model?.fields.splice(n,1),this.markDirty(!0)},onMove:o=>{let a=n+o;a<0||a>=s.length||([s[n],s[a]]=[s[a],s[n]],this.pendingFieldReveal=this.fieldId(t.definition),this.markDirty(!0))},canMoveUp:n>0,canMoveDown:n{i.open?this.expandedFields.add(s):this.expandedFields.delete(s)};let a=n.name||n.staticLabel||"Unnamed field",c=i.createEl("summary",{cls:"mdbase-field-summary"});c.setAttr("data-focus-key",`field-${s}-summary`);let l=c.createSpan({cls:"mdbase-field-chevron"});l.setAttr("aria-hidden","true"),(0,Qe.setIcon)(l,"chevron-right"),c.createSpan({cls:"mdbase-field-summary-name",text:a}),c.createSpan({cls:"mdbase-field-summary-type",text:Qm($a(t))});let u=c.createSpan({cls:"mdbase-field-summary-rules"}),d=()=>{u.textContent=Fx(t).join(" \xB7 ")};d(),n.required&&c.createSpan({cls:"mdbase-field-summary-rule",text:"Required"}),n.onMove&&!n.readOnly&&c.addEventListener("keydown",y=>{!y.altKey||y.key!=="ArrowUp"&&y.key!=="ArrowDown"||(y.preventDefault(),y.key==="ArrowUp"&&n.canMoveUp&&n.onMove?.(-1),y.key==="ArrowDown"&&n.canMoveDown&&n.onMove?.(1))});let f=i.createDiv({cls:"mdbase-field-row"});if(n.staticLabel)f.createDiv({cls:"mdbase-field-role",text:n.staticLabel});else{let y=f.createEl("input",{type:"text",cls:"mdbase-field-name-control"});y.setAttr("data-focus-key",`field-${s}-name`),y.setAttr("aria-label",n.nameLabel),y.placeholder="Field name",y.value=n.name??"",y.disabled=n.readOnly,n.onNameInput&&(y.oninput=()=>n.onNameInput?.(y.value)),n.onNameCommit&&(y.onchange=()=>n.onNameCommit?.(y.value,y))}let p=f.createEl("select",{cls:"mdbase-field-type-control"});p.setAttr("data-focus-key",`field-${s}-type`),p.setAttr("aria-label",`${n.name||n.staticLabel||"Field"} type`);for(let y of Ax)p.createEl("option",{value:y,text:Qm(y)});p.value=$a(t),p.disabled=n.readOnly,p.onchange=()=>{t.type=p.value,p.value==="list"&&!Se(t.items)&&(t.items={type:"string"}),p.value==="object"&&!Se(t.fields)&&(t.fields={}),p.value==="enum"&&!Array.isArray(t.values)&&(t.values=[]),p.value!=="integer"&&p.value!=="number"&&(delete t.min,delete t.max),p.value!=="string"&&delete t.pattern,["string","list"].includes(p.value)||(delete t.min_length,delete t.max_length),delete t.default,this.markDirty(!0)};let h=f.createEl("input",{type:"text",cls:"mdbase-field-description-control"});if(h.setAttr("data-focus-key",`field-${s}-description`),h.setAttr("aria-label",`${n.name||n.staticLabel||"Field"} description`),h.placeholder="Description",h.value=typeof t.description=="string"?t.description:"",h.disabled=n.readOnly,h.oninput=()=>{h.value?t.description=h.value:delete t.description,this.markDirty()},n.onRequiredChange){let y=f.createEl("label",{cls:"mdbase-field-required"}),g=y.createEl("input",{type:"checkbox"});g.setAttr("data-focus-key",`field-${s}-required`),g.checked=n.required===!0,g.disabled=n.readOnly,g.onchange=()=>n.onRequiredChange?.(g.checked),y.createSpan({text:"Required"})}if(n.onRemove||n.onMove){let y=this.ctx.iconButton(f,"more-horizontal",`${a} actions`);y.addClass("mdbase-field-menu"),y.setAttr("data-focus-key",`field-${s}-menu`),y.disabled=n.readOnly,y.onclick=g=>{let b=new Qe.Menu;if(n.onMove&&(b.addItem(v=>v.setTitle("Move up").setIcon("arrow-up").setDisabled(!n.canMoveUp).onClick(()=>n.onMove?.(-1))),b.addItem(v=>v.setTitle("Move down").setIcon("arrow-down").setDisabled(!n.canMoveDown).onClick(()=>n.onMove?.(1)))),n.onRemove&&(n.onMove&&b.addSeparator(),b.addItem(v=>{v.setTitle("Remove field").setIcon("trash-2").onClick(()=>n.onRemove?.()),v.setWarning(!0)})),g.detail===0){let v=y.getBoundingClientRect();b.showAtPosition({x:v.left,y:v.bottom})}else b.showAtMouseEvent(g)}}let m=$a(t);this.renderConstraintControls(i,t,m,n,d),m==="enum"&&this.renderEnumFieldDetails(i,t,n,d),m==="link"&&this.renderLinkFieldDetails(i,t,n),m==="list"&&this.renderListFieldDetails(i,t,n),m==="object"&&this.renderObjectFieldDetails(i,t,n)}renderConstraintControls(e,t,n,i,s){let a=n==="integer"||n==="number"?[["min","Minimum"],["max","Maximum"]]:n==="string"?[["min_length","Min length"],["max_length","Max length"]]:n==="list"?[["min_length","Min items"],["max_length","Max items"]]:[],c=!["list","object","any","link"].includes(n);if(!a.length&&n!=="string"&&!c)return;let l=e.createDiv({cls:"mdbase-field-details mdbase-field-constraints"}),u=i.name||i.staticLabel||"Field",d=this.fieldId(t);for(let[g,b]of a){let v=l.createDiv({cls:"mdbase-constraint"}),S=v.createEl("label",{text:b}),_=v.createEl("input",{type:"number"});_.id=`mdbase-${d}-${g}`,S.htmlFor=_.id,_.setAttr("data-focus-key",`field-${d}-${g}`),_.setAttr("aria-label",`${u} ${b.toLowerCase()}`),(g.endsWith("length")||n==="integer")&&(_.step="1"),g.endsWith("length")&&(_.min="0"),_.value=typeof t[g]=="number"?String(t[g]):"",_.disabled=i.readOnly,_.oninput=()=>{let E=_.value.trim()===""?NaN:Number(_.value);Number.isFinite(E)?t[g]=E:delete t[g],s(),this.markDirty()}}if(n==="string"){let g=l.createDiv({cls:"mdbase-constraint mdbase-constraint-wide"}),b=g.createEl("label",{text:"Pattern"}),v=g.createEl("input",{type:"text"});v.id=`mdbase-${d}-pattern`,b.htmlFor=v.id,v.setAttr("data-focus-key",`field-${d}-pattern`),v.setAttr("aria-label",`${u} pattern`),v.placeholder="Regular expression",v.spellcheck=!1,v.value=typeof t.pattern=="string"?t.pattern:"",v.disabled=i.readOnly,v.oninput=()=>{v.value?t.pattern=v.value:delete t.pattern,s(),this.markDirty()}}if(!c)return;let f=l.createDiv({cls:"mdbase-constraint mdbase-constraint-wide"}),p=f.createEl("label",{text:"Default"}),h=`mdbase-${d}-default`;if(p.htmlFor=h,n==="enum"||n==="boolean"){let g=f.createEl("select");g.id=h,g.setAttr("data-focus-key",`field-${d}-default`),g.createEl("option",{value:"",text:"None"});let b=n==="boolean"?[!0,!1]:Array.isArray(t.values)?t.values:[];for(let[S,_]of b.entries())g.createEl("option",{value:String(S),text:sn(_)});let v=b.findIndex(S=>JSON.stringify(S)===JSON.stringify(t.default));t.default!==void 0&&v===-1?(g.createEl("option",{value:"missing",text:`${sn(t.default)} \xB7 not allowed`}),g.value="missing"):g.value=v===-1?"":String(v),g.disabled=i.readOnly,g.onchange=()=>{g.value===""?delete t.default:g.value!=="missing"&&(t.default=b[Number(g.value)]),s(),this.markDirty()};return}let m=f.createEl("input",{type:"text"});m.id=h,m.setAttr("data-focus-key",`field-${d}-default`),m.setAttr("aria-label",`${u} default`),m.placeholder=n==="date"?"YYYY-MM-DD":n==="time"?"HH:MM":"None",m.value=t.default===void 0?"":sn(t.default),m.disabled=i.readOnly;let y=f.createDiv({cls:"mdbase-constraint-error"});m.oninput=()=>{let g=qx(m.value,n);y.textContent=g.error??"",m.toggleClass("is-invalid",!!g.error),!g.error&&(g.value===void 0?delete t.default:t.default=g.value,s(),this.markDirty())}}fieldId(e){let t=this.fieldIds.get(e);if(t)return t;let n=`field-${this.nextFieldId}`;return this.nextFieldId+=1,this.fieldIds.set(e,n),n}fieldMatches(e,t,n){return`${e} ${$a(t)} ${typeof t.description=="string"?t.description:""}`.toLowerCase().includes(n)||Se(t.items)&&this.fieldMatches("item",t.items,n)?!0:Se(t.fields)?Object.entries(t.fields).some(([s,o])=>Se(o)&&this.fieldMatches(s,o,n)):!1}renderEnumFieldDetails(e,t,n,i){let s=e.createDiv({cls:"mdbase-field-details mdbase-enum-values"}),o=n.name||n.staticLabel||"Enum",a=this.fieldId(t);s.createDiv({cls:"mdbase-field-children-label",text:"Allowed values"});let c=Array.isArray(t.values)?t.values:[];!Array.isArray(t.values)&&!n.readOnly&&(t.values=c);let l=s.createDiv({cls:"mdbase-enum-list"});l.setAttr("role","list");let u=new Set(c.map(f=>typeof f)).size>1;for(let[f,p]of c.entries()){let h=l.createDiv({cls:"mdbase-enum-row"});h.setAttr("role","listitem");let m=h.createEl("input",{type:"text"});m.setAttr("data-focus-key",`field-${a}-value-${f}`),m.setAttr("aria-label",`${o} allowed value ${f+1}`),m.value=sn(p),m.disabled=n.readOnly,m.oninput=()=>{c[f]=jx(m.value,p,c.filter((g,b)=>b!==f)),i(),this.markDirty()},m.onkeydown=g=>{g.key==="Enter"&&(g.preventDefault(),c.splice(f+1,0,""),this.ctx.pendingFocusKey=`field-${a}-value-${f+1}`,this.markDirty(!0))},u&&h.createSpan({cls:"mdbase-enum-kind",text:typeof p});for(let[g,b,v]of[["arrow-up","Move value up",-1],["arrow-down","Move value down",1]]){let S=this.ctx.iconButton(h,g,`${b}: ${sn(p)}`);S.disabled=n.readOnly||f+v<0||f+v>=c.length,S.onclick=()=>{[c[f],c[f+v]]=[c[f+v],c[f]],this.markDirty(!0)}}let y=this.ctx.iconButton(h,"x",`Remove value ${sn(p)}`);y.disabled=n.readOnly,y.onclick=()=>{c.splice(f,1),this.markDirty(!0)}}let d=s.createEl("button",{cls:"mdbase-link-button",text:"Add value"});d.disabled=n.readOnly,d.onclick=()=>{c.push(""),this.ctx.pendingFocusKey=`field-${a}-value-${c.length-1}`,this.markDirty(!0)}}renderLinkFieldDetails(e,t,n){let i=e.createDiv({cls:"mdbase-field-details mdbase-field-options"}),s=this.fieldId(t),o=i.createEl("label",{text:"Target type"}),a=i.createEl("select");a.setAttr("data-focus-key",`field-${s}-target`),a.setAttr("aria-label",`${n.name||n.staticLabel||"Link"} target type`),a.createEl("option",{value:"",text:"Any type"});let c=typeof t.target=="string"?t.target:"";for(let d of this.typeEntries())a.createEl("option",{value:d.name,text:d.name});c&&!this.typeEntries().some(d=>d.name===c)&&a.createEl("option",{value:c,text:`${c} \xB7 missing`}),a.value=c,a.disabled=n.readOnly,a.onchange=()=>{a.value?t.target=a.value:delete t.target,this.markDirty()},o.htmlFor=a.id=`mdbase-${s}-target`;let l=i.createEl("label",{cls:"mdbase-field-required"}),u=l.createEl("input",{type:"checkbox"});u.setAttr("data-focus-key",`field-${s}-exists`),u.checked=t.validate_exists===!0,u.disabled=n.readOnly,u.onchange=()=>{t.validate_exists=u.checked,this.markDirty()},l.createSpan({text:"Validate target exists"})}renderListFieldDetails(e,t,n){let i=e.createDiv({cls:"mdbase-field-children"});i.createDiv({cls:"mdbase-field-children-label",text:"List items"});let s=Se(t.items)?t.items:{type:"any"};!Se(t.items)&&!n.readOnly&&(t.items=s),this.renderFieldDefinition(i,s,{staticLabel:"Item",nameLabel:"List item",readOnly:n.readOnly,depth:n.depth+1})}renderObjectFieldDetails(e,t,n){let i=e.createDiv({cls:"mdbase-field-children"});i.createDiv({cls:"mdbase-field-children-label",text:"Object fields"});let s=Se(t.fields)?t.fields:{};!Se(t.fields)&&!n.readOnly&&(t.fields=s);let o=i.createDiv({cls:"mdbase-nested-fields"}),a=i.createEl("button",{cls:"mdbase-link-button",text:"Add nested field"});a.disabled=n.readOnly,a.onclick=()=>{let l=Px(s);Sd(s,l,{type:"string"}),this.expandedFields.add(this.fieldId(s[l])),this.markDirty(!0)};let c=Object.entries(s).filter(l=>Se(l[1]));if(!c.length){o.createDiv({cls:"mdbase-empty-list",text:"No nested fields."});return}for(let[l,[u,d]]of c.entries()){let f=u;this.renderFieldDefinition(o,d,{name:f,nameLabel:`${f} nested field name`,onNameCommit:(p,h)=>{let m=p.trim();if(!m){new Qe.Notice("Nested field name is required."),h.value=f;return}if(m!==f&&Object.prototype.hasOwnProperty.call(s,m)){new Qe.Notice(`Nested field already exists: ${m}`),h.value=f;return}m!==f&&(delete s[f],Sd(s,m,d),f=m,this.markDirty())},required:d.required===!0,onRequiredChange:p=>{d.required=p,this.markDirty()},onRemove:()=>{delete s[f],this.markDirty(!0)},onMove:p=>{let h=Object.keys(s),m=h.indexOf(f),y=m+p;if(m===-1||y<0||y>=h.length)return;[h[m],h[y]]=[h[y],h[m]];let g=h.map(b=>[b,s[b]]);for(let b of h)delete s[b];for(let[b,v]of g)Se(v)&&Sd(s,b,v);this.pendingFieldReveal=this.fieldId(d),this.markDirty(!0)},canMoveUp:l>0,canMoveDown:lthis.onYamlInput(s.value)}}ensureYamlEditor(e){try{return this.yamlEditor?(this.yamlEditor.setValue(this.yamlDraft),this.yamlEditor.setReadOnly(e)):this.yamlEditor=new Ad({doc:this.yamlDraft,readOnly:e,labelledBy:"mdbase-mode-yaml",onChange:t=>this.onYamlInput(t)}),this.yamlEditor.setProblems(this.yamlProblems()),this.yamlEditor}catch(t){return console.error("mdbase: YAML editor unavailable",t),this.yamlEditor=null,null}}onYamlInput(e){this.yamlDraft=e,this.markDirty(!1),this.yamlProblemTimer!==null&&window.clearTimeout(this.yamlProblemTimer),this.yamlProblemTimer=window.setTimeout(()=>{this.yamlProblemTimer=null;let t=this.yamlProblems();this.yamlEditor?.setProblems(t);let n=this.ctx.containerEl.querySelector(".mdbase-yaml-problems");n&&(n.empty(),this.fillYamlProblems(n,t))},250)}fillYamlProblems(e,t=this.yamlProblems()){if(!(!this.dirty||!t.length))for(let n of t.slice(0,20)){let i=e.createEl("button",{cls:"mdbase-yaml-problem"});if(i.setAttr("data-severity",n.severity),i.createSpan({cls:"mdbase-yaml-problem-line-number",text:n.line?`Line ${n.line}`:"Type"}),i.createSpan({text:n.message}),i.disabled=n.line===null,n.line!==null){let s=n.line;i.onclick=()=>this.yamlEditor?.revealLine(s)}}}async leaveCurrentType(){this.dirty&&await this.flushTypeDraft(),this.yamlEditor?.destroy(),this.yamlEditor=null,this.impact=null,this.showAllMatches=!1}async selectType(e,t=!0){t&&e!==this.selectedPath&&await this.leaveCurrentType();let n=++this.typeSelectionVersion,i=await this.ctx.host.loadTypeModel(e);if(n!==this.typeSelectionVersion)return;let s=this.ctx.host.loadTypeDraft(e),o=s?.version===1&&s.sourceRevision===(i.sourceRevision??null),a=o?qn(s.model):i;this.selectedPath=e,this.model=a,this.originalModel=qn(i),this.yamlDraft=o&&s.yamlDraft!==void 0?s.yamlDraft:`${mt(Ea(i),i.body)} -`,this.dirty=!vd(this.originalModel,a),this.editorMode=o&&s.editorMode==="yaml"?"yaml":"design",this.editorMode==="yaml"&&(this.dirty=!0),o&&this.dirty?this.sessionDrafts.has(e)||(this.ctx.message=`Recovered unsaved changes for ${e}.`):s&&!o&&(this.ctx.message=`An older draft for ${e} was kept, but the source changed. The current file is shown.`),this.scheduleImpact(0),this.ctx.render()}async createType(){await this.leaveCurrentType(),this.typeSelectionVersion+=1;let e=this.ctx.host.loadTypeDraft(null),t=e?.version===1?qn(e.model):Hm();this.selectedPath=null,this.model=t,this.originalModel=null,this.yamlDraft=e?.yamlDraft??"",this.dirty=!0,e&&!this.sessionDrafts.has("__new__")&&(this.ctx.message="Recovered an unsaved new type."),this.editorMode=e?.editorMode??"design",this.scheduleImpact(0),this.ctx.render()}switchEditorMode(e){if(!(!this.model||e===this.editorMode)){if(e==="yaml")try{this.yamlDraft=`${mt(Ea(this.model),this.model.body)} +`),i=t.length>200||n.length>200,s=t.slice(0,200),o=n.slice(0,200),a=Array.from({length:s.length+1},()=>new Uint16Array(o.length+1));for(let d=s.length-1;d>=0;d-=1)for(let f=o.length-1;f>=0;f-=1)a[d][f]=s[d]===o[f]?a[d+1][f+1]+1:Math.max(a[d+1][f],a[d][f+1]);let c=[],l=0,u=0;for(;(l=300);)l=o.length||l=a[l][u+1]?(c.push({kind:"local",value:s[l]}),l+=1):(c.push({kind:"remote",value:o[u]}),u+=1);return{lines:c,truncated:i||l0&&!r.actions.some(o=>o.command!=="advance_checkpoint"))return{actionLabel:"Resolve issues",actionDisabled:!0,message:"Synchronization is paused. Resolve the blocking issues, then refresh the review."};let n=r.actions.filter(o=>o.command!=="advance_checkpoint").length,i=r.actions.some(o=>o.command==="advance_checkpoint"),s=r.issues.some(o=>o.code==="invalid_frontmatter"&&!o.blocking);return{actionLabel:n?`Sync ${n}${r.summary.blocking_issues?" available":""} ${n===1?"change":"changes"}`:i?"Confirm sync":"Up to date",actionDisabled:t||r.actions.length===0,message:r.summary.blocking_issues>0?"Sync available changes. Unresolved items are isolated and remain for the next review; they do not stop independent transfers.":s?"Frontmatter warnings do not block this sync. Document bytes are preserved; synchronization does not repair YAML.":e?"Review each transfer below, then sync when ready.":"This vault and the hosted collection are already aligned."}}function pr(r){return r<1024?`${r} B`:r<1024*1024?`${(r/1024).toFixed(r<10*1024?1:0)} KB`:r<1024*1024*1024?`${(r/(1024*1024)).toFixed(r<10*1024*1024?1:0)} MB`:`${(r/(1024*1024*1024)).toFixed(1)} GB`}function Dx(r){let{connected:e,status:t,progress:n,fileProgress:i,problem:s,validationIssues:o,localChangeObserved:a}=r,c=r.reviewChanges??0;if(!e)return o?{state:"attention",label:`mdbase: ${o} ${o===1?"issue":"issues"}`,detail:"Open validation issues",destination:"issues"}:{state:"local",label:"mdbase: Local",detail:"This vault is not connected",destination:"sync"};if(i){let u=i.totalBytes>0?Math.min(100,Math.round(i.transferredBytes/i.totalBytes*100)):100;return{state:"syncing",label:`mdbase: ${i.direction==="upload"?"Uploading":"Downloading"} ${u}%`,detail:`${i.path} \xB7 ${pr(i.transferredBytes)} of ${pr(i.totalBytes)}`,destination:"sync"}}if(n)return{state:"syncing",label:`mdbase: Syncing${n.total==null?"":` ${n.completed}/${n.total}`}`,detail:"Open synchronization progress",destination:"sync"};if(s&&s.kind!=="busy")return{state:s.kind==="paused"?"paused":s.kind==="offline"?"offline":"attention",label:s.kind==="paused"?"mdbase: Paused":s.kind==="offline"?"mdbase: Offline":s.kind==="device"?"mdbase: Set up sync":"mdbase: Needs attention",detail:s.kind==="offline"?`${s.title}. Changes will sync when it's back.`:s.title,destination:"sync"};if(c>0)return{state:"attention",label:`mdbase: Review ${c} ${c===1?"change":"changes"}`,detail:"Some changes need review before syncing",destination:"sync"};if(t?.recovery_required||t?.conflicts.length||t?.local_issues.length||["attention","blocked","failed","stale"].includes(t?.state??""))return{state:"attention",label:"mdbase: Needs attention",detail:"Review synchronization",destination:"sync"};if(t?.state==="cancelled")return{state:"paused",label:"mdbase: Paused",detail:"Review and resume synchronization",destination:"sync"};let l=t?.pending??0;return a||l>0||t?.state==="changes_waiting"||t?.state==="planned"?{state:"waiting",label:l>0?`mdbase: ${l} ${l===1?"change":"changes"}`:"mdbase: Changes waiting",detail:"Review local and hosted changes",destination:"sync"}:t?.state==="up_to_date"?{state:"synced",label:"mdbase: Synced",detail:"Local and hosted collections are aligned",destination:"sync"}:{state:"waiting",label:"mdbase: Ready to sync",detail:"Review the first synchronization",destination:"sync"}}var YF=new Set(["mirror_credentials_missing","invalid_mirror_enrollment","mirror_enrollment_expired","mirror_pairing_not_found","invalid_mirror_pairing","mirror_access_rejected","replica_revoked"]);function Rt(r){let e=QF(r);return e==="mirror_busy"?{code:e,kind:"busy",title:"Synchronization is already running",message:"The active transfer is still using this vault. Its progress is shown below.",action:"resume",actionLabel:"Show progress"}:e==="mirror_other_device"?{code:e,kind:"device",title:"Set up sync on this device",message:"This vault's sync settings came from another device or another copy of the vault, probably through a different sync service. Approve this copy to give it its own connection. Your files stay as they are.",action:"reauthorize",actionLabel:"Set up this device"}:YF.has(e)?{code:e,kind:"auth",title:"Connect approval is required again",message:"Your local files and mirror checkpoint are safe. Approve this vault again to restore access.",action:"reauthorize",actionLabel:"Sign in again"}:["operation_cancelled","cancelled","sync_cancelled","AbortError"].includes(e)?{code:e,kind:"paused",title:"Synchronization paused",message:"Completed changes are saved. Sync resumes from the same point when you continue.",action:"resume",actionLabel:"Resume sync"}:["stale","stale_mirror_plan","mirror_plan_stale","sync_plan_stale","conflict_decision_stale"].includes(e)?{code:e,kind:"decision",title:"The collection changed again",message:"No stale decision was applied. Review the newest local and hosted versions.",action:"review",actionLabel:"Review newest changes"}:["enrollment_recovery_required","mirror_recovery_required","pending_mirror_recovery"].includes(e)?{code:e,kind:"recovery",title:"Synchronization needs recovery",message:"Your original files are safe. Resume from the durable checkpoint before disconnecting this vault.",action:"resume",actionLabel:"Resume recovery"}:oa(r)?{code:e,kind:"offline",title:"Can't reach mdbase Connect",message:"Your changes are saved on this device and sync automatically when the connection returns.",action:"retry",actionLabel:"Retry now"}:{code:e,kind:"internal",title:"Sync stopped unexpectedly",message:`${ZF(r,"An unexpected error stopped synchronization.")} Your files are safe. Sync tries again automatically; if this keeps happening, copy the diagnostics and report it.`,action:"retry",actionLabel:"Try again"}}function Nx(r){return Rt(Object.assign(new Error(r.message),{code:r.code}))}function Lx(r){return Array.isArray(r)?r.filter(XF).slice(-JF):[]}function XF(r){if(!r||typeof r!="object"||Array.isArray(r))return!1;let e=r;return typeof e.id=="string"&&typeof e.occurredAt=="string"&&typeof e.summary=="string"&&(e.detail===void 0||typeof e.detail=="string")&&(e.path===void 0||typeof e.path=="string")&&["success","info","attention","error"].includes(e.tone??"")&&typeof e.requiresAcknowledgement=="boolean"}function QF(r){return r instanceof DOMException?r.name:r&&typeof r=="object"&&"code"in r&&typeof r.code=="string"?r.code:r instanceof Error&&r.name?r.name:"sync_failed"}function ZF(r,e){return r instanceof Error&&r.message?r.message:e}var xd=class{constructor(e){this.ctx=e;this.conflictComparisons=new Map;this.loadingConflictComparisons=new Set;this.pendingSyncFocus=null;this.historyQuery="";this.transferQuery="";this.transferFilter="all";this.transferPages=new Map;this.historyLimit=xa;this.previewComparisons=new Map;this.comparedPreview=null;this.loadingPreviewComparisons=new Set;this.enrollmentVerification="";this.enrollmentAbort=null;this.enrollmentControlUrl=wd;this.enrollmentMirrorName=Px(this.ctx.app.vault.getName());this.enrollmentCollectionId="";this.enrollmentMode="read_write";this.filePolicyDraft=null;this.adoptionFileProgress="";this.adoptionPreview=null;this.adoptionRenamePlan=null;this.adoptionStage="";this.adoptionFailed=!1}getState(){return{historyQuery:this.historyQuery}}setState(e){typeof e.historyQuery=="string"&&(this.historyQuery=e.historyQuery.slice(0,2e3))}get session(){return this.ctx.host.sync}dispose(){this.enrollmentAbort?.abort(),this.enrollmentAbort=null}focusSection(e){this.ctx.destination="sync",this.pendingSyncFocus=e,this.ctx.render(),window.setTimeout(()=>this.focusPendingSyncSection(),0)}async reconnectCollection(){await this.session.reconnect()==="reauthorize"&&await this.ctx.perform(()=>this.reauthorizeCollection())}render(e){let t=e.createDiv({cls:"mdbase-sync-document"}),n=this.ctx.host.getMirrorProfile();if(!n){this.renderEnrollment(t);return}let i=this.session.state,s=!!(i.fileProgress||i.progress),a=(i.problem?.kind==="busy"?null:i.problem)??(i.paused&&!s?{code:"sync_paused",kind:"paused",title:"Sync is paused",message:"Changes on this device and in Connect wait until you resume.",action:"resume",actionLabel:"Resume sync"}:i.status?.recovery_required?{code:"mirror_recovery_required",kind:"recovery",title:"Synchronization needs recovery",message:"Your original files are safe. Resume from the durable checkpoint before disconnecting this vault.",action:"resume",actionLabel:"Resume recovery"}:null),c=s?"Syncing":i.busy?"Checking\u2026":a?.kind==="paused"?"Paused":a?.kind==="offline"?"Offline":a?.kind==="auth"?"Approval needed":a?.kind==="device"?"Set up this device":a?"Needs attention":Rx(i.status),l=t.createEl("section",{cls:"mdbase-sync-status"});l.setAttr("data-state",i.status?.state??"checking");let u=l.createDiv({cls:"mdbase-sync-heading"});u.createEl("h2",{text:n.name}),u.createDiv({cls:"mdbase-muted",text:`${c} \xB7 ${Tx(i.status?.last_synced_at)}`});let d=u.createDiv({cls:"mdbase-muted mdbase-sync-scope"});d.createSpan({text:this.syncScopeText(n.mode)});let f=d.createEl("button",{cls:"mdbase-link-button",text:"Settings"});if(f.setAttr("aria-label","Open sync settings"),f.onclick=()=>this.ctx.host.openSettings(),i.message&&!i.problem){let b=l.createDiv({cls:"mdbase-inline-message mdbase-notice"});b.createSpan({text:i.message}).setAttr("role","status");let v=this.ctx.iconButton(b,"x","Dismiss sync message");v.onclick=()=>this.session.clearMessage()}if(s){let b=l.createDiv({cls:"mdbase-sync-progress",attr:{"aria-live":"polite"}}),v=i.fileProgress?.totalBytes??i.progress?.total??null,S=i.fileProgress?.transferredBytes??i.progress?.completed??0,_=b.createEl("progress");_.max=v??1,_.value=v==null?0:S,v==null&&_.removeAttribute("value"),b.createDiv({cls:"mdbase-progress-label",text:i.fileProgress?`${i.fileProgress.direction==="upload"?"Uploading":"Downloading"} ${i.fileProgress.path} \xB7 ${pr(S)} of ${pr(v??0)}`:`${i.progress?.phase==="uploading"?"Uploading local changes":i.progress?.phase==="downloading"?"Downloading collection files":"Applying changes"} \xB7 ${S}${v==null?"":` of ${v}`}`});let E=b.createEl("button",{text:"Stop"});E.onclick=()=>this.session.cancel()}let p=this.ctx.host.otherSyncServices();p.length&&l.createDiv({cls:"mdbase-inline-message mdbase-sync-coexistence",text:`${p.join(" and ")} also ${p.length===1?"syncs":"sync"} this vault. Two services syncing the same notes can duplicate them or bring deleted ones back; let only one of them sync this vault's notes.`}),a&&this.renderRecoveryCard(l,a);let m=this.ctx.busy||i.busy||s,h=i.preview;h!==this.comparedPreview&&(this.previewComparisons.clear(),this.comparedPreview=h,this.transferPages.clear());let y=this.session.safety(),g=!!(h?.plan.actions.length||h?.entries.length);if(!s&&!a){let b=l.createDiv({cls:"mdbase-sync-actions"});if(g&&h){let v=ry(h.plan,h.entries.length,m);if(h.plan.actions.length&&!v.actionDisabled){let _=b.createEl("button",{text:v.actionLabel,cls:"mod-cta"});_.disabled=v.actionDisabled,_.onclick=()=>void this.session.apply()}let S=this.ctx.iconButton(b,"refresh-cw","Refresh review");S.disabled=m,S.onclick=()=>void this.session.review()}else{let v=b.createEl("button",{text:i.busy?"Checking\u2026":"Sync now",cls:"mod-cta"});v.disabled=m,v.onclick=()=>void this.session.syncNow()}}g&&y&&!y.safe&&h?.plan.actions.length&&l.createDiv({cls:"mdbase-muted mdbase-review-reasons",text:`Review needed: ${y.reasons.join(", ").toLowerCase()}.`}),h&&g&&this.renderMirrorPreview(t,h),i.status?.conflicts.length&&this.renderConflicts(t,i.status),i.status?.local_issues.length&&!g&&this.renderLocalMirrorIssues(t,i.status),this.renderHistory(t),window.setTimeout(()=>this.focusPendingSyncSection(),0)}syncScopeText(e){let t=this.ctx.host.connectSync.getSelectiveSync().excluded_folders,n=t.length?`Whole vault except ${t.length>2?`${t.slice(0,2).join(", ")} +${t.length-2}`:t.join(", ")}`:"Whole vault";return`${e==="read_only"?"Read only":"Read and write"} \xB7 ${n}`}renderRecoveryCard(e,t){let n=e.createDiv({cls:"mdbase-recovery-card"});n.setAttr("data-kind",t.kind);let i=n.createDiv();i.createEl("strong",{text:t.title}),i.createDiv({text:t.message});let s=this.session.state.retryAt;if(s&&(t.kind==="offline"||t.kind==="internal")){let c=Math.max(0,Math.round((s-Date.now())/1e3));i.createDiv({cls:"mdbase-muted",text:c<=1?"Trying again now\u2026":c<60?`Trying again in ${c}s.`:`Trying again in ${Math.round(c/60)} min.`})}let o=n.createDiv({cls:"mdbase-recovery-actions"}),a=o.createEl("button",{text:t.actionLabel,cls:"mod-cta"});if(a.disabled=this.ctx.busy||this.session.state.busy,a.onclick=()=>{t.kind==="auth"?this.reconnectCollection():t.action==="reauthorize"?this.ctx.perform(()=>this.reauthorizeCollection()):t.action==="review"?this.session.review():this.session.syncNow()},t.kind==="internal"||t.kind==="recovery"){let c=o.createEl("button",{text:"Copy diagnostics"});c.onclick=()=>void this.ctx.host.copySyncDiagnostics()}}async reauthorizeCollection(){this.enrollmentAbort?.abort();let e=new AbortController;this.enrollmentAbort=e;try{await this.session.reauthorize({signal:e.signal,onVerification:t=>{this.enrollmentVerification=t.verificationUri,this.ctx.message="Approve this vault again in Connect. Its local files and checkpoint remain unchanged.",window.open(t.verificationUri,"_blank","noopener,noreferrer"),this.ctx.render()},onStatus:t=>{this.ctx.message=t.state==="waiting_for_approval"?"Waiting for approval in Connect\u2026":`Connect is retrying approval (attempt ${t.attempt}).`,this.ctx.render()}}),this.enrollmentVerification="",this.ctx.message=""}finally{this.enrollmentAbort===e&&(this.enrollmentAbort=null)}}renderHistory(e){let t=this.session.historyRuns();if(!t.length)return;let n=t.filter(l=>l.needsAcknowledgement),i=this.ctx.disclosure(e,"sync-activity","History",n.length>0);i.addClass("mdbase-activity"),i.id="mdbase-sync-activity";for(let l of[...n].reverse())this.renderEventRow(i,l);let s=i.createDiv({cls:"mdbase-section-header mdbase-history-controls"}),o=s.createEl("input",{type:"search"});if(o.setAttr("aria-label","Filter history by path"),o.setAttr("data-focus-key","history-search"),o.placeholder="Filter by path",o.value=this.historyQuery,o.oninput=()=>{this.historyQuery=o.value,this.historyLimit=xa,this.ctx.render()},t.length>n.length){let l=s.createEl("button",{text:"Clear history"});l.disabled=this.ctx.busy,l.onclick=()=>void this.session.clearHistory()}let a=this.historyQuery.trim().toLowerCase(),c=K$(t.filter(l=>!l.needsAcknowledgement),a).sort((l,u)=>u.finishedAt.localeCompare(l.finishedAt));if(!c.length){i.createDiv({cls:"mdbase-muted",text:a?"No synced files match.":"No completed syncs."});return}for(let l of c.slice(0,this.historyLimit))U$(l)?this.renderEventRow(i,l):this.renderHistoryRun(i,l,a!=="");if(c.length>this.historyLimit){let l=i.createEl("button",{cls:"mdbase-link-button",text:`Show ${Math.min(xa,c.length-this.historyLimit)} more`});l.setAttr("data-focus-key","history-more"),l.onclick=()=>{this.historyLimit+=xa,this.ctx.render()}}}renderHistoryRun(e,t,n){let i=e.createEl("details",{cls:"mdbase-history-run"}),s=`history-run-${t.id}`;n?i.open=!0:(i.dataset.disclosure=s,i.open=this.ctx.disclosures.get(s)??!1);let o=i.createEl("summary",{cls:"mdbase-activity-row"});o.setAttr("data-focus-key",`disclosure-${s}`);let a=t.outcome==="applied"?"success":t.outcome==="failed"?"error":"attention";o.setAttr("data-tone",a),(0,Is.setIcon)(o.createSpan(),a==="success"?"check":"circle-alert");let c=o.createDiv();c.createEl("strong",{text:H$(t)});let l=Mx[t.outcome];c.createSpan({cls:"mdbase-muted",text:l?`${ks(t.finishedAt)} \xB7 ${l}`:ks(t.finishedAt)}),t.message&&t.outcome!=="applied"&&c.createDiv({text:t.message}),(0,Is.setIcon)(o.createSpan({cls:"mdbase-history-chevron"}),"chevron-right");let u=i.createDiv({cls:"mdbase-transfer-ledger mdbase-history-files"});for(let d of t.files.slice(0,250)){let f=u.createDiv({cls:"mdbase-transfer-row"});f.setAttr("title",new Date(d.at).toLocaleString()),f.createSpan({cls:"mdbase-transfer-action",text:d.action}).setAttr("data-action",d.status==="completed"?d.action:"fix");let m=f.createDiv({cls:"mdbase-transfer-body"}),h=m.createDiv({cls:"mdbase-transfer-path"}),y=h.createSpan({cls:"mdbase-history-direction"}),g=d.direction==="download"?"Downloaded":d.direction==="upload"?"Uploaded":"Needs attention";if(y.setAttr("aria-label",g),y.setAttr("title",g),(0,Is.setIcon)(y,d.direction==="download"?"download":d.direction==="upload"?"upload":"circle-alert"),d.action!=="delete"&&this.ctx.app.vault.getAbstractFileByPath(d.path)){let b=h.createEl("button",{cls:"mdbase-link-button mdbase-transfer-open"});b.createEl("code",{text:d.path}),b.setAttr("title",`Open ${d.path}`),b.onclick=()=>void this.ctx.host.openFileByPath(d.path)}else h.createEl("code",{text:d.path});d.fromPath&&m.createDiv({cls:"mdbase-muted",text:`From ${d.fromPath}`}),d.status!=="completed"&&m.createDiv({text:d.message?`${ey(d.status)}: ${d.message}`:ey(d.status)})}t.files.length>250&&u.createDiv({cls:"mdbase-transfer-more",text:`${t.files.length-250} more files are recorded in this sync.`})}renderEventRow(e,t){let n=t.tone??"info",i=e.createDiv({cls:"mdbase-activity-row"});i.setAttr("data-tone",n),(0,Is.setIcon)(i.createSpan(),n==="success"?"check":n==="info"?"info":"circle-alert");let s=i.createDiv(),o=t.summary??"";if(t.message&&t.message!==o){let a=s.createEl("details");a.createEl("summary",{text:o}),a.createDiv({text:t.message})}else s.createEl("strong",{text:o});if(s.createSpan({cls:"mdbase-muted",text:ks(t.finishedAt)}),t.needsAcknowledgement){let a=i.createEl("button",{text:"Dismiss"});a.disabled=this.ctx.busy,a.onclick=()=>void this.session.dismissEvent(t.id)}}focusPendingSyncSection(){if(!this.pendingSyncFocus)return;let e=this.pendingSyncFocus==="activity"?"mdbase-sync-activity":"mdbase-sync-conflicts",t=this.ctx.containerEl.querySelector(`#${e}`);if(!t)return;this.pendingSyncFocus=null;let n=t.closest("details");n&&(n.open=!0),t.scrollIntoView({block:"nearest"})}filePolicy(){return this.filePolicyDraft??=JSON.parse(JSON.stringify(this.ctx.host.connectSync.getSelectiveSync())),this.filePolicyDraft}renderFilePolicyControls(e){let t=this.filePolicy(),n=e.createEl("section",{cls:"mdbase-editor-section mdbase-file-policy"});n.createEl("h3",{text:"Attachments"});let i=n.createDiv({cls:"mdbase-file-class-grid"}),s=[["image","Images"],["audio","Audio"],["video","Video"],["pdf","PDFs"],["other","Other files"]];for(let[o,a]of s){let c=i.createEl("label"),l=c.createEl("input",{type:"checkbox"});l.setAttr("data-focus-key",`file-class-${o}`),l.checked=t.file_classes.includes(o),l.onchange=()=>{t.file_classes=l.checked?[...new Set([...t.file_classes,o])]:t.file_classes.filter(u=>u!==o),this.ctx.render()},c.createSpan({text:a})}n.createDiv({cls:"mdbase-form-description",text:Sd}),n.createEl("h4",{text:"Excluded folders"}),$d(this.ctx.app,n,t.excluded_folders,o=>{t.excluded_folders=o}),t.file_classes.includes("other")&&n.createDiv({cls:"mdbase-inline-message",text:"Other files includes all remaining visible file formats."})}renderEnrollment(e){if(this.ctx.schema||this.ctx.host.connectSync.getAdoptionMarker()){this.renderLocalAdoption(e);return}let t=e.createEl("section",{cls:"mdbase-editor-section mdbase-enrollment"});if(t.createEl("h3",{text:"Copy a collection from Connect"}),t.createEl("p",{cls:"mdbase-muted",text:"Connect holds the collection; this vault syncs a copy. Choose a collection in Connect, then review the first sync."}),this.enrollmentVerification){let p=t.createDiv({cls:"mdbase-approval-link"});p.createSpan({text:"Waiting for approval \xB7 "});let m=p.createEl("a",{text:"Open Connect",href:this.enrollmentVerification});m.setAttr("target","_blank"),m.setAttr("rel","noopener noreferrer")}if(this.enrollmentAbort&&this.enrollmentVerification){let p=t.createEl("button",{text:"Stop waiting"});p.onclick=()=>this.enrollmentAbort?.abort();return}Tt(t,"Device name",this.enrollmentMirrorName,p=>{this.enrollmentMirrorName=p});let n=t.createDiv({cls:"mdbase-form-row"}),i=n.createEl("label",{text:"Access"}),s=n.createEl("select");i.htmlFor=s.id="mdbase-enrollment-access",s.createEl("option",{value:"read_write",text:"Read and write"}),s.createEl("option",{value:"read_only",text:"Read only"}),s.value=this.enrollmentMode,s.onchange=()=>{this.enrollmentMode=s.value==="read_only"?"read_only":"read_write",this.ctx.render()};let o=t.createDiv({cls:"mdbase-form-row mdbase-sync-target"});o.createEl("label",{text:"Syncs"});let a=o.createDiv({cls:"mdbase-sync-target-value"}),c=this.filePolicy().excluded_folders;a.createSpan({text:`Whole vault \u201C${this.ctx.app.vault.getName()}\u201D${c.length?` except ${c.join(", ")}`:""}`});let l=a.createEl("button",{cls:"mdbase-link-button",text:"Exclude folders"});l.onclick=()=>{this.ctx.disclosures.set("enrollment-options",!0),this.ctx.render()},t.createEl("p",{cls:"mdbase-form-description",text:this.enrollmentMode==="read_write"?"Existing notes may upload. Nothing moves until you review and sync.":"Downloads only. Existing local changes must be resolved or excluded."});let u=this.ctx.disclosure(t,"enrollment-options","Advanced");Tt(u,"Connect URL",this.enrollmentControlUrl,p=>{this.enrollmentControlUrl=p},{placeholder:wd}),Tt(u,"Collection ID",this.enrollmentCollectionId,p=>{this.enrollmentCollectionId=p},{placeholder:"Choose during approval"}),this.renderFilePolicyControls(u);let d=t.createDiv({cls:"mdbase-actions mdbase-enrollment-actions"}),f=d.createEl("button",{text:this.enrollmentAbort?"Waiting for approval\u2026":"Connect"});if(f.setAttr("title","Opens Connect in your browser to choose a collection"),f.addClass("mod-cta"),f.disabled=this.ctx.busy,f.onclick=()=>void this.ctx.perform(async()=>{this.enrollmentAbort?.abort();let p=new AbortController;this.enrollmentAbort=p;try{await this.ctx.host.connectSync.enroll({controlUrl:this.enrollmentControlUrl,mirrorName:this.enrollmentMirrorName,mode:this.enrollmentMode,selectiveSync:this.filePolicy(),...this.enrollmentCollectionId.trim()?{collectionId:this.enrollmentCollectionId.trim()}:{}},{signal:p.signal,onVerification:g=>{this.enrollmentVerification=g.verificationUri,this.ctx.message="",window.open(g.verificationUri,"_blank","noopener,noreferrer"),this.ctx.render()},onStatus:g=>{this.ctx.message=g.state==="waiting_for_approval"?"Waiting for approval in Connect\u2026":`Connect is retrying enrollment (attempt ${g.attempt}).`,this.ctx.render()}}),this.enrollmentVerification="";let m=await this.session.review(),h=m?.entries.reduce((g,b)=>g+(b.estimatedBytes??0),0)??0,y=m?.entries.length??0;this.ctx.message=`Connected. Review ${y} ${y===1?"item":"items"}${h?` \xB7 ${pr(h)}`:""} before syncing.`,this.ctx.render()}catch(m){if(!ty(m))throw m;this.enrollmentVerification="",this.ctx.message="Cancelled. No files synced."}finally{this.enrollmentAbort===p&&(this.enrollmentAbort=null)}}),this.enrollmentAbort){let p=d.createEl("button",{text:"Stop waiting"});p.onclick=()=>{this.enrollmentAbort?.abort(),this.enrollmentVerification="",this.ctx.message="Cancelled. No files synced.",this.ctx.render()}}}renderLocalAdoption(e){let t=this.ctx.host.connectSync.getAdoptionMarker(),n=t?this.ctx.host.connectSync.getAdoptionRecovery():null,i=!t||["waiting_for_approval","uploading"].includes(t.phase),s=i?this.adoptionPreview?.conflicts??[]:[],o=e.createEl("section",{cls:"mdbase-editor-section mdbase-enrollment"});o.createEl("h3",{text:"Upload to Connect"}),o.createEl("p",{cls:"mdbase-muted",text:n?n.canReset?"This upload expired and its device authorization is missing. Reset setup to start again. Your files stay local.":n.canReconnect?"Device authorization is unavailable. Reconnect to the hosted collection through Connect. This vault stays protected until approval succeeds.":`Device authorization is unavailable. Restore Obsidian's secret storage, or reset setup after ${new Date(t?.session.expiresAt??"").toLocaleString()}.`:this.ctx.busy&&this.adoptionStage?this.adoptionStage:t?t.phase==="waiting_for_approval"?"Not connected yet. Approval is pending in Connect.":t.phase==="adopted"?"Collection is hosted. Finish connecting this device.":t.phase==="activating"?"Activation outcome is pending. Resume to check it safely.":s.length||this.adoptionFailed?"Approval received. Upload stopped; this vault is not connected yet.":"Approval received. Transfer is not running; resume to continue.":"This vault holds the collection. Upload it to Connect to sync it with other devices; Connect then holds the collection and this vault syncs a copy.",attr:{role:"status","aria-live":"polite"}});let a=this.enrollmentVerification||(!n&&t?.phase==="waiting_for_approval"?t.session.verificationUri:void 0);if(a){let u=o.createDiv({cls:"mdbase-approval-link"});u.createSpan({text:"Approval page: "});let d=u.createEl("a",{text:"Open Connect",href:a});d.setAttr("target","_blank"),d.setAttr("rel","noopener noreferrer")}if(t&&(this.enrollmentControlUrl=t.session.controlUrl,this.enrollmentMirrorName=t.session.requested.mirrorName??"Obsidian"),t){let u=this.ctx.disclosure(o,"adoption-details","Details");zt(u,"Collection",t.session.requested.collectionId),zt(u,"Phase",t.phase.replace(/_/g," ")),zt(u,"Connect",t.session.controlUrl);let d=this.ctx.host.connectSync.getSelectiveSync();zt(u,"Files",d.file_classes.length?d.file_classes.join(", "):"Markdown only")}else{Tt(o,"Device name",this.enrollmentMirrorName,d=>{this.enrollmentMirrorName=d});let u=this.ctx.disclosure(o,"adoption-options","Advanced");Tt(u,"Connect URL",this.enrollmentControlUrl,d=>{this.enrollmentControlUrl=d},{placeholder:wd}),this.renderFilePolicyControls(u)}!n&&i&&(this.adoptionPreview&&o.createEl("p",{cls:"mdbase-muted",text:`${this.adoptionPreview.records.toLocaleString()} notes \xB7 ${this.adoptionPreview.files.toLocaleString()} attachments`}),s.length&&(o.createEl("h4",{text:`${s.length} filename conflicts`}),this.renderAdoptionRenameReview(o,s))),n||o.createEl("p",{cls:"mdbase-form-description",text:"Sync starts only after the upload completes."});let c=o.createDiv({cls:"mdbase-actions mdbase-enrollment-actions"});if(!n&&i){let u=c.createEl("button",{text:"Check files"});u.disabled=this.ctx.busy,u.onclick=()=>void this.ctx.perform(async()=>{this.adoptionRenamePlan=null,this.adoptionPreview=await this.ctx.host.connectSync.previewAdoption(this.filePolicy()),this.ctx.message=this.adoptionPreview.conflicts.length?"Resolve the listed filename conflicts before continuing.":"Files checked. No filename conflicts."})}if(n&&!n.canReconnect){if(n.canReset){let u=c.createEl("button",{text:"Reset setup",cls:"mod-cta"});u.disabled=this.ctx.busy,u.onclick=()=>void this.ctx.perform(async()=>{this.filePolicyDraft=this.ctx.host.connectSync.getSelectiveSync(),await this.ctx.host.connectSync.resetExpiredAdoption(),this.enrollmentVerification="",this.ctx.message="Expired setup cleared. Your files and collection identity are unchanged. Start a new upload to approve this device again.",await this.ctx.refresh(!0)})}else{let u=c.createEl("button",{text:"Check again"});u.disabled=this.ctx.busy,u.onclick=()=>this.ctx.render()}return}if(t&&!n&&!["activating","adopted"].includes(t.phase)){let u=c.createEl("button",{text:"Cancel upload"});u.disabled=this.ctx.busy,u.onclick=()=>void this.ctx.perform(async()=>{await this.ctx.host.connectSync.cancelAdoption(),this.enrollmentVerification="",this.ctx.message="Upload cancelled. The collection is still local.",await this.ctx.refresh(!0)})}if(this.enrollmentAbort){let u=c.createEl("button",{text:t?.phase==="waiting_for_approval"?"Stop waiting":"Pause upload"});u.onclick=()=>{this.enrollmentAbort?.abort(),this.ctx.message="Upload paused. Resume when ready.",this.ctx.render()}}let l=c.createEl("button",{text:n?"Reconnect collection":t?"Resume upload":"Upload to Connect"});l.addClass("mod-cta"),l.disabled=this.ctx.busy||!n&&s.length>0,l.onclick=()=>void this.ctx.perform(async()=>{this.adoptionFailed=!1,this.adoptionStage="Checking files\u2026",this.enrollmentAbort?.abort();let u=new AbortController;this.enrollmentAbort=u;let d=y=>{this.enrollmentVerification=y.verificationUri,this.adoptionStage="Waiting for approval in Connect\u2026",this.ctx.message="Approve the upload in Connect.",this.ctx.render()},f=y=>{this.ctx.message=y.state==="waiting_for_approval"?"Waiting for upload approval in Connect\u2026":`Connect is retrying (attempt ${y.attempt}).`,this.ctx.render()},p=y=>{this.adoptionStage=y.stage==="checking"?"Checking files\u2026":y.stage==="uploading"?`Approval received. Uploading ${y.records?.toLocaleString()??""} notes\u2026`:y.stage==="activating"?"Activating hosted collection. Keep this vault open\u2026":"Finishing this device's connection\u2026",this.enrollmentVerification="",this.ctx.message="",this.ctx.render()},m=(y,g,b)=>{this.adoptionFileProgress=`${y} \xB7 ${pr(g)} of ${pr(b)}`,this.adoptionStage=`Uploading ${this.adoptionFileProgress}`,this.ctx.render()},h={signal:u.signal,onVerification:d,onStatus:f,onFileProgress:m,onProgress:p};try{n?await this.ctx.host.connectSync.reconnectAdoption(h):t?await this.ctx.host.connectSync.resumeAdoption(h):await this.ctx.host.connectSync.adoptLocalCollection({controlUrl:this.enrollmentControlUrl,mirrorName:this.enrollmentMirrorName,selectiveSync:this.filePolicy()},h),this.enrollmentVerification="",this.ctx.message="Collection hosted. This vault is now connected.",await this.ctx.refresh(!0)}catch(y){if(this.ctx.host.connectSync.getAdoptionMarker()?.phase!=="waiting_for_approval"&&(this.enrollmentVerification=""),!ty(y))throw this.adoptionFailed=!0,await this.ctx.host.connectSync.previewAdoption(this.filePolicy()).then(g=>{this.adoptionPreview=g}).catch(()=>{}),y;this.ctx.message="Upload paused. Resume when ready."}finally{this.adoptionStage="",this.enrollmentAbort===u&&(this.enrollmentAbort=null)}})}renderAdoptionRenameReview(e,t){let n=this.adoptionRenamePlan;e.createEl("p",{text:n?"Keep both files with distinct names. Nothing is merged or deleted. Link updates follow your Obsidian settings.":"Names must also be distinct on case-insensitive devices. Review suggested names, or rename the files yourself."});let i=e.createEl("ul",{cls:"mdbase-adoption-conflicts"}),s=n?n.renames.map(l=>[l.from,l.to]):t;for(let l of s){let u=i.createEl("li");l.forEach((d,f)=>{f&&u.appendText(n?" \u2192 ":" \u2194 "),u.createEl("code",{text:d})})}n?.manual.length&&e.createEl("p",{text:"Collection-resource conflicts need manual review: "+n.manual.map(l=>l.join(" \u2194 ")).join("; ")});let o=e.createDiv({cls:"mdbase-actions"});if(!n){let l=o.createEl("button",{text:"Review renames\u2026"});l.disabled=this.ctx.busy,l.onclick=()=>void this.ctx.perform(async()=>{this.adoptionRenamePlan=await this.ctx.host.connectSync.planAdoptionRenames(this.filePolicy())});return}let a=o.createEl("button",{text:`Rename ${n.renames.length} ${n.renames.length===1?"file":"files"}`,cls:"mod-cta"});a.disabled=this.ctx.busy||!n.renames.length,a.onclick=()=>void this.ctx.perform(async()=>{try{let l=await this.ctx.host.connectSync.applyAdoptionRenames(n,this.filePolicy(),(u,d)=>{this.adoptionStage=`Renaming ${u} of ${d} files\u2026`,this.ctx.render()});this.ctx.message=`Renamed ${l} ${l===1?"file":"files"}. Review the file check, then resume the upload.`}finally{this.adoptionStage="",this.adoptionRenamePlan=null,await this.ctx.host.connectSync.previewAdoption(this.filePolicy()).then(l=>{this.adoptionPreview=l}).catch(()=>{})}});let c=o.createEl("button",{text:"Cancel"});c.disabled=this.ctx.busy,c.onclick=()=>{this.adoptionRenamePlan=null,this.ctx.render()}}renderMirrorPreview(e,t){let n=e.createEl("section",{cls:"mdbase-transfer-review"}),i=n.createDiv({cls:"mdbase-transfer-heading"});i.createDiv().createEl("h3",{text:t.phase==="initial"?"First sync":"Changes"});let o=t.entries.reduce((p,m)=>p+(m.estimatedBytes??0),0);i.createSpan({cls:"mdbase-transfer-total",text:t.entries.length?`${t.entries.length} ${t.entries.length===1?"item":"items"}${o?` \xB7 ${pr(o)}`:""}`:"No changes"});let a=n.createDiv({cls:"mdbase-issue-controls"}),c=a.createEl("input",{type:"search",placeholder:"Search transfer paths"});c.setAttr("aria-label","Search transfer paths"),c.setAttr("data-focus-key","transfer-search"),c.value=this.transferQuery,c.oninput=()=>{this.transferQuery=c.value,this.transferPages.clear(),this.ctx.render()};let l=a.createEl("select");l.setAttr("aria-label","Filter transfers");for(let[p,m]of[["all","All changes"],["delete","Deletes"],["replace","Replacements"],["upload","Uploads"],["download","Downloads"],["attention","Needs attention"]])l.createEl("option",{value:p,text:m});l.value=this.transferFilter,l.onchange=()=>{this.transferFilter=l.value,this.transferPages.clear(),this.ctx.render()};let u=this.transferQuery.trim().toLowerCase(),d=t.entries.filter(p=>(!u||`${p.path} ${p.detail}`.toLowerCase().includes(u))&&(this.transferFilter==="all"||p.action===this.transferFilter||p.direction===this.transferFilter));d.length||n.createDiv({cls:"mdbase-muted",text:"No changes match these filters."}),n.createDiv({cls:"mdbase-muted",text:`Showing ${d.length} of ${t.entries.length} items. Approval always applies to the entire reviewed plan, not just these filters.`});let f=[{direction:"download",title:"Downloads"},{direction:"upload",title:"Uploads"},{direction:"attention",title:"Needs attention"}];for(let p of f){let m=d.filter(_=>_.direction===p.direction);if(!m.length)continue;let h=n.createEl("section",{cls:"mdbase-transfer-group"});h.setAttr("data-direction",p.direction);let y=h.createDiv({cls:"mdbase-transfer-group-heading"}),g=y.createSpan({cls:"mdbase-transfer-group-icon"});(0,Is.setIcon)(g,p.direction==="download"?"download":p.direction==="upload"?"upload":"circle-alert"),y.createEl("h4",{text:p.title}),y.createSpan({text:String(m.length),cls:"mdbase-transfer-count"});let b=h.createDiv({cls:"mdbase-transfer-ledger"}),v=Math.min(this.transferPages.get(p.direction)??0,Math.floor((m.length-1)/250)),S=v*250;for(let _ of m.slice(S,S+250)){let E=b.createDiv({cls:"mdbase-transfer-row"});E.createSpan({cls:"mdbase-transfer-action",text:_.action}).setAttr("data-action",_.action);let $=E.createDiv({cls:"mdbase-transfer-body"}),M=$.createDiv({cls:"mdbase-transfer-path"}),x=this.ctx.app.vault.getAbstractFileByPath(_.path)?_.path:null;if(x){let T=M.createEl("button",{cls:"mdbase-link-button mdbase-transfer-open"});T.createEl("code",{text:_.path}),T.setAttr("title",`Open ${_.path}`),T.onclick=()=>void this.ctx.host.openFileByPath(x)}else M.createEl("code",{text:_.path});_.estimatedBytes!==void 0&&M.createSpan({cls:"mdbase-transfer-size",text:pr(_.estimatedBytes)}),_.direction==="attention"||["rename","replace","delete"].includes(_.action)?$.createDiv({text:_.detail}):E.setAttr("title",_.detail);let q=_.recordId;if(q&&_.kind==="document"&&_.action==="update"&&x){let T=`${q}:${_.path}`,V=this.previewComparisons.get(T),P=E.createEl("button",{text:V?"Hide":this.loadingPreviewComparisons.has(T)?"Loading\u2026":"Compare"});P.setAttr("data-focus-key",`preview-compare-${T}`),P.disabled=this.loadingPreviewComparisons.has(T),P.onclick=()=>{V?(this.previewComparisons.delete(T),this.ctx.render()):this.loadPreviewComparison(T,q,_.path)},V&&this.renderConflictComparison($,V)}}if(m.length>250){let _=b.createDiv({cls:"mdbase-actions"});_.createSpan({cls:"mdbase-muted",text:`Showing ${S+1}\u2013${Math.min(S+250,m.length)} of ${m.length}`});let E=_.createEl("button",{text:`Previous ${p.title.toLowerCase()}`});E.disabled=v===0,E.setAttr("data-focus-key",`transfer-previous-${p.direction}`),E.onclick=()=>{this.transferPages.set(p.direction,v-1),this.ctx.render()};let k=_.createEl("button",{text:`Next ${p.title.toLowerCase()}`});k.disabled=S+250>=m.length,k.setAttr("data-focus-key",`transfer-next-${p.direction}`),k.onclick=()=>{this.transferPages.set(p.direction,v+1),this.ctx.render()}}}t.collisions.length?n.createDiv({cls:"mdbase-inline-error",text:"Colliding files and related moves are left unchanged. Independent files can still sync. Move or rename the obstruction, then review again."}):t.local_issues.length&&n.createDiv({cls:"mdbase-inline-message",text:t.plan.summary.blocking_issues>0?ry(t.plan,t.entries.length).message:"These diagnostics do not block synchronization. Document bytes are preserved unchanged."})}renderConflicts(e,t){let n=e.createEl("section",{cls:"mdbase-editor-section"});n.id="mdbase-sync-conflicts",n.createEl("h3",{text:"Conflicts"});for(let i of t.conflicts){let s=n.createDiv({cls:"mdbase-conflict-row"}),o=s.createDiv({cls:"mdbase-conflict-summary"});o.createEl("strong",{text:i.path??i.object_id}),o.createDiv({text:i.message});let a=s.createDiv({cls:"mdbase-actions"}),c=`${i.object_id}:${i.decision_id}`,l=this.conflictComparisons.get(c),u=a.createEl("button",{text:l?"Hide":this.loadingConflictComparisons.has(c)?"Loading\u2026":"Resolve\u2026"});if(u.setAttr("data-focus-key",`compare-${c}`),u.disabled=this.ctx.busy||this.loadingConflictComparisons.has(c),u.onclick=()=>{if(l){this.conflictComparisons.delete(c),this.ctx.render();return}this.loadConflictComparison(i,c)},l){for(let d of["local","remote"]){let f=a.createEl("button",{text:d==="local"?"Keep local":"Use hosted"});f.disabled=this.ctx.busy,f.onclick=()=>void this.resolveMirrorConflict(i,d,!1)}if(i.path){let d=a.createEl("button",{text:"Keep both"});d.disabled=this.ctx.busy,d.onclick=()=>void this.resolveMirrorConflict(i,"remote",!0)}this.renderConflictComparison(s,l)}}}async loadPreviewComparison(e,t,n){this.loadingPreviewComparisons.add(e),this.ctx.render();try{this.previewComparisons.set(e,await this.ctx.host.connectSync.recordComparison(t,n))}catch(i){this.ctx.message=Rt(i).message}finally{this.loadingPreviewComparisons.delete(e),this.ctx.render()}}async loadConflictComparison(e,t){this.loadingConflictComparisons.add(t),this.ctx.render();try{this.conflictComparisons.set(t,await this.ctx.host.connectSync.conflictComparison(e))}catch(n){this.session.reportProblem(n).code==="conflict_decision_stale"&&await this.session.refreshStatus()}finally{this.loadingConflictComparisons.delete(t),this.ctx.render()}}renderConflictComparison(e,t){let n=e.createDiv({cls:"mdbase-conflict-comparison"});if(t.entity==="record"){let s=Ox(t.local.document??"",t.remote.document??""),o=n.createDiv({cls:"mdbase-conflict-legend"});o.createSpan({text:"\u2212 Local only",cls:"is-local"}),o.createSpan({text:"+ Hosted only",cls:"is-remote"});let a=n.createEl("pre",{cls:"mdbase-conflict-diff"});for(let c of s.lines){let l=a.createEl("div",{cls:`is-${c.kind}`});l.createSpan({text:c.kind==="local"?"\u2212":c.kind==="remote"?"+":" "}),l.createSpan({text:c.value||" "})}s.truncated&&n.createDiv({cls:"mdbase-muted",text:"Diff shortened for a responsive review. Open the local note to inspect it in full."});return}let i=n.createDiv({cls:"mdbase-conflict-sides"});this.renderConflictSide(i,"Local",t.local),this.renderConflictSide(i,"Hosted",t.remote)}renderConflictSide(e,t,n){let i=e.createDiv({cls:"mdbase-conflict-side"});if(i.createEl("h4",{text:t}),n.state==="absent"){i.createDiv({cls:"mdbase-muted",text:"File is absent in this version."});return}if(n.path&&i.createEl("code",{text:n.path}),n.size!==void 0&&i.createDiv({text:`Size: ${pr(n.size)}`}),n.modifiedAt&&i.createDiv({text:`Modified: ${new Date(n.modifiedAt).toLocaleString()}`}),n.revision&&i.createDiv({cls:"mdbase-conflict-digest",text:`Digest: ${n.revision}`}),n.resourceUrl&&n.path&&/\.(?:avif|gif|jpe?g|png|svg|webp)$/i.test(n.path)){let s=i.createEl("img",{cls:"mdbase-conflict-image-preview"});s.src=n.resourceUrl,s.alt=`${t} preview of ${n.path}`}else t==="Hosted"&&i.createDiv({cls:"mdbase-muted",text:"Hosted binary preview is materialized only after you choose it."})}async resolveMirrorConflict(e,t,n){await this.ctx.perform(async()=>{await this.session.resolveConflict(e,t,n)&&this.conflictComparisons.delete(`${e.object_id}:${e.decision_id}`)})}renderLocalMirrorIssues(e,t){let n=e.createEl("section",{cls:"mdbase-editor-section"});n.createEl("h3",{text:"Local files needing attention"}),n.createEl("p",{text:"Review these file diagnostics. The sync preview identifies which issues block synchronization; a diagnostic alone does not mean syncing is paused."});for(let i of t.local_issues){let s=n.createDiv({cls:"mdbase-conflict-row"}),o=s.createDiv();o.createEl("strong",{text:i.path}),o.createDiv({text:i.message});let c=s.createDiv({cls:"mdbase-actions"}).createEl("button",{text:"Open file"});c.disabled=this.ctx.busy,c.onclick=()=>void this.ctx.host.openFileByPath(i.path)}}async refresh(){if(!this.session.isSyncing()){if(!this.ctx.host.getMirrorProfile()){if(!this.ctx.schema||this.enrollmentAbort)return;try{this.adoptionPreview=await this.ctx.host.connectSync.previewAdoption(this.filePolicy())}catch(e){this.ctx.message=Rt(e).message}return}await this.session.refreshStatus()}}};var Qe=require("obsidian");qt();function Fx(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function Os(r){return typeof r=="number"&&Number.isFinite(r)?r:null}function ny(r,e,t=""){let n=t?` ${t}`:"";return r!==null&&e!==null?r===e?`${r}${n}`:`${r}\u2013${e}${n}`:r!==null?`\u2265 ${r}${n}`:e!==null?`\u2264 ${e}${n}`:null}function sn(r){return typeof r=="string"?r:typeof r=="number"||typeof r=="boolean"||typeof r=="bigint"?String(r):JSON.stringify(r)??""}function iy(r){let e=sn(r);return e.length>24?`${e.slice(0,23)}\u2026`:e}function jx(r){let e=typeof r.type=="string"?r.type:"any",t=[];if(e==="enum"&&Array.isArray(r.values)){let n=r.values.map(iy);t.push(n.length>3?`${n.slice(0,3).join(", ")}, +${n.length-3}`:n.join(", ")||"no values")}if(e==="integer"||e==="number"){let n=ny(Os(r.min),Os(r.max));n&&t.push(n)}if(e==="list"){let n=ny(Os(r.min_length),Os(r.max_length),"items");n&&t.push(n),Fx(r.items)&&typeof r.items.type=="string"&&t.push(`of ${r.items.type}`)}else{let n=ny(Os(r.min_length),Os(r.max_length),"chars");n&&t.push(n)}if(typeof r.pattern=="string"&&r.pattern&&t.push(`/${iy(r.pattern)}/`),e==="link"&&typeof r.target=="string"&&r.target&&t.push(`\u2192 ${r.target}`),e==="object"&&Fx(r.fields)){let n=Object.keys(r.fields).length;t.push(`${n} ${n===1?"field":"fields"}`)}return r.default!==void 0&&t.push(`default ${iy(r.default)}`),r.unique===!0&&t.push("unique"),r.deprecated===!0&&t.push("deprecated"),t}function qx(r,e,t){if(e!==void 0&&sn(e)===r)return e;let n=r.trim()!==""&&Number.isFinite(Number(r)),i=r==="true"||r==="false",s=o=>t.length>0&&t.every(a=>typeof a===o);return n&&(typeof e=="number"||typeof e!="boolean"&&s("number"))?Number(r):i&&(typeof e=="boolean"||typeof e!="number"&&s("boolean"))?r==="true":r}function Bx(r,e){if(r==="")return{};if(e==="integer"||e==="number"){let t=Number(r);return Number.isFinite(t)?e==="integer"&&!Number.isInteger(t)?{error:"Default must be a whole number."}:{value:t}:{error:"Default must be a number."}}return e==="boolean"?r==="true"?{value:!0}:r==="false"?{value:!1}:{error:"Default must be true or false."}:{value:r}}var Un=require("@codemirror/commands"),Vn=require("@codemirror/language"),Kt=require("@codemirror/state"),$t=require("@codemirror/view"),Bn=require("@lezer/highlight"),ej=Vn.StreamLanguage.define({startState:()=>({section:"start"}),copyState:r=>({...r}),token(r,e){return r.sol()&&r.match(/^---\s*$/)?(e.section=e.section==="start"?"yaml":"body","meta"):e.section==="body"?(r.skipToEnd(),null):(e.section==="start"&&(e.section="yaml"),r.eatSpace()?null:r.match("#")?(r.skipToEnd(),"comment"):r.match(/^-(?=\s|$)/)?"punctuation":r.match(/^(?:[^\s:#'"[\]{},][^:#]*?|"[^"]*"|'[^']*')(?=\s*:(?:\s|$))/)?"propertyName":r.match(/^"(?:[^"\\]|\\.)*"?/)||r.match(/^'(?:[^']|'')*'?/)?"string":r.match(/^-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?(?=[\s,\]}]|$)/)?"number":r.match(/^(?:true|false|null|~)(?=[\s,\]}]|$)/)?"atom":r.match(/^[:[\]{},|>]/)?"punctuation":(r.eatWhile(/[^\s#:,[\]{}]/),r.current()===""&&r.next(),"string"))}}),tj=Vn.HighlightStyle.define([{tag:Bn.tags.propertyName,color:"var(--text-accent)"},{tag:Bn.tags.string,color:"var(--text-normal)"},{tag:Bn.tags.number,color:"var(--color-orange)"},{tag:Bn.tags.atom,color:"var(--color-purple)"},{tag:Bn.tags.comment,color:"var(--text-faint)",fontStyle:"italic"},{tag:Bn.tags.meta,color:"var(--text-faint)"},{tag:Bn.tags.punctuation,color:"var(--text-muted)"}]),Ux=Kt.StateEffect.define(),rj=Kt.StateField.define({create:()=>$t.Decoration.none,update(r,e){let t=r.map(e.changes);for(let n of e.effects){if(!n.is(Ux))continue;let i=new Kt.RangeSetBuilder,s=[...new Set(n.value.map(o=>o.line).filter(o=>o!==null&&o>=1&&o<=e.state.doc.lines))].sort((o,a)=>o-a);for(let o of s){let a=e.state.doc.line(o),c=n.value.find(l=>l.line===o)?.severity??"error";i.add(a.from,a.from,$t.Decoration.line({class:`mdbase-yaml-problem-line is-${c}`}))}t=i.finish()}return t},provide:r=>$t.EditorView.decorations.from(r)}),Ed=class{constructor(e){this.editable=new Kt.Compartment;this.applyingExternalChange=!1;this.view=new $t.EditorView({state:Kt.EditorState.create({doc:e.doc,extensions:[(0,$t.lineNumbers)(),(0,Un.history)(),Vn.indentUnit.of(" "),Kt.EditorState.tabSize.of(2),$t.keymap.of([...Un.defaultKeymap,...Un.historyKeymap,Un.indentWithTab]),ej,(0,Vn.syntaxHighlighting)(tj),rj,$t.EditorView.lineWrapping,this.editable.of(this.editability(e.readOnly)),$t.EditorView.contentAttributes.of({"aria-labelledby":e.labelledBy,"data-focus-key":"yaml-editor",spellcheck:"false"}),$t.EditorView.updateListener.of(t=>{t.docChanged&&!this.applyingExternalChange&&e.onChange(t.state.doc.toString())})]})}),this.dom=this.view.dom,this.dom.addClass("mdbase-yaml-editor")}get value(){return this.view.state.doc.toString()}setValue(e){if(e!==this.value){this.applyingExternalChange=!0;try{this.view.dispatch({changes:{from:0,to:this.view.state.doc.length,insert:e}})}finally{this.applyingExternalChange=!1}}}setReadOnly(e){this.view.dispatch({effects:this.editable.reconfigure(this.editability(e))})}setProblems(e){this.view.dispatch({effects:Ux.of(e)})}revealLine(e){if(e<1||e>this.view.state.doc.lines)return;let t=this.view.state.doc.line(e).from;this.view.dispatch({selection:{anchor:t},scrollIntoView:!0}),this.view.focus()}destroy(){this.view.destroy()}editability(e){return[Kt.EditorState.readOnly.of(e),$t.EditorView.editable.of(!e)]}};function Vx(r,e=2){let t=r.match(/line (\d+)/i)??r.match(/\((\d+):\d+\)/);return t?Number(t[1])+e-1:null}function sy(r,e){if(!e)return null;let t=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),n=new RegExp(`^\\s*(?:-\\s+)?["']?${t}["']?\\s*:`),s=r.split(` +`).findIndex(o=>n.test(o));return s===-1?null:s+1}var Ad=class{constructor(e){this.ctx=e;this.editorMode="design";this.query="";this.selectedPath=null;this.model=null;this.originalModel=null;this.yamlDraft="";this.dirty=!1;this.migrationPlan=null;this.allowLossy=!1;this.statsCache=null;this.impact=null;this.impactVersion=0;this.impactTimer=null;this.showAllMatches=!1;this.pendingFieldReveal=null;this.sessionDrafts=new Set;this.yamlEditor=null;this.yamlProblemTimer=null;this.draftSaveTimer=null;this.fieldQuery="";this.expandedFields=new Set;this.fieldIds=new WeakMap;this.nextFieldId=1;this.typeSelectionVersion=0}async onSchemaLoaded(e,t){if(this.selectedPath&&!this.typeEntries().some(n=>n.filePath===this.selectedPath)&&(this.selectedPath=null,this.model=null,this.originalModel=null),!this.selectedPath&&this.typeEntries().length&&!Qe.Platform.isMobile&&(this.selectedPath=this.typeEntries()[0].filePath),this.selectedPath&&(!this.model||e)){if(this.dirty&&await this.flushTypeDraft(),!t())return;await this.selectType(this.selectedPath,!1)}}onRecordsLoaded(e){(e||!this.impact)&&this.scheduleImpact(0)}afterRender(e){if(!this.pendingFieldReveal)return;let t=e.querySelector(`[data-field-id="${this.pendingFieldReveal}"]`);t&&(t.scrollIntoView({block:"nearest"}),(!e.contains(e.ownerDocument.activeElement)||e.ownerDocument.activeElement===e.ownerDocument.body)&&t.querySelector("summary")?.focus({preventScroll:!0}),t.addClass("is-revealed")),this.pendingFieldReveal=null}getState(){return{selectedPath:this.selectedPath,editorMode:this.editorMode,query:this.query,fieldQuery:this.fieldQuery}}async setState(e){for(let t of["query","fieldQuery"])typeof e[t]=="string"&&(this[t]=e[t].slice(0,2e3));typeof e.selectedPath=="string"&&e.selectedPath!==this.selectedPath&&(await this.leaveCurrentType(),this.selectedPath=e.selectedPath,this.model=null,this.originalModel=null)}restoreEditorMode(e){e==="yaml"&&this.editorMode!=="yaml"&&this.switchEditorMode("yaml")}async dispose(){this.impactTimer!==null&&window.clearTimeout(this.impactTimer),this.yamlProblemTimer!==null&&window.clearTimeout(this.yamlProblemTimer),this.impactVersion++,await this.flushTypeDraft(),this.yamlEditor?.destroy(),this.yamlEditor=null}async openTypeField(e,t){this.ctx.destination="types",(e!==this.selectedPath||!this.model)&&await this.selectType(e),!(!this.model||this.selectedPath!==e)&&(t&&this.revealField(t),this.ctx.render())}revealField(e){if(!this.model)return;let t=e.split(".").filter(Boolean),n=t.shift()?.replace(/\[\]$/g,"")??"",i=this.model.fields.find(s=>s.name===n)?.definition;if(i){this.editorMode="design",this.fieldQuery="",this.expandedFields.add(this.fieldId(i));for(let s of t){let o=s.replace(/\[\]$/g,""),a=Se(i.items)?i.items:i,c=Se(a.fields)?a.fields[o]:void 0;if(!Se(c))break;a!==i&&this.expandedFields.add(this.fieldId(a)),i=c,this.expandedFields.add(this.fieldId(i))}this.pendingFieldReveal=this.fieldId(i)}}currentStats(){let e=this.ctx.host.getIssues(),t=this.ctx.schema?.types??null,n=this.statsCache;if(n&&n.records===this.ctx.records&&n.types===t&&n.issues===e)return n;let i=this.ctx.records&&this.ctx.schema?$x(this.ctx.records,this.ctx.schema.config,this.ctx.schema.types):new Map;return this.statsCache={records:this.ctx.records,types:t,issues:e,recordTypes:i,stats:xx(i,e)},this.statsCache}scheduleImpact(e=400){this.impactTimer!==null&&window.clearTimeout(this.impactTimer),this.impactTimer=window.setTimeout(()=>{this.impactTimer=null,this.computeImpact().then(t=>{t!==void 0&&(this.impact=t,this.updateImpactRegions())})},e)}async computeImpact(){let e=++this.impactVersion,t=this.editorMode==="yaml"?this.modelFromYamlDraft():null;if(t&&"error"in t)return{error:t.error};let n=t?.model??this.model;if(!n||!this.ctx.schema||!this.ctx.records||n.specProfile!=="v0.3"||n.readOnlyReason)return null;let i=this.selectedPath?[...this.ctx.schema.types.values()].find(o=>o.filePath===this.selectedPath)?.name??null:null,s=await Ex({records:this.ctx.records,config:this.ctx.schema.config,types:this.ctx.schema.types,draft:n,savedName:i,filePath:this.selectedPath,isCurrent:()=>e===this.impactVersion});return e===this.impactVersion&&s!==null?s:void 0}updateImpactRegions(){let e=this.ctx.containerEl.querySelector(".mdbase-match-preview");e&&(e.empty(),this.fillMatchPreview(e));let t=this.ctx.containerEl.querySelector("[data-disclosure='type-matching'] > summary");t&&(t.textContent=this.matchingLabel());let n=this.ctx.containerEl.querySelector(".mdbase-impact");n&&(n.empty(),this.fillImpact(n));let i=this.ctx.containerEl.querySelector(".mdbase-type-editor-pane"),s=i?.querySelector(".mdbase-draft-bar");i&&s&&this.model&&(s.remove(),this.renderDraftBar(i,this.model))}createNewType(){this.ctx.destination="types",this.createType()}async editType(e){this.ctx.destination="types",await this.selectType(e)}typeEntries(){return this.ctx.schema?[...this.ctx.schema.types.values()].sort((e,t)=>e.name.localeCompare(t.name)):[]}renderSetup(e){let t=e.createDiv({cls:"mdbase-empty-state mdbase-setup"});if(this.ctx.host.getMirrorProfile()){t.createEl("h2",{text:"Waiting for the first sync"}),t.createEl("p",{text:"Types appear here once the hosted collection has synced."});let s=t.createEl("button",{text:"Open sync",cls:"mod-cta"});s.onclick=()=>this.ctx.showDestination("sync");return}t.createEl("h2",{text:"Set up mdbase"});let n=t.createDiv({cls:"mdbase-setup-choices"}),i=(s,o,a,c)=>{let l=n.createDiv({cls:"mdbase-setup-choice"}),u=l.createDiv();u.createEl("strong",{text:s}),u.createDiv({cls:"mdbase-muted",text:o});let d=l.createEl("button",{text:s,cls:a?"mod-cta":""});d.disabled=this.ctx.busy,d.onclick=c};i("Start a collection","This vault holds the collection. You can upload it to Connect later.",!0,()=>{this.ctx.perform(async()=>{await this.ctx.host.initializeCollection(),await this.ctx.refresh(!0)})}),i("Copy from Connect","Connect holds the collection. This vault syncs a copy.",!1,()=>{this.ctx.showDestination("sync")})}render(e){if(!this.ctx.schema){this.renderSetup(e);return}if(this.ctx.schema.config.spec_version.startsWith("0.2.")&&this.renderLegacyBanner(e),!this.typeEntries().length&&!this.model){let n=e.createDiv({cls:"mdbase-empty-state"});n.createEl("h2",{text:"Add your first type"}),n.createEl("p",{text:"Install ready-made types and application contracts from mdbase-contracts, or design your own type."});let i=n.createDiv({cls:"mdbase-actions"}),s=i.createEl("button",{text:"Browse ready-made types",cls:"mod-cta"});s.disabled=this.ctx.busy||this.ctx.schema.config.spec_version.startsWith("0.2.")||this.ctx.host.getMirrorProfile()!==null,s.onclick=()=>void this.ctx.perform(()=>this.ctx.host.openContractCatalog());let o=i.createEl("button",{text:"Design a custom type"});o.disabled=this.ctx.schema.config.spec_version.startsWith("0.2.")||this.ctx.host.getMirrorProfile()?.mode==="read_only",o.onclick=()=>void this.createType();return}let t=e.createDiv({cls:"mdbase-types-layout"});this.model&&t.addClass("has-selection"),this.renderTypeList(t),this.renderTypeEditor(t)}renderLegacyBanner(e){let t=e.createDiv({cls:"mdbase-legacy-banner"}),n=t.createDiv();if(n.createEl("strong",{text:"Read-only \xB7 v0.2 collection"}),n.createEl("p",{text:"Migrate to edit types."}),!this.migrationPlan){let i=t.createEl("button",{text:"Review migration"});i.disabled=this.ctx.busy||this.ctx.host.getMirrorProfile()!==null,i.onclick=()=>void this.ctx.perform(async()=>{this.migrationPlan=await this.ctx.host.analyzeMigration(),this.ctx.render()})}this.ctx.host.getMirrorProfile()&&t.createDiv({cls:"mdbase-form-description",text:"Hosted resources must be migrated at the collection authority."}),this.migrationPlan&&this.renderMigrationReview(e,this.migrationPlan)}renderMigrationReview(e,t){let n=e.createDiv({cls:"mdbase-migration-review"}),i=n.createDiv({cls:"mdbase-section-header"});i.createEl("h3",{text:"Migration review"}),i.createSpan({cls:"mdbase-spec-badge",text:`${t.sourceVersion} \u2192 ${t.targetVersion}`});let s=n.createDiv({cls:"mdbase-status-list"});zt(s,"Files replaced",String(t.operations.length)),zt(s,"Type definitions",String(t.typeSummaries.length)),zt(s,"Record reads verified",String(t.recordsVerified)),t.recordsSkipped&&zt(s,"Records skipped",String(t.recordsSkipped)),zt(s,"Record files rewritten","0"),zt(s,"Recovery backup",t.backupLocation);let o=n.createDiv({cls:"mdbase-review-list"});t.diagnostics.length||o.createDiv({cls:"mdbase-review-ok",text:"No migration diagnostics."});for(let u of t.diagnostics.slice(0,250)){let d=o.createDiv({cls:"mdbase-review-item"});d.setAttr("data-severity",u.severity),d.createDiv({cls:"mdbase-review-code",text:`${u.severity} \xB7 ${u.path}`}),d.createDiv({text:u.message})}if(t.diagnostics.length>250&&o.createDiv({cls:"mdbase-form-description",text:`Showing 250 of ${t.diagnostics.length} diagnostics.`}),!t.applicable){let u=n.createEl("label",{cls:"mdbase-consent"}),d=u.createEl("input",{type:"checkbox"});d.checked=this.allowLossy,d.onchange=()=>{this.allowLossy=d.checked,this.ctx.render()},u.createSpan({text:"I reviewed the lossy diagnostics and want to apply this migration."})}let a=n.createDiv({cls:"mdbase-actions"}),c=a.createEl("button",{text:"Apply migration"});c.addClass("mod-warning"),c.disabled=this.ctx.busy||!t.applicable&&!this.allowLossy,c.onclick=()=>void this.ctx.perform(async()=>{await this.ctx.host.applyMigration(t,this.allowLossy),this.migrationPlan=null,this.allowLossy=!1,this.model=null,this.originalModel=null,await this.ctx.refresh(!0)});let l=a.createEl("button",{text:"Close review"});l.onclick=()=>{this.migrationPlan=null,this.ctx.render()}}renderTypeList(e){let t=e.createDiv({cls:"mdbase-type-list-pane"}),n=t.createDiv({cls:"mdbase-pane-header"});n.createEl("h2",{text:"Types"});let i=this.ctx.iconButton(n,"download","Browse ready-made types");i.disabled=this.ctx.busy||this.ctx.schema?.config.spec_version.startsWith("0.2.")===!0||this.ctx.host.getMirrorProfile()!==null,i.onclick=()=>void this.ctx.perform(()=>this.ctx.host.openContractCatalog());let s=this.ctx.schema?.config.spec_version.startsWith("0.2.")??!0?"Migrate to v0.3 to create types":this.ctx.host.getMirrorProfile()?.mode==="read_only"?"Read-only mirror":"",o=this.ctx.iconButton(n,"plus",s?`Create type \xB7 ${s}`:"Create type");o.disabled=!!s,o.onclick=()=>void this.createType();let a=t.createEl("input",{type:"search"});a.addClass("mdbase-type-search"),a.placeholder="Search types",a.setAttr("aria-label","Search types"),a.setAttr("data-focus-key","type-search"),a.value=this.query,a.oninput=()=>{this.query=a.value,this.ctx.render();let f=this.ctx.containerEl.querySelector(".mdbase-type-search");f?.focus(),f?.setSelectionRange(f.value.length,f.value.length)};let c=t.createDiv({cls:"mdbase-type-list"});c.setAttr("data-scroll-key","type-list");let l=this.query.trim().toLowerCase(),u=this.typeEntries().filter(f=>`${f.name} ${f.description??""} ${f.filePath}`.toLowerCase().includes(l));if(!u.length){c.createDiv({cls:"mdbase-empty-list",text:l?"No matching types.":"No type definitions."});return}let{stats:d}=this.currentStats();for(let f of u){let p=c.createEl("button",{cls:"mdbase-type-row"});f.filePath===this.selectedPath&&p.addClass("is-active"),p.setAttr("aria-current",f.filePath===this.selectedPath?"true":"false");let m=p.createDiv({cls:"mdbase-type-name-line"});if(m.createSpan({cls:"mdbase-type-name",text:f.name}),f.filePath===this.selectedPath?this.dirty:this.ctx.host.loadTypeDraft(f.filePath)!==null){let g=m.createSpan({cls:"mdbase-unsaved-dot"});g.setAttr("aria-label","Unsaved changes"),g.setAttr("title","Unsaved changes")}let y=d.get(f.name);if(this.ctx.records){let g=p.createDiv({cls:"mdbase-type-meta"}),b=y?.notes??0;g.createSpan({text:`${b.toLocaleString()} ${b===1?"note":"notes"}`}),y?.issues&&g.createSpan({cls:"mdbase-type-issues",text:`${y.issues.toLocaleString()} ${y.issues===1?"issue":"issues"}`})}p.onclick=()=>void this.selectType(f.filePath)}}renderTypeEditor(e){let t=e.createDiv({cls:"mdbase-type-editor-pane"});if(t.setAttr("data-scroll-key","type-editor"),!this.model){t.createDiv({cls:"mdbase-empty-state"}).createEl("p",{text:"Select a type"});return}let n=this.ctx.host.getMirrorProfile()?.mode==="read_only",i=this.model.specProfile==="v0.2"||n||!!this.model.readOnlyReason,s=this.model.readOnlyReason??(n?"Read-only mirror. Reconnect with write access to edit.":"Migrate this v0.2 collection to edit types."),o=t.createDiv({cls:"mdbase-editor-header"}),a=this.ctx.iconButton(o,"arrow-left","Back to type list");a.addClass("mdbase-mobile-back"),a.onclick=()=>void this.leaveCurrentType().then(()=>{this.selectedPath=null,this.model=null,this.originalModel=null,this.ctx.render()});let c=o.createDiv({cls:"mdbase-editor-heading"});c.createDiv({cls:"mdbase-editor-title-line"}).createEl("h2",{text:this.model.name||"Untitled type"}),c.createDiv({cls:"mdbase-editor-path",text:this.selectedPath??"New type"});let u=o.createDiv({cls:"mdbase-editor-actions"});if(this.selectedPath){let p=this.selectedPath,m=this.ctx.iconButton(u,"file-code","Open source");m.onclick=()=>void this.ctx.host.openFileByPath(p)}if(this.selectedPath){let p=this.model.name,m=u.createEl("button",{text:"New note"});m.disabled=i||this.ctx.busy,m.onclick=()=>void this.ctx.host.createNoteFromType(p),this.renderStaleDrafts(t)}i&&t.createDiv({cls:"mdbase-readonly-note",text:s});let d=t.createDiv({cls:"mdbase-mode-switch"});d.setAttr("role","tablist");for(let[p,m]of[["design","Design"],["yaml","YAML"]]){let h=d.createEl("button",{text:m});h.id=`mdbase-mode-${p}`,h.setAttr("role","tab"),h.setAttr("aria-selected",String(this.editorMode===p)),this.editorMode===p&&h.addClass("is-active"),h.onclick=()=>this.switchEditorMode(p)}let f=t.createDiv({cls:"mdbase-editor-document"});f.setAttr("data-scroll-key","type-document"),this.editorMode==="design"?this.renderDesignEditor(f,this.model,i):this.renderYamlEditor(f,i),this.dirty&&!i&&this.renderDraftBar(t,this.model)}renderStaleDrafts(e){if(!this.selectedPath||!this.originalModel)return;let t=this.selectedPath,n=this.ctx.host.loadTypeDraft(t),i=[...this.ctx.host.getArchivedTypeDrafts(t),...n&&n.sourceRevision!==(this.originalModel.sourceRevision??null)?[n]:[]];for(let s of i){let o=e.createDiv({cls:"mdbase-recovery-card"});o.createDiv({text:`An older draft from ${new Date(s.updatedAt).toLocaleString()} is available. The source changed; it will not be applied automatically.`});let a=o.createEl("button",{text:"Compare draft"});a.onclick=()=>{let u=new Qe.Modal(this.ctx.app);u.titleEl.setText("Current source and recovered draft");let d=s.yamlDraft;if(d===void 0)try{d=mt(Ea(s.model),s.model.body)}catch{d=JSON.stringify(s.model,null,2)}u.contentEl.createEl("h3",{text:"Current source"}),u.contentEl.createEl("pre",{text:this.originalModel?mt(Ea(this.originalModel),this.originalModel.body):this.yamlDraft}),u.contentEl.createEl("h3",{text:"Recovered draft (read-only)"}),u.contentEl.createEl("pre",{text:d}),u.contentEl.createEl("p",{text:"Copy the parts you want into the current definition, then review before saving."}),u.open()};let c=o.createEl("button",{text:"Export draft"});c.onclick=()=>void this.ctx.perform(async()=>{let u="mdbase-draft-recovery";this.ctx.app.vault.getAbstractFileByPath(u)||await this.ctx.app.vault.createFolder(u);let d=await this.ctx.app.vault.create(`${u}/draft-${crypto.randomUUID()}.txt`,s.yamlDraft??JSON.stringify(s.model,null,2));this.ctx.message=`Exported recovery draft to ${d.path}. The original draft is still retained.`});let l=o.createEl("button",{text:"Discard old draft"});l.onclick=()=>{let u=new Qe.Modal(this.ctx.app);u.titleEl.setText("Discard this recovered draft?"),u.contentEl.createEl("p",{text:"This removes the saved recovery copy, not the current source or your current edits. Export it first if you might need it."}),u.contentEl.createEl("button",{text:"Cancel"}).onclick=()=>u.close(),u.contentEl.createEl("button",{text:"Discard old draft",cls:"mod-warning"}).onclick=()=>{u.close(),this.ctx.perform(async()=>{s===n?await this.ctx.host.clearTypeDraft(t):await this.ctx.host.discardArchivedTypeDraft(s)})},u.open()}}}renderDraftBar(e,t){let n=_a(this.originalModel,t),s=wa(t,{knownTypes:this.typeEntries().map(h=>h.name),contracts:this.ctx.schema?.contracts.values()}).filter(h=>h.severity==="error").length,o=n.filter(h=>h.risk==="high").length,a=this.newlyFailing(),c=this.editorMode==="yaml"?this.yamlProblems().filter(h=>h.severity==="error").length:0,l=e.createDiv({cls:"mdbase-draft-bar"}),u=l.createDiv({cls:"mdbase-draft-summary"}),d=this.editorMode==="yaml"?c:s;u.setAttr("data-tone",d?"error":a||o?"warning":"normal"),u.createSpan({text:d?`${d} ${d===1?"error":"errors"}`:a?`${a} ${a===1?"note":"notes"} would fail`:o?`${o} high-impact ${o===1?"change":"changes"}`:"Unsaved changes"});let f=l.createDiv({cls:"mdbase-actions"});if(this.editorMode==="design"){let h=f.createEl("button",{text:"Review"});h.onclick=()=>{let g=this.ctx.containerEl.querySelector("#mdbase-section-review")?.closest("details");g&&(g.open=!0),this.ctx.render(),this.ctx.containerEl.querySelector("#mdbase-section-review")?.scrollIntoView({block:"nearest"})}}let p=f.createEl("button",{text:"Discard"});p.onclick=()=>void this.discardCurrentType();let m=f.createEl("button",{text:"Save"});m.addClass("mod-cta"),m.disabled=(this.editorMode==="design"?s>0:c>0)||this.ctx.busy,m.onclick=()=>void this.saveCurrentType()}newlyFailing(){return!this.dirty||!this.impact||"error"in this.impact?0:this.impact.impact.failing.filter(e=>e.isNew).length}matchingLabel(){let e=this.impact&&!("error"in this.impact)?this.impact.impact.matched.length:this.savedTypeName()?this.currentStats().stats.get(this.savedTypeName()??"")?.notes:void 0;return e===void 0||!this.ctx.records?"Matching":`Matching \xB7 ${e.toLocaleString()} ${e===1?"note":"notes"}`}savedTypeName(){return!this.selectedPath||!this.ctx.schema?null:[...this.ctx.schema.types.values()].find(e=>e.filePath===this.selectedPath)?.name??null}fillMatchPreview(e){let t=this.impact,n,i=[],s=[];if(t&&!("error"in t))({matched:n,added:i,removed:s}=t.impact);else{let d=this.savedTypeName();if(!this.ctx.records||!d||t&&"error"in t&&this.dirty){e.createDiv({cls:"mdbase-muted",text:this.ctx.records?t&&"error"in t?"Fix errors to preview matching notes.":"Save the type to preview matching notes.":"Counting notes\u2026"});return}n=[...this.currentStats().recordTypes].filter(([,f])=>f.includes(d)).map(([f])=>f)}let o=e.createDiv({cls:"mdbase-match-summary"});o.createSpan({text:`${n.length.toLocaleString()} ${n.length===1?"note matches":"notes match"}`}),i.length&&o.createSpan({cls:"mdbase-match-added",text:`${i.length} added`}),s.length&&o.createSpan({cls:"mdbase-match-removed",text:`${s.length} no longer match`});let a=new Set(i),c=[...i.map(d=>({path:d,change:"added"})),...s.map(d=>({path:d,change:"removed"})),...n.filter(d=>!a.has(d)).map(d=>({path:d,change:null}))];if(!c.length)return;let l=this.showAllMatches?200:5,u=e.createDiv({cls:"mdbase-match-list"});for(let d of c.slice(0,l)){let f=u.createEl("button",{cls:"mdbase-match-row"});d.change&&(f.setAttr("data-change",d.change),f.createSpan({cls:"mdbase-match-marker",text:d.change==="added"?"+":"\u2212",attr:{"aria-label":d.change==="added"?"Added":"No longer matches"}})),f.createSpan({text:d.path}),f.setAttr("title",`Open ${d.path}`),f.onclick=()=>void this.ctx.host.openFileByPath(d.path)}if(c.length>5){let d=e.createEl("button",{cls:"mdbase-link-button",text:this.showAllMatches?"Show fewer":c.length>200?`Show 200 of ${c.length.toLocaleString()}`:`Show all ${c.length.toLocaleString()}`});d.onclick=()=>{this.showAllMatches=!this.showAllMatches,e.empty(),this.fillMatchPreview(e)}}}fillImpact(e){let t=this.impact;if(!t){e.createDiv({cls:"mdbase-muted",text:this.ctx.records?"Checking notes\u2026":"Counting notes\u2026"});return}if("error"in t){e.createDiv({cls:"mdbase-muted",text:"Fix errors to check existing notes."});return}let{impact:n}=t,i=n.failing.filter(l=>l.isNew),s=n.failing.length-i.length,o=e.createDiv({cls:"mdbase-impact-heading"});o.setAttr("data-tone",i.length?"warning":"normal"),o.createEl("strong",{text:i.length?`${i.length} ${i.length===1?"note":"notes"} would fail`:"No notes newly fail"});let a=[`${n.matched.length.toLocaleString()} ${n.matched.length===1?"note":"notes"} checked`];if(n.fixed&&a.push(`${n.fixed} fixed`),s&&a.push(`${s} already failing`),o.createSpan({cls:"mdbase-muted",text:a.join(" \xB7 ")}),!i.length)return;let c=e.createDiv({cls:"mdbase-impact-list"});for(let l of i.slice(0,10)){let u=c.createDiv({cls:"mdbase-impact-row"}),d=u.createEl("button",{cls:"mdbase-link-button",text:l.path});d.onclick=()=>void this.ctx.host.openFileByPath(l.path,l.issues[0]?.field),u.createSpan({cls:"mdbase-muted",text:`${l.issues[0]?.message??""}${l.issues.length>1?` \xB7 +${l.issues.length-1} more`:""}`})}i.length>10&&c.createDiv({cls:"mdbase-muted",text:`${i.length-10} more notes`})}renderDesignEditor(e,t,n){let i=wa(t,{knownTypes:this.typeEntries().map(T=>T.name),contracts:this.ctx.schema?.contracts.values()}),s=e.createEl("section",{cls:"mdbase-editor-section"});s.id="mdbase-section-identity";let o=Tt(s,"Name",t.name,T=>{t.name=T,this.markDirty()});o.disabled=n;let a=Tt(s,"Description",t.description,T=>{t.description=T,this.markDirty()},{multiline:!0});a.disabled=n;let c=this.ctx.disclosure(e,"type-options","Options"),l=c.createDiv({cls:"mdbase-form-row"}),u=l.createEl("label",{text:"Display field"}),d=l.createEl("select");u.htmlFor=d.id="mdbase-display-field",d.createEl("option",{value:"",text:"Use the file name"});for(let T of t.fields)d.createEl("option",{value:T.name,text:T.name||"Unnamed field"});t.displayNameKey&&!t.fields.some(T=>T.name===t.displayNameKey)&&d.createEl("option",{value:t.displayNameKey,text:`${t.displayNameKey} \xB7 missing`}),d.value=t.displayNameKey,d.onchange=()=>{t.displayNameKey=d.value,this.markDirty()},d.disabled=n;let f=c.createEl("label",{cls:"mdbase-checkbox-row"}),p=f.createEl("input",{type:"checkbox"});p.checked=t.strictMode===!0,p.disabled=n,p.onchange=()=>{t.strictMode=p.checked,this.markDirty()},f.createSpan({text:"Reject undeclared fields"});let m=this.ctx.disclosure(e,"type-matching",this.matchingLabel());m.id="mdbase-section-membership",this.fillMatchPreview(m.createDiv({cls:"mdbase-match-preview"}));let h=Tt(m,"Path glob",t.matchPathGlob,T=>{t.matchPathGlob=T,this.markDirty()},{placeholder:"Projects/**/*.md"});h.disabled=n;let y=Tt(m,"Fields present",t.matchFieldsPresent,T=>{t.matchFieldsPresent=T,this.markDirty()},{description:"Comma-separated frontmatter keys."});y.disabled=n;let g=Tt(m,"Where",t.matchWhere,T=>{t.matchWhere=T,this.markDirty()},{multiline:!0,description:"YAML predicate, including contains and nested equality conditions.",placeholder:`tags: + contains: task`});g.disabled=n;let b=e.createEl("section",{cls:"mdbase-editor-section"});b.id="mdbase-section-fields";let v=b.createDiv({cls:"mdbase-section-header"});v.createEl("h3",{text:"Fields"});let S=v.createDiv({cls:"mdbase-section-actions"});if(this.expandedFields.size){let T=this.ctx.iconButton(S,"fold-vertical","Collapse all fields");T.onclick=()=>{this.expandedFields.clear(),this.ctx.render()}}let _=this.ctx.iconButton(S,"plus","Add field");if(_.disabled=n,_.onclick=()=>{let T={type:"string"};t.fields.push({name:"",definition:T}),this.expandedFields.add(this.fieldId(T)),this.markDirty(!0)},t.fields.length>6||this.fieldQuery){let P=b.createDiv({cls:"mdbase-field-toolbar"}).createDiv({cls:"mdbase-field-toolbar-actions"}).createEl("input",{type:"search"});P.placeholder="Filter fields",P.setAttr("aria-label","Filter fields"),P.setAttr("data-focus-key","field-search"),P.value=this.fieldQuery,P.oninput=()=>{this.fieldQuery=P.value,this.ctx.render()}}let E=b.createDiv({cls:"mdbase-fields"}),k=this.fieldQuery.trim().toLowerCase(),$=t.fields.filter(T=>!k||this.fieldMatches(T.name,T.definition,k));for(let T of $){let V=t.fields.indexOf(T);this.renderFieldRow(E,T,V,n)}$.length||E.createDiv({cls:"mdbase-empty-list",text:t.fields.length?"No fields match this filter.":"No fields declared."}),m.parentElement&&e.appendChild(m.parentElement),c.parentElement&&e.appendChild(c.parentElement);let x=Tt(c,"Path pattern",t.pathPattern,T=>{t.pathPattern=T,this.markDirty()},{placeholder:"Notes/{title}.md"});if(x.disabled=n,this.renderContractEditor(e,t,n),!this.dirty&&!i.length)return;let q=this.ctx.disclosure(e,"type-review","Changes",i.some(T=>T.severity==="error"));if(q.id="mdbase-section-review",this.dirty&&this.fillImpact(q.createDiv({cls:"mdbase-impact"})),i.length){let T=q.createDiv({cls:"mdbase-diagnostic-summary"}),V=i.filter(C=>C.severity==="error").length,P=i.length-V;T.createEl("strong",{text:`${V} ${V===1?"error":"errors"} \xB7 ${P} ${P===1?"warning":"warnings"}`});for(let C of i.slice(0,12)){let Be=T.createDiv({cls:"mdbase-diagnostic-item"});Be.setAttr("data-severity",C.severity),Be.createEl("code",{text:C.path}),Be.createSpan({text:C.message})}}if(this.dirty){let T=q.createEl("ul");for(let V of _a(this.originalModel,t))T.createEl("li",{text:V.summary}).setAttr("data-risk",V.risk)}}renderContractEditor(e,t,n){let i=this.ctx.disclosure(e,"type-applications","Applications");i.addClass("mdbase-contracts-section"),i.id="mdbase-section-applications";let s=[...this.ctx.schema?.contracts.values()??[]],o=new Set(t.implementations.map(c=>`${c.contract}@${c.version}`)),a=s.filter(c=>!o.has(Ms(c)));s.length||i.createDiv({cls:"mdbase-contract-empty",text:"No application contracts installed."});for(let c of t.implementations){let l=s.find(u=>u.id===c.contract&&u.version===c.version);this.renderContractImplementation(i,t,c,l,n)}if(a.length){let c=i.createDiv({cls:"mdbase-contract-add"}),l=c.createEl("label",{text:"Installed contract"}),u=c.createEl("select");l.htmlFor=u.id=`mdbase-contract-${Math.random().toString(36).slice(2)}`;for(let f of a)u.createEl("option",{value:Ms(f),text:`${f.id} \xB7 ${f.version}`});let d=c.createEl("button",{text:"Add contract"});d.disabled=n,d.onclick=()=>{let f=a.find(p=>Ms(p)===u.value);if(f)try{px(t,f),this.markDirty(!0)}catch(p){new Qe.Notice(p instanceof Error?p.message:String(p))}}}}renderContractImplementation(e,t,n,i,s){let o=e.createEl("article",{cls:"mdbase-contract-implementation"}),a=o.createDiv({cls:"mdbase-contract-header"}),c=a.createDiv();c.createEl("strong",{text:n.contract}),c.createSpan({cls:"mdbase-contract-version",text:n.version});let l=a.createEl("button",{text:"Remove"});if(l.disabled=s,l.onclick=()=>{hx(t,n.contract,n.version),this.markDirty(!0)},!i){o.createDiv({cls:"mdbase-contract-unavailable",text:"This exact contract is not installed in the collection. Restore it or remove this implementation before saving."});return}let u=ya(i),d=ga(t),f=u.filter(b=>Ts(n,b)),p=u.filter(b=>b.required),m=p.filter(b=>Ts(n,b)).length,h=o.createEl("details");h.open=mx.reference===v),_=ba(b,S),E=g.createDiv({cls:`mdbase-contract-mapping-row ${_.level}`}),k=E.createDiv({cls:"mdbase-contract-field-definition"});k.createEl("code",{text:b.reference}),k.createSpan({cls:b.required?"mdbase-contract-required":"mdbase-contract-optional",text:b.required?"Required":"Optional"}),k.createEl("small",{text:b.description||yx(b.schema)});let $=E.createEl("select");$.setAttr("aria-label",`${n.contract} ${b.reference} source field`),$.setAttr("aria-invalid",_.level==="error"?"true":"false"),$.disabled=s,$.createEl("option",{value:"",text:b.required?"Choose a source field":"Not exposed"});for(let x of d){let q=ba(b,x),T=$.createEl("option",{value:x.reference,text:`${x.reference} \xB7 ${x.type}${q.level==="warning"?" \xB7 review":""}`});T.disabled=q.level==="error"}$.value=v,$.onchange=()=>{mx(n,b.reference,$.value||void 0),this.markDirty(!0)};let M=E.createDiv({cls:"mdbase-contract-mapping-status"});M.createEl("strong",{text:_.label}),M.createEl("small",{text:_.message})}if(i.binding_schema){let b=o.createEl("details",{cls:"mdbase-contract-settings"});b.open=!!n.binding;let v=b.createEl("summary");v.createSpan({text:"Contract settings"}),v.createSpan({cls:"mdbase-contract-summary",text:n.binding?"Configured":"Optional"});let S=b.createDiv({cls:"mdbase-contract-settings-body"});if(S.createEl("p",{cls:"mdbase-form-description",text:"Control how compatible applications interpret this type. Values follow the contract's schema."}),n.binding)this.renderContractSchemaValue(S,i.binding_schema,n.binding,_=>{Se(_)&&(zm(n,_),this.markDirty())},"Settings",s);else{let _=S.createEl("button",{text:"Configure settings"});_.disabled=s,_.onclick=()=>{let E=va(i.binding_schema);Se(E)&&(zm(n,E),this.markDirty(!0))}}}}renderContractSchemaValue(e,t,n,i,s,o){if(jn(t)==="object"){let c=Se(n)?n:{},l=e.createEl("fieldset",{cls:"mdbase-contract-schema-object"});l.createEl("legend",{text:s});let u=Se(t.properties)?t.properties:{},d=new Set(Array.isArray(t.required)?t.required.map(String):[]),f=[...new Set([...d,...Object.keys(c).filter(m=>m in u)])];for(let m of f){let h=u[m];if(!Se(h))continue;let y=l.createDiv({cls:"mdbase-contract-schema-field"}),g=typeof h.description=="string"?h.description:void 0;y.createEl("label",{text:`${m}${d.has(m)?" \xB7 required":""}`}),g&&y.createEl("small",{text:g}),this.renderContractSchemaControl(y,h,c[m],b=>{i({...c,[m]:b})},m,o)}f.length||l.createDiv({cls:"mdbase-empty-list",text:"No settings declared."});let p=Object.keys(u).filter(m=>!f.includes(m));if(p.length){let m=l.createDiv({cls:"mdbase-contract-schema-add"}),h=m.createEl("select");for(let g of p)h.createEl("option",{value:g,text:g});let y=m.createEl("button",{text:"Add optional setting"});y.disabled=o,y.onclick=()=>{let g=h.value,b=u[g];Se(b)&&i({...c,[g]:va(b)})}}return}this.renderContractSchemaControl(e,t,n,i,s,o)}renderContractSchemaControl(e,t,n,i,s,o){let a=jn(t);if(Array.isArray(t.enum)){let l=e.createEl("select");l.setAttr("aria-label",s);for(let u of t.enum)l.createEl("option",{value:JSON.stringify(u),text:String(u)});l.value=JSON.stringify(n),l.disabled=o,l.onchange=()=>i(JSON.parse(l.value));return}if(a==="array"){let l=Se(t.items)?t.items:{type:"string"},u=Array.isArray(n)?n:[],d=e.createDiv({cls:"mdbase-contract-schema-array"});for(let[p,m]of u.entries()){let h=d.createDiv({cls:"mdbase-contract-schema-array-item"});h.createSpan({text:`${p+1}.`}),this.renderContractSchemaControl(h,l,m,g=>{i(u.map((b,v)=>v===p?g:b))},`${s} item ${p+1}`,o);let y=h.createEl("button",{text:"Remove"});y.disabled=o||u.length<=(typeof t.minItems=="number"?t.minItems:0),y.onclick=()=>i(u.filter((g,b)=>b!==p))}let f=e.createEl("button",{text:`Add ${s.toLowerCase()} item`});f.disabled=o||typeof t.maxItems=="number"&&u.length>=t.maxItems,f.onclick=()=>i([...u,va(l)]);return}if(a==="object"){this.renderContractSchemaValue(e,t,n,i,s,o);return}if(a==="boolean"){let l=e.createEl("input",{type:"checkbox"});l.checked=n===!0,l.disabled=o,l.setAttr("aria-label",s),l.onchange=()=>i(l.checked);return}let c=e.createEl("input",{type:a==="number"||a==="integer"?"number":"text"});c.setAttr("aria-label",s),c.value=n==null?"":typeof n=="string"?n:typeof n=="number"||typeof n=="boolean"?String(n):"",c.disabled=o,c.oninput=()=>i(a==="number"||a==="integer"?Number(c.value):c.value)}renderFieldRow(e,t,n,i){let s=this.model?.fields??[];this.renderFieldDefinition(e,t.definition,{name:t.name,nameLabel:`Field ${n+1} name`,onNameInput:o=>{t.name=o,this.markDirty()},required:t.definition.required===!0,onRequiredChange:o=>{t.definition.required=o,this.markDirty()},onRemove:()=>{this.model?.fields.splice(n,1),this.markDirty(!0)},onMove:o=>{let a=n+o;a<0||a>=s.length||([s[n],s[a]]=[s[a],s[n]],this.pendingFieldReveal=this.fieldId(t.definition),this.markDirty(!0))},canMoveUp:n>0,canMoveDown:n{i.open?this.expandedFields.add(s):this.expandedFields.delete(s)};let a=n.name||n.staticLabel||"Unnamed field",c=i.createEl("summary",{cls:"mdbase-field-summary"});c.setAttr("data-focus-key",`field-${s}-summary`);let l=c.createSpan({cls:"mdbase-field-chevron"});l.setAttr("aria-hidden","true"),(0,Qe.setIcon)(l,"chevron-right"),c.createSpan({cls:"mdbase-field-summary-name",text:a}),c.createSpan({cls:"mdbase-field-summary-type",text:Qm($a(t))});let u=c.createSpan({cls:"mdbase-field-summary-rules"}),d=()=>{u.textContent=jx(t).join(" \xB7 ")};d(),n.required&&c.createSpan({cls:"mdbase-field-summary-rule",text:"Required"}),n.onMove&&!n.readOnly&&c.addEventListener("keydown",y=>{!y.altKey||y.key!=="ArrowUp"&&y.key!=="ArrowDown"||(y.preventDefault(),y.key==="ArrowUp"&&n.canMoveUp&&n.onMove?.(-1),y.key==="ArrowDown"&&n.canMoveDown&&n.onMove?.(1))});let f=i.createDiv({cls:"mdbase-field-row"});if(n.staticLabel)f.createDiv({cls:"mdbase-field-role",text:n.staticLabel});else{let y=f.createEl("input",{type:"text",cls:"mdbase-field-name-control"});y.setAttr("data-focus-key",`field-${s}-name`),y.setAttr("aria-label",n.nameLabel),y.placeholder="Field name",y.value=n.name??"",y.disabled=n.readOnly,n.onNameInput&&(y.oninput=()=>n.onNameInput?.(y.value)),n.onNameCommit&&(y.onchange=()=>n.onNameCommit?.(y.value,y))}let p=f.createEl("select",{cls:"mdbase-field-type-control"});p.setAttr("data-focus-key",`field-${s}-type`),p.setAttr("aria-label",`${n.name||n.staticLabel||"Field"} type`);for(let y of kx)p.createEl("option",{value:y,text:Qm(y)});p.value=$a(t),p.disabled=n.readOnly,p.onchange=()=>{t.type=p.value,p.value==="list"&&!Se(t.items)&&(t.items={type:"string"}),p.value==="object"&&!Se(t.fields)&&(t.fields={}),p.value==="enum"&&!Array.isArray(t.values)&&(t.values=[]),p.value!=="integer"&&p.value!=="number"&&(delete t.min,delete t.max),p.value!=="string"&&delete t.pattern,["string","list"].includes(p.value)||(delete t.min_length,delete t.max_length),delete t.default,this.markDirty(!0)};let m=f.createEl("input",{type:"text",cls:"mdbase-field-description-control"});if(m.setAttr("data-focus-key",`field-${s}-description`),m.setAttr("aria-label",`${n.name||n.staticLabel||"Field"} description`),m.placeholder="Description",m.value=typeof t.description=="string"?t.description:"",m.disabled=n.readOnly,m.oninput=()=>{m.value?t.description=m.value:delete t.description,this.markDirty()},n.onRequiredChange){let y=f.createEl("label",{cls:"mdbase-field-required"}),g=y.createEl("input",{type:"checkbox"});g.setAttr("data-focus-key",`field-${s}-required`),g.checked=n.required===!0,g.disabled=n.readOnly,g.onchange=()=>n.onRequiredChange?.(g.checked),y.createSpan({text:"Required"})}if(n.onRemove||n.onMove){let y=this.ctx.iconButton(f,"more-horizontal",`${a} actions`);y.addClass("mdbase-field-menu"),y.setAttr("data-focus-key",`field-${s}-menu`),y.disabled=n.readOnly,y.onclick=g=>{let b=new Qe.Menu;if(n.onMove&&(b.addItem(v=>v.setTitle("Move up").setIcon("arrow-up").setDisabled(!n.canMoveUp).onClick(()=>n.onMove?.(-1))),b.addItem(v=>v.setTitle("Move down").setIcon("arrow-down").setDisabled(!n.canMoveDown).onClick(()=>n.onMove?.(1)))),n.onRemove&&(n.onMove&&b.addSeparator(),b.addItem(v=>{v.setTitle("Remove field").setIcon("trash-2").onClick(()=>n.onRemove?.()),v.setWarning(!0)})),g.detail===0){let v=y.getBoundingClientRect();b.showAtPosition({x:v.left,y:v.bottom})}else b.showAtMouseEvent(g)}}let h=$a(t);this.renderConstraintControls(i,t,h,n,d),h==="enum"&&this.renderEnumFieldDetails(i,t,n,d),h==="link"&&this.renderLinkFieldDetails(i,t,n),h==="list"&&this.renderListFieldDetails(i,t,n),h==="object"&&this.renderObjectFieldDetails(i,t,n)}renderConstraintControls(e,t,n,i,s){let a=n==="integer"||n==="number"?[["min","Minimum"],["max","Maximum"]]:n==="string"?[["min_length","Min length"],["max_length","Max length"]]:n==="list"?[["min_length","Min items"],["max_length","Max items"]]:[],c=!["list","object","any","link"].includes(n);if(!a.length&&n!=="string"&&!c)return;let l=e.createDiv({cls:"mdbase-field-details mdbase-field-constraints"}),u=i.name||i.staticLabel||"Field",d=this.fieldId(t);for(let[g,b]of a){let v=l.createDiv({cls:"mdbase-constraint"}),S=v.createEl("label",{text:b}),_=v.createEl("input",{type:"number"});_.id=`mdbase-${d}-${g}`,S.htmlFor=_.id,_.setAttr("data-focus-key",`field-${d}-${g}`),_.setAttr("aria-label",`${u} ${b.toLowerCase()}`),(g.endsWith("length")||n==="integer")&&(_.step="1"),g.endsWith("length")&&(_.min="0"),_.value=typeof t[g]=="number"?String(t[g]):"",_.disabled=i.readOnly,_.oninput=()=>{let E=_.value.trim()===""?NaN:Number(_.value);Number.isFinite(E)?t[g]=E:delete t[g],s(),this.markDirty()}}if(n==="string"){let g=l.createDiv({cls:"mdbase-constraint mdbase-constraint-wide"}),b=g.createEl("label",{text:"Pattern"}),v=g.createEl("input",{type:"text"});v.id=`mdbase-${d}-pattern`,b.htmlFor=v.id,v.setAttr("data-focus-key",`field-${d}-pattern`),v.setAttr("aria-label",`${u} pattern`),v.placeholder="Regular expression",v.spellcheck=!1,v.value=typeof t.pattern=="string"?t.pattern:"",v.disabled=i.readOnly,v.oninput=()=>{v.value?t.pattern=v.value:delete t.pattern,s(),this.markDirty()}}if(!c)return;let f=l.createDiv({cls:"mdbase-constraint mdbase-constraint-wide"}),p=f.createEl("label",{text:"Default"}),m=`mdbase-${d}-default`;if(p.htmlFor=m,n==="enum"||n==="boolean"){let g=f.createEl("select");g.id=m,g.setAttr("data-focus-key",`field-${d}-default`),g.createEl("option",{value:"",text:"None"});let b=n==="boolean"?[!0,!1]:Array.isArray(t.values)?t.values:[];for(let[S,_]of b.entries())g.createEl("option",{value:String(S),text:sn(_)});let v=b.findIndex(S=>JSON.stringify(S)===JSON.stringify(t.default));t.default!==void 0&&v===-1?(g.createEl("option",{value:"missing",text:`${sn(t.default)} \xB7 not allowed`}),g.value="missing"):g.value=v===-1?"":String(v),g.disabled=i.readOnly,g.onchange=()=>{g.value===""?delete t.default:g.value!=="missing"&&(t.default=b[Number(g.value)]),s(),this.markDirty()};return}let h=f.createEl("input",{type:"text"});h.id=m,h.setAttr("data-focus-key",`field-${d}-default`),h.setAttr("aria-label",`${u} default`),h.placeholder=n==="date"?"YYYY-MM-DD":n==="time"?"HH:MM":"None",h.value=t.default===void 0?"":sn(t.default),h.disabled=i.readOnly;let y=f.createDiv({cls:"mdbase-constraint-error"});h.oninput=()=>{let g=Bx(h.value,n);y.textContent=g.error??"",h.toggleClass("is-invalid",!!g.error),!g.error&&(g.value===void 0?delete t.default:t.default=g.value,s(),this.markDirty())}}fieldId(e){let t=this.fieldIds.get(e);if(t)return t;let n=`field-${this.nextFieldId}`;return this.nextFieldId+=1,this.fieldIds.set(e,n),n}fieldMatches(e,t,n){return`${e} ${$a(t)} ${typeof t.description=="string"?t.description:""}`.toLowerCase().includes(n)||Se(t.items)&&this.fieldMatches("item",t.items,n)?!0:Se(t.fields)?Object.entries(t.fields).some(([s,o])=>Se(o)&&this.fieldMatches(s,o,n)):!1}renderEnumFieldDetails(e,t,n,i){let s=e.createDiv({cls:"mdbase-field-details mdbase-enum-values"}),o=n.name||n.staticLabel||"Enum",a=this.fieldId(t);s.createDiv({cls:"mdbase-field-children-label",text:"Allowed values"});let c=Array.isArray(t.values)?t.values:[];!Array.isArray(t.values)&&!n.readOnly&&(t.values=c);let l=s.createDiv({cls:"mdbase-enum-list"});l.setAttr("role","list");let u=new Set(c.map(f=>typeof f)).size>1;for(let[f,p]of c.entries()){let m=l.createDiv({cls:"mdbase-enum-row"});m.setAttr("role","listitem");let h=m.createEl("input",{type:"text"});h.setAttr("data-focus-key",`field-${a}-value-${f}`),h.setAttr("aria-label",`${o} allowed value ${f+1}`),h.value=sn(p),h.disabled=n.readOnly,h.oninput=()=>{c[f]=qx(h.value,p,c.filter((g,b)=>b!==f)),i(),this.markDirty()},h.onkeydown=g=>{g.key==="Enter"&&(g.preventDefault(),c.splice(f+1,0,""),this.ctx.pendingFocusKey=`field-${a}-value-${f+1}`,this.markDirty(!0))},u&&m.createSpan({cls:"mdbase-enum-kind",text:typeof p});for(let[g,b,v]of[["arrow-up","Move value up",-1],["arrow-down","Move value down",1]]){let S=this.ctx.iconButton(m,g,`${b}: ${sn(p)}`);S.disabled=n.readOnly||f+v<0||f+v>=c.length,S.onclick=()=>{[c[f],c[f+v]]=[c[f+v],c[f]],this.markDirty(!0)}}let y=this.ctx.iconButton(m,"x",`Remove value ${sn(p)}`);y.disabled=n.readOnly,y.onclick=()=>{c.splice(f,1),this.markDirty(!0)}}let d=s.createEl("button",{cls:"mdbase-link-button",text:"Add value"});d.disabled=n.readOnly,d.onclick=()=>{c.push(""),this.ctx.pendingFocusKey=`field-${a}-value-${c.length-1}`,this.markDirty(!0)}}renderLinkFieldDetails(e,t,n){let i=e.createDiv({cls:"mdbase-field-details mdbase-field-options"}),s=this.fieldId(t),o=i.createEl("label",{text:"Target type"}),a=i.createEl("select");a.setAttr("data-focus-key",`field-${s}-target`),a.setAttr("aria-label",`${n.name||n.staticLabel||"Link"} target type`),a.createEl("option",{value:"",text:"Any type"});let c=typeof t.target=="string"?t.target:"";for(let d of this.typeEntries())a.createEl("option",{value:d.name,text:d.name});c&&!this.typeEntries().some(d=>d.name===c)&&a.createEl("option",{value:c,text:`${c} \xB7 missing`}),a.value=c,a.disabled=n.readOnly,a.onchange=()=>{a.value?t.target=a.value:delete t.target,this.markDirty()},o.htmlFor=a.id=`mdbase-${s}-target`;let l=i.createEl("label",{cls:"mdbase-field-required"}),u=l.createEl("input",{type:"checkbox"});u.setAttr("data-focus-key",`field-${s}-exists`),u.checked=t.validate_exists===!0,u.disabled=n.readOnly,u.onchange=()=>{t.validate_exists=u.checked,this.markDirty()},l.createSpan({text:"Validate target exists"})}renderListFieldDetails(e,t,n){let i=e.createDiv({cls:"mdbase-field-children"});i.createDiv({cls:"mdbase-field-children-label",text:"List items"});let s=Se(t.items)?t.items:{type:"any"};!Se(t.items)&&!n.readOnly&&(t.items=s),this.renderFieldDefinition(i,s,{staticLabel:"Item",nameLabel:"List item",readOnly:n.readOnly,depth:n.depth+1})}renderObjectFieldDetails(e,t,n){let i=e.createDiv({cls:"mdbase-field-children"});i.createDiv({cls:"mdbase-field-children-label",text:"Object fields"});let s=Se(t.fields)?t.fields:{};!Se(t.fields)&&!n.readOnly&&(t.fields=s);let o=i.createDiv({cls:"mdbase-nested-fields"}),a=i.createEl("button",{cls:"mdbase-link-button",text:"Add nested field"});a.disabled=n.readOnly,a.onclick=()=>{let l=Cx(s);_d(s,l,{type:"string"}),this.expandedFields.add(this.fieldId(s[l])),this.markDirty(!0)};let c=Object.entries(s).filter(l=>Se(l[1]));if(!c.length){o.createDiv({cls:"mdbase-empty-list",text:"No nested fields."});return}for(let[l,[u,d]]of c.entries()){let f=u;this.renderFieldDefinition(o,d,{name:f,nameLabel:`${f} nested field name`,onNameCommit:(p,m)=>{let h=p.trim();if(!h){new Qe.Notice("Nested field name is required."),m.value=f;return}if(h!==f&&Object.prototype.hasOwnProperty.call(s,h)){new Qe.Notice(`Nested field already exists: ${h}`),m.value=f;return}h!==f&&(delete s[f],_d(s,h,d),f=h,this.markDirty())},required:d.required===!0,onRequiredChange:p=>{d.required=p,this.markDirty()},onRemove:()=>{delete s[f],this.markDirty(!0)},onMove:p=>{let m=Object.keys(s),h=m.indexOf(f),y=h+p;if(h===-1||y<0||y>=m.length)return;[m[h],m[y]]=[m[y],m[h]];let g=m.map(b=>[b,s[b]]);for(let b of m)delete s[b];for(let[b,v]of g)Se(v)&&_d(s,b,v);this.pendingFieldReveal=this.fieldId(d),this.markDirty(!0)},canMoveUp:l>0,canMoveDown:lthis.onYamlInput(s.value)}}ensureYamlEditor(e){try{return this.yamlEditor?(this.yamlEditor.setValue(this.yamlDraft),this.yamlEditor.setReadOnly(e)):this.yamlEditor=new Ed({doc:this.yamlDraft,readOnly:e,labelledBy:"mdbase-mode-yaml",onChange:t=>this.onYamlInput(t)}),this.yamlEditor.setProblems(this.yamlProblems()),this.yamlEditor}catch(t){return console.error("mdbase: YAML editor unavailable",t),this.yamlEditor=null,null}}onYamlInput(e){this.yamlDraft=e,this.markDirty(!1),this.yamlProblemTimer!==null&&window.clearTimeout(this.yamlProblemTimer),this.yamlProblemTimer=window.setTimeout(()=>{this.yamlProblemTimer=null;let t=this.yamlProblems();this.yamlEditor?.setProblems(t);let n=this.ctx.containerEl.querySelector(".mdbase-yaml-problems");n&&(n.empty(),this.fillYamlProblems(n,t))},250)}fillYamlProblems(e,t=this.yamlProblems()){if(!(!this.dirty||!t.length))for(let n of t.slice(0,20)){let i=e.createEl("button",{cls:"mdbase-yaml-problem"});if(i.setAttr("data-severity",n.severity),i.createSpan({cls:"mdbase-yaml-problem-line-number",text:n.line?`Line ${n.line}`:"Type"}),i.createSpan({text:n.message}),i.disabled=n.line===null,n.line!==null){let s=n.line;i.onclick=()=>this.yamlEditor?.revealLine(s)}}}async leaveCurrentType(){this.dirty&&await this.flushTypeDraft(),this.yamlEditor?.destroy(),this.yamlEditor=null,this.impact=null,this.showAllMatches=!1}async selectType(e,t=!0){t&&e!==this.selectedPath&&await this.leaveCurrentType();let n=++this.typeSelectionVersion,i=await this.ctx.host.loadTypeModel(e);if(n!==this.typeSelectionVersion)return;let s=this.ctx.host.loadTypeDraft(e),o=s?.version===1&&s.sourceRevision===(i.sourceRevision??null),a=o?qn(s.model):i;this.selectedPath=e,this.model=a,this.originalModel=qn(i),this.yamlDraft=o&&s.yamlDraft!==void 0?s.yamlDraft:`${mt(Ea(i),i.body)} +`,this.dirty=!bd(this.originalModel,a),this.editorMode=o&&s.editorMode==="yaml"?"yaml":"design",this.editorMode==="yaml"&&(this.dirty=!0),o&&this.dirty?this.sessionDrafts.has(e)||(this.ctx.message=`Recovered unsaved changes for ${e}.`):s&&!o&&(this.ctx.message=`An older draft for ${e} was kept, but the source changed. The current file is shown.`),this.scheduleImpact(0),this.ctx.render()}async createType(){await this.leaveCurrentType(),this.typeSelectionVersion+=1;let e=this.ctx.host.loadTypeDraft(null),t=e?.version===1?qn(e.model):Hm();this.selectedPath=null,this.model=t,this.originalModel=null,this.yamlDraft=e?.yamlDraft??"",this.dirty=!0,e&&!this.sessionDrafts.has("__new__")&&(this.ctx.message="Recovered an unsaved new type."),this.editorMode=e?.editorMode??"design",this.scheduleImpact(0),this.ctx.render()}switchEditorMode(e){if(!(!this.model||e===this.editorMode)){if(e==="yaml")try{this.yamlDraft=`${mt(Ea(this.model),this.model.body)} `}catch(t){new Qe.Notice(t instanceof Error?t.message:String(t));return}else if(!this.readYamlDraftIntoModel())return;this.editorMode=e,e==="design"&&(this.yamlEditor?.destroy(),this.yamlEditor=null),this.scheduleImpact(0),this.ctx.render()}}modelFromYamlDraft(){let e=Me(this.yamlDraft);if(!e.hasFrontmatter)return{error:"Type YAML must start with a --- frontmatter block.",line:1};if(e.error)return{error:`Invalid YAML: ${e.error.split(` -`)[0].replace(/:$/,"").replace(/ at line \d+, column \d+$/,"")}`,line:Ux(e.error)};if(e.frontmatter.kind!=="mdbase.type")return{error:"Canonical v0.3 type YAML requires kind: mdbase.type.",line:sy(this.yamlDraft,"kind")??2};try{let t=bd(e.frontmatter,e.body,this.model?.name||"type");return this.model?.sourceRevision&&(t.sourceRevision=this.model.sourceRevision),{model:t}}catch(t){return{error:t instanceof Error?t.message:String(t),line:null}}}yamlProblems(){let e=this.modelFromYamlDraft();return"error"in e?[{line:e.line??null,message:e.error,severity:"error"}]:wa(e.model,{knownTypes:this.typeEntries().map(t=>t.name),contracts:this.ctx.schema?.contracts.values()}).map(t=>{let n=t.path.startsWith("fields.")?t.path.slice(7).split(/[.[]/)[0]:t.path==="identity.displayNameKey"?"name_field":t.path.split(".").pop()??"";return{line:sy(this.yamlDraft,n),message:t.message,severity:t.severity==="error"?"error":"warning"}})}readYamlDraftIntoModel(){let e=this.modelFromYamlDraft();return"error"in e?(new Qe.Notice(e.error),e.line&&this.yamlEditor?.revealLine(e.line),!1):(this.model=e.model,!0)}async saveCurrentType(){if(!this.model||this.model.specProfile!=="v0.3"||this.model.readOnlyReason||this.editorMode==="yaml"&&!this.readYamlDraftIntoModel())return;let t=wa(this.model,{knownTypes:this.typeEntries().map(a=>a.name),contracts:this.ctx.schema?.contracts.values()}).filter(a=>a.severity==="error");if(t.length){this.ctx.message=`${t.length} ${t.length===1?"error must":"errors must"} be fixed before saving.`,this.ctx.render(),new Qe.Notice(t[0].message);return}let n=_a(this.originalModel,this.model).filter(a=>a.risk==="high"),i=await this.computeImpact();i!==void 0&&(this.impact=i);let s=this.impact&&!("error"in this.impact)?this.impact.impact.failing.filter(a=>a.isNew).map(a=>a.path):[];if(n.length||s.length){let a=n.length?n:_a(this.originalModel,this.model).filter(l=>l.risk!=="safe");if(!await new xc(this.ctx.app).confirm(a,s))return}let o=this.model;await this.flushTypeDraft(),await this.ctx.perform(async()=>{let a=this.selectedPath,c=await this.ctx.host.saveTypeModel(o,a,this.originalModel?.sourceRevision);await this.ctx.host.clearTypeDraft(a),a!==c.path&&await this.ctx.host.clearTypeDraft(c.path),this.selectedPath=c.path,this.originalModel=qn(o),this.dirty=!1,this.ctx.message=`Saved ${c.path}.`,await this.ctx.refresh(!0)})}markDirty(e=!1){let t=this.dirty;if(this.dirty=this.editorMode==="yaml"?!0:!vd(this.originalModel,this.model),this.scheduleTypeDraftSave(),this.scheduleImpact(),this.dirty&&!t&&(this.ctx.message=""),e||t!==this.dirty){this.ctx.render();return}let n=this.ctx.containerEl.querySelector(".mdbase-type-editor-pane"),i=n?.querySelector(".mdbase-draft-bar");if(n&&i&&this.model){i.remove(),this.renderDraftBar(n,this.model);let s=n.querySelector(".mdbase-editor-title-line h2");s&&(s.textContent=this.model.name||"Untitled type")}}scheduleTypeDraftSave(){this.draftSaveTimer!==null&&window.clearTimeout(this.draftSaveTimer),this.draftSaveTimer=window.setTimeout(()=>{this.draftSaveTimer=null,this.flushTypeDraft()},2e3)}async flushTypeDraft(){if(this.draftSaveTimer!==null&&(window.clearTimeout(this.draftSaveTimer),this.draftSaveTimer=null),!this.model)return;if(!this.dirty){let t=this.ctx.host.loadTypeDraft(this.selectedPath);t&&t.sourceRevision===(this.originalModel?.sourceRevision??null)&&await this.ctx.host.clearTypeDraft(this.selectedPath);return}this.sessionDrafts.add(this.selectedPath??"__new__");let e={version:1,path:this.selectedPath,sourceRevision:this.originalModel?.sourceRevision??null,model:qn(this.model),editorMode:this.editorMode,yamlDraft:this.editorMode==="yaml"?this.yamlDraft:void 0,updatedAt:new Date().toISOString()};await this.ctx.host.saveTypeDraft(e)}async discardCurrentType(){let e=this.selectedPath,t=this.ctx.host.loadTypeDraft(e);if((!t||t.sourceRevision===(this.originalModel?.sourceRevision??null))&&await this.ctx.host.clearTypeDraft(e),e){let n=await this.ctx.host.loadTypeModel(e);this.model=n,this.originalModel=qn(n),this.yamlDraft=`${mt(Ea(n),n.body)} -`,this.dirty=!1}else this.model=null,this.originalModel=null,this.yamlDraft="",this.dirty=!1;this.ctx.message="Unsaved changes discarded.",this.ctx.render()}};function Ea(r){return r.specProfile==="v0.3"&&!r.readOnlyReason?Fn(r):qn(r.originalFrontmatter??{name:r.name,fields:Object.fromEntries(r.fields.map(e=>[e.name,e.definition]))})}var Dr="mdbase-workspace-view",Pd=class extends Ds.ItemView{constructor(t,n){super(t);this.host=n;this.destination="types";this.message="";this.pendingFocusKey=null;this.busy=!1;this.schema=null;this.records=null;this.disclosures=new Map;this.types=new kd(this);this.sync=new Ed(this);this.issues=new wd(this);this.refreshVersion=0;this.unsubscribeSync=null}getState(){return this.captureRenderSnapshot(this.containerEl),{destination:this.destination,...this.types.getState(),...this.issues.getState(),...this.sync.getState(),disclosures:Object.fromEntries(this.disclosures)}}async setState(t,n){if(["types","sync","issues"].includes(String(t.destination))&&(this.destination=t.destination),t.disclosures&&typeof t.disclosures=="object")for(let[i,s]of Object.entries(t.disclosures))typeof s=="boolean"&&this.disclosures.set(i,s);await this.types.setState(t),this.issues.setState(t),this.sync.setState(t),await this.refresh(),this.types.restoreEditorMode(t.editorMode),await super.setState(t,n)}refreshValidationControls(){this.destination==="issues"&&this.render()}updateValidationProgress(){this.issues.updateValidationProgress()}getViewType(){return Dr}getDisplayText(){return"mdbase"}getIcon(){return Sa}async onOpen(){this.containerEl.addClass("mdbase-workspace"),this.registerDomEvent(this.containerEl,"keydown",t=>{(t.metaKey||t.ctrlKey)&&t.key.toLowerCase()==="s"&&this.types.dirty&&(t.preventDefault(),this.types.saveCurrentType())}),this.unsubscribeSync=this.host.sync.subscribe(()=>{this.destination==="sync"?this.render():this.renderTopbarOnly()}),await this.refresh(!0)}async onClose(){this.refreshVersion++,this.unsubscribeSync?.(),this.unsubscribeSync=null,await this.types.dispose(),this.sync.dispose()}async refresh(t=!1){let n=++this.refreshVersion,i=()=>n===this.refreshVersion;try{let s=await this.host.loadWorkspaceSchema(t);if(!i()||(this.schema=s,await this.types.onSchemaLoaded(t,i),!i())||(this.destination==="sync"&&await this.sync.refresh(),!i()))return;let o=s?await this.host.loadCollectionRecords():null;if(!i())return;let a=o!==this.records;this.records=o,this.types.onRecordsLoaded(a||t),this.render()}catch(s){if(!i())return;this.message=s instanceof Error?s.message:String(s),this.render()}}showDestination(t){this.destination=t,this.render(),t==="sync"&&this.sync.refresh().then(()=>this.render())}showIssuesForPath(t){this.issues.filterToPath(t),this.showDestination("issues")}openTypeField(t,n){return this.types.openTypeField(t,n)}recordTypes(){return this.types.currentStats().recordTypes}createNewType(){this.types.createNewType()}editType(t){return this.types.editType(t)}focusSyncSection(t){this.sync.focusSection(t)}reconnectCollection(){return this.sync.reconnectCollection()}render(){let t=this.containerEl,n=this.captureRenderSnapshot(t);t.empty(),t.addClass("mdbase-workspace");let i=t.createDiv({cls:"mdbase-shell"});if(this.renderTopbar(i),this.message){let o=i.createDiv({cls:"mdbase-inline-message mdbase-notice"});o.createSpan({text:this.message}).setAttr("role","status");let a=this.iconButton(o,"x","Dismiss message");a.onclick=()=>{this.message="",this.render()}}let s=i.createDiv({cls:"mdbase-workspace-content"});s.setAttr("data-scroll-key","workspace"),this.destination==="types"?this.types.render(s):this.destination==="sync"?this.sync.render(s):this.issues.render(s),this.restoreRenderSnapshot(t,n),this.app.workspace?.requestSaveLayout(),this.pendingFocusKey&&(t.querySelector(`[data-focus-key="${this.pendingFocusKey}"]`)?.focus(),this.pendingFocusKey=null),this.destination==="types"&&this.types.afterRender(t)}syncAttention(){let{status:t,preview:n}=this.host.sync.state,i=t?.conflicts.length??0;if(i)return{count:i,label:`${i} sync ${i===1?"conflict":"conflicts"}`};let s=this.host.sync.safety(),o=s&&!s.safe?n?.plan.actions.length??0:0;return o?{count:o,label:`${o} ${o===1?"change needs":"changes need"} review`}:null}renderTopbarOnly(){let t=this.containerEl.querySelector(".mdbase-topbar");if(!t)return;let n=this.containerEl.ownerDocument.createElement("div");this.renderTopbar(n);let i=n.firstElementChild;i&&t.replaceWith(i)}captureRenderSnapshot(t){for(let a of Array.from(t.querySelectorAll("details[data-disclosure]"))){let c=a.dataset.disclosure;c&&this.disclosures.set(c,a.open)}let n=t.ownerDocument,i=t.contains(n.activeElement)?n.activeElement:null,s=i instanceof HTMLInputElement||i instanceof HTMLTextAreaElement?i:null,o=new Map;for(let a of Array.from(t.querySelectorAll("[data-scroll-key]"))){let c=a.getAttr("data-scroll-key");c&&o.set(c,{top:a.scrollTop,left:a.scrollLeft})}return{focusKey:i?.getAttr("data-focus-key")??null,selectionStart:s?.selectionStart??null,selectionEnd:s?.selectionEnd??null,scroll:o}}restoreRenderSnapshot(t,n){for(let[s,o]of n.scroll){let a=t.querySelector(`[data-scroll-key="${s}"]`);a&&(a.scrollTop=o.top,a.scrollLeft=o.left)}if(!n.focusKey)return;let i=t.querySelector(`[data-focus-key="${n.focusKey}"]`);i?.focus({preventScroll:!0}),(i instanceof HTMLInputElement||i instanceof HTMLTextAreaElement)&&n.selectionStart!==null&&n.selectionEnd!==null&&i.setSelectionRange(n.selectionStart,n.selectionEnd)}iconButton(t,n,i){let s=t.createEl("button",{cls:"clickable-icon mdbase-icon-button"});return s.setAttr("aria-label",i),s.setAttr("title",i),s.setAttr("data-focus-key",`action-${i.toLowerCase().replace(/[^a-z0-9]+/g,"-")}`),(0,Ds.setIcon)(s,n),s}disclosure(t,n,i,s=!1){let o=t.createEl("details",{cls:"mdbase-disclosure"});return o.dataset.disclosure=n,o.open=this.disclosures.get(n)??s,o.addEventListener("toggle",()=>{this.containerEl.contains(o)&&(this.disclosures.set(n,o.open),this.app.workspace?.requestSaveLayout())}),o.createEl("summary",{text:i}).setAttr("data-focus-key",`disclosure-${n}`),o.createDiv({cls:"mdbase-disclosure-body"})}renderTopbar(t){let i=t.createDiv({cls:"mdbase-topbar"}).createDiv({cls:"mdbase-nav"});i.setAttr("role","tablist");for(let[s,o]of[["types","Types"],["sync","Sync"],["issues","Issues"]]){let a=i.createEl("button",{text:o,cls:"clickable-icon"});if(a.addClass("mdbase-nav-button"),a.setAttr("role","tab"),a.setAttr("data-focus-key",`destination-${s}`),a.setAttr("aria-selected",String(this.destination===s)),this.destination===s&&a.addClass("is-active"),s==="issues"&&this.host.getIssues().length){let l=this.host.getIssues().length;a.createSpan({cls:"mdbase-count",text:Zm(l)}).setAttr("title",`${l} issues`)}let c=s==="sync"?this.syncAttention():null;c&&a.createSpan({cls:"mdbase-count",text:Zm(c.count)}).setAttr("title",c.label),a.onclick=()=>this.showDestination(s)}}async perform(t){if(!this.busy){this.busy=!0,this.message="",this.render();try{await t()}catch(n){let i=n instanceof Error?n.message:String(n);this.message=i,new Ds.Notice(i)}finally{this.busy=!1,this.render()}}}};var Aa=class{constructor(e,t){this.delayMs=e;this.task=t;this.entries=new Map;if(!Number.isFinite(e)||e<0)throw new Error("Debounce delay must be a non-negative finite number.")}has(e){return this.entries.has(e)}schedule(e,t){let n=this.entries.get(e);n||(n={value:t,revision:0,timer:null,ready:!1,running:!1},this.entries.set(e,n)),n.value=t,n.revision+=1,n.ready=!1,n.timer!==null&&clearTimeout(n.timer),n.timer=setTimeout(()=>{this.entries.get(e)===n&&(n.timer=null,n.ready=!0,this.drain(e,n))},this.delayMs)}cancel(e){let t=this.entries.get(e);t&&(t.timer!==null&&clearTimeout(t.timer),this.entries.delete(e))}clear(){for(let e of this.entries.values())e.timer!==null&&clearTimeout(e.timer);this.entries.clear()}async drain(e,t){if(this.entries.get(e)!==t||t.running||!t.ready)return;t.ready=!1,t.running=!0;let n=t.revision,i=t.value,s=()=>this.entries.get(e)===t&&t.revision===n;try{await this.task(i,s)}finally{t.running=!1,this.entries.get(e)===t&&(t.ready?this.drain(e,t):t.timer===null&&t.revision===n&&this.entries.delete(e))}}};var Vx=require("obsidian");var Cd=class extends Vx.Modal{constructor(t,n,i){super(t);this.path=n;this.runs=i}onOpen(){this.titleEl.setText(`Sync history \xB7 ${this.path.split("/").pop()??this.path}`),this.contentEl.addClass("mdbase-note-history");let t=z$(this.runs,this.path).map(({run:i,file:s})=>({at:s.at,label:i.summary??W$(s),detail:i.summary===void 0&&s.fromPath?`From ${s.fromPath}`:s.message}));if(!t.length){this.contentEl.createEl("p",{cls:"mdbase-muted",text:"No syncs of this note are recorded on this device."});return}let n=this.contentEl.createDiv({cls:"mdbase-transfer-ledger"});for(let i of t){let s=n.createDiv({cls:"mdbase-note-history-row"});s.createSpan({cls:"mdbase-muted",text:ks(i.at)});let o=s.createDiv();o.createDiv({text:i.label}),i.detail&&o.createDiv({cls:"mdbase-muted",text:i.detail})}}onClose(){this.contentEl.empty()}};var Ne=require("obsidian");var nj=[["image","Images"],["audio","Audio"],["video","Video"],["pdf","PDFs"],["other","Other files"]],Md=class extends Ne.PluginSettingTab{constructor(t,n){super(t,n);this.plugin=n}display(){let{containerEl:t,plugin:n}=this;t.empty(),new Ne.Setting(t).setName("Validate notes automatically").setDesc("Check notes against their types when they are opened or saved.").addToggle(i=>i.setValue(n.settings.validateOnSave||n.settings.validateOnOpen).onChange(async s=>{n.settings.validateOnSave=s,n.settings.validateOnOpen=s,await n.saveSettings(),this.display()})),n.settings.validateOnSave&&new Ne.Setting(t).setName("Show validation notices").setDesc("Notify when saving a note with issues.").addToggle(i=>i.setValue(n.settings.showNoticeOnSave).onChange(async s=>{n.settings.showNoticeOnSave=s,await n.saveSettings()})),new Ne.Setting(t).setName("Allow plugin integrations").setDesc("Let other installed plugins exchange mdbase events and actions in this vault.").addToggle(i=>i.setValue(n.settings.interopEnabled).onChange(async s=>{n.settings.interopEnabled=s,await n.saveSettings()})),this.displaySync(t)}displaySync(t){let{plugin:n}=this,i=n.getMirrorProfile();if(new Ne.Setting(t).setName("Sync").setHeading(),!i){new Ne.Setting(t).setName("Not connected").setDesc("Connect this vault to mdbase Connect from the sync tab of the mdbase workspace.").addButton(l=>l.setButtonText("Open sync").onClick(()=>{n.openWorkspace("sync")}));return}new Ne.Setting(t).setName(i.name).setDesc(`${i.mode==="read_write"?"Read and write":"Read only"} \xB7 ${new URL(i.controlUrl).host}`).addButton(l=>l.setButtonText("Reconnect").onClick(async()=>{l.setDisabled(!0),await n.openWorkspace("sync").then(u=>u.reconnectCollection()),l.setDisabled(!1)})),new Ne.Setting(t).setName("Sync automatically").setDesc("Keep this vault in sync in the background. Deleted files go to the trash, and conflicting edits are merged or kept as two files. Deleting many files at once on this device waits for your review.").addToggle(l=>l.setValue(n.settings.autoSync).onChange(async u=>{n.settings.autoSync=u,await n.saveSettings(),n.requestSync()}));let s=n.connectSync.getSelectiveSync(),o=async l=>{try{await n.sync.configureSelectiveSync(l)}catch(u){new Ne.Notice(u instanceof Error?u.message:String(u)),this.display()}};for(let[l,u]of nj)new Ne.Setting(t).setName(`Sync ${u.toLowerCase()}`).setDesc(l==="other"?"All remaining visible file formats. Markdown always syncs.":"").addToggle(d=>d.setValue(s.file_classes.includes(l)).onChange(async f=>{let p=n.connectSync.getSelectiveSync();await o({...p,file_classes:f?[...new Set([...p.file_classes,l])]:p.file_classes.filter(h=>h!==l)})}));let a=[...s.excluded_folders],c=new Ne.Setting(t).setName("Excluded folders").setDesc($d);xd(this.app,c.controlEl,a,l=>{a=l}),c.addButton(l=>l.setButtonText("Apply").onClick(async()=>{await o({...n.connectSync.getSelectiveSync(),excluded_folders:a}),new Ne.Notice("Excluded folders updated. The next sync applies them.")})),new Ne.Setting(t).setName("Disconnect").setDesc("Stop syncing this vault. The hosted collection is not deleted.").addButton(l=>l.setButtonText("Disconnect\u2026").setWarning().setDisabled(n.sync.isSyncing()).onClick(async()=>{let u=await new Ac(this.app).choose(i.name);if(u){try{await n.sync.disconnect(i,u==="remove"),new Ne.Notice(n.sync.state.message)}catch(d){new Ne.Notice(d instanceof Error?d.message:String(d))}this.display()}}))}};async function Hx(r,e,t,n){let i=await r.resolveConflict(e,t,n),s=await r.preview();return{status:i,preview:s}}var ij=4,zx={status:null,preview:null,progress:null,fileProgress:null,problem:null,message:"",localChangeObserved:!1,busy:!1,paused:!1,retryAt:null},Td=class{constructor(e,t,n,i=()=>{}){this.controller=e;this.getProfile=t;this.history=n;this.notify=i;this.current={...zx};this.listeners=new Set;this.pinnedFailure=null}get state(){return this.current}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}update(e){this.current={...this.current,...e};for(let t of this.listeners)t()}reset(){this.update({...zx})}isSyncing(){return this.controller.isSyncing()}clearMessage(){this.current.message&&this.update({message:""})}observeLocalChange(){this.current.localChangeObserved||this.update({localChangeObserved:!0})}historyRuns(){let e=this.getProfile()?.collectionId;return e?this.history?.list(e)??[]:[]}async recordEvent(e,t=this.getProfile()?.collectionId){if(!(!t||!this.history)){try{await this.history.append(cd(t,e))}catch(n){console.error("mdbase: could not save sync history",n)}this.update({})}}async dismissEvent(e){await this.history?.remove(e),this.update({})}async clearHistory(){await this.history?.clear(),this.update({})}async refreshStatus(){let e=this.getProfile();if(!e)return this.reset(),null;if(this.controller.isSyncing())return this.current.status;try{let t=await this.controller.status();return Kx(e,this.getProfile())?(this.update({status:t,problem:null}),t):null}catch(t){return Kx(e,this.getProfile())&&this.update({problem:Rt(t)}),null}}async review(){return this.getProfile()?await this.exclusive(async()=>(await this.loadPreview(),this.current.preview))??null:null}async apply(){if(!this.current.preview){await this.review();return}await this.exclusive(()=>this.applyReviewed())}async syncNow(e={}){return this.getProfile()?this.current.busy||this.controller.isSyncing()?"busy":e.automatic&&this.current.paused?"paused":(!e.automatic&&this.current.paused&&this.update({paused:!1}),await this.exclusive(async()=>{let n=!1;for(let i=0;it.outcome!=="unresolved")}safety(){return this.current.preview?D$(this.current.preview):null}cancel(){this.update({paused:!0}),this.controller.isSyncing()&&(this.controller.cancelSync(),this.update({message:"Stopping\u2026"}))}async reconnect(){return await this.exclusive(async()=>{try{let t=await this.controller.reconnect();return this.update({status:t,problem:null,message:"Connection restored."}),await this.recordEvent({summary:"Collection reconnected",message:"Connect credentials were renewed and the mirror checkpoint was preserved.",tone:"success"}),"connected"}catch(t){let n=Rt(t);return this.update({problem:n,message:n.action==="reauthorize"?"":n.message}),n.action==="reauthorize"?"reauthorize":"failed"}})??"failed"}async reauthorize(e){let t=await this.controller.reauthorize(e);this.update({status:t,problem:null,message:"Approval restored. The mirror checkpoint was preserved."}),await this.recordEvent({summary:"Connect approval restored",message:"The existing mirror checkpoint and local files were preserved.",tone:"success"})}async disconnect(e,t){let n=await this.controller.disconnect(t),i=t?`${n.removed.length} unchanged synced ${n.removed.length===1?"file was":"files were"} removed. ${n.preserved.length} locally changed ${n.preserved.length===1?"file was":"files were"} preserved.`:"All local files were retained as an unsynced copy.";return this.reset(),this.update({message:`Disconnected from ${e.name}. ${i}`}),n}async configureSelectiveSync(e){await this.controller.configureSelectiveSync(e),this.update({preview:null,message:"Sync settings updated."})}async resolveConflict(e,t,n){let i=null;try{n&&(i=await this.controller.preserveConflictCopy(e.path??"")),this.update({preview:null});let s=await Hx(this.controller,e.object_id,e.decision_id,t),o=i?`Local copy saved to ${i}. Sync to apply the hosted version.`:"Conflict resolved. Sync to continue.";return this.update({status:s.status,preview:s.preview,problem:null,message:o}),await this.recordEvent({summary:i?"Conflict kept as two files":`Conflict resolved with ${t==="local"?"local":"hosted"} version`,message:o,...e.path?{path:e.path}:{},tone:"info"}),!0}catch(s){let o=Rt(s);return i&&(o.message=`The local copy at ${i} is safe, but the original changed again. Review the newest versions before deciding.`),this.update({problem:o,message:o.message}),o.code==="conflict_decision_stale"&&(this.update({preview:null}),await this.refreshStatus()),await this.recordEvent({summary:o.title,message:o.message,...e.path?{path:e.path}:{},tone:"attention",needsAcknowledgement:!0}),!1}}reportProblem(e){let t=Rt(e);return this.update({problem:t,message:t.message}),t}async exclusive(e,t=!1){if(!this.current.busy){this.update({busy:!0,...t?{}:{message:""}});try{return await e()}finally{this.update({busy:!1})}}}async loadPreview(){try{let{preview:e,status:t}=await this.controller.inspect();return this.update({preview:e,status:t,problem:null}),e}catch(e){let t=Rt(e);return this.update({problem:t,message:t.message}),null}}async applyReviewed(){let e=this.current.preview;if(!e)return"failed";let t=this.getProfile()?.collectionId,n=new Date().toISOString(),i=[],s="failed",o;try{let a=await this.controller.sync(e,h=>this.update({progress:h}),h=>this.update({fileProgress:h}),(h,m)=>{let y=V$(h,m,new Date().toISOString());y&&i.push(y)});s=a.status,o=a.failure?.message;let{preview:c,status:l}=await this.controller.inspect(),u=a.status==="cancelled"?Rt(new DOMException("Synchronization stopped.","AbortError")):a.status==="failed"||a.status==="blocked"?Dx(a.failure??{code:"sync_failed",message:"Synchronization stopped."}):null,d=a.status==="applied"?"Sync complete.":a.status==="attention"?a.applied>0?"Available changes synced. Remaining items need attention.":"No available changes. Resolve the listed items and review again.":a.status==="cancelled"?`Sync paused after ${a.applied} ${a.applied===1?"change":"changes"}. Resume to finish the rest.`:a.status==="stale"?"Files changed during sync; checking again.":u?.message??`Sync stopped: ${a.failure?.message??a.status}.`;this.update({status:l,preview:c.plan.actions.length||c.entries.length?c:null,problem:u,message:d,...a.status==="applied"&&a.pending===0?{localChangeObserved:!1}:{}});let f=u?`${u.kind}:${u.code}`:null,p=a.status==="stale"||u?.kind==="offline"||a.status==="attention"&&l.conflicts.length>0||f!==null&&f===this.pinnedFailure;return a.status==="applied"?this.pinnedFailure=null:f&&!p&&(this.pinnedFailure=f),!p&&(a.status!=="applied"||!i.length)&&await this.recordEvent({summary:a.status==="applied"?`Synchronized ${a.applied} ${a.applied===1?"change":"changes"}`:a.status==="cancelled"?"Synchronization paused safely":a.applied>0?"Synced available changes":"Synchronization needs attention",message:d,tone:a.status==="applied"?"success":"attention",needsAcknowledgement:a.status!=="applied"&&a.status!=="attention"},t),a.status==="blocked"?"failed":a.status}catch(a){let c=Rt(a);s=c.kind==="paused"?"cancelled":"failed",o=c.message,this.update({problem:c,message:c.message});let l=`${c.kind}:${c.code}`;return c.kind!=="offline"&&l!==this.pinnedFailure&&(this.pinnedFailure=l,await this.recordEvent({summary:c.title,message:c.message,tone:c.kind==="paused"?"attention":"error",needsAcknowledgement:c.kind!=="paused"},t)),c.kind==="paused"?"cancelled":"failed"}finally{if(this.update({progress:null,fileProgress:null}),t&&i.length&&this.history){try{await this.history.append({id:crypto.randomUUID(),collectionId:t,startedAt:n,finishedAt:new Date().toISOString(),outcome:s,files:i,...o?{message:o}:{}})}catch(a){console.error("mdbase: could not save sync history",a)}this.update({})}}}};function Kx(r,e){return r?.collectionId===e?.collectionId}function sj(r){let e=r.path.split("/").pop()??r.path;switch(r.outcome){case"merged":return{summary:`Merged edits to ${e}`,message:"Changes made here and on another device were combined.",path:r.path,tone:"success"};case"kept_both":return{summary:`Kept both versions of ${e}`,message:`The same part was edited on two devices. The other device's version is in place and this device's version was saved as ${r.copyPath??"a copy"}.`,path:r.path,tone:"attention",needsAcknowledgement:!0};case"restored":return{summary:`Restored ${e}`,message:"It was deleted here but edited on another device, so the edited version was kept.",path:r.path,tone:"info"};case"kept_local":return{summary:`Kept ${e}`,message:"It was deleted on another device but edited here, so this version was uploaded again.",path:r.path,tone:"info"};case"took_hosted":return{summary:`Settled ${e}`,message:"The hosted version was kept.",path:r.path,tone:"info"};case"unresolved":return{summary:`Couldn't sync ${e}`,message:r.reason??"This change needs a decision.",path:r.path,tone:"attention",needsAcknowledgement:!0}}}var oj={localQuietMs:3e3,localMaxWaitMs:2e4,probeVisibleMs:3e4,probeHiddenMs:5*6e4,safetyNetMs:15*6e4,retryBaseMs:5e3,retryMaxMs:5*6e4,unexpectedRetryMaxMs:30*6e4},Wx=new Set(["auth","device","paused"]),Rd=class{constructor(e,t=aj,n=oj){this.host=e;this.clock=t;this.timing=n;this.timer=null;this.dueAt=null;this.dueIsDebounce=!1;this.firstLocalChangeAt=null;this.changed=!0;this.failures=0;this.running=!1;this.rerun=!1;this.visible=!0;this.stopped=!0;this.lastSyncAt=t.now()}start(){this.stopped=!1,this.schedule(this.clock.now())}stop(){this.stopped=!0,this.timer!==null&&this.clock.clearTimeout(this.timer),this.timer=null,this.dueAt=null}noteLocalChange(){let e=this.clock.now();this.firstLocalChangeAt??=e,this.changed=!0,this.schedule(Math.min(e+this.timing.localQuietMs,this.firstLocalChangeAt+this.timing.localMaxWaitMs),!0)}noteVisibility(e){let t=this.visible;this.visible=e,e&&!t&&this.schedule(this.clock.now())}noteOnline(){this.failures>0&&(this.changed=!0),this.failures=0,this.host.setRetryAt(null),this.schedule(this.clock.now())}requestSoon(){this.schedule(this.clock.now())}async tick(){if(this.stopped)return;if(this.running){this.rerun=!0;return}this.running=!0,this.dueAt=null;let e=null;try{e=await this.decide()}finally{this.running=!1;let t=this.clock.now();this.rerun?(this.rerun=!1,this.schedule(t)):e!==null&&this.schedule(t+e),this.schedule(t+(this.visible?this.timing.probeVisibleMs:this.timing.probeHiddenMs))}}async decide(){if(!this.host.connected())return null;let e=this.host.problemKind();if(e&&Wx.has(e))return null;let t=this.clock.now(),n=this.changed;if(this.changed=!1,this.firstLocalChangeAt=null,!this.host.automatic())return(n||await this.probe()===!0)&&await this.host.refreshStatus(),null;let i=n||this.failures>0||t-this.lastSyncAt>=this.timing.safetyNetMs;if(!i){let o=await this.probe();if(o===null)return this.failed(!0);i=o}if(!i)return null;this.lastSyncAt=t;let s=await this.host.autoSync();if(s==="busy")return this.changed||=n,2e3;if(s==="failed"){this.changed||=n;let o=this.host.problemKind();return o&&Wx.has(o)?this.settled():this.failed(o==="offline")}return this.settled()}async probe(){try{return await this.host.remoteChangesWaiting()}catch(e){return this.host.reportProblem(e),oa(e)?null:!0}}failed(e){let t=Pm(this.failures,{baseDelayMs:this.timing.retryBaseMs,maxDelayMs:e?this.timing.retryMaxMs:this.timing.unexpectedRetryMaxMs,random:()=>this.clock.random()});return this.failures+=1,this.host.setRetryAt(this.clock.now()+t),t}settled(){return this.failures=0,this.host.setRetryAt(null),null}schedule(e,t=!1){if(this.stopped)return;let n=this.timer===null?null:this.dueAt;n!==null&&n<=e&&!(t&&this.dueIsDebounce)||(this.timer!==null&&this.clock.clearTimeout(this.timer),this.dueAt=e,this.dueIsDebounce=t,this.timer=this.clock.setTimeout(()=>{this.timer=null,this.dueAt=null,this.tick()},Math.max(0,e-this.clock.now())))}},aj={now:()=>Date.now(),setTimeout:(r,e)=>window.setTimeout(r,e),clearTimeout:r=>window.clearTimeout(r),random:()=>Math.random()};function Jx(r){let{profile:e,state:t}=r,n=["mdbase sync diagnostics",`Generated: ${r.generatedAt}`,`Plugin ${r.pluginVersion} \xB7 Obsidian ${r.obsidianVersion} \xB7 ${r.platform}`,"","Connection"];e?n.push(` Collection: ${e.collectionId}`,` Replica: ${e.replicaId} (${e.mode})`,` Connect: ${Gx(e.controlUrl)} \xB7 sync ${Gx(e.syncUrl)}`,` Access token expires: ${e.accessTokenExpiresAt}`,` Enrolled on this device: ${r.otherDevice?"no \u2014 copied from another device or vault":"yes"}`,` File classes: ${e.selectiveSync?.file_classes.join(", ")||"notes only"}`,` Excluded folders: ${e.selectiveSync?.excluded_folders.length??0}`):n.push(" Not connected"),n.push(` Automatic sync: ${r.automatic?"on":"off"}${t.paused?" (paused)":""}`,` Other sync services on this vault: ${r.otherSyncServices.join(", ")||"none detected"}`,"","State",` Engine state: ${t.status?.state??"unknown"} \xB7 pending ${t.status?.pending??"?"} \xB7 conflicts ${t.status?.conflicts.length??0} \xB7 local issues ${t.status?.local_issues.length??0}`,` Last synced: ${t.status?.last_synced_at??"never"}`,` Problem: ${t.problem?`${t.problem.kind}/${t.problem.code} \u2014 ${t.problem.message}`:"none"}`,` Next automatic attempt: ${t.retryAt?new Date(t.retryAt).toISOString():"not scheduled"}`,` Plan on screen: ${t.preview?`${t.preview.plan.kind}, ${t.preview.plan.actions.length} actions, ${t.preview.plan.summary.blocking_issues} blocking issues`:"none"}`,` Checkpoint: ${r.checkpoint?`cursor ${r.checkpoint.cursor}, generation ${r.checkpoint.generation}`:"none"}`,` Interrupted batch: ${r.checkpoint?.batch??"none"}${r.checkpoint?.failure?` (${r.checkpoint.failure})`:""}`,"","Recent history (newest first)");let i=[...r.history].sort((s,o)=>o.finishedAt.localeCompare(s.finishedAt)).slice(0,25);i.length||n.push(" none");for(let s of i){let o=s.summary??`${s.files.length} ${s.files.length===1?"file":"files"}`;n.push(` ${s.finishedAt} \xB7 ${s.outcome}${s.tone?`/${s.tone}`:""} \xB7 ${o}${s.message?` \u2014 ${s.message}`:""}`)}return`${n.join(` +`)[0].replace(/:$/,"").replace(/ at line \d+, column \d+$/,"")}`,line:Vx(e.error)};if(e.frontmatter.kind!=="mdbase.type")return{error:"Canonical v0.3 type YAML requires kind: mdbase.type.",line:sy(this.yamlDraft,"kind")??2};try{let t=gd(e.frontmatter,e.body,this.model?.name||"type");return this.model?.sourceRevision&&(t.sourceRevision=this.model.sourceRevision),{model:t}}catch(t){return{error:t instanceof Error?t.message:String(t),line:null}}}yamlProblems(){let e=this.modelFromYamlDraft();return"error"in e?[{line:e.line??null,message:e.error,severity:"error"}]:wa(e.model,{knownTypes:this.typeEntries().map(t=>t.name),contracts:this.ctx.schema?.contracts.values()}).map(t=>{let n=t.path.startsWith("fields.")?t.path.slice(7).split(/[.[]/)[0]:t.path==="identity.displayNameKey"?"name_field":t.path.split(".").pop()??"";return{line:sy(this.yamlDraft,n),message:t.message,severity:t.severity==="error"?"error":"warning"}})}readYamlDraftIntoModel(){let e=this.modelFromYamlDraft();return"error"in e?(new Qe.Notice(e.error),e.line&&this.yamlEditor?.revealLine(e.line),!1):(this.model=e.model,!0)}async saveCurrentType(){if(!this.model||this.model.specProfile!=="v0.3"||this.model.readOnlyReason||this.editorMode==="yaml"&&!this.readYamlDraftIntoModel())return;let t=wa(this.model,{knownTypes:this.typeEntries().map(a=>a.name),contracts:this.ctx.schema?.contracts.values()}).filter(a=>a.severity==="error");if(t.length){this.ctx.message=`${t.length} ${t.length===1?"error must":"errors must"} be fixed before saving.`,this.ctx.render(),new Qe.Notice(t[0].message);return}let n=_a(this.originalModel,this.model).filter(a=>a.risk==="high"),i=await this.computeImpact();i!==void 0&&(this.impact=i);let s=this.impact&&!("error"in this.impact)?this.impact.impact.failing.filter(a=>a.isNew).map(a=>a.path):[];if(n.length||s.length){let a=n.length?n:_a(this.originalModel,this.model).filter(l=>l.risk!=="safe");if(!await new xc(this.ctx.app).confirm(a,s))return}let o=this.model;await this.flushTypeDraft(),await this.ctx.perform(async()=>{let a=this.selectedPath,c=await this.ctx.host.saveTypeModel(o,a,this.originalModel?.sourceRevision);await this.ctx.host.clearTypeDraft(a),a!==c.path&&await this.ctx.host.clearTypeDraft(c.path),this.selectedPath=c.path,this.originalModel=qn(o),this.dirty=!1,this.ctx.message=`Saved ${c.path}.`,await this.ctx.refresh(!0)})}markDirty(e=!1){let t=this.dirty;if(this.dirty=this.editorMode==="yaml"?!0:!bd(this.originalModel,this.model),this.scheduleTypeDraftSave(),this.scheduleImpact(),this.dirty&&!t&&(this.ctx.message=""),e||t!==this.dirty){this.ctx.render();return}let n=this.ctx.containerEl.querySelector(".mdbase-type-editor-pane"),i=n?.querySelector(".mdbase-draft-bar");if(n&&i&&this.model){i.remove(),this.renderDraftBar(n,this.model);let s=n.querySelector(".mdbase-editor-title-line h2");s&&(s.textContent=this.model.name||"Untitled type")}}scheduleTypeDraftSave(){this.draftSaveTimer!==null&&window.clearTimeout(this.draftSaveTimer),this.draftSaveTimer=window.setTimeout(()=>{this.draftSaveTimer=null,this.flushTypeDraft()},2e3)}async flushTypeDraft(){if(this.draftSaveTimer!==null&&(window.clearTimeout(this.draftSaveTimer),this.draftSaveTimer=null),!this.model)return;if(!this.dirty){let t=this.ctx.host.loadTypeDraft(this.selectedPath);t&&t.sourceRevision===(this.originalModel?.sourceRevision??null)&&await this.ctx.host.clearTypeDraft(this.selectedPath);return}this.sessionDrafts.add(this.selectedPath??"__new__");let e={version:1,path:this.selectedPath,sourceRevision:this.originalModel?.sourceRevision??null,model:qn(this.model),editorMode:this.editorMode,yamlDraft:this.editorMode==="yaml"?this.yamlDraft:void 0,updatedAt:new Date().toISOString()};await this.ctx.host.saveTypeDraft(e)}async discardCurrentType(){let e=this.selectedPath,t=this.ctx.host.loadTypeDraft(e);if((!t||t.sourceRevision===(this.originalModel?.sourceRevision??null))&&await this.ctx.host.clearTypeDraft(e),e){let n=await this.ctx.host.loadTypeModel(e);this.model=n,this.originalModel=qn(n),this.yamlDraft=`${mt(Ea(n),n.body)} +`,this.dirty=!1}else this.model=null,this.originalModel=null,this.yamlDraft="",this.dirty=!1;this.ctx.message="Unsaved changes discarded.",this.ctx.render()}};function Ea(r){return r.specProfile==="v0.3"&&!r.readOnlyReason?Fn(r):qn(r.originalFrontmatter??{name:r.name,fields:Object.fromEntries(r.fields.map(e=>[e.name,e.definition]))})}var Dr="mdbase-workspace-view",kd=class extends Ds.ItemView{constructor(t,n){super(t);this.host=n;this.destination="types";this.message="";this.pendingFocusKey=null;this.busy=!1;this.schema=null;this.records=null;this.disclosures=new Map;this.types=new Ad(this);this.sync=new xd(this);this.issues=new vd(this);this.refreshVersion=0;this.unsubscribeSync=null;this.syncRenderTimer=null}getState(){return this.captureRenderSnapshot(this.containerEl),{destination:this.destination,...this.types.getState(),...this.issues.getState(),...this.sync.getState(),disclosures:Object.fromEntries(this.disclosures)}}async setState(t,n){if(["types","sync","issues"].includes(String(t.destination))&&(this.destination=t.destination),t.disclosures&&typeof t.disclosures=="object")for(let[i,s]of Object.entries(t.disclosures))typeof s=="boolean"&&this.disclosures.set(i,s);await this.types.setState(t),this.issues.setState(t),this.sync.setState(t),await this.refresh(),this.types.restoreEditorMode(t.editorMode),await super.setState(t,n)}refreshValidationControls(){this.destination==="issues"&&this.render()}updateValidationProgress(){this.issues.updateValidationProgress()}getViewType(){return Dr}getDisplayText(){return"mdbase"}getIcon(){return Sa}async onOpen(){this.containerEl.addClass("mdbase-workspace"),this.registerDomEvent(this.containerEl,"keydown",n=>{(n.metaKey||n.ctrlKey)&&n.key.toLowerCase()==="s"&&this.types.dirty&&(n.preventDefault(),this.types.saveCurrentType())});let t=this.host.sync.state;this.unsubscribeSync=this.host.sync.subscribe(()=>{let n=this.host.sync.state,i=Object.keys(n).every(s=>s==="progress"||s==="fileProgress"||t[s]===n[s]);if(t=n,i&&(n.progress||n.fileProgress)){this.destination==="sync"&&this.syncRenderTimer===null&&(this.syncRenderTimer=window.setTimeout(()=>{this.syncRenderTimer=null,this.destination==="sync"&&this.render()},100));return}this.cancelSyncRender(),this.destination==="sync"?this.render():this.renderTopbarOnly()}),await this.refresh(!0)}async onClose(){this.refreshVersion++,this.unsubscribeSync?.(),this.unsubscribeSync=null,this.cancelSyncRender(),await this.types.dispose(),this.sync.dispose()}cancelSyncRender(){this.syncRenderTimer!==null&&window.clearTimeout(this.syncRenderTimer),this.syncRenderTimer=null}async refresh(t=!1){let n=++this.refreshVersion,i=()=>n===this.refreshVersion;try{let s=await this.host.loadWorkspaceSchema(t);if(!i()||(this.schema=s,await this.types.onSchemaLoaded(t,i),!i())||(this.destination==="sync"&&await this.sync.refresh(),!i()))return;let o=s?await this.host.loadCollectionRecords():null;if(!i())return;let a=o!==this.records;this.records=o,this.types.onRecordsLoaded(a||t),this.render()}catch(s){if(!i())return;this.message=s instanceof Error?s.message:String(s),this.render()}}showDestination(t){this.destination=t,this.render(),t==="sync"&&this.sync.refresh().then(()=>this.render())}showIssuesForPath(t){this.issues.filterToPath(t),this.showDestination("issues")}openTypeField(t,n){return this.types.openTypeField(t,n)}recordTypes(){return this.types.currentStats().recordTypes}createNewType(){this.types.createNewType()}editType(t){return this.types.editType(t)}focusSyncSection(t){this.sync.focusSection(t)}reconnectCollection(){return this.sync.reconnectCollection()}render(){let t=this.containerEl,n=this.captureRenderSnapshot(t);t.empty(),t.addClass("mdbase-workspace");let i=t.createDiv({cls:"mdbase-shell"});if(this.renderTopbar(i),this.message){let o=i.createDiv({cls:"mdbase-inline-message mdbase-notice"});o.createSpan({text:this.message}).setAttr("role","status");let a=this.iconButton(o,"x","Dismiss message");a.onclick=()=>{this.message="",this.render()}}let s=i.createDiv({cls:"mdbase-workspace-content"});s.setAttr("data-scroll-key","workspace"),this.destination==="types"?this.types.render(s):this.destination==="sync"?this.sync.render(s):this.issues.render(s),this.restoreRenderSnapshot(t,n),this.app.workspace?.requestSaveLayout(),this.pendingFocusKey&&(t.querySelector(`[data-focus-key="${this.pendingFocusKey}"]`)?.focus(),this.pendingFocusKey=null),this.destination==="types"&&this.types.afterRender(t)}syncAttention(){let{status:t,preview:n}=this.host.sync.state,i=t?.conflicts.length??0;if(i)return{count:i,label:`${i} sync ${i===1?"conflict":"conflicts"}`};let s=this.host.sync.safety(),o=s&&!s.safe?n?.plan.actions.length??0:0;return o?{count:o,label:`${o} ${o===1?"change needs":"changes need"} review`}:null}renderTopbarOnly(){let t=this.containerEl.querySelector(".mdbase-topbar");if(!t)return;let n=this.containerEl.ownerDocument.createElement("div");this.renderTopbar(n);let i=n.firstElementChild;i&&t.replaceWith(i)}captureRenderSnapshot(t){for(let a of Array.from(t.querySelectorAll("details[data-disclosure]"))){let c=a.dataset.disclosure;c&&this.disclosures.set(c,a.open)}let n=t.ownerDocument,i=t.contains(n.activeElement)?n.activeElement:null,s=i instanceof HTMLInputElement||i instanceof HTMLTextAreaElement?i:null,o=new Map;for(let a of Array.from(t.querySelectorAll("[data-scroll-key]"))){let c=a.getAttr("data-scroll-key");c&&o.set(c,{top:a.scrollTop,left:a.scrollLeft})}return{focusKey:i?.getAttr("data-focus-key")??null,selectionStart:s?.selectionStart??null,selectionEnd:s?.selectionEnd??null,scroll:o}}restoreRenderSnapshot(t,n){for(let[s,o]of n.scroll){let a=t.querySelector(`[data-scroll-key="${s}"]`);a&&(a.scrollTop=o.top,a.scrollLeft=o.left)}if(!n.focusKey)return;let i=t.querySelector(`[data-focus-key="${n.focusKey}"]`);i?.focus({preventScroll:!0}),(i instanceof HTMLInputElement||i instanceof HTMLTextAreaElement)&&n.selectionStart!==null&&n.selectionEnd!==null&&i.setSelectionRange(n.selectionStart,n.selectionEnd)}iconButton(t,n,i){let s=t.createEl("button",{cls:"clickable-icon mdbase-icon-button"});return s.setAttr("aria-label",i),s.setAttr("title",i),s.setAttr("data-focus-key",`action-${i.toLowerCase().replace(/[^a-z0-9]+/g,"-")}`),(0,Ds.setIcon)(s,n),s}disclosure(t,n,i,s=!1){let o=t.createEl("details",{cls:"mdbase-disclosure"});return o.dataset.disclosure=n,o.open=this.disclosures.get(n)??s,o.addEventListener("toggle",()=>{this.containerEl.contains(o)&&(this.disclosures.set(n,o.open),this.app.workspace?.requestSaveLayout())}),o.createEl("summary",{text:i}).setAttr("data-focus-key",`disclosure-${n}`),o.createDiv({cls:"mdbase-disclosure-body"})}renderTopbar(t){let i=t.createDiv({cls:"mdbase-topbar"}).createDiv({cls:"mdbase-nav"});i.setAttr("role","tablist");for(let[s,o]of[["types","Types"],["sync","Sync"],["issues","Issues"]]){let a=i.createEl("button",{text:o,cls:"clickable-icon"});if(a.addClass("mdbase-nav-button"),a.setAttr("role","tab"),a.setAttr("data-focus-key",`destination-${s}`),a.setAttr("aria-selected",String(this.destination===s)),this.destination===s&&a.addClass("is-active"),s==="issues"&&this.host.getIssues().length){let l=this.host.getIssues().length;a.createSpan({cls:"mdbase-count",text:Zm(l)}).setAttr("title",`${l} issues`)}let c=s==="sync"?this.syncAttention():null;c&&a.createSpan({cls:"mdbase-count",text:Zm(c.count)}).setAttr("title",c.label),a.onclick=()=>this.showDestination(s)}}async perform(t){if(!this.busy){this.busy=!0,this.message="",this.render();try{await t()}catch(n){let i=n instanceof Error?n.message:String(n);this.message=i,new Ds.Notice(i)}finally{this.busy=!1,this.render()}}}};var Aa=class{constructor(e,t){this.delayMs=e;this.task=t;this.entries=new Map;if(!Number.isFinite(e)||e<0)throw new Error("Debounce delay must be a non-negative finite number.")}has(e){return this.entries.has(e)}schedule(e,t){let n=this.entries.get(e);n||(n={value:t,revision:0,timer:null,ready:!1,running:!1},this.entries.set(e,n)),n.value=t,n.revision+=1,n.ready=!1,n.timer!==null&&clearTimeout(n.timer),n.timer=setTimeout(()=>{this.entries.get(e)===n&&(n.timer=null,n.ready=!0,this.drain(e,n))},this.delayMs)}cancel(e){let t=this.entries.get(e);t&&(t.timer!==null&&clearTimeout(t.timer),this.entries.delete(e))}clear(){for(let e of this.entries.values())e.timer!==null&&clearTimeout(e.timer);this.entries.clear()}async drain(e,t){if(this.entries.get(e)!==t||t.running||!t.ready)return;t.ready=!1,t.running=!0;let n=t.revision,i=t.value,s=()=>this.entries.get(e)===t&&t.revision===n;try{await this.task(i,s)}finally{t.running=!1,this.entries.get(e)===t&&(t.ready?this.drain(e,t):t.timer===null&&t.revision===n&&this.entries.delete(e))}}};var Hx=require("obsidian");var Pd=class extends Hx.Modal{constructor(t,n,i){super(t);this.path=n;this.runs=i}onOpen(){this.titleEl.setText(`Sync history \xB7 ${this.path.split("/").pop()??this.path}`),this.contentEl.addClass("mdbase-note-history");let t=z$(this.runs,this.path).map(({run:i,file:s})=>({at:s.at,label:i.summary??W$(s),detail:i.summary===void 0&&s.fromPath?`From ${s.fromPath}`:s.message}));if(!t.length){this.contentEl.createEl("p",{cls:"mdbase-muted",text:"No syncs of this note are recorded on this device."});return}let n=this.contentEl.createDiv({cls:"mdbase-transfer-ledger"});for(let i of t){let s=n.createDiv({cls:"mdbase-note-history-row"});s.createSpan({cls:"mdbase-muted",text:ks(i.at)});let o=s.createDiv();o.createDiv({text:i.label}),i.detail&&o.createDiv({cls:"mdbase-muted",text:i.detail})}}onClose(){this.contentEl.empty()}};var Ne=require("obsidian");var nj=[["image","Images"],["audio","Audio"],["video","Video"],["pdf","PDFs"],["other","Other files"]],Cd=class extends Ne.PluginSettingTab{constructor(t,n){super(t,n);this.plugin=n}display(){let{containerEl:t,plugin:n}=this;t.empty(),new Ne.Setting(t).setName("Validate notes automatically").setDesc("Check notes against their types when they are opened or saved.").addToggle(i=>i.setValue(n.settings.validateOnSave||n.settings.validateOnOpen).onChange(async s=>{n.settings.validateOnSave=s,n.settings.validateOnOpen=s,await n.saveSettings(),this.display()})),n.settings.validateOnSave&&new Ne.Setting(t).setName("Show validation notices").setDesc("Notify when saving a note with issues.").addToggle(i=>i.setValue(n.settings.showNoticeOnSave).onChange(async s=>{n.settings.showNoticeOnSave=s,await n.saveSettings()})),new Ne.Setting(t).setName("Allow plugin integrations").setDesc("Let other installed plugins exchange mdbase events and actions in this vault.").addToggle(i=>i.setValue(n.settings.interopEnabled).onChange(async s=>{n.settings.interopEnabled=s,await n.saveSettings()})),this.displaySync(t)}displaySync(t){let{plugin:n}=this,i=n.getMirrorProfile();if(new Ne.Setting(t).setName("Sync").setHeading(),!i){new Ne.Setting(t).setName("Not connected").setDesc("Connect this vault to mdbase Connect from the sync tab of the mdbase workspace.").addButton(l=>l.setButtonText("Open sync").onClick(()=>{n.openWorkspace("sync")}));return}new Ne.Setting(t).setName(i.name).setDesc(`${i.mode==="read_write"?"Read and write":"Read only"} \xB7 ${new URL(i.controlUrl).host}`).addButton(l=>l.setButtonText("Reconnect").onClick(async()=>{l.setDisabled(!0),await n.openWorkspace("sync").then(u=>u.reconnectCollection()),l.setDisabled(!1)})),new Ne.Setting(t).setName("Sync automatically").setDesc("Keep this vault in sync in the background. Deleted files go to the trash, and conflicting edits are merged or kept as two files. Deleting many files at once on this device waits for your review.").addToggle(l=>l.setValue(n.settings.autoSync).onChange(async u=>{n.settings.autoSync=u,await n.saveSettings(),n.requestSync()}));let s=n.connectSync.getSelectiveSync(),o=async l=>{try{await n.sync.configureSelectiveSync(l)}catch(u){new Ne.Notice(u instanceof Error?u.message:String(u)),this.display()}};for(let[l,u]of nj)new Ne.Setting(t).setName(`Sync ${u.toLowerCase()}`).setDesc(l==="other"?"All remaining visible file formats. Markdown always syncs.":"").addToggle(d=>d.setValue(s.file_classes.includes(l)).onChange(async f=>{let p=n.connectSync.getSelectiveSync();await o({...p,file_classes:f?[...new Set([...p.file_classes,l])]:p.file_classes.filter(m=>m!==l)})}));let a=[...s.excluded_folders],c=new Ne.Setting(t).setName("Excluded folders").setDesc(Sd);$d(this.app,c.controlEl,a,l=>{a=l}),c.addButton(l=>l.setButtonText("Apply").onClick(async()=>{await o({...n.connectSync.getSelectiveSync(),excluded_folders:a}),new Ne.Notice("Excluded folders updated. The next sync applies them.")})),new Ne.Setting(t).setName("Disconnect").setDesc("Stop syncing this vault. The hosted collection is not deleted.").addButton(l=>l.setButtonText("Disconnect\u2026").setWarning().setDisabled(n.sync.isSyncing()).onClick(async()=>{let u=await new Ac(this.app).choose(i.name);if(u){try{await n.sync.disconnect(i,u==="remove"),new Ne.Notice(n.sync.state.message)}catch(d){new Ne.Notice(d instanceof Error?d.message:String(d))}this.display()}}))}};async function zx(r,e,t,n){let i=await r.resolveConflict(e,t,n),s=await r.preview();return{status:i,preview:s}}var ij=4,Kx={status:null,preview:null,progress:null,fileProgress:null,problem:null,message:"",localChangeObserved:!1,busy:!1,paused:!1,retryAt:null},Md=class{constructor(e,t,n,i=()=>{}){this.controller=e;this.getProfile=t;this.history=n;this.notify=i;this.current={...Kx};this.listeners=new Set;this.safetyPreview=null;this.previewSafety=null;this.pinnedFailure=null}get state(){return this.current}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}update(e){this.current={...this.current,...e};for(let t of this.listeners)t()}reset(){this.update({...Kx})}isSyncing(){return this.controller.isSyncing()}clearMessage(){this.current.message&&this.update({message:""})}observeLocalChange(){this.current.localChangeObserved||this.update({localChangeObserved:!0})}historyRuns(){let e=this.getProfile()?.collectionId;return e?this.history?.list(e)??[]:[]}async recordEvent(e,t=this.getProfile()?.collectionId){if(!(!t||!this.history)){try{await this.history.append(cd(t,e))}catch(n){console.error("mdbase: could not save sync history",n)}this.update({})}}async dismissEvent(e){await this.history?.remove(e),this.update({})}async clearHistory(){await this.history?.clear(),this.update({})}async refreshStatus(){let e=this.getProfile();if(!e)return this.reset(),null;if(this.controller.isSyncing())return this.current.status;try{let t=await this.controller.status();return Wx(e,this.getProfile())?(this.update({status:t,problem:null}),t):null}catch(t){return Wx(e,this.getProfile())&&this.update({problem:Rt(t)}),null}}async review(){return this.getProfile()?await this.exclusive(async()=>(await this.loadPreview(),this.current.preview))??null:null}async apply(){if(!this.current.preview){await this.review();return}await this.exclusive(()=>this.applyReviewed())}async syncNow(e={}){return this.getProfile()?this.current.busy||this.controller.isSyncing()?"busy":e.automatic&&this.current.paused?"paused":(!e.automatic&&this.current.paused&&this.update({paused:!1}),await this.exclusive(async()=>{let n=!1;for(let i=0;it.outcome!=="unresolved")}safety(){let e=this.current.preview;return e!==this.safetyPreview&&(this.safetyPreview=e,this.previewSafety=e?D$(e):null),this.previewSafety}cancel(){this.update({paused:!0}),this.controller.isSyncing()&&(this.controller.cancelSync(),this.update({message:"Stopping\u2026"}))}async reconnect(){return await this.exclusive(async()=>{try{let t=await this.controller.reconnect();return this.update({status:t,problem:null,message:"Connection restored."}),await this.recordEvent({summary:"Collection reconnected",message:"Connect credentials were renewed and the mirror checkpoint was preserved.",tone:"success"}),"connected"}catch(t){let n=Rt(t);return this.update({problem:n,message:n.action==="reauthorize"?"":n.message}),n.action==="reauthorize"?"reauthorize":"failed"}})??"failed"}async reauthorize(e){let t=await this.controller.reauthorize(e);this.update({status:t,problem:null,message:"Approval restored. The mirror checkpoint was preserved."}),await this.recordEvent({summary:"Connect approval restored",message:"The existing mirror checkpoint and local files were preserved.",tone:"success"})}async disconnect(e,t){let n=await this.controller.disconnect(t),i=t?`${n.removed.length} unchanged synced ${n.removed.length===1?"file was":"files were"} removed. ${n.preserved.length} locally changed ${n.preserved.length===1?"file was":"files were"} preserved.`:"All local files were retained as an unsynced copy.";return this.reset(),this.update({message:`Disconnected from ${e.name}. ${i}`}),n}async configureSelectiveSync(e){await this.controller.configureSelectiveSync(e),this.update({preview:null,message:"Sync settings updated."})}async resolveConflict(e,t,n){let i=null;try{n&&(i=await this.controller.preserveConflictCopy(e.path??"")),this.update({preview:null});let s=await zx(this.controller,e.object_id,e.decision_id,t),o=i?`Local copy saved to ${i}. Sync to apply the hosted version.`:"Conflict resolved. Sync to continue.";return this.update({status:s.status,preview:s.preview,problem:null,message:o}),await this.recordEvent({summary:i?"Conflict kept as two files":`Conflict resolved with ${t==="local"?"local":"hosted"} version`,message:o,...e.path?{path:e.path}:{},tone:"info"}),!0}catch(s){let o=Rt(s);return i&&(o.message=`The local copy at ${i} is safe, but the original changed again. Review the newest versions before deciding.`),this.update({problem:o,message:o.message}),o.code==="conflict_decision_stale"&&(this.update({preview:null}),await this.refreshStatus()),await this.recordEvent({summary:o.title,message:o.message,...e.path?{path:e.path}:{},tone:"attention",needsAcknowledgement:!0}),!1}}reportProblem(e){let t=Rt(e);return this.update({problem:t,message:t.message}),t}async exclusive(e,t=!1){if(!this.current.busy){this.update({busy:!0,...t?{}:{message:""}});try{return await e()}finally{this.update({busy:!1})}}}async loadPreview(){try{let{preview:e,status:t}=await this.controller.inspect();return this.update({preview:e,status:t,problem:null}),e}catch(e){let t=Rt(e);return this.update({problem:t,message:t.message}),null}}async applyReviewed(){let e=this.current.preview;if(!e)return"failed";let t=this.getProfile()?.collectionId,n=new Date().toISOString(),i=[],s="failed",o;try{let a=await this.controller.sync(e,m=>this.update({progress:m}),m=>this.update({fileProgress:m}),(m,h)=>{let y=V$(m,h,new Date().toISOString());y&&i.push(y)});s=a.status,o=a.failure?.message;let{preview:c,status:l}=await this.controller.inspect(),u=a.status==="cancelled"?Rt(new DOMException("Synchronization stopped.","AbortError")):a.status==="failed"||a.status==="blocked"?Nx(a.failure??{code:"sync_failed",message:"Synchronization stopped."}):null,d=a.status==="applied"?"Sync complete.":a.status==="attention"?a.applied>0?"Available changes synced. Remaining items need attention.":"No available changes. Resolve the listed items and review again.":a.status==="cancelled"?`Sync paused after ${a.applied} ${a.applied===1?"change":"changes"}. Resume to finish the rest.`:a.status==="stale"?"Files changed during sync; checking again.":u?.message??`Sync stopped: ${a.failure?.message??a.status}.`;this.update({status:l,preview:c.plan.actions.length||c.entries.length?c:null,problem:u,message:d,...a.status==="applied"&&a.pending===0?{localChangeObserved:!1}:{}});let f=u?`${u.kind}:${u.code}`:null,p=a.status==="stale"||u?.kind==="offline"||a.status==="attention"&&l.conflicts.length>0||f!==null&&f===this.pinnedFailure;return a.status==="applied"?this.pinnedFailure=null:f&&!p&&(this.pinnedFailure=f),!p&&(a.status!=="applied"||!i.length)&&await this.recordEvent({summary:a.status==="applied"?`Synchronized ${a.applied} ${a.applied===1?"change":"changes"}`:a.status==="cancelled"?"Synchronization paused safely":a.applied>0?"Synced available changes":"Synchronization needs attention",message:d,tone:a.status==="applied"?"success":"attention",needsAcknowledgement:a.status!=="applied"&&a.status!=="attention"},t),a.status==="blocked"?"failed":a.status}catch(a){let c=Rt(a);s=c.kind==="paused"?"cancelled":"failed",o=c.message,this.update({problem:c,message:c.message});let l=`${c.kind}:${c.code}`;return c.kind!=="offline"&&l!==this.pinnedFailure&&(this.pinnedFailure=l,await this.recordEvent({summary:c.title,message:c.message,tone:c.kind==="paused"?"attention":"error",needsAcknowledgement:c.kind!=="paused"},t)),c.kind==="paused"?"cancelled":"failed"}finally{if(this.update({progress:null,fileProgress:null}),t&&i.length&&this.history){try{await this.history.append({id:crypto.randomUUID(),collectionId:t,startedAt:n,finishedAt:new Date().toISOString(),outcome:s,files:i,...o?{message:o}:{}})}catch(a){console.error("mdbase: could not save sync history",a)}this.update({})}}}};function Wx(r,e){return r?.collectionId===e?.collectionId}function sj(r){let e=r.path.split("/").pop()??r.path;switch(r.outcome){case"merged":return{summary:`Merged edits to ${e}`,message:"Changes made here and on another device were combined.",path:r.path,tone:"success"};case"kept_both":return{summary:`Kept both versions of ${e}`,message:`The same part was edited on two devices. The other device's version is in place and this device's version was saved as ${r.copyPath??"a copy"}.`,path:r.path,tone:"attention",needsAcknowledgement:!0};case"restored":return{summary:`Restored ${e}`,message:"It was deleted here but edited on another device, so the edited version was kept.",path:r.path,tone:"info"};case"kept_local":return{summary:`Kept ${e}`,message:"It was deleted on another device but edited here, so this version was uploaded again.",path:r.path,tone:"info"};case"took_hosted":return{summary:`Settled ${e}`,message:"The hosted version was kept.",path:r.path,tone:"info"};case"unresolved":return{summary:`Couldn't sync ${e}`,message:r.reason??"This change needs a decision.",path:r.path,tone:"attention",needsAcknowledgement:!0}}}var oj={localQuietMs:3e3,localMaxWaitMs:2e4,probeVisibleMs:3e4,probeHiddenMs:5*6e4,safetyNetMs:15*6e4,retryBaseMs:5e3,retryMaxMs:5*6e4,unexpectedRetryMaxMs:30*6e4},Gx=new Set(["auth","device","paused"]),Td=class{constructor(e,t=aj,n=oj){this.host=e;this.clock=t;this.timing=n;this.timer=null;this.dueAt=null;this.dueIsDebounce=!1;this.firstLocalChangeAt=null;this.changed=!0;this.failures=0;this.running=!1;this.rerun=!1;this.visible=!0;this.stopped=!0;this.lastSyncAt=t.now()}start(){this.stopped=!1,this.schedule(this.clock.now())}stop(){this.stopped=!0,this.timer!==null&&this.clock.clearTimeout(this.timer),this.timer=null,this.dueAt=null}noteLocalChange(){let e=this.clock.now();this.firstLocalChangeAt??=e,this.changed=!0,this.schedule(Math.min(e+this.timing.localQuietMs,this.firstLocalChangeAt+this.timing.localMaxWaitMs),!0)}noteVisibility(e){let t=this.visible;this.visible=e,e&&!t&&this.schedule(this.clock.now())}noteOnline(){this.failures>0&&(this.changed=!0),this.failures=0,this.host.setRetryAt(null),this.schedule(this.clock.now())}requestSoon(){this.schedule(this.clock.now())}async tick(){if(this.stopped)return;if(this.running){this.rerun=!0;return}this.running=!0,this.dueAt=null;let e=null;try{e=await this.decide()}finally{this.running=!1;let t=this.clock.now();this.rerun?(this.rerun=!1,this.schedule(t)):e!==null?this.schedule(t+e):this.schedule(t+(this.visible?this.timing.probeVisibleMs:this.timing.probeHiddenMs))}}async decide(){if(!this.host.connected())return null;let e=this.host.problemKind();if(e&&Gx.has(e))return null;let t=this.clock.now(),n=this.changed;if(this.changed=!1,this.firstLocalChangeAt=null,!this.host.automatic())return(n||await this.probe()===!0)&&await this.host.refreshStatus(),null;let i=n||this.failures>0||t-this.lastSyncAt>=this.timing.safetyNetMs;if(!i){let o=await this.probe();if(o===null)return this.failed(!0);i=o}if(!i)return null;this.lastSyncAt=t;let s=await this.host.autoSync();if(s==="busy")return this.changed||=n,2e3;if(s==="failed"){this.changed||=n;let o=this.host.problemKind();return o&&Gx.has(o)?this.settled():this.failed(o==="offline")}return this.settled()}async probe(){try{return await this.host.remoteChangesWaiting()}catch(e){return this.host.reportProblem(e),oa(e)?null:!0}}failed(e){let t=km(this.failures,{baseDelayMs:this.timing.retryBaseMs,maxDelayMs:e?this.timing.retryMaxMs:this.timing.unexpectedRetryMaxMs,random:()=>this.clock.random()});return this.failures+=1,this.host.setRetryAt(this.clock.now()+t),t}settled(){return this.failures=0,this.host.setRetryAt(null),null}schedule(e,t=!1){if(this.stopped)return;let n=this.timer===null?null:this.dueAt;n!==null&&n<=e&&!(t&&this.dueIsDebounce)||(this.timer!==null&&this.clock.clearTimeout(this.timer),this.dueAt=e,this.dueIsDebounce=t,this.timer=this.clock.setTimeout(()=>{this.timer=null,this.dueAt=null,this.tick()},Math.max(0,e-this.clock.now())))}},aj={now:()=>Date.now(),setTimeout:(r,e)=>window.setTimeout(r,e),clearTimeout:r=>window.clearTimeout(r),random:()=>Math.random()};function Yx(r){let{profile:e,state:t}=r,n=["mdbase sync diagnostics",`Generated: ${r.generatedAt}`,`Plugin ${r.pluginVersion} \xB7 Obsidian ${r.obsidianVersion} \xB7 ${r.platform}`,"","Connection"];e?n.push(` Collection: ${e.collectionId}`,` Replica: ${e.replicaId} (${e.mode})`,` Connect: ${Jx(e.controlUrl)} \xB7 sync ${Jx(e.syncUrl)}`,` Access token expires: ${e.accessTokenExpiresAt}`,` Enrolled on this device: ${r.otherDevice?"no \u2014 copied from another device or vault":"yes"}`,` File classes: ${e.selectiveSync?.file_classes.join(", ")||"notes only"}`,` Excluded folders: ${e.selectiveSync?.excluded_folders.length??0}`):n.push(" Not connected"),n.push(` Automatic sync: ${r.automatic?"on":"off"}${t.paused?" (paused)":""}`,` Other sync services on this vault: ${r.otherSyncServices.join(", ")||"none detected"}`,"","State",` Engine state: ${t.status?.state??"unknown"} \xB7 pending ${t.status?.pending??"?"} \xB7 conflicts ${t.status?.conflicts.length??0} \xB7 local issues ${t.status?.local_issues.length??0}`,` Last synced: ${t.status?.last_synced_at??"never"}`,` Problem: ${t.problem?`${t.problem.kind}/${t.problem.code} \u2014 ${t.problem.message}`:"none"}`,` Next automatic attempt: ${t.retryAt?new Date(t.retryAt).toISOString():"not scheduled"}`,` Plan on screen: ${t.preview?`${t.preview.plan.kind}, ${t.preview.plan.actions.length} actions, ${t.preview.plan.summary.blocking_issues} blocking issues`:"none"}`,` Checkpoint: ${r.checkpoint?`cursor ${r.checkpoint.cursor}, generation ${r.checkpoint.generation}`:"none"}`,` Interrupted batch: ${r.checkpoint?.batch??"none"}${r.checkpoint?.failure?` (${r.checkpoint.failure})`:""}`,"","Recent history (newest first)");let i=[...r.history].sort((s,o)=>o.finishedAt.localeCompare(s.finishedAt)).slice(0,25);i.length||n.push(" none");for(let s of i){let o=s.summary??`${s.files.length} ${s.files.length===1?"file":"files"}`;n.push(` ${s.finishedAt} \xB7 ${s.outcome}${s.tone?`/${s.tone}`:""} \xB7 ${o}${s.message?` \u2014 ${s.message}`:""}`)}return`${n.join(` `)} -`}function Gx(r){try{return new URL(r).host}catch{return"invalid URL"}}var cj={validateOnSave:!0,validateOnOpen:!0,showNoticeOnSave:!1,interopEnabled:!1,mirrorProfile:null,typeDrafts:{},archivedTypeDrafts:[],autoSync:!0,syncSettingsVersion:2},Yx="mdbase-sync-device-id";function lj(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"&&(e.selectiveSync===void 0||Array.isArray(e.selectiveSync.file_classes)&&Array.isArray(e.selectiveSync.excluded_folders))}function dj(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var Id=class extends L.Plugin{constructor(t,n){super(t,n);this.issueMap=new Map;this.validation=new Ta;this.validationAbort=null;this.sortedIssuesCache=null;this.noteStatusVersion=0;this.syncScheduler=null;this.recordCache=null;this.recordCacheSettings="";this.recordList=null;this.recordLoadPromise=null;this.dirtyRecordPaths=new Set;this.schemaCache=null;this.schemaLoadPromise=null;this.saveValidationDebounceMs=2e3;this.schemaRefreshDebounceMs=2e3;this.saveValidations=new Aa(this.saveValidationDebounceMs,async(t,n)=>{try{await this.validateFileAndStore(t,"save",n)}catch(i){console.error("mdbase: background validation failed",i)}});this.schemaRefreshes=new Aa(this.schemaRefreshDebounceMs,async()=>{this.invalidateSchemaCache(),this.refreshWorkspaceViews()});this.connectSync=new pd(t,{getMirrorProfile:()=>this.getMirrorProfile(),saveMirrorProfile:async i=>{this.settings.mirrorProfile=i,await this.saveSettings(),i?this.requestSync():this.sync?.reset()},deviceId:()=>this.deviceId()}),this.interopBridge=new Vc(t,()=>this.settings?.interopEnabled===!0),this.api={apiVersion:1,interop:this.interopBridge,getInteropStatus:()=>({enabled:this.settings?.interopEnabled===!0,profileVersion:"0.1"})}}async onload(){await this.loadSettings(),await this.connectSync.initialize(),await this.createSyncSession(),(0,L.addIcon)(Sa,vx),this.statusBarEl=this.addStatusBarItem(),this.statusBarEl.addClass("mdbase-status-bar"),this.statusBarEl.setAttr("role","button"),this.statusBarEl.setAttr("tabindex","0"),this.registerDomEvent(this.statusBarEl,"click",()=>void this.openStatusDestination()),this.registerDomEvent(this.statusBarEl,"keydown",n=>{n.key!=="Enter"&&n.key!==" "||(n.preventDefault(),this.openStatusDestination())}),this.noteStatusEl=this.addStatusBarItem(),this.noteStatusEl.addClass("mdbase-note-status"),this.noteStatusEl.setAttr("role","button"),this.noteStatusEl.setAttr("tabindex","0"),this.noteStatusEl.hide(),this.registerDomEvent(this.noteStatusEl,"click",()=>void this.openNoteStatusDestination()),this.registerDomEvent(this.noteStatusEl,"keydown",n=>{n.key!=="Enter"&&n.key!==" "||(n.preventDefault(),this.openNoteStatusDestination())}),this.updateStatusBar(),this.registerView(Dr,n=>new Pd(n,this)),this.addSettingTab(new Md(this.app,this)),this.addRibbonIcon(Sa,"Open mdbase",()=>void this.openWorkspace()),gw(this),this.registerEvent(this.app.vault.on("modify",n=>{n instanceof L.TFile&&this.onVaultModify(n)})),this.registerEvent(this.app.vault.on("rename",(n,i)=>{n instanceof L.TFile&&this.onVaultRename(n,i)})),this.registerEvent(this.app.vault.on("delete",n=>{n instanceof L.TFile&&this.onVaultDelete(n)})),this.registerEvent(this.app.vault.on("create",n=>{n instanceof L.TFile&&this.onVaultCreate(n)})),this.registerEvent(this.app.workspace.on("file-open",n=>{this.settings.validateOnOpen&&(!(n instanceof L.TFile)||n.extension!=="md"||this.validateFileAndStore(n,"open"))})),this.registerEvent(this.app.workspace.on("active-leaf-change",()=>void this.updateNoteStatus())),this.registerEvent(this.app.metadataCache.on("changed",n=>{n.path===this.app.workspace.getActiveFile()?.path&&this.updateNoteStatus()})),this.registerEvent(this.app.workspace.on("editor-change",(n,i)=>{let s=i.file;s instanceof L.TFile&&(this.saveValidations.has(s.path)&&this.scheduleSaveValidation(s),this.schemaRefreshes.has("schema")&&this.isSchemaRelevantPath(s.path)&&this.scheduleSchemaRefresh())}));try{await Ld(this.app)}catch(n){new L.Notice(`Contract pack recovery needs attention: ${String(n)}`,0)}let t=this.app.workspace.getActiveFile();t&&this.settings.validateOnOpen&&this.validateFileAndStore(t,"open"),this.startSyncScheduler()}startSyncScheduler(){this.syncScheduler=new Rd({connected:()=>this.getMirrorProfile()!==null,automatic:()=>this.settings.autoSync,problemKind:()=>this.sync.state.problem?.kind??(this.sync.state.paused?"paused":null),autoSync:()=>this.sync.autoSync(),refreshStatus:()=>this.sync.refreshStatus(),remoteChangesWaiting:()=>this.connectSync.remoteChangesWaiting(),reportProblem:n=>{this.sync.reportProblem(n)},setRetryAt:n=>this.sync.setRetryAt(n)}),this.registerDomEvent(window,"online",()=>this.syncScheduler?.noteOnline()),this.registerDomEvent(window,"focus",()=>this.syncScheduler?.noteVisibility(!0));let t=window.document;this.registerDomEvent(t,"visibilitychange",()=>{this.syncScheduler?.noteVisibility(t.visibilityState==="visible")}),this.syncScheduler.start()}requestSync(){this.syncScheduler?.requestSoon()}deviceId(){let t=this.app.loadLocalStorage(Yx);if(typeof t=="string"&&t)return t;let n=crypto.randomUUID();return this.app.saveLocalStorage(Yx,n),n}onunload(){this.validationAbort?.abort(),this.syncScheduler?.stop(),this.connectSync.dispose(),this.interopBridge.dispose().catch(t=>{console.error("mdbase: failed to dispose the interoperability bridge",t)}),this.app.workspace.getLeavesOfType(Dr).forEach(t=>t.detach()),this.saveValidations.clear(),this.schemaRefreshes.clear()}async loadSettings(){let t=await this.loadData();if(this.settings=Object.assign({},cj,t),t&&(t.syncSettingsVersion??1)<2&&(this.settings.autoSync=!0,this.settings.syncSettingsVersion=2),!lj(this.settings.mirrorProfile))this.settings.mirrorProfile=null;else try{this.settings.mirrorProfile.selectiveSync=fr(this.settings.mirrorProfile.selectiveSync)}catch{this.settings.mirrorProfile.selectiveSync=fr()}(!this.settings.typeDrafts||typeof this.settings.typeDrafts!="object"||Array.isArray(this.settings.typeDrafts))&&(this.settings.typeDrafts={}),this.settings.archivedTypeDrafts=Array.isArray(this.settings.archivedTypeDrafts)?this.settings.archivedTypeDrafts:[]}async saveSettings(){await this.saveData(this.settings)}getIssues(){return this.sortedIssuesCache??=Array.from(this.issueMap.values()).flat().sort((t,n)=>t.path.localeCompare(n.path)||t.severity.localeCompare(n.severity)||t.code.localeCompare(n.code)),this.sortedIssuesCache}getMirrorProfile(){return this.settings.mirrorProfile?JSON.parse(JSON.stringify(this.settings.mirrorProfile)):null}otherSyncServices(){let t=[],n=this.app,i=n.internalPlugins?.getEnabledPluginById?.("sync");typeof i?.vaultId=="string"&&i.vaultId&&t.push("Obsidian Sync");let s={"obsidian-livesync":"Self-hosted LiveSync","remotely-save":"Remotely Save","obsidian-git":"Obsidian Git"};for(let[l,u]of Object.entries(s))n.plugins?.enabledPlugins?.has(l)&&t.push(u);let o=this.app.vault.adapter,a=typeof L.FileSystemAdapter=="function"&&o instanceof L.FileSystemAdapter?o.getBasePath():"",c=[[/Mobile Documents|iCloud/i,"iCloud Drive"],[/[\\/]Dropbox[\\/]/i,"Dropbox"],[/[\\/]OneDrive/i,"OneDrive"],[/Google ?Drive|GoogleDrive/i,"Google Drive"]];for(let[l,u]of c)l.test(a)&&t.push(u);return t}async copySyncDiagnostics(){let t=this.getMirrorProfile(),n=null;try{n=await this.connectSync.checkpointSummary()}catch(s){console.error("mdbase: could not read the sync checkpoint for diagnostics",s)}let i=Jx({generatedAt:new Date().toISOString(),pluginVersion:this.manifest.version,obsidianVersion:L.apiVersion,platform:L.Platform.isIosApp?"iOS":L.Platform.isAndroidApp?"Android":L.Platform.isMacOS?"macOS":L.Platform.isWin?"Windows":L.Platform.isLinux?"Linux":"unknown",profile:t,otherDevice:this.connectSync.isOtherDevice(t),automatic:this.settings.autoSync,otherSyncServices:this.otherSyncServices(),state:this.sync.state,checkpoint:n,history:this.sync.historyRuns()});await navigator.clipboard.writeText(i),new L.Notice("Copied sync diagnostics. They name the collection and recent files but contain no note text or credentials.")}openNoteSyncHistory(t){new Cd(this.app,t,this.sync.historyRuns()).open()}openSettings(){let t=this.app.setting;t?.open(),t?.openTabById(this.manifest.id)}async createSyncSession(){let t=this.manifest.dir??`${this.app.vault.configDir}/plugins/${this.manifest.id}`,n=new ad(this.app.vault.adapter,(0,L.normalizePath)(`${t}/sync-history.jsonl`));try{await n.load(),await this.migrateSyncActivity(n)}catch(i){console.error("mdbase: could not load sync history",i)}this.sync=new Td(this.connectSync,()=>this.getMirrorProfile(),n,i=>{new L.Notice(`mdbase: ${i}`,1e4)}),this.register(this.sync.subscribe(()=>this.updateStatusBar()))}async migrateSyncActivity(t){let n=Nx(this.settings.syncActivity),i=this.settings.mirrorProfile?.collectionId;if(i)for(let s of n)await t.append(cd(i,{summary:s.summary,tone:s.tone,...s.detail?{message:s.detail}:{},...s.path?{path:s.path}:{},...s.requiresAcknowledgement?{needsAcknowledgement:!0}:{}},s.occurredAt));this.settings.syncActivity!==void 0&&(delete this.settings.syncActivity,await this.saveSettings())}async loadWorkspaceSchema(t=!1){return this.getConfigAndTypes(t)}async loadTypeModel(t){let n=this.app.vault.getAbstractFileByPath((0,L.normalizePath)(t));if(!(n instanceof L.TFile))throw new Error(`Type file not found: ${t}`);let i=await this.app.vault.cachedRead(n),s=Me(i);if(!s.hasFrontmatter||s.error)throw new Error(`Invalid type frontmatter: ${s.error??"frontmatter is missing"}`);let o=bd(s.frontmatter,s.body,n.basename);return o.sourceRevision=Jm(i),o}loadTypeDraft(t){let n=this.settings.typeDrafts[t??"__new__"];return n?JSON.parse(JSON.stringify(n)):null}async saveTypeDraft(t){let n=this.loadTypeDraft(t.path);n&&n.sourceRevision!==t.sourceRevision&&this.settings.archivedTypeDrafts.push(n),this.settings.typeDrafts[t.path??"__new__"]=JSON.parse(JSON.stringify(t)),await this.saveSettings()}getArchivedTypeDrafts(t){return this.settings.archivedTypeDrafts.filter(n=>n.path===t)}async discardArchivedTypeDraft(t){this.settings.archivedTypeDrafts=this.settings.archivedTypeDrafts.filter(n=>n.path!==t.path||n.updatedAt!==t.updatedAt||n.sourceRevision!==t.sourceRevision),await this.saveSettings()}async clearTypeDraft(t){let n=t??"__new__";n in this.settings.typeDrafts&&(delete this.settings.typeDrafts[n],await this.saveSettings())}async saveTypeModel(t,n,i){if(this.connectSync.assertLocalAuthorityWritable(),this.getMirrorProfile()?.mode==="read_only")throw new Error("This mirror has read-only access. Re-enroll it with write access before editing types.");let s=await ai(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 o=n?this.app.vault.getAbstractFileByPath((0,L.normalizePath)(n)):null;if(o!=null&&!(o instanceof L.TFile))throw new Error(`Type file not found: ${n}`);let a=await this.writeTypeDefinition(s,t,o,i);return this.refreshWorkspaceViews(!0),a}getValidationSummary(){let t=this.schemaCache?.config,n=this.app.vault.getMarkdownFiles().filter(i=>!t||!yt(i.path,t)).map(i=>i.path);return this.validation.summary(n)}isValidating(){return this.validationAbort!==null}cancelValidation(){this.validationAbort?.abort()}async openContractCatalog(){if(this.getMirrorProfile())throw new Error("Install packs at the hosted collection authority using mdbase editor.");let t=await this.getConfigAndTypes();if(!t||!t.config.spec_version.startsWith("0.3."))throw new Error("Initialize or migrate this collection first.");if(t.config.settings.types_folder!=="_types"||(t.config.settings.contracts_folder??"_contracts")!=="_contracts")throw new Error("Catalog packs require the standard _types and _contracts folders. Use mdbase editor for custom target mappings.");new Ma(this.app,()=>{if(this.connectSync.assertLocalAuthorityWritable(),this.getMirrorProfile())throw new Error("The vault role changed. Install at the collection authority instead.")},async n=>{this.invalidateSchemaCache();let i=await this.openWorkspace("types");await i.refresh(!0);let s=await this.getConfigAndTypes(),o=n?s?.types.get(n):null;o&&await i.editType(o.filePath),new L.Notice("Installed contract pack. Edit its type or create a note to try it.")}).open()}async createNoteFromType(t){await jp(this,t)}async initializeCollection(){this.connectSync.assertLocalAuthorityWritable();let{created:t}=await $o(this.app.vault,{seedNoteType:!1});this.invalidateSchemaCache(),new L.Notice(t.length?`Initialized mdbase collection: ${t.join(", ")}`:"mdbase collection already initialized."),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 cx(this.app.vault)}async applyMigration(t,n){if(this.connectSync.assertLocalAuthorityWritable(),this.getMirrorProfile())throw new Error("Collection authority resources must be migrated at the collection authority.");let i=await lx(this.app.vault,t,{allowLossy:n});if(!i.applied)throw new Error(i.restored?`Migration failed and all writes were rolled back. ${i.error??""}`.trim():`Migration needs manual recovery. See ${i.manifestPath}. ${i.error??""}`.trim());this.invalidateSchemaCache(),new L.Notice(`Migrated to mdbase v0.3. Recovery manifest: ${i.manifestPath}`),this.refreshWorkspaceViews(!0)}async openIssue(t){await this.openFileByPath(t.path,t.field)}getQuickFixLabel(t){return ww(t)}async applyQuickFix(t){this.connectSync.assertLocalAuthorityWritable();let n=this.app.vault.getAbstractFileByPath(t.path);if(!(n instanceof L.TFile)){new L.Notice(`File not found: ${t.path}`);return}if(this.getMirrorProfile()?.mode==="read_only")throw new Error("This mirror has read-only access.");let i=!1;await this.app.vault.process(n,s=>{this.connectSync.assertLocalAuthorityWritable();let o=qp(s,t);return i=o.changed,o.content}),new L.Notice(i?`Updated '${t.field??"field"}' in ${n.basename}`:"The field changed or no safe quick fix is available. Revalidate the note."),await this.validateFileAndStore(n,"manual")}async applyQuickFixes(t){if(this.connectSync.assertLocalAuthorityWritable(),this.getMirrorProfile()?.mode==="read_only")throw new Error("This mirror has read-only access.");let n=0,i=0,s=new Map;for(let o of t){let a=this.app.vault.getAbstractFileByPath(o.path);if(!(a instanceof L.TFile)){i+=1;continue}let c=!1;await this.app.vault.process(a,l=>{this.connectSync.assertLocalAuthorityWritable();let u=qp(l,o);return c=u.changed,u.content}),c?(n+=1,s.set(a.path,a)):i+=1}for(let o of s.values())await this.validateFileAndStore(o,"manual");return{changed:n,skipped:i}}async openFileByPath(t,n){let i=this.app.vault.getAbstractFileByPath(t);if(!(i instanceof L.TFile)){new L.Notice(`File not found: ${t}`);return}await this.app.workspace.getLeaf(!0).openFile(i),n&&this.revealFrontmatterField(i,n)}revealFrontmatterField(t,n){let i=this.app.workspace.getMostRecentLeaf();if(!i||!(i.view instanceof L.MarkdownView))return;let s=i.view;if(!(s.file instanceof L.TFile)||s.file.path!==t.path)return;let o=s.editor,a=o.lineCount();if(a<3)return;let c=Np(n),l=new RegExp(`^\\s*${dj(c)}\\s*:`);if(o.getLine(0).trim()==="---")for(let u=1;ud.severity==="error").length,c=this.validation.isChecked(n.path),l=c?o.length?` \xB7 ${o.length} ${o.length===1?"issue":"issues"}`:" \xB7 checked":" \xB7 not checked";this.noteStatusEl.setText(`${s.join(", ")}${l}`),this.noteStatusEl.setAttr("data-state",c?a?"error":o.length?"warning":"valid":"unchecked"),this.noteStatusEl.setAttr("data-path",n.path);let u=o.length?`${n.basename}: ${o.length} ${o.length===1?"issue":"issues"}. Open issues for this note.`:`${n.basename} is a ${s.join(", ")} note. Edit the type.`;this.noteStatusEl.setAttr("aria-label",u),this.noteStatusEl.setAttr("title",u),this.noteStatusEl.show()}async openNoteStatusDestination(){let t=this.noteStatusEl.getAttr("data-path");if(!t)return;if(this.issueMap.get(t)?.length){(await this.openWorkspace("issues")).showIssuesForPath(t);return}let n=this.app.vault.getAbstractFileByPath(t),i=await this.getConfigAndTypes();if(!(n instanceof L.TFile)||!i)return;let[s]=Ke(t,this.app.metadataCache.getFileCache(n)?.frontmatter??{},i.config,i.types),o=s?i.types.get(s):void 0;if(!o)return;await(await this.openWorkspace("types")).editType(o.filePath)}markRecordChanged(t){this.validation.changed(t),this.recordCache&&(this.dirtyRecordPaths.add((0,L.normalizePath)(t)),this.recordList=null)}loadCollectionRecords(){return this.recordLoadPromise??=this.readRecords().finally(()=>{this.recordLoadPromise=null}),this.recordLoadPromise}async readRecords(){let t=await this.getConfigAndTypes();if(!t)return[];let n=JSON.stringify(t.config.settings);if(!this.recordCache||n!==this.recordCacheSettings){this.dirtyRecordPaths.clear();let i=await Ap(this.app.vault,t.config);this.recordCache=new Map(i.map(s=>[s.path,s])),this.recordCacheSettings=n,this.recordList=null}else if(this.dirtyRecordPaths.size){let i=[...this.dirtyRecordPaths];this.dirtyRecordPaths.clear();for(let s of i){this.recordCache.delete(s);let o=this.app.vault.getAbstractFileByPath(s);if(!(o instanceof L.TFile)||o.extension!=="md"||yt(s,t.config))continue;let a=Me(await this.app.vault.cachedRead(o));a.error||this.recordCache.set(s,{path:s,frontmatter:a.frontmatter})}this.recordList=null}return this.recordList??=[...this.recordCache.values()].sort((i,s)=>i.path.localeCompare(s.path)),this.recordList}syncIndicator(t){let n=this.sync.state,i=this.sync.safety();return Ox({connected:this.getMirrorProfile()!==null,status:n.status,progress:n.progress,fileProgress:n.fileProgress,problem:n.problem,validationIssues:t,localChangeObserved:n.localChangeObserved,reviewChanges:i&&!i.safe?n.preview?.plan.actions.length??0:0})}async openStatusDestination(){await this.openWorkspace(this.syncIndicator(this.getIssues().length).destination)}async openIssuesView(){await this.openWorkspace("issues")}async openWorkspace(t="types"){let n=this.app.workspace.getLeavesOfType(Dr)[0];if(n){await this.app.workspace.revealLeaf(n);let o=n.view;return o.showDestination(t),await o.refresh(),o}let i=this.app.workspace.getLeaf(!0);await i.setViewState({type:Dr,active:!0}),await this.app.workspace.revealLeaf(i);let s=i.view;return await s.refresh(),s.showDestination(t),s}refreshWorkspaceViews(t=!1){for(let n of this.app.workspace.getLeavesOfType(Dr)){let i=n.view;typeof i.refresh=="function"&&i.refresh(t)}}refreshIssueViews(){this.updateStatusBar(),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 i=this.issueMap.get(t);i&&(this.issueMap.delete(t),this.issueMap.set(n,i.map(s=>({...s,path:n}))),this.sortedIssuesCache=null,this.refreshIssueViews())}clearPendingSaveValidation(t){this.saveValidations.cancel(t)}scheduleSaveValidation(t){this.saveValidations.schedule(t.path,t)}scheduleSchemaRefresh(){this.schemaRefreshes.schedule("schema",void 0)}refreshSchemaNow(){this.schemaRefreshes.cancel("schema"),this.invalidateSchemaCache(),this.refreshWorkspaceViews()}isSchemaRelevantPath(t){let n=(0,L.normalizePath)(t);if(n==="mdbase.yaml")return!0;let i=new Set(["_types","_contracts"]);this.schemaCache&&(i.add((0,L.normalizePath)(this.schemaCache.config.settings.types_folder)),i.add((0,L.normalizePath)(this.schemaCache.config.settings.contracts_folder??"_contracts")));for(let s of i)if(n===s||n.startsWith(`${s}/`))return!0;return!1}invalidateSchemaCache(){this.validation.changed(),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 ai(this.app.vault);if(!n)return null;let i=await kp(this.app.vault,n),s=await Pp(this.app.vault,n);return{config:n,types:i,contracts:s}})();try{let n=await this.schemaLoadPromise;return n&&(this.schemaCache=n),n}finally{this.schemaLoadPromise=null}}async requireConfigAndTypes(t={}){let n=t.background??!1,i=await this.getConfigAndTypes(t.forceReload??!1);return i?(i.types.size===0&&!n&&new L.Notice(`No types found in ${i.config.settings.types_folder}`),i):(n||new L.Notice("No mdbase.yaml found. Run 'mdbase: Initialize collection' first."),null)}onVaultModify(t){this.observeLocalMirrorChange(t.path),this.markRecordChanged(t.path),this.isSchemaRelevantPath(t.path)&&this.scheduleSchemaRefresh(),this.settings.validateOnSave&&t.extension==="md"&&this.scheduleSaveValidation(t)}onVaultRename(t,n){this.observeLocalMirrorChange(n),this.markRecordChanged(n),this.markRecordChanged(t.path),this.observeLocalMirrorChange(t.path),(this.isSchemaRelevantPath(n)||this.isSchemaRelevantPath(t.path))&&this.refreshSchemaNow(),t.extension==="md"&&(this.clearPendingSaveValidation(n),this.moveFileIssues(n,t.path),this.settings.validateOnSave&&this.scheduleSaveValidation(t))}onVaultDelete(t){this.observeLocalMirrorChange(t.path),this.markRecordChanged(t.path),this.isSchemaRelevantPath(t.path)&&this.refreshSchemaNow(),t.extension==="md"&&(this.clearPendingSaveValidation(t.path),this.clearFileIssues(t.path))}onVaultCreate(t){this.observeLocalMirrorChange(t.path),this.markRecordChanged(t.path),this.isSchemaRelevantPath(t.path)&&this.refreshSchemaNow()}observeLocalMirrorChange(t){if(!this.getMirrorProfile()||this.connectSync.isEngineWrite(t))return;let n=(0,L.normalizePath)(t);[this.app.vault.configDir,".mdbase",".trash",".git"].some(s=>n===s||n.startsWith(`${s}/`))||(this.sync.observeLocalChange(),this.syncScheduler?.noteLocalChange())}async validateFileAndStore(t,n,i=()=>!0){let s=await this.requireConfigAndTypes({background:n!=="manual"});if(!i())return[];if(!s)return n!=="manual"&&this.clearFileIssues(t.path),[];let o=this.validation.revision,a=await _c(this.app.vault,t,s.config,s.types);return!i()||o!==this.validation.revision||(this.validation.markChecked(t.path),this.setFileIssues(t.path,a),n==="save"&&this.settings.showNoticeOnSave&&a.length>0&&new L.Notice(`mdbase: ${a.length} issue${a.length===1?"":"s"} in ${t.basename}`)),a}async runCollectionValidation(t){if(this.validationAbort)return;let n=await this.requireConfigAndTypes({background:!1});if(!n||this.validationAbort)return;let i=new AbortController;this.validationAbort=i,this.validation.cancelled=!1;let s=this.validation.revision,o=new Map;try{let a=await Tp(this.app.vault,n.config,n.types,{signal:i.signal,onProgress:c=>{if(this.validation.progress=c,c.completed===0)for(let l of this.app.workspace.getLeavesOfType(Dr))l.view.refreshValidationControls();else if(c.completed%25===0||c.phase==="uniqueness")for(let l of this.app.workspace.getLeavesOfType(Dr))l.view.updateValidationProgress()},onFile:(c,l)=>{s===this.validation.revision&&(this.validation.markChecked(c.path),o.set(c.path,l),l.length?this.issueMap.set(c.path,l):this.issueMap.delete(c.path),this.sortedIssuesCache=null)}});if(s!==this.validation.revision){new L.Notice("Files changed during validation. Validate again for a complete result.");return}o.clear();for(let c of a)o.set(c.path,[...o.get(c.path)??[],c]);this.issueMap=o,this.validation.lastCompletedAt=new Date().toISOString(),this.validation.completedRevision=s,t&&(new L.Notice(a.length?`Collection validation: ${a.length} issues`:"Collection validation passed with no issues."),a.length&&await this.openIssuesView())}catch(a){if(this.validation.cancelled=!0,s===this.validation.revision)for(let[c,l]of o)l.length?this.issueMap.set(c,l):this.issueMap.delete(c);new L.Notice(i.signal.aborted?"Validation stopped. Results are incomplete.":`Validation could not finish: ${String(a)}. Results are incomplete.`)}finally{this.validation.progress=null,this.validationAbort=null,this.sortedIssuesCache=null;for(let a of this.app.workspace.getLeavesOfType(Dr))a.view.refreshValidationControls();this.refreshIssueViews()}}async ensureFolderExists(t){let n=(0,L.normalizePath)(t).replace(/\/+$/,"");if(!n)return;let i=n.split("/"),s="";for(let o of i)s=s?`${s}/${o}`:o,await this.app.vault.adapter.exists(s)||await this.app.vault.createFolder(s)}async writeTypeDefinition(t,n,i,s){let o=n.name.trim();if(!o)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 a=Fn(n),c=n.body.trim()||`# ${o} +`}function Jx(r){try{return new URL(r).host}catch{return"invalid URL"}}var cj={validateOnSave:!0,validateOnOpen:!0,showNoticeOnSave:!1,interopEnabled:!1,mirrorProfile:null,typeDrafts:{},archivedTypeDrafts:[],autoSync:!0,syncSettingsVersion:2},Xx="mdbase-sync-device-id";function lj(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"&&(e.selectiveSync===void 0||Array.isArray(e.selectiveSync.file_classes)&&Array.isArray(e.selectiveSync.excluded_folders))}function dj(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var Rd=class extends L.Plugin{constructor(t,n){super(t,n);this.issueMap=new Map;this.validation=new Ta;this.validationAbort=null;this.sortedIssuesCache=null;this.noteStatusVersion=0;this.syncScheduler=null;this.recordCache=null;this.recordCacheSettings="";this.recordList=null;this.recordLoadPromise=null;this.dirtyRecordPaths=new Set;this.schemaCache=null;this.schemaLoadPromise=null;this.saveValidationDebounceMs=2e3;this.schemaRefreshDebounceMs=2e3;this.saveValidations=new Aa(this.saveValidationDebounceMs,async(t,n)=>{try{await this.validateFileAndStore(t,"save",n)}catch(i){console.error("mdbase: background validation failed",i)}});this.schemaRefreshes=new Aa(this.schemaRefreshDebounceMs,async()=>{this.invalidateSchemaCache(),this.refreshWorkspaceViews()});this.connectSync=new fd(t,{getMirrorProfile:()=>this.getMirrorProfile(),saveMirrorProfile:async i=>{this.settings.mirrorProfile=i,await this.saveSettings(),i?this.requestSync():this.sync?.reset()},deviceId:()=>this.deviceId()}),this.interopBridge=new Vc(t,()=>this.settings?.interopEnabled===!0),this.api={apiVersion:1,interop:this.interopBridge,getInteropStatus:()=>({enabled:this.settings?.interopEnabled===!0,profileVersion:"0.1"})}}async onload(){await this.loadSettings(),await this.connectSync.initialize(),await this.createSyncSession(),(0,L.addIcon)(Sa,wx),this.statusBarEl=this.addStatusBarItem(),this.statusBarEl.addClass("mdbase-status-bar"),this.statusBarEl.setAttr("role","button"),this.statusBarEl.setAttr("tabindex","0"),this.registerDomEvent(this.statusBarEl,"click",()=>void this.openStatusDestination()),this.registerDomEvent(this.statusBarEl,"keydown",n=>{n.key!=="Enter"&&n.key!==" "||(n.preventDefault(),this.openStatusDestination())}),this.noteStatusEl=this.addStatusBarItem(),this.noteStatusEl.addClass("mdbase-note-status"),this.noteStatusEl.setAttr("role","button"),this.noteStatusEl.setAttr("tabindex","0"),this.noteStatusEl.hide(),this.registerDomEvent(this.noteStatusEl,"click",()=>void this.openNoteStatusDestination()),this.registerDomEvent(this.noteStatusEl,"keydown",n=>{n.key!=="Enter"&&n.key!==" "||(n.preventDefault(),this.openNoteStatusDestination())}),this.updateStatusBar(),this.registerView(Dr,n=>new kd(n,this)),this.addSettingTab(new Cd(this.app,this)),this.addRibbonIcon(Sa,"Open mdbase",()=>void this.openWorkspace()),gw(this),this.registerEvent(this.app.vault.on("modify",n=>{n instanceof L.TFile&&this.onVaultModify(n)})),this.registerEvent(this.app.vault.on("rename",(n,i)=>{n instanceof L.TFile&&this.onVaultRename(n,i)})),this.registerEvent(this.app.vault.on("delete",n=>{n instanceof L.TFile&&this.onVaultDelete(n)})),this.registerEvent(this.app.vault.on("create",n=>{n instanceof L.TFile&&this.onVaultCreate(n)})),this.registerEvent(this.app.workspace.on("file-open",n=>{this.settings.validateOnOpen&&(!(n instanceof L.TFile)||n.extension!=="md"||this.validateFileAndStore(n,"open"))})),this.registerEvent(this.app.workspace.on("active-leaf-change",()=>void this.updateNoteStatus())),this.registerEvent(this.app.metadataCache.on("changed",n=>{n.path===this.app.workspace.getActiveFile()?.path&&this.updateNoteStatus()})),this.registerEvent(this.app.workspace.on("editor-change",(n,i)=>{let s=i.file;s instanceof L.TFile&&(this.saveValidations.has(s.path)&&this.scheduleSaveValidation(s),this.schemaRefreshes.has("schema")&&this.isSchemaRelevantPath(s.path)&&this.scheduleSchemaRefresh())}));try{await Nd(this.app)}catch(n){new L.Notice(`Contract pack recovery needs attention: ${String(n)}`,0)}let t=this.app.workspace.getActiveFile();t&&this.settings.validateOnOpen&&this.validateFileAndStore(t,"open"),this.startSyncScheduler()}startSyncScheduler(){this.syncScheduler=new Td({connected:()=>this.getMirrorProfile()!==null,automatic:()=>this.settings.autoSync,problemKind:()=>this.sync.state.problem?.kind??(this.sync.state.paused?"paused":null),autoSync:()=>this.sync.autoSync(),refreshStatus:()=>this.sync.refreshStatus(),remoteChangesWaiting:()=>this.connectSync.remoteChangesWaiting(),reportProblem:n=>{this.sync.reportProblem(n)},setRetryAt:n=>this.sync.setRetryAt(n)}),this.registerDomEvent(window,"online",()=>this.syncScheduler?.noteOnline()),this.registerDomEvent(window,"focus",()=>this.syncScheduler?.noteVisibility(!0));let t=window.document;this.registerDomEvent(t,"visibilitychange",()=>{this.syncScheduler?.noteVisibility(t.visibilityState==="visible")}),this.syncScheduler.start()}requestSync(){this.syncScheduler?.requestSoon()}deviceId(){let t=this.app.loadLocalStorage(Xx);if(typeof t=="string"&&t)return t;let n=crypto.randomUUID();return this.app.saveLocalStorage(Xx,n),n}onunload(){this.validationAbort?.abort(),this.syncScheduler?.stop(),this.connectSync.dispose(),this.interopBridge.dispose().catch(t=>{console.error("mdbase: failed to dispose the interoperability bridge",t)}),this.app.workspace.getLeavesOfType(Dr).forEach(t=>t.detach()),this.saveValidations.clear(),this.schemaRefreshes.clear()}async loadSettings(){let t=await this.loadData();if(this.settings=Object.assign({},cj,t),t&&(t.syncSettingsVersion??1)<2&&(this.settings.autoSync=!0,this.settings.syncSettingsVersion=2),!lj(this.settings.mirrorProfile))this.settings.mirrorProfile=null;else try{this.settings.mirrorProfile.selectiveSync=fr(this.settings.mirrorProfile.selectiveSync)}catch{this.settings.mirrorProfile.selectiveSync=fr()}(!this.settings.typeDrafts||typeof this.settings.typeDrafts!="object"||Array.isArray(this.settings.typeDrafts))&&(this.settings.typeDrafts={}),this.settings.archivedTypeDrafts=Array.isArray(this.settings.archivedTypeDrafts)?this.settings.archivedTypeDrafts:[]}async saveSettings(){await this.saveData(this.settings)}getIssues(){return this.sortedIssuesCache??=Array.from(this.issueMap.values()).flat().sort((t,n)=>t.path.localeCompare(n.path)||t.severity.localeCompare(n.severity)||t.code.localeCompare(n.code)),this.sortedIssuesCache}getMirrorProfile(){return this.settings.mirrorProfile?JSON.parse(JSON.stringify(this.settings.mirrorProfile)):null}otherSyncServices(){let t=[],n=this.app,i=n.internalPlugins?.getEnabledPluginById?.("sync");typeof i?.vaultId=="string"&&i.vaultId&&t.push("Obsidian Sync");let s={"obsidian-livesync":"Self-hosted LiveSync","remotely-save":"Remotely Save","obsidian-git":"Obsidian Git"};for(let[l,u]of Object.entries(s))n.plugins?.enabledPlugins?.has(l)&&t.push(u);let o=this.app.vault.adapter,a=typeof L.FileSystemAdapter=="function"&&o instanceof L.FileSystemAdapter?o.getBasePath():"",c=[[/Mobile Documents|iCloud/i,"iCloud Drive"],[/[\\/]Dropbox[\\/]/i,"Dropbox"],[/[\\/]OneDrive/i,"OneDrive"],[/Google ?Drive|GoogleDrive/i,"Google Drive"]];for(let[l,u]of c)l.test(a)&&t.push(u);return t}async copySyncDiagnostics(){let t=this.getMirrorProfile(),n=null;try{n=await this.connectSync.checkpointSummary()}catch(s){console.error("mdbase: could not read the sync checkpoint for diagnostics",s)}let i=Yx({generatedAt:new Date().toISOString(),pluginVersion:this.manifest.version,obsidianVersion:L.apiVersion,platform:L.Platform.isIosApp?"iOS":L.Platform.isAndroidApp?"Android":L.Platform.isMacOS?"macOS":L.Platform.isWin?"Windows":L.Platform.isLinux?"Linux":"unknown",profile:t,otherDevice:this.connectSync.isOtherDevice(t),automatic:this.settings.autoSync,otherSyncServices:this.otherSyncServices(),state:this.sync.state,checkpoint:n,history:this.sync.historyRuns()});await navigator.clipboard.writeText(i),new L.Notice("Copied sync diagnostics. They name the collection and recent files but contain no note text or credentials.")}openNoteSyncHistory(t){new Pd(this.app,t,this.sync.historyRuns()).open()}openSettings(){let t=this.app.setting;t?.open(),t?.openTabById(this.manifest.id)}async createSyncSession(){let t=this.manifest.dir??`${this.app.vault.configDir}/plugins/${this.manifest.id}`,n=new ad(this.app.vault.adapter,(0,L.normalizePath)(`${t}/sync-history.jsonl`));try{await n.load(),await this.migrateSyncActivity(n)}catch(i){console.error("mdbase: could not load sync history",i)}this.sync=new Md(this.connectSync,()=>this.getMirrorProfile(),n,i=>{new L.Notice(`mdbase: ${i}`,1e4)}),this.register(this.sync.subscribe(()=>this.updateStatusBar()))}async migrateSyncActivity(t){let n=Lx(this.settings.syncActivity),i=this.settings.mirrorProfile?.collectionId;if(i)for(let s of n)await t.append(cd(i,{summary:s.summary,tone:s.tone,...s.detail?{message:s.detail}:{},...s.path?{path:s.path}:{},...s.requiresAcknowledgement?{needsAcknowledgement:!0}:{}},s.occurredAt));this.settings.syncActivity!==void 0&&(delete this.settings.syncActivity,await this.saveSettings())}async loadWorkspaceSchema(t=!1){return this.getConfigAndTypes(t)}async loadTypeModel(t){let n=this.app.vault.getAbstractFileByPath((0,L.normalizePath)(t));if(!(n instanceof L.TFile))throw new Error(`Type file not found: ${t}`);let i=await this.app.vault.cachedRead(n),s=Me(i);if(!s.hasFrontmatter||s.error)throw new Error(`Invalid type frontmatter: ${s.error??"frontmatter is missing"}`);let o=gd(s.frontmatter,s.body,n.basename);return o.sourceRevision=Jm(i),o}loadTypeDraft(t){let n=this.settings.typeDrafts[t??"__new__"];return n?JSON.parse(JSON.stringify(n)):null}async saveTypeDraft(t){let n=this.loadTypeDraft(t.path);n&&n.sourceRevision!==t.sourceRevision&&this.settings.archivedTypeDrafts.push(n),this.settings.typeDrafts[t.path??"__new__"]=JSON.parse(JSON.stringify(t)),await this.saveSettings()}getArchivedTypeDrafts(t){return this.settings.archivedTypeDrafts.filter(n=>n.path===t)}async discardArchivedTypeDraft(t){this.settings.archivedTypeDrafts=this.settings.archivedTypeDrafts.filter(n=>n.path!==t.path||n.updatedAt!==t.updatedAt||n.sourceRevision!==t.sourceRevision),await this.saveSettings()}async clearTypeDraft(t){let n=t??"__new__";n in this.settings.typeDrafts&&(delete this.settings.typeDrafts[n],await this.saveSettings())}async saveTypeModel(t,n,i){if(this.connectSync.assertLocalAuthorityWritable(),this.getMirrorProfile()?.mode==="read_only")throw new Error("This mirror has read-only access. Re-enroll it with write access before editing types.");let s=await ai(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 o=n?this.app.vault.getAbstractFileByPath((0,L.normalizePath)(n)):null;if(o!=null&&!(o instanceof L.TFile))throw new Error(`Type file not found: ${n}`);let a=await this.writeTypeDefinition(s,t,o,i);return this.refreshWorkspaceViews(!0),a}getValidationSummary(){let t=this.schemaCache?.config,n=this.app.vault.getMarkdownFiles().filter(i=>!t||!yt(i.path,t)).map(i=>i.path);return this.validation.summary(n)}isValidating(){return this.validationAbort!==null}cancelValidation(){this.validationAbort?.abort()}async openContractCatalog(){if(this.getMirrorProfile())throw new Error("Install packs at the hosted collection authority using mdbase editor.");let t=await this.getConfigAndTypes();if(!t||!t.config.spec_version.startsWith("0.3."))throw new Error("Initialize or migrate this collection first.");if(t.config.settings.types_folder!=="_types"||(t.config.settings.contracts_folder??"_contracts")!=="_contracts")throw new Error("Catalog packs require the standard _types and _contracts folders. Use mdbase editor for custom target mappings.");new Ma(this.app,()=>{if(this.connectSync.assertLocalAuthorityWritable(),this.getMirrorProfile())throw new Error("The vault role changed. Install at the collection authority instead.")},async n=>{this.invalidateSchemaCache();let i=await this.openWorkspace("types");await i.refresh(!0);let s=await this.getConfigAndTypes(),o=n?s?.types.get(n):null;o&&await i.editType(o.filePath),new L.Notice("Installed contract pack. Edit its type or create a note to try it.")}).open()}async createNoteFromType(t){await Fp(this,t)}async initializeCollection(){this.connectSync.assertLocalAuthorityWritable();let{created:t}=await $o(this.app.vault,{seedNoteType:!1});this.invalidateSchemaCache(),new L.Notice(t.length?`Initialized mdbase collection: ${t.join(", ")}`:"mdbase collection already initialized."),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 lx(this.app.vault)}async applyMigration(t,n){if(this.connectSync.assertLocalAuthorityWritable(),this.getMirrorProfile())throw new Error("Collection authority resources must be migrated at the collection authority.");let i=await dx(this.app.vault,t,{allowLossy:n});if(!i.applied)throw new Error(i.restored?`Migration failed and all writes were rolled back. ${i.error??""}`.trim():`Migration needs manual recovery. See ${i.manifestPath}. ${i.error??""}`.trim());this.invalidateSchemaCache(),new L.Notice(`Migrated to mdbase v0.3. Recovery manifest: ${i.manifestPath}`),this.refreshWorkspaceViews(!0)}async openIssue(t){await this.openFileByPath(t.path,t.field)}getQuickFixLabel(t){return ww(t)}async applyQuickFix(t){this.connectSync.assertLocalAuthorityWritable();let n=this.app.vault.getAbstractFileByPath(t.path);if(!(n instanceof L.TFile)){new L.Notice(`File not found: ${t.path}`);return}if(this.getMirrorProfile()?.mode==="read_only")throw new Error("This mirror has read-only access.");let i=!1;await this.app.vault.process(n,s=>{this.connectSync.assertLocalAuthorityWritable();let o=jp(s,t);return i=o.changed,o.content}),new L.Notice(i?`Updated '${t.field??"field"}' in ${n.basename}`:"The field changed or no safe quick fix is available. Revalidate the note."),await this.validateFileAndStore(n,"manual")}async applyQuickFixes(t){if(this.connectSync.assertLocalAuthorityWritable(),this.getMirrorProfile()?.mode==="read_only")throw new Error("This mirror has read-only access.");let n=0,i=0,s=new Map;for(let o of t){let a=this.app.vault.getAbstractFileByPath(o.path);if(!(a instanceof L.TFile)){i+=1;continue}let c=!1;await this.app.vault.process(a,l=>{this.connectSync.assertLocalAuthorityWritable();let u=jp(l,o);return c=u.changed,u.content}),c?(n+=1,s.set(a.path,a)):i+=1}for(let o of s.values())await this.validateFileAndStore(o,"manual");return{changed:n,skipped:i}}async openFileByPath(t,n){let i=this.app.vault.getAbstractFileByPath(t);if(!(i instanceof L.TFile)){new L.Notice(`File not found: ${t}`);return}await this.app.workspace.getLeaf(!0).openFile(i),n&&this.revealFrontmatterField(i,n)}revealFrontmatterField(t,n){let i=this.app.workspace.getMostRecentLeaf();if(!i||!(i.view instanceof L.MarkdownView))return;let s=i.view;if(!(s.file instanceof L.TFile)||s.file.path!==t.path)return;let o=s.editor,a=o.lineCount();if(a<3)return;let c=Dp(n),l=new RegExp(`^\\s*${dj(c)}\\s*:`);if(o.getLine(0).trim()==="---")for(let u=1;ud.severity==="error").length,c=this.validation.isChecked(n.path),l=c?o.length?` \xB7 ${o.length} ${o.length===1?"issue":"issues"}`:" \xB7 checked":" \xB7 not checked";this.noteStatusEl.setText(`${s.join(", ")}${l}`),this.noteStatusEl.setAttr("data-state",c?a?"error":o.length?"warning":"valid":"unchecked"),this.noteStatusEl.setAttr("data-path",n.path);let u=o.length?`${n.basename}: ${o.length} ${o.length===1?"issue":"issues"}. Open issues for this note.`:`${n.basename} is a ${s.join(", ")} note. Edit the type.`;this.noteStatusEl.setAttr("aria-label",u),this.noteStatusEl.setAttr("title",u),this.noteStatusEl.show()}async openNoteStatusDestination(){let t=this.noteStatusEl.getAttr("data-path");if(!t)return;if(this.issueMap.get(t)?.length){(await this.openWorkspace("issues")).showIssuesForPath(t);return}let n=this.app.vault.getAbstractFileByPath(t),i=await this.getConfigAndTypes();if(!(n instanceof L.TFile)||!i)return;let[s]=Ke(t,this.app.metadataCache.getFileCache(n)?.frontmatter??{},i.config,i.types),o=s?i.types.get(s):void 0;if(!o)return;await(await this.openWorkspace("types")).editType(o.filePath)}markRecordChanged(t){this.validation.changed(t),this.recordCache&&(this.dirtyRecordPaths.add((0,L.normalizePath)(t)),this.recordList=null)}loadCollectionRecords(){return this.recordLoadPromise??=this.readRecords().finally(()=>{this.recordLoadPromise=null}),this.recordLoadPromise}async readRecords(){let t=await this.getConfigAndTypes();if(!t)return[];let n=JSON.stringify(t.config.settings);if(!this.recordCache||n!==this.recordCacheSettings){this.dirtyRecordPaths.clear();let i=await Ep(this.app.vault,t.config);this.recordCache=new Map(i.map(s=>[s.path,s])),this.recordCacheSettings=n,this.recordList=null}else if(this.dirtyRecordPaths.size){let i=[...this.dirtyRecordPaths];this.dirtyRecordPaths.clear();for(let s of i){this.recordCache.delete(s);let o=this.app.vault.getAbstractFileByPath(s);if(!(o instanceof L.TFile)||o.extension!=="md"||yt(s,t.config))continue;let a=Me(await this.app.vault.cachedRead(o));a.error||this.recordCache.set(s,{path:s,frontmatter:a.frontmatter})}this.recordList=null}return this.recordList??=[...this.recordCache.values()].sort((i,s)=>i.path.localeCompare(s.path)),this.recordList}syncIndicator(t){let n=this.sync.state,i=this.sync.safety();return Dx({connected:this.getMirrorProfile()!==null,status:n.status,progress:n.progress,fileProgress:n.fileProgress,problem:n.problem,validationIssues:t,localChangeObserved:n.localChangeObserved,reviewChanges:i&&!i.safe?n.preview?.plan.actions.length??0:0})}async openStatusDestination(){await this.openWorkspace(this.syncIndicator(this.getIssues().length).destination)}async openIssuesView(){await this.openWorkspace("issues")}async openWorkspace(t="types"){let n=this.app.workspace.getLeavesOfType(Dr)[0];if(n){await this.app.workspace.revealLeaf(n);let o=n.view;return o.showDestination(t),await o.refresh(),o}let i=this.app.workspace.getLeaf(!0);await i.setViewState({type:Dr,active:!0}),await this.app.workspace.revealLeaf(i);let s=i.view;return await s.refresh(),s.showDestination(t),s}refreshWorkspaceViews(t=!1){for(let n of this.app.workspace.getLeavesOfType(Dr)){let i=n.view;typeof i.refresh=="function"&&i.refresh(t)}}refreshIssueViews(){this.updateStatusBar(),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 i=this.issueMap.get(t);i&&(this.issueMap.delete(t),this.issueMap.set(n,i.map(s=>({...s,path:n}))),this.sortedIssuesCache=null,this.refreshIssueViews())}clearPendingSaveValidation(t){this.saveValidations.cancel(t)}scheduleSaveValidation(t){this.saveValidations.schedule(t.path,t)}scheduleSchemaRefresh(){this.schemaRefreshes.schedule("schema",void 0)}refreshSchemaNow(){this.schemaRefreshes.cancel("schema"),this.invalidateSchemaCache(),this.refreshWorkspaceViews()}isSchemaRelevantPath(t){let n=(0,L.normalizePath)(t);if(n==="mdbase.yaml")return!0;let i=new Set(["_types","_contracts"]);this.schemaCache&&(i.add((0,L.normalizePath)(this.schemaCache.config.settings.types_folder)),i.add((0,L.normalizePath)(this.schemaCache.config.settings.contracts_folder??"_contracts")));for(let s of i)if(n===s||n.startsWith(`${s}/`))return!0;return!1}invalidateSchemaCache(){this.validation.changed(),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 ai(this.app.vault);if(!n)return null;let i=await Ap(this.app.vault,n),s=await kp(this.app.vault,n);return{config:n,types:i,contracts:s}})();try{let n=await this.schemaLoadPromise;return n&&(this.schemaCache=n),n}finally{this.schemaLoadPromise=null}}async requireConfigAndTypes(t={}){let n=t.background??!1,i=await this.getConfigAndTypes(t.forceReload??!1);return i?(i.types.size===0&&!n&&new L.Notice(`No types found in ${i.config.settings.types_folder}`),i):(n||new L.Notice("No mdbase.yaml found. Run 'mdbase: Initialize collection' first."),null)}onVaultModify(t){this.observeLocalMirrorChange(t.path),this.markRecordChanged(t.path),this.isSchemaRelevantPath(t.path)&&this.scheduleSchemaRefresh(),this.settings.validateOnSave&&t.extension==="md"&&this.scheduleSaveValidation(t)}onVaultRename(t,n){this.observeLocalMirrorChange(n),this.markRecordChanged(n),this.markRecordChanged(t.path),this.observeLocalMirrorChange(t.path),(this.isSchemaRelevantPath(n)||this.isSchemaRelevantPath(t.path))&&this.refreshSchemaNow(),t.extension==="md"&&(this.clearPendingSaveValidation(n),this.moveFileIssues(n,t.path),this.settings.validateOnSave&&this.scheduleSaveValidation(t))}onVaultDelete(t){this.observeLocalMirrorChange(t.path),this.markRecordChanged(t.path),this.isSchemaRelevantPath(t.path)&&this.refreshSchemaNow(),t.extension==="md"&&(this.clearPendingSaveValidation(t.path),this.clearFileIssues(t.path))}onVaultCreate(t){this.observeLocalMirrorChange(t.path),this.markRecordChanged(t.path),this.isSchemaRelevantPath(t.path)&&this.refreshSchemaNow()}observeLocalMirrorChange(t){if(!this.getMirrorProfile()||this.connectSync.isEngineWrite(t))return;let n=(0,L.normalizePath)(t);[this.app.vault.configDir,".mdbase",".trash",".git"].some(s=>n===s||n.startsWith(`${s}/`))||(this.sync.observeLocalChange(),this.syncScheduler?.noteLocalChange())}async validateFileAndStore(t,n,i=()=>!0){let s=await this.requireConfigAndTypes({background:n!=="manual"});if(!i())return[];if(!s)return n!=="manual"&&this.clearFileIssues(t.path),[];let o=this.validation.revision,a=await _c(this.app.vault,t,s.config,s.types);return!i()||o!==this.validation.revision||(this.validation.markChecked(t.path),this.setFileIssues(t.path,a),n==="save"&&this.settings.showNoticeOnSave&&a.length>0&&new L.Notice(`mdbase: ${a.length} issue${a.length===1?"":"s"} in ${t.basename}`)),a}async runCollectionValidation(t){if(this.validationAbort)return;let n=await this.requireConfigAndTypes({background:!1});if(!n||this.validationAbort)return;let i=new AbortController;this.validationAbort=i,this.validation.cancelled=!1;let s=this.validation.revision,o=new Map;try{let a=await Mp(this.app.vault,n.config,n.types,{signal:i.signal,onProgress:c=>{if(this.validation.progress=c,c.completed===0)for(let l of this.app.workspace.getLeavesOfType(Dr))l.view.refreshValidationControls();else if(c.completed%25===0||c.phase==="uniqueness")for(let l of this.app.workspace.getLeavesOfType(Dr))l.view.updateValidationProgress()},onFile:(c,l)=>{s===this.validation.revision&&(this.validation.markChecked(c.path),o.set(c.path,l),l.length?this.issueMap.set(c.path,l):this.issueMap.delete(c.path),this.sortedIssuesCache=null)}});if(s!==this.validation.revision){new L.Notice("Files changed during validation. Validate again for a complete result.");return}o.clear();for(let c of a)o.set(c.path,[...o.get(c.path)??[],c]);this.issueMap=o,this.validation.lastCompletedAt=new Date().toISOString(),this.validation.completedRevision=s,t&&(new L.Notice(a.length?`Collection validation: ${a.length} issues`:"Collection validation passed with no issues."),a.length&&await this.openIssuesView())}catch(a){if(this.validation.cancelled=!0,s===this.validation.revision)for(let[c,l]of o)l.length?this.issueMap.set(c,l):this.issueMap.delete(c);new L.Notice(i.signal.aborted?"Validation stopped. Results are incomplete.":`Validation could not finish: ${String(a)}. Results are incomplete.`)}finally{this.validation.progress=null,this.validationAbort=null,this.sortedIssuesCache=null;for(let a of this.app.workspace.getLeavesOfType(Dr))a.view.refreshValidationControls();this.refreshIssueViews()}}async ensureFolderExists(t){let n=(0,L.normalizePath)(t).replace(/\/+$/,"");if(!n)return;let i=n.split("/"),s="";for(let o of i)s=s?`${s}/${o}`:o,await this.app.vault.adapter.exists(s)||await this.app.vault.createFolder(s)}async writeTypeDefinition(t,n,i,s){let o=n.name.trim();if(!o)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 a=Fn(n),c=n.body.trim()||`# ${o} Type definition for ${o}.`,l=`${mt(a,c)} -`,u=(0,L.normalizePath)(t.settings.types_folder),d=(0,L.normalizePath)(`${u}/${o}.md`);if(!i){if(await this.ensureFolderExists(u),await this.app.vault.adapter.exists(d))throw new Error(`Type already exists: ${d}`);let v=await this.app.vault.create(d,l);return this.invalidateSchemaCache(),v}let f=i.path,p=await this.app.vault.cachedRead(i);if(s&&Jm(p)!==s)throw new Error(`The source changed after this draft was opened: ${f}. Reopen the type and review both versions before saving.`);let h=i.path.lastIndexOf("/"),m=h>=0?i.path.slice(0,h):"",g=(0,L.normalizePath)(`${m?`${m}/`:""}${o}.md`)||d;if(g!==i.path&&await this.app.vault.adapter.exists(g))throw new Error(`Cannot rename type file to ${g}; file already exists.`);let b=!1;try{g!==i.path&&(await this.app.fileManager.renameFile(i,g),b=!0);let v=this.app.vault.getAbstractFileByPath(g);if(!(v instanceof L.TFile))throw new Error(`Unable to access updated type file: ${g}`);return await this.app.vault.modify(v,l),this.invalidateSchemaCache(),v}catch(v){try{let S=this.app.vault.getAbstractFileByPath(b?g:f);S instanceof L.TFile&&(await this.app.vault.modify(S,p),b&&await this.app.fileManager.renameFile(S,f))}catch(S){throw new Error(`Saving the type failed and automatic recovery also failed. Review '${f}' and '${g}'. ${v instanceof Error?v.message:String(v)}; recovery: ${S instanceof Error?S.message:String(S)}`)}throw v}}}; +`,u=(0,L.normalizePath)(t.settings.types_folder),d=(0,L.normalizePath)(`${u}/${o}.md`);if(!i){if(await this.ensureFolderExists(u),await this.app.vault.adapter.exists(d))throw new Error(`Type already exists: ${d}`);let v=await this.app.vault.create(d,l);return this.invalidateSchemaCache(),v}let f=i.path,p=await this.app.vault.cachedRead(i);if(s&&Jm(p)!==s)throw new Error(`The source changed after this draft was opened: ${f}. Reopen the type and review both versions before saving.`);let m=i.path.lastIndexOf("/"),h=m>=0?i.path.slice(0,m):"",g=(0,L.normalizePath)(`${h?`${h}/`:""}${o}.md`)||d;if(g!==i.path&&await this.app.vault.adapter.exists(g))throw new Error(`Cannot rename type file to ${g}; file already exists.`);let b=!1;try{g!==i.path&&(await this.app.fileManager.renameFile(i,g),b=!0);let v=this.app.vault.getAbstractFileByPath(g);if(!(v instanceof L.TFile))throw new Error(`Unable to access updated type file: ${g}`);return await this.app.vault.modify(v,l),this.invalidateSchemaCache(),v}catch(v){try{let S=this.app.vault.getAbstractFileByPath(b?g:f);S instanceof L.TFile&&(await this.app.vault.modify(S,p),b&&await this.app.fileManager.renameFile(S,f))}catch(S){throw new Error(`Saving the type failed and automatic recovery also failed. Review '${f}' and '${g}'. ${v instanceof Error?v.message:String(v)}; recovery: ${S instanceof Error?S.message:String(S)}`)}throw v}}}; diff --git a/src/connectSync.ts b/src/connectSync.ts index 3c326d7..78fd652 100644 --- a/src/connectSync.ts +++ b/src/connectSync.ts @@ -1037,11 +1037,18 @@ export class ObsidianMirrorFileSystem implements MirrorFileSystem { return binaryInfo(bytes); } - async writeBinary(input: string, source: AsyncIterable): Promise { + async writeBinary(input: string, source: AsyncIterable, expected?: MirrorBinaryInfo | null): Promise { const path = assertVisibleBinaryPath(input); + // A stream can take seconds to consume. Remember its destination before + // reading any bytes, then recheck it after staging and folder creation. + const before = expected === undefined ? await this.inspectBinary(path) : expected; const bytes = await collectBinary(source); const slash = path.lastIndexOf("/"); if (slash >= 0) await ensureFolder(this.vault, path.slice(0, slash)); + const current = await this.inspectBinary(path); + if (current?.content_digest !== before?.content_digest || current?.size !== before?.size) { + throw new SyncError("sync_plan_stale", `${path} changed before it could be written. Review sync again.`); + } const existing = this.vault.getAbstractFileByPath(path); if (existing instanceof TFolder) throw new SyncError("mirror_path_collision", `A folder blocks the mirror file ${path}.`); this.assertActive(); @@ -1769,21 +1776,34 @@ export class ConnectSyncController { if (enrollment.collectionId !== profile.collectionId) { throw new SyncError("mirror_identity_conflict", "Connect approved a different collection. The existing mirror was not changed."); } - const nextProfile = profileFromEnrollment(enrollment, profile.selectiveSync); - if (oldState && enrollment.replicaId !== profile.replicaId) { - await this.stateStoreFor(nextProfile).write({ - ...oldState, - replica_id: enrollment.replicaId, - }); - } - await this.persistEnrollment(enrollment, profile.selectiveSync); - if (!copied && enrollment.replicaId !== profile.replicaId) { - this.clearCredentials(profile); - if ("clear" in oldStore && typeof oldStore.clear === "function") await oldStore.clear(); - } - const status = await this.status(); - if (!status) throw new SyncError("mirror_not_configured", "The reauthorized mirror profile could not be loaded."); - return status; + return this.withMirrorOperation(async () => { + // Browser approval can stay open while background sync advances or a + // disconnect retires this connection. Only migrate its latest checkpoint, + // under the same queue that protects all other mirror state operations. + const current = this.requireProfile(); + if (current.collectionId !== profile.collectionId || current.replicaId !== profile.replicaId + || current.enrollmentId !== profile.enrollmentId) { + throw new SyncError("mirror_identity_conflict", "The connection changed during approval. The current mirror was not changed."); + } + const latestState = copied ? null : await oldStore.read(); + if (latestState?.batch) { + throw new SyncError("mirror_recovery_required", "Resume the durable synchronization checkpoint before approving this vault again."); + } + const nextProfile = profileFromEnrollment(enrollment, current.selectiveSync); + if (latestState && enrollment.replicaId !== profile.replicaId) { + await this.stateStoreFor(nextProfile).write({ + ...latestState, + replica_id: enrollment.replicaId, + }); + } + await this.persistEnrollment(enrollment, current.selectiveSync); + if (!copied && enrollment.replicaId !== profile.replicaId) { + this.clearCredentials(profile); + if ("clear" in oldStore && typeof oldStore.clear === "function") await oldStore.clear(); + } + const mirror = await this.createMirror(); + return mirror.status(); + }); } async conflictComparison( @@ -2017,32 +2037,55 @@ export class ConnectSyncController { private async writeConflictCopy(pathInput: string, document: string, label: string): Promise { const path = safeMirrorPath(this.app.vault, pathInput); - const target = await this.conflictCopyPath(path, label); - await this.app.vault.create(target, document); - return target; + return this.createConflictCopy(path, new TextEncoder().encode(document).buffer, label); } - private async conflictCopyPath(path: string, label: string): Promise { + private async createConflictCopy(path: string, document: ArrayBuffer, label: string): Promise { const slash = path.lastIndexOf("/"); const dot = path.lastIndexOf("."); const extension = dot > slash ? path.slice(dot) : ""; - const base = extension ? path.slice(0, -extension.length) : path; - let target = `${base} (${label})${extension}`; - let suffix = 2; - while (this.app.vault.getAbstractFileByPath(target) || await this.app.vault.adapter.exists(target)) { - target = `${base} (${label} ${suffix})${extension}`; - suffix += 1; + const stem = extension ? path.slice(0, -extension.length) : path; + // A copy can itself conflict on another device. Keep the sibling names + // flat rather than producing copies of copies of copies. + const base = stem.replace(/(?: \((?:local|hosted) conflict copy(?: \d+)?\))+$/, ""); + const bytes = new Uint8Array(document); + let suffix = 1; + while (true) { + const target = `${base} (${label}${suffix === 1 ? "" : ` ${suffix}`})${extension}`; + if (target === path) { + suffix += 1; + continue; + } + if (this.app.vault.getAbstractFileByPath(target) || await this.app.vault.adapter.exists(target)) { + // A stale decision may be retried after its copy was already saved. + // Reuse only byte-identical copies; never modify an older recovery file. + try { + const existing = new Uint8Array(await this.app.vault.adapter.readBinary(target)); + if (existing.length === bytes.length && existing.every((byte, index) => byte === bytes[index])) return target; + } catch { + // Folders and unreadable copies still reserve their name. + } + suffix += 1; + continue; + } + try { + // Unlike adapter.copy, Vault.createBinary refuses an occupied target, + // including one that appears after the name check. Preserve exact bytes. + await this.app.vault.createBinary(target, document); + return target; + } catch (error) { + if (!await this.app.vault.adapter.exists(target)) throw error; + // A concurrent creator won this name. Inspect it before choosing again. + } } - return target; } async preserveConflictCopy(pathInput: string): Promise { const path = safeMirrorPath(this.app.vault, pathInput); const existing = this.app.vault.getAbstractFileByPath(path); if (!(existing instanceof TFile)) throw new SyncError("mirror_conflict_copy_missing", `No local file exists at ${path}.`); - const target = await this.conflictCopyPath(path, "local conflict copy"); - await this.app.vault.adapter.copy(path, target); - return target; + const document = await this.app.vault.adapter.readBinary(path); + return this.createConflictCopy(path, document, "local conflict copy"); } async disconnect(removeSyncedFiles: boolean): Promise { @@ -2802,8 +2845,16 @@ export class ConnectSyncController { accessToken: this.readSecret("access", profile) ?? "", refreshCredential, accessTokenExpiresAt: profile.accessTokenExpiresAt, - }); - await this.persistEnrollment(renewed, profile.selectiveSync); + }, { signal: this.lifetime.signal }); + // Renewal may overlap a disconnect or a fresh browser enrollment. Never + // recreate the retired connection (or replace the new one's credentials). + const current = this.requireProfile(); + if (current.collectionId !== profile.collectionId || current.replicaId !== profile.replicaId + || current.enrollmentId !== profile.enrollmentId) { + throw new SyncError("mirror_identity_conflict", "The connection changed while credentials were renewing. Retry with the current connection."); + } + // Settings can change independently while the request is in flight. + await this.persistEnrollment(renewed, current.selectiveSync); return renewed.accessToken; } diff --git a/src/syncHistory.ts b/src/syncHistory.ts index 4d4fa95..595ccdd 100644 --- a/src/syncHistory.ts +++ b/src/syncHistory.ts @@ -95,7 +95,7 @@ export function historyFileFromReceipt( * A resumed batch already carries earlier receipts; they are the baseline. */ export class ReceiptObservingStateStore implements MirrorStateStore { - private readonly seen = new Map(); + private readonly seen = new Map }>(); constructor( private readonly inner: MirrorStateStore, @@ -112,10 +112,17 @@ export class ReceiptObservingStateStore implements MirrorStateStore { if (!batch) return; const fingerprint = batch.plan.fingerprint; const previous = this.seen.get(fingerprint); - this.seen.set(fingerprint, batch.receipts.length); - if (previous === undefined) return; - for (const receipt of batch.receipts.slice(previous)) { - const action = batch.plan.actions.find((candidate) => candidate.action_id === receipt.action_id); + if (previous === undefined) { + this.seen.set(fingerprint, { + receipts: batch.receipts.length, + actions: new Map(batch.plan.actions.map((action) => [action.action_id, action])), + }); + return; + } + const start = previous.receipts; + previous.receipts = batch.receipts.length; + for (const receipt of batch.receipts.slice(start)) { + const action = previous.actions.get(receipt.action_id); if (action) this.onReceipt(action, receipt); } } diff --git a/src/syncMerge.ts b/src/syncMerge.ts index 264b1a7..54d8fd7 100644 --- a/src/syncMerge.ts +++ b/src/syncMerge.ts @@ -27,21 +27,23 @@ export function mergeDocuments( if (parts.every((part) => part === null)) { const merged = mergeLines(base, local, remote); return merged === null - ? { clean: false, reason: "Both versions changed the same lines." } + ? { clean: false, reason: "The line edits could not be merged safely." } : { clean: true, text: merged }; } const [b, l, r] = parts; if (!b || !l || !r || b.open !== l.open || l.open !== r.open) { return { clean: false, reason: "Only one version has frontmatter." }; } + const close = mergeValue(b.close, l.close, r.close); + if (close === null) return { clean: false, reason: "Both versions changed the frontmatter fence." }; const frontmatter = mergeFrontmatter(b.frontmatter, l.frontmatter, r.frontmatter); if (frontmatter === null) return { clean: false, reason: "Both versions changed the same field." }; const body = mergeLines(b.body, l.body, r.body); - if (body === null) return { clean: false, reason: "Both versions changed the same lines." }; - if (frontmatter.length && !validFrontmatter(frontmatter.join("\n"))) { + if (body === null) return { clean: false, reason: "The line edits could not be merged safely." }; + if (frontmatter.length && !validFrontmatter(frontmatter.join("\n") + "\n")) { return { clean: false, reason: "The combined frontmatter would not be valid YAML." }; } - return { clean: true, text: [l.open, ...frontmatter, l.close].join("\n") + body }; + return { clean: true, text: [l.open, ...frontmatter, close].join("\n") + body }; } interface DocumentParts { @@ -68,11 +70,22 @@ function splitDocument(document: string): DocumentParts | null { } function mergeLines(base: string, local: string, remote: string): string | null { - const regions = diff3Merge(local.split("\n"), base.split("\n"), remote.split("\n"), { excludeFalseConflicts: true }); + if (local === remote || remote === base) return local; + if (local === base) return remote; + const b = base.split("\n"); + const l = local.split("\n"); + const r = remote.split("\n"); + // node-diff3's LCS is quadratic in the worst case (especially repeated + // lines). Never freeze Obsidian's UI trying to merge a pathological note: + // the caller keeps both exact documents instead. Ordinary field/body edits + // above avoid diffing an unchanged body regardless of its size. + const work = b.length * (l.length + r.length); + if (work > 4_000_000) return null; + const regions = diff3Merge(l, b, r, { excludeFalseConflicts: true }); const merged: string[] = []; for (const region of regions) { if (region.conflict) return null; - merged.push(...(region.ok ?? [])); + for (const line of region.ok ?? []) merged.push(line); } return merged.join("\n"); } @@ -100,14 +113,21 @@ function fieldBlocks(lines: string[]): FieldBlocks | null { blocks.get(current)?.push(line); } } - return { order, blocks: new Map([...blocks].map(([key, value]) => [key, value.join("\n")])) }; + return { order, blocks: new Map([...blocks].filter(([, value]) => value.length > 0).map(([key, value]) => [key, value.join("\n")])) }; } function mergeFrontmatter(base: string[], local: string[], remote: string[]): string[] | null { const b = fieldBlocks(base); const l = fieldBlocks(local); const r = fieldBlocks(remote); - if (!b || !l || !r) { + // Field-wise merging cannot represent moves. A line merge either preserves + // the reordered text or conservatively keeps both versions. + const reordered = (ancestor: FieldBlocks, changed: FieldBlocks) => { + const common = new Set(ancestor.order.filter((key) => changed.blocks.has(key))); + return ancestor.order.filter((key) => common.has(key)).join("\n") + !== changed.order.filter((key) => common.has(key)).join("\n"); + }; + if (!b || !l || !r || reordered(b, l) || reordered(b, r)) { return mergeLines(base.join("\n"), local.join("\n"), remote.join("\n"))?.split("\n") ?? null; } const merged = new Map(); @@ -123,11 +143,8 @@ function mergeFrontmatter(base: string[], local: string[], remote: string[]): st const before = r.order.slice(0, index).reverse().find((candidate) => order.includes(candidate)); order.splice(before === undefined ? 0 : order.indexOf(before) + 1, 0, key); } - // An empty preamble is the absence of lines, not an empty one. - return order.flatMap((key) => { - const value = merged.get(key) ?? ""; - return key === PREAMBLE && value === "" ? [] : value.split("\n"); - }); + // An absent preamble is different from one containing a single blank line. + return order.flatMap((key) => (merged.get(key) ?? "").split("\n")); } /** `undefined` is an absent field; `null` means both sides changed it differently. */ diff --git a/src/syncScheduler.ts b/src/syncScheduler.ts index a09344e..c7a7486 100644 --- a/src/syncScheduler.ts +++ b/src/syncScheduler.ts @@ -131,9 +131,12 @@ export class SyncScheduler { this.rerun = false; this.schedule(now); } else if (retryIn !== null) { + // A routine probe must not preempt the advertised failure backoff. + // Explicit edits, online and foreground events can still request sooner. this.schedule(now + retryIn); + } else { + this.schedule(now + (this.visible ? this.timing.probeVisibleMs : this.timing.probeHiddenMs)); } - this.schedule(now + (this.visible ? this.timing.probeVisibleMs : this.timing.probeHiddenMs)); } } diff --git a/src/syncSession.ts b/src/syncSession.ts index 3f5f211..573113c 100644 --- a/src/syncSession.ts +++ b/src/syncSession.ts @@ -87,6 +87,8 @@ const EMPTY_STATE: SyncSessionState = { export class SyncSession { private current: SyncSessionState = { ...EMPTY_STATE }; private readonly listeners = new Set<() => void>(); + private safetyPreview: MdbaseSyncPreview | null = null; + private previewSafety: SyncPlanSafety | null = null; /** The last failure pinned to history, so automatic retries do not pin it again. */ private pinnedFailure: string | null = null; @@ -208,10 +210,16 @@ export class SyncSession { const result = await this.exclusive(async (): Promise => { let applied = false; for (let round = 0; round < MAX_SYNC_ROUNDS; round += 1) { + if (this.current.paused) return "paused"; const preview = await this.loadPreview(); + // Inspection is not a transfer and cannot be cancelled by cancelSync(). + // Honour Stop before starting any writes once that inspection returns. + if (this.current.paused) return "paused"; if (!preview) return "failed"; if (!preview.plan.actions.length) { - if (await this.settleConflicts()) continue; + const settled = await this.settleConflicts(); + if (this.current.paused) return "paused"; + if (settled) continue; if (!applied && !options.quiet) this.update({ message: "Already up to date." }); return applied ? "applied" : "up_to_date"; } @@ -224,7 +232,10 @@ export class SyncSession { if (outcome === "cancelled") return "paused"; if (outcome === "failed") return "failed"; applied = true; - if (await this.settleConflicts()) continue; + if (this.current.paused) return "paused"; + const settled = await this.settleConflicts(); + if (this.current.paused) return "paused"; + if (settled) continue; if (!this.current.preview) return "applied"; } return applied ? "applied" : "up_to_date"; @@ -267,7 +278,14 @@ export class SyncSession { } safety(): SyncPlanSafety | null { - return this.current.preview ? syncPlanSafety(this.current.preview) : null; + const preview = this.current.preview; + // Engine previews are replaced, not mutated. Transfer progress can notify + // several surfaces per file; none needs to rescan the same consent policy. + if (preview !== this.safetyPreview) { + this.safetyPreview = preview; + this.previewSafety = preview ? syncPlanSafety(preview) : null; + } + return this.previewSafety; } /** Stop now and keep automatic sync off until the person resumes it. */ diff --git a/src/workspace/syncPane.ts b/src/workspace/syncPane.ts index d322610..6e9981f 100644 --- a/src/workspace/syncPane.ts +++ b/src/workspace/syncPane.ts @@ -105,13 +105,35 @@ export class SyncPane { } const state = this.session.state; const syncing = Boolean(state.fileProgress || state.progress); + const problem = state.problem?.kind === "busy" ? null : state.problem; + const recoveryProblem: SyncProblem | null = problem ?? (state.paused && !syncing ? { + code: "sync_paused", + kind: "paused", + title: "Sync is paused", + message: "Changes on this device and in Connect wait until you resume.", + action: "resume", + actionLabel: "Resume sync", + } : state.status?.recovery_required ? { + code: "mirror_recovery_required", + kind: "recovery", + title: "Synchronization needs recovery", + message: "Your original files are safe. Resume from the durable checkpoint before disconnecting this vault.", + action: "resume", + actionLabel: "Resume recovery", + } : null); + const label = syncing ? "Syncing" : state.busy ? "Checking…" + : recoveryProblem?.kind === "paused" ? "Paused" + : recoveryProblem?.kind === "offline" ? "Offline" + : recoveryProblem?.kind === "auth" ? "Approval needed" + : recoveryProblem?.kind === "device" ? "Set up this device" + : recoveryProblem ? "Needs attention" : syncStateLabel(state.status); const status = document.createEl("section", { cls: "mdbase-sync-status" }); status.setAttr("data-state", state.status?.state ?? "checking"); const heading = status.createDiv({ cls: "mdbase-sync-heading" }); heading.createEl("h2", { text: profile.name }); heading.createDiv({ cls: "mdbase-muted", text: - `${syncing ? "Syncing" : syncStateLabel(state.status)} · ${relativeTime(state.status?.last_synced_at)}`, + `${label} · ${relativeTime(state.status?.last_synced_at)}`, }); const scope = heading.createDiv({ cls: "mdbase-muted mdbase-sync-scope" }); scope.createSpan({ text: this.syncScopeText(profile.mode) }); @@ -156,25 +178,7 @@ export class SyncPane { }); } - if (state.paused && !state.problem && !syncing) { - this.renderRecoveryCard(status, { - code: "sync_paused", - kind: "paused", - title: "Sync is paused", - message: "Changes on this device and in Connect wait until you resume.", - action: "resume", - actionLabel: "Resume sync", - }); - } else if (state.problem || state.status?.recovery_required) { - this.renderRecoveryCard(status, state.problem ?? { - code: "mirror_recovery_required", - kind: "recovery", - title: "Synchronization needs recovery", - message: "Your original files are safe. Resume from the durable checkpoint before disconnecting this vault.", - action: "resume", - actionLabel: "Resume recovery", - }); - } + if (recoveryProblem) this.renderRecoveryCard(status, recoveryProblem); const busy = this.ctx.busy || state.busy || syncing; const preview = state.preview; @@ -186,8 +190,8 @@ export class SyncPane { } const safety = this.session.safety(); const reviewing = Boolean(preview?.plan.actions.length || preview?.entries.length); - const actions = status.createDiv({ cls: "mdbase-sync-actions" }); - if (!syncing && !(state.problem && state.problem.action !== "review")) { + if (!syncing && !recoveryProblem) { + const actions = status.createDiv({ cls: "mdbase-sync-actions" }); if (reviewing && preview) { // The plan needs consent: apply exactly what is listed below. const presentation = syncReviewPresentation(preview.plan, preview.entries.length, busy); diff --git a/src/workspaceView.ts b/src/workspaceView.ts index 004c0ac..0378e0f 100644 --- a/src/workspaceView.ts +++ b/src/workspaceView.ts @@ -34,6 +34,7 @@ export class MdbaseWorkspaceView extends ItemView implements WorkspaceContext { readonly issues = new IssuesPane(this); private refreshVersion = 0; private unsubscribeSync: (() => void) | null = null; + private syncRenderTimer: number | null = null; constructor(leaf: WorkspaceLeaf, readonly host: MdbaseWorkspaceHost) { super(leaf); @@ -81,8 +82,24 @@ export class MdbaseWorkspaceView extends ItemView implements WorkspaceContext { void this.types.saveCurrentType(); } }); - // Sync state changes (progress, outcomes) only redraw the destination that shows them. + // Progress is current in the session immediately, but a burst of transfer + // callbacks needs only one presentation update. Decisions/outcomes never wait. + let previous = this.host.sync.state; this.unsubscribeSync = this.host.sync.subscribe(() => { + const state = this.host.sync.state; + const progressOnly = (Object.keys(state) as Array).every((key) => + key === "progress" || key === "fileProgress" || previous[key] === state[key]); + previous = state; + if (progressOnly && (state.progress || state.fileProgress)) { + if (this.destination === "sync" && this.syncRenderTimer === null) { + this.syncRenderTimer = window.setTimeout(() => { + this.syncRenderTimer = null; + if (this.destination === "sync") this.render(); + }, 100); + } + return; + } + this.cancelSyncRender(); if (this.destination === "sync") this.render(); else this.renderTopbarOnly(); }); @@ -93,10 +110,16 @@ export class MdbaseWorkspaceView extends ItemView implements WorkspaceContext { this.refreshVersion++; this.unsubscribeSync?.(); this.unsubscribeSync = null; + this.cancelSyncRender(); await this.types.dispose(); this.sync.dispose(); } + private cancelSyncRender(): void { + if (this.syncRenderTimer !== null) window.clearTimeout(this.syncRenderTimer); + this.syncRenderTimer = null; + } + async refresh(forceReload = false): Promise { const version = ++this.refreshVersion; const isCurrent = () => version === this.refreshVersion; diff --git a/test/binaryLimits.test.ts b/test/binaryLimits.test.ts index af5731e..8941808 100644 --- a/test/binaryLimits.test.ts +++ b/test/binaryLimits.test.ts @@ -17,7 +17,7 @@ test("oversized local binaries are rejected before the Vault allocates their con }); test("oversized incoming streams never reach a Vault write", async () => { - const adapter = new ObsidianMirrorFileSystem({} as never); + const adapter = new ObsidianMirrorFileSystem({ getAbstractFileByPath: () => null } as never); await assert.rejects(adapter.writeBinary("large.mp4", (async function* () { const chunk = new Uint8Array(1024 * 1024); for (let i = 0; i < 33; i++) yield chunk; diff --git a/test/connectSync.settlement.test.ts b/test/connectSync.settlement.test.ts new file mode 100644 index 0000000..8e426c5 --- /dev/null +++ b/test/connectSync.settlement.test.ts @@ -0,0 +1,176 @@ +import "fake-indexeddb/auto"; +import * as assert from "node:assert/strict"; +import { test } from "node:test"; +import type { TFile } from "obsidian"; +import { MemoryAuthority, type SyncTransport } from "@mdbase-dev/connect-sync"; +import { MemoryMirrorBlobStore, MemoryMirrorStateStore, WritableDirectoryMirror } from "@mdbase-dev/connect-sync/mirror"; +import { ConnectSyncController, ObsidianMirrorFileSystem, type MirrorProfile } from "../src/connectSync"; +import { MemoryVault } from "./memoryVault"; + +async function pair(document = "base line\n") { + const hosted = new MemoryAuthority(); + hosted.seed([{ record_id: "plan", path: "plan.md", frontmatter: {}, body: document, document, types: [] }]); + const replicaId = hosted.registerReplica({ name: "Here", mode: "read_write" }); + const vault = new MemoryVault(); + const state = new MemoryMirrorStateStore(); + await vault.createFolder(".mdbase"); + await vault.create(".mdbase/connect-role.json", JSON.stringify({ version: 1, role: "mirror", collection_id: hosted.collectionId })); + let profile: MirrorProfile | null = { + version: 1, syncUrl: `https://sync.example/v1/authorities/${hosted.collectionId}/sync`, + controlUrl: "https://connect.example", collectionId: hosted.collectionId, replicaId, + mode: "read_write", name: "Here", enrollmentId: "11111111-1111-4111-8111-111111111111", + accessTokenExpiresAt: "2099-01-01T00:00:00.000Z", + }; + let wrapTransport = (transport: SyncTransport) => transport; + const controller = new ConnectSyncController({ vault, secretStorage: { + getSecret: () => "test-credential", setSecret: () => undefined, + } } as never, { + getMirrorProfile: () => profile, saveMirrorProfile: async (next) => { profile = next; }, + deviceId: () => "test-device", + }, { + stateStoreFactory: () => state, blobStoreFactory: () => new MemoryMirrorBlobStore(), + fileSystem: new ObsidianMirrorFileSystem(vault as never), + transportFactory: () => wrapTransport(hosted.transport(replicaId)), + }); + const remoteVault = new MemoryVault(); + const remoteReplica = hosted.registerReplica({ name: "There", mode: "read_write" }); + const remoteMirror = new WritableDirectoryMirror(remoteReplica, hosted.transport(remoteReplica), { + fileSystem: new ObsidianMirrorFileSystem(remoteVault as never), stateStore: new MemoryMirrorStateStore(), + }); + const sync = async () => controller.sync((await controller.inspect()).preview); + await sync(); + await remoteMirror.sync(); + const conflict = async (local = "local line\n", remote = "remote line\n") => { + await remoteVault.modify(remoteVault.getAbstractFileByPath("plan.md") as TFile, remote); + await remoteMirror.sync(); + await vault.modify(vault.getAbstractFileByPath("plan.md") as TFile, local); + assert.equal((await sync()).status, "attention"); + }; + return { hosted, vault, state, controller, remoteVault, remoteMirror, sync, conflict, + wrap: (wrapper: typeof wrapTransport) => { wrapTransport = wrapper; } }; +} + +const copies = (vault: MemoryVault) => vault.getFiles().map((file) => file.path).filter((path) => path.includes("conflict copy")); + +function interceptSnapshot(transport: SyncTransport, intercept: () => Promise): SyncTransport { + return { ...transport, openSession: () => transport.openSession(), changes: (after, limit) => transport.changes(after, limit), + mutate: (mutation) => transport.mutate(mutation), + snapshot: async (id, page) => { await intercept(); return transport.snapshot(id, page); } }; +} + +test("repeated settling of a stale local decision does not multiply identical copies", async () => { + const here = await pair(); + await here.conflict(); + await here.vault.modify(here.vault.getAbstractFileByPath("plan.md") as TFile, "local changed again\n"); + for (let attempt = 0; attempt < 3; attempt++) await here.controller.autoResolveConflicts(); + assert.ok(copies(here.vault).length <= 1, "stale decisions must not create the same copy on every attempt"); + assert.equal(here.vault.read("plan.md"), "local changed again\n"); + await here.sync(); + await here.controller.autoResolveConflicts(); + assert.equal(here.vault.read("plan.md"), "remote line\n"); + assert.equal(copies(here.vault).length, 1); + assert.equal(here.vault.read(copies(here.vault)[0]!), "local changed again\n"); +}); + +test("a conflict that changes on Connect mid-settle leaves at most one recoverable copy", async () => { + const here = await pair(); + await here.conflict(); + let raced = false; + here.wrap((transport) => interceptSnapshot(transport, async () => { + if (raced) return; + raced = true; + await here.remoteVault.modify(here.remoteVault.getAbstractFileByPath("plan.md") as TFile, "hosted changed again\n"); + await here.remoteMirror.sync(); + })); + for (let attempt = 0; attempt < 3; attempt++) await here.controller.autoResolveConflicts(); + assert.ok(copies(here.vault).length <= 1); + assert.equal(here.vault.read("plan.md"), "local line\n"); + assert.equal((await here.controller.status())?.conflicts.length, 1); + await here.sync(); + await here.controller.autoResolveConflicts(); + assert.equal(here.vault.read("plan.md"), "hosted changed again\n"); + assert.equal(copies(here.vault).length, 1); +}); + +test("a merged write racing a user edit preserves the edit and the hosted half", async () => { + const base = "---\nstatus: open\npriority: low\n---\nBody\n"; + const here = await pair(base); + const local = base.replace("status: open", "status: done"); + const remote = base.replace("priority: low", "priority: high"); + await here.conflict(local, remote); + const process = here.vault.process.bind(here.vault); + here.vault.process = async (file, transform) => { + await here.vault.modify(file, local + "user edit during merge\n"); + return process(file, transform); + }; + const [result] = await here.controller.autoResolveConflicts(); + assert.equal(result?.outcome, "kept_both"); + assert.equal(here.vault.read("plan.md"), local + "user edit during merge\n"); + assert.equal(here.vault.read(result!.copyPath!), remote); +}); + +test("an old conflict without ancestor capture keeps both and settles only once", async () => { + const here = await pair(); + await here.conflict(); + const state = (await here.state.read())!; + delete state.planned_conflicts!.plan!.ancestor_document; + await here.state.write(state); + const [result] = await here.controller.autoResolveConflicts(); + assert.equal(result?.outcome, "kept_both"); + assert.equal(here.vault.read(result!.copyPath!), "local line\n"); + assert.deepEqual(await here.controller.autoResolveConflicts(), []); + await here.sync(); + assert.deepEqual(await here.controller.autoResolveConflicts(), []); + assert.equal(copies(here.vault).length, 1); +}); + +test("existing copy-name collisions preserve older files", async () => { + const here = await pair(); + await here.conflict(); + await here.vault.create("plan (local conflict copy).md", "older copy\n"); + await here.vault.createFolder("plan (local conflict copy 2).md"); + const [result] = await here.controller.autoResolveConflicts(); + assert.equal(result?.copyPath, "plan (local conflict copy 3).md"); + assert.equal(here.vault.read("plan (local conflict copy).md"), "older copy\n"); + assert.equal(here.vault.read(result!.copyPath!), "local line\n"); +}); + +test("a collision created after naming a binary copy is never overwritten", async () => { + const here = await pair(); + const content = new Uint8Array([0, 255, 1, 128]); + await here.vault.createBinary("image.png", content.buffer); + const exists = here.vault.adapter.exists.bind(here.vault.adapter); + let raced = false; + here.vault.adapter.exists = async (path) => { + const occupied = await exists(path); + if (path === "image (local conflict copy).png" && !raced) { + raced = true; + await here.vault.createBinary(path, new Uint8Array([7, 8, 9]).buffer); + } + return occupied; + }; + try { await here.controller.preserveConflictCopy("image.png"); } catch { /* Refusing the copy is safe. */ } + assert.deepEqual(here.vault.readBytes("image (local conflict copy).png"), new Uint8Array([7, 8, 9])); + assert.deepEqual(here.vault.readBytes("image.png"), content); +}); + +test("a conflict on a conflict copy does not nest copy labels", async () => { + const here = await pair(); + await here.vault.create("plan (local conflict copy).md", "copy edited again\n"); + const path = await here.controller.preserveConflictCopy("plan (local conflict copy).md"); + assert.equal(path, "plan (local conflict copy 2).md"); +}); + +test("hosted rename plus local edit retains both versions without waiting", async () => { + const here = await pair(); + await here.remoteVault.rename(here.remoteVault.getAbstractFileByPath("plan.md") as TFile, "renamed.md"); + await here.remoteMirror.sync(); + await here.vault.modify(here.vault.getAbstractFileByPath("plan.md") as TFile, "local edit while renamed\n"); + await here.sync(); + const results = await here.controller.autoResolveConflicts(); + assert.ok(results.every((result) => result.outcome !== "unresolved")); + await here.sync(); + const texts = here.vault.getMarkdownFiles().map((file) => here.vault.read(file.path)); + assert.ok(texts.includes("local edit while renamed\n")); + assert.equal((await here.controller.status())?.conflicts.length, 0); +}); diff --git a/test/memoryVault.ts b/test/memoryVault.ts index b6b2642..c326093 100644 --- a/test/memoryVault.ts +++ b/test/memoryVault.ts @@ -91,9 +91,9 @@ export class MemoryVault { } async cachedRead(file: TFile): Promise { - const entry = this.files.get(file.path); - if (!entry) throw new Error(`missing ${file.path}`); - return entry.content; + const text = this.read(file.path); + if (text === null) throw new Error(`missing ${file.path}`); + return text; } async create(path: string, content: string): Promise { @@ -180,7 +180,12 @@ export class MemoryVault { } read(path: string): string | null { - return this.files.get(normalizePath(path))?.content ?? null; + const normalized = normalizePath(path); + const text = this.files.get(normalized); + if (text) return text.content; + const binary = this.binaryFiles.get(normalized); + // Vault.createBinary may create Markdown; Obsidian can still read its text. + return binary ? new TextDecoder("utf-8", { ignoreBOM: true }).decode(binary.content) : null; } readBytes(path: string): Uint8Array | null { diff --git a/test/syncHistory.test.ts b/test/syncHistory.test.ts index c0f0cb5..987ade1 100644 --- a/test/syncHistory.test.ts +++ b/test/syncHistory.test.ts @@ -103,6 +103,26 @@ test("a resumed batch does not re-report receipts from the interrupted run", asy assert.deepEqual(seen, ["b"]); }); +test("receipt lookup indexes a large plan once instead of scanning it per action", async () => { + const actions = Array.from({ length: 20_000 }, (_, index) => write(String(index), `${index}.md`)); + let inspectedActions = 0; + for (const action of actions) { + const id = action.action_id; + Object.defineProperty(action, "action_id", { get: () => { inspectedActions++; return id; } }); + } + const state = batchState(actions, 0); + const seen: string[] = []; + const store = new ReceiptObservingStateStore(new RecordingStore(), (action) => seen.push(action.action_id)); + await store.write(state); + for (let index = 0; index < actions.length; index++) { + state.batch!.receipts.push({ action_id: String(index), status: "completed" }); + await store.write(state); + } + assert.equal(seen.length, actions.length); + assert.ok(inspectedActions <= actions.length * 2, + `Expected one index and one callback read per action, got ${inspectedActions} reads`); +}); + test("history rows describe direction, verb, rename source and failures", () => { const created = historyFileFromReceipt(write("a", "notes/a.md"), { action_id: "a", status: "completed" }, "t"); assert.deepEqual(created, { path: "notes/a.md", kind: "document", direction: "download", action: "create", status: "completed", at: "t" }); diff --git a/test/syncMerge.properties.test.ts b/test/syncMerge.properties.test.ts new file mode 100644 index 0000000..8b107f6 --- /dev/null +++ b/test/syncMerge.properties.test.ts @@ -0,0 +1,133 @@ +import * as assert from "node:assert/strict"; +import { test } from "node:test"; +import { Worker } from "node:worker_threads"; +import { parse } from "yaml"; +import { mergeDocuments } from "../src/syncMerge"; + +const validYaml = (yaml: string) => { + try { + const value: unknown = parse(yaml); + return value === null || (typeof value === "object" && !Array.isArray(value)); + } catch { + return false; + } +}; +const merge = (base: string, local: string, remote: string) => mergeDocuments(base, local, remote, validYaml); + +// Stable Mulberry32: a failure identifies its seed and iteration for replay. +function random(seed: number) { + return () => { + seed |= 0; + seed = (seed + 0x6D2B79F5) | 0; + let value = Math.imul(seed ^ (seed >>> 15), 1 | seed); + value ^= value + Math.imul(value ^ (value >>> 7), 61 | value); + return ((value ^ (value >>> 14)) >>> 0) / 4294967296; + }; +} + +const field = (key: string, value: string, style: number) => [ + `${key}: "${value}" # inline comment`, + `${key}: |\n ${value}\n literal --- and emoji 🥒`, + `${key}: >-\n ${value}\n continuation`, + `${key}: {nested: "${value}", list: [a, b]}`, + `${key}:\n nested:\n value: "${value}"\n list:\n - α\n - 🥒`, + `${key}: ["${value}", "emoji 🥒"]`, +][style]!; + +for (const seed of [1, 0xC0FFEE, 0xDEADBEEF]) { + test(`seed ${seed}: disjoint field/body edits are verbatim, valid and never invented`, () => { + const next = random(seed); + for (let iteration = 0; iteration < 200; iteration++) { + const styleA = Math.floor(next() * 6); + const styleB = Math.floor(next() * 6); + const eol = next() < 0.5 ? "\n" : "\r\n"; + const bom = next() < 0.5 ? "" : "\uFEFF"; + const trailing = next() < 0.5 ? "" : "\n"; + const preamble = next() < 0.5 ? "# header comment\n" : "\n"; + const a = `local-${seed}-${iteration}-α🥒`; + const b = `hosted-${seed}-${iteration}-β🌈`; + const render = (left: string, right: string, first: string, last: string) => + `${bom}---\n${preamble}${field("left", left, styleA)}\n${field("right", right, styleB)}\n---\n${first}\n\n---\n\n${last}${trailing}`.split("\n").join(eol); + const base = render("base-left", "base-right", "first", "last"); + const local = render(a, "base-right", `first-${a}`, "last"); + const remote = render("base-left", b, "first", `last-${b}`); + const expected = render(a, b, `first-${a}`, `last-${b}`); + const result = merge(base, local, remote); + assert.deepEqual(result, { clean: true, text: expected }, `iteration ${iteration}`); + if (!result.clean) continue; + const sourceLines = new Set([base, local, remote].flatMap((text) => text.split("\n"))); + for (const line of result.text.split("\n")) assert.ok(sourceLines.has(line), `invented ${line}`); + assert.equal(validYaml(result.text.split(eol).slice(1, result.text.split(eol).indexOf("---", 1)).join(eol) + eol), true); + } + }); +} + +test("overlapping generated fields keep both, including block scalars and nested maps", () => { + for (let style = 0; style < 6; style++) { + const render = (value: string) => `---\n${field("value", value, style)}\n---\nBody`; + assert.equal(merge(render("base"), render("local α"), render("hosted 🥒")).clean, false); + } +}); + +test("field additions and deletions preserve every independent change", () => { + const base = "---\n# header\na: 1\nb: 2\nc: 3\n---\nBody"; + const local = base.replace("b: 2\n", ""); + const remote = base.replace("c: 3", "c: 4\nd: [α, 🥒]"); + assert.deepEqual(merge(base, local, remote), { clean: true, text: local.replace("c: 3", "c: 4\nd: [α, 🥒]") }); +}); + +test("duplicate keys are not emitted by a combined merge", () => { + const base = "---\na: 1\na: 2\nb: 1\n---\nBody"; + assert.equal(merge(base, base.replace("a: 1", "a: 3"), base.replace("b: 1", "b: 4")).clean, false); +}); + +test("added or removed frontmatter with another body edit keeps both", () => { + const plain = "Body\n\n---\ninside body"; + const frontmatter = `---\n\n---\n${plain}`; + assert.equal(merge(plain, frontmatter, plain.replace("Body", "Edited")).clean, false); + assert.equal(merge(frontmatter, plain, frontmatter.replace("Body", "Edited")).clean, false); +}); + +// Isolate performance cases so a regression cannot hang the entire test runner. +async function largeMerge(scenario: string): Promise { + const moduleUrl = new URL("../src/syncMerge.js", import.meta.url).href; + const worker = new Worker(` + const { parentPort } = require("node:worker_threads"); + import(${JSON.stringify(moduleUrl)}).then(({ mergeDocuments }) => { + const body = "a\\n".repeat(512 * 1024); + const base = "---\\nstatus: open\\n---\\n" + body; + ${scenario} + parentPort.postMessage(mergeDocuments(base, local, remote, () => true)); + }); + `, { eval: true }); + try { + await new Promise((resolve, reject) => { + const timer = setTimeout(() => reject(new Error("1 MB merge exceeded 3 seconds")), 3000); + worker.once("error", (error) => { clearTimeout(timer); reject(error); }); + worker.once("message", (result: { clean: boolean; text?: string }) => { + clearTimeout(timer); + try { + // Keeping both is acceptable for pathological diffs; a clean merge + // must retain both edits, not return a partial result. + if (result.clean) { + assert.ok(result.text?.includes("local edit")); + assert.ok(result.text?.includes("hosted edit")); + } + resolve(); + } catch (error) { reject(error); } + }); + }); + } finally { + await worker.terminate(); + } +} + +test("1 MB repeated-line body with independent frontmatter edit stays responsive", async () => { + await largeMerge(`const local = base.replace("status: open", "status: local edit"); + const remote = base + "hosted edit\\n";`); +}); + +test("1 MB repeated-line body edited on both sides stays responsive", async () => { + await largeMerge(`const local = base.replace("---\\na", "---\\nlocal edit"); + const remote = base + "hosted edit\\n";`); +}); diff --git a/test/syncMerge.test.ts b/test/syncMerge.test.ts index f16585f..275d652 100644 --- a/test/syncMerge.test.ts +++ b/test/syncMerge.test.ts @@ -81,6 +81,41 @@ test("byte order marks and Windows line endings survive a merge", () => { assert.deepEqual(merge(base, local, remote), { clean: true, text: "---\r\nstatus: done\r\ntitle: B\r\n---\r\nBody\r\n" }); }); +test("blank lines in empty frontmatter survive an independent body edit", () => { + const base = doc("", "Body\n"); + const local = doc("\nstatus: done", "Body\n"); + const remote = doc("", "Changed body\n"); + assert.deepEqual(merge(base, local, remote), { + clean: true, + text: doc("\nstatus: done", "Changed body\n"), + }); +}); + +test("a hosted field reorder is never silently discarded", () => { + const base = doc("title: Plan\nstatus: open\npriority: low", "Body\n"); + const local = doc("title: Plan\nstatus: done\npriority: low", "Body\n"); + const remote = doc("priority: low\ntitle: Plan\nstatus: open", "Body\n"); + const result = merge(base, local, remote); + if (result.clean) assert.equal(result.text, doc("priority: low\ntitle: Plan\nstatus: done", "Body\n")); +}); + +test("changes to a closing fence's line ending are not silently discarded", () => { + const base = doc("status: open", "Body\n"); + const local = doc("status: done", "Body\n"); + const remote = base.replace("\n---\n", "\n---\r\n"); + assert.deepEqual(merge(base, local, remote), { + clean: true, + text: local.replace("\n---\n", "\n---\r\n"), + }); +}); + +test("CRLF flow values at the end of frontmatter validate without a bare CR", () => { + const base = doc("status: open\ntags: [a]", "Body\n").split("\n").join("\r\n"); + const local = base.replace("status: open", "status: done"); + const remote = base.replace("[a]", "[a, b]"); + assert.deepEqual(merge(base, local, remote), { clean: true, text: local.replace("[a]", "[a, b]") }); +}); + test("trivial cases need no merge at all", () => { assert.deepEqual(merge("a", "a", "b"), { clean: true, text: "b" }); assert.deepEqual(merge("a", "b", "a"), { clean: true, text: "b" }); diff --git a/test/syncReliability.test.ts b/test/syncReliability.test.ts index b1da1a8..4adb822 100644 --- a/test/syncReliability.test.ts +++ b/test/syncReliability.test.ts @@ -46,6 +46,7 @@ async function device(hosted: MemoryAuthority, collectionId: string, options: De await vault.createFolder(".mdbase"); await vault.create(".mdbase/connect-role.json", `${JSON.stringify({ version: 1, role: "mirror", collection_id: collectionId })}\n`); const state = options.state ?? new MemoryMirrorStateStore(); + const states = new Map([[replicaId, state]]); const secrets = options.secrets ?? new MemorySecrets(); let profile: MirrorProfile | null = { version: 1, @@ -68,17 +69,24 @@ async function device(hosted: MemoryAuthority, collectionId: string, options: De }, deviceId: () => options.deviceId ?? "this-device", }, { - stateStoreFactory: () => state, + stateStoreFactory: (current) => { + let store = states.get(current.replicaId); + if (!store) { + store = new MemoryMirrorStateStore(); + states.set(current.replicaId, store); + } + return store; + }, blobStoreFactory: () => new MemoryMirrorBlobStore(), fileSystem: new ObsidianMirrorFileSystem(vault as never), - transportFactory: () => options.wrapTransport?.(hosted.transport(replicaId)) ?? hosted.transport(replicaId), + transportFactory: (current) => options.wrapTransport?.(hosted.transport(current.replicaId)) ?? hosted.transport(current.replicaId), ...(options.enrollmentClient ? { enrollmentClient: options.enrollmentClient as MirrorEnrollmentClient } : {}), }); const syncOnce = async () => { const { preview } = await controller.inspect(); return controller.sync(preview); }; - return { vault, controller, state, secrets, replicaId, profile: () => profile, syncOnce }; + return { vault, controller, state, states, secrets, replicaId, profile: () => profile, syncOnce }; } /** A second device that edits through the bare SDK engine. */ @@ -101,6 +109,12 @@ async function collectionId(hosted: MemoryAuthority): Promise { return (await hosted.transport(probe).openSession()).collection_id; } +function deferred() { + let release!: () => void; + const promise = new Promise((resolve) => { release = resolve; }); + return { promise, release }; +} + const note = (status: string, priority: string, body = "Body\n") => `---\nstatus: ${status}\npriority: ${priority}\n---\n${body}`; test("edits to different fields on two devices are merged and synced without asking", async () => { @@ -268,6 +282,34 @@ test("the mirror's own writes are recognised as echoes, not edits", async () => assert.equal(controller.isEngineWrite("notes/other.md"), false); }); +test("binary edits made while a download stream is consumed are not overwritten", async () => { + const vault = new MemoryVault(); + const original = new Uint8Array([1, 2, 3]).buffer; + const edited = new Uint8Array([7, 8, 9]).buffer; + const file = await vault.createBinary("photo.png", original); + const fs = new ObsidianMirrorFileSystem(vault as never); + const source = (async function* () { + yield new Uint8Array([4]); + await vault.modifyBinary(file, edited); + yield new Uint8Array([5, 6]); + })(); + await assert.rejects(fs.writeBinary("photo.png", source), (error: unknown) => + (error as { code?: string }).code === "sync_plan_stale"); + assert.deepEqual(vault.readBytes("photo.png"), new Uint8Array(edited)); +}); + +test("a binary file created during a download is not silently overwritten", async () => { + const vault = new MemoryVault(); + const fs = new ObsidianMirrorFileSystem(vault as never); + const source = (async function* () { + await vault.createBinary("photo.png", new Uint8Array([7, 8, 9]).buffer); + yield new Uint8Array([4, 5, 6]); + })(); + await assert.rejects(fs.writeBinary("photo.png", source), (error: unknown) => + (error as { code?: string }).code === "sync_plan_stale"); + assert.deepEqual(vault.readBytes("photo.png"), new Uint8Array([7, 8, 9])); +}); + test("a vault copied to another device or folder refuses to sync until it is set up there", async () => { const hosted = new MemoryAuthority(); hosted.seed([{ record_id: "a", path: "a.md", frontmatter: {}, body: "a\n", types: [] }]); @@ -327,6 +369,135 @@ test("credentials stored under the old collection-only key are found and carried assert.equal(secrets.getSecret(`mdbase-connect-access-${here.replicaId}`), "renewed"); }); +test("a token renewal finishing after disconnect cannot recreate the connection", async () => { + const hosted = new MemoryAuthority(); + const id = await collectionId(hosted); + const entered = deferred(); + const finish = deferred(); + const here = await device(hosted, id, { + enrollmentClient: { + renew: async (enrollment) => { + entered.release(); + await finish.promise; + return { ...enrollment, accessToken: "renewed", accessTokenExpiresAt: "2099-01-01T00:00:00.000Z" }; + }, + }, + }); + const renewal = here.controller.reconnect(); + // Install the rejection handler before releasing either operation. + const completed = Promise.allSettled([renewal]); + await entered.promise; + await here.controller.disconnect(false); + assert.equal(here.profile(), null); + finish.release(); + await completed; + assert.equal(here.profile(), null, "a late response must not resurrect a disconnected profile"); + assert.equal(here.secrets.getSecret(`mdbase-connect-access-${here.replicaId}`), ""); +}); + +test("token renewal preserves selective-sync settings changed while it was in flight", async () => { + const hosted = new MemoryAuthority(); + const id = await collectionId(hosted); + const entered = deferred(); + const finish = deferred(); + const here = await device(hosted, id, { + enrollmentClient: { + renew: async (enrollment) => { + entered.release(); + await finish.promise; + return { ...enrollment, accessToken: "renewed", accessTokenExpiresAt: "2099-01-01T00:00:00.000Z" }; + }, + }, + }); + await here.controller.configureSelectiveSync({ file_classes: [], excluded_folders: [] }); + const renewal = here.controller.reconnect(); + await entered.promise; + const policy = { file_classes: ["image" as const], excluded_folders: ["private"] }; + await here.controller.configureSelectiveSync(policy); + finish.release(); + await renewal; + assert.deepEqual(here.profile()?.selectiveSync, policy); +}); + +test("reauthorization migrates the latest checkpoint, not the checkpoint from before browser approval", async () => { + const hosted = new MemoryAuthority(); + hosted.seed([{ record_id: "a", path: "a.md", frontmatter: {}, body: "original\n", types: [] }]); + const id = await collectionId(hosted); + const approvedReplica = hosted.registerReplica({ name: "Reapproved", mode: "read_write" }); + const entered = deferred(); + const finish = deferred(); + const here = await device(hosted, id, { + enrollmentClient: { + enroll: async () => { + entered.release(); + await finish.promise; + return { + controlUrl: "https://connect.example", syncUrl: `https://sync.example/v1/authorities/${id}/sync`, + collectionId: id, replicaId: approvedReplica, mode: "read_write", name: "Reapproved", + enrollmentId: "22222222-2222-4222-8222-222222222222", accessToken: "approved-access", + refreshCredential: "approved-refresh", accessTokenExpiresAt: "2099-01-01T00:00:00.000Z", + }; + }, + }, + }); + await here.syncOnce(); + const approval = here.controller.reauthorize({ onVerification: () => undefined }); + await entered.promise; + await edit(here.vault, "a.md", "edited while approval was open\n"); + await here.syncOnce(); + await here.syncOnce(); + const latest = await here.state.read(); + finish.release(); + await approval; + const migrated = await here.states.get(approvedReplica)!.read(); + assert.equal(migrated?.cursor, latest?.cursor, "approval must not roll back the checkpoint"); + assert.deepEqual(migrated?.records, latest?.records); + assert.equal(here.vault.read("a.md"), "edited while approval was open\n"); +}); + +test("reauthorization refuses to discard a batch prepared while browser approval was open", async () => { + const hosted = new MemoryAuthority(); + hosted.seed([{ record_id: "a", path: "a.md", frontmatter: {}, body: "original\n", types: [] }]); + const id = await collectionId(hosted); + const approvedReplica = hosted.registerReplica({ name: "Reapproved", mode: "read_write" }); + const entered = deferred(); + const finish = deferred(); + const here = await device(hosted, id, { + enrollmentClient: { + enroll: async () => { + entered.release(); + await finish.promise; + return { + controlUrl: "https://connect.example", syncUrl: `https://sync.example/v1/authorities/${id}/sync`, + collectionId: id, replicaId: approvedReplica, mode: "read_write", name: "Reapproved", + enrollmentId: "22222222-2222-4222-8222-222222222222", accessToken: "approved-access", + refreshCredential: "approved-refresh", accessTokenExpiresAt: "2099-01-01T00:00:00.000Z", + }; + }, + }, + }); + await here.syncOnce(); + const approval = here.controller.reauthorize({ onVerification: () => undefined }); + const refused = assert.rejects(approval, (error: unknown) => + (error as { code?: string }).code === "mirror_recovery_required"); + await entered.promise; + const there = otherDevice(hosted); + await there.mirror.sync(); + await there.vault.create("b.md", "new note\n"); + await there.mirror.sync(); + here.vault.failCreatePath = "b.md"; + assert.equal((await here.syncOnce()).status, "failed"); + const latest = structuredClone(await here.state.read()); + assert.ok(latest?.batch, "the failed write leaves its approved batch durable"); + finish.release(); + await refused; + assert.equal(here.profile()?.replicaId, here.replicaId); + assert.deepEqual(await here.state.read(), latest); + here.vault.failCreatePath = null; + assert.equal((await here.syncOnce()).status, "applied", "the original checkpoint can still resume"); + assert.equal(here.vault.read("b.md"), "new note\n"); +}); + test("overlapping operations share one token renewal instead of revoking each other's token", async () => { const hosted = new MemoryAuthority(); const id = await collectionId(hosted); diff --git a/test/syncScheduler.test.ts b/test/syncScheduler.test.ts index d23a942..b04567c 100644 --- a/test/syncScheduler.test.ts +++ b/test/syncScheduler.test.ts @@ -140,6 +140,23 @@ test("offline failures retry with growing backoff and reset when the network ret assert.equal(h.retryAt(), null); }); +test("offline backoff is not shortened by the ordinary probe timer", async () => { + const h = harness(); + h.setResult("failed"); + h.setProblem("offline"); + h.scheduler.start(); + await h.clock.advance(0); + for (let attempt = 1; attempt <= 8; attempt++) { + const due = h.retryAt()!; + const before = h.calls.autoSync; + await h.clock.advance(due - h.clock.now() - 1); + assert.equal(h.calls.autoSync, before, `attempt ${attempt} waits for its advertised retry`); + await h.clock.advance(1); + assert.equal(h.calls.autoSync, before + 1); + } + assert.equal(h.retryAt()! - h.clock.now(), SYNC_TIMING.retryMaxMs); +}); + test("an unreachable probe counts as offline and is retried with backoff", async () => { const h = harness({ remoteChangesWaiting: async () => { diff --git a/test/syncSession.test.ts b/test/syncSession.test.ts index 27c493b..9210f55 100644 --- a/test/syncSession.test.ts +++ b/test/syncSession.test.ts @@ -114,9 +114,34 @@ function harness(initial: MdbaseSyncPreview, options: HarnessOptions = {}) { clear: async () => undefined, }; const session = new SyncSession(controller as never, () => profile as never, history); - return { session, applied, runs, resolveCalls: () => resolveCalls, setNext: (preview: MdbaseSyncPreview) => { next = preview; } }; + return { session, controller, applied, runs, resolveCalls: () => resolveCalls, setNext: (preview: MdbaseSyncPreview) => { next = preview; } }; } +test("progress and unrelated updates do not rescan a large plan's consent policy", () => { + const preview = previewFromPlan(plan(Array.from({ length: 20_000 }, (_, index) => write(`${index}.md`)))); + const { session } = harness(preview); + let reads = 0; + for (const action of preview.plan.actions) { + const command = action.command; + Object.defineProperty(action, "command", { get: () => { reads++; return command; } }); + } + session.update({ preview }); + const safety = session.safety(); + const baselineReads = reads; + for (let index = 0; index < 100; index++) { + session.update({ progress: { phase: "downloading", completed: index, total: 20_000, done: false } }); + assert.deepEqual(session.safety(), safety); + } + assert.equal(reads, baselineReads, "the immutable preview's safety should be reused during transfers"); + const deletionPreview = previewFromPlan(plan(Array.from({ length: 21 }, (_, index) => ({ + ...remove(`${index}.md`), command: "delete_remote", expected_remote: { state: "absent" }, + } as MirrorSyncPlan["actions"][number])))); + session.update({ preview: deletionPreview }); + assert.equal(session.safety()?.safe, false, "a replacement preview must recompute consent"); + session.update({ preview: null }); + assert.equal(session.safety(), null); +}); + test("Sync now applies a routine plan in one step and records the outcome", async () => { const { session, applied, runs } = harness(previewFromPlan(plan([write("a.md"), write("b.md")]))); assert.equal(await session.syncNow(), "applied"); @@ -206,6 +231,25 @@ test("automatic sync waits while paused or while Connect needs approval", async assert.equal(await session.autoSync(), "needs_review"); }); +test("Stop sync during inspection never starts the reviewed transfer", async () => { + const h = harness(previewFromPlan(plan([write("a.md")]))); + const inspect = h.controller.inspect; + let release!: () => void; + const gate = new Promise((resolve) => { release = resolve; }); + h.controller.inspect = async () => { + await gate; + return inspect(); + }; + const running = h.session.syncNow(); + assert.equal(h.session.state.busy, true); + h.session.cancel(); + release(); + assert.equal(await running, "paused"); + assert.equal(h.applied.length, 0, "stopping an inspection must not upload or delete files afterward"); + assert.equal(h.session.state.paused, true); + assert.equal(await h.session.syncNow(), "applied", "manual retry resumes the paused plan"); +}); + test("automatic sync keeps the last message instead of clearing it", async () => { const { session } = harness(previewFromPlan(plan([]))); session.update({ message: "Disconnected elsewhere." }); diff --git a/test/workspaceView.test.ts b/test/workspaceView.test.ts index 57c04f7..5cf2225 100644 --- a/test/workspaceView.test.ts +++ b/test/workspaceView.test.ts @@ -133,6 +133,42 @@ function button(root: HTMLElement, label: string): HTMLButtonElement { return result; } +test("transfer notifications coalesce renders, keep completion immediate, and cancel on close", async () => { + const f = fixture(true); + await f.view.onOpen(); + let renders = 0; + let badgeRenders = 0; + f.view.render = () => { renders++; }; + (f.view as unknown as { renderTopbarOnly(): void }).renderTopbarOnly = () => { badgeRenders++; }; + const timers = new Map void>(); + let next = 0; + f.dom.window.setTimeout = ((callback: () => void) => { + timers.set(++next, callback); + return next; + }) as typeof window.setTimeout; + f.dom.window.clearTimeout = (id: number) => { timers.delete(id); }; + for (let completed = 0; completed < 1_000; completed++) { + f.host.sync.update({ progress: { phase: "downloading", completed, total: 1_000, done: false } }); + } + assert.equal(renders, 0, "a fast transfer must not rebuild the pane once per file"); + assert.equal(timers.size, 1); + const [id, callback] = [...timers][0]; + timers.delete(id); + callback(); + assert.equal(renders, 1); + f.host.sync.update({ progress: null, message: "Sync complete." }); + assert.equal(renders, 2, "completion is visible immediately"); + f.state.destination = "types"; + f.host.sync.update({ progress: { phase: "downloading", completed: 0, total: 10, done: false } }); + assert.equal(badgeRenders, 0, "transfer-only changes cannot affect tab badges"); + f.state.destination = "sync"; + f.host.sync.update({ progress: { phase: "downloading", completed: 1, total: 10, done: false } }); + assert.equal(timers.size, 1); + await f.view.onClose(); + assert.equal(timers.size, 0, "closing the view must cancel a queued render"); + f.dom.window.close(); +}); + test("connected Sync is one status and one primary action; settings live in the settings tab", () => { const f = fixture(true); f.state.render(); @@ -146,6 +182,37 @@ test("connected Sync is one status and one primary action; settings live in the f.dom.window.close(); }); +test("recovery states have one next action and never show a stale healthy heading", () => { + for (const scenario of [ + { patch: { paused: true }, action: "Resume sync", label: "Paused" }, + { patch: { status: { state: "up_to_date", recovery_required: true, conflicts: [], local_issues: [] } }, action: "Resume recovery", label: "Needs attention" }, + { patch: { problem: { code: "stale_mirror_plan", kind: "decision", title: "The collection changed again", message: "Review the newest versions.", action: "review", actionLabel: "Review newest changes" } }, action: "Review newest changes", label: "Needs attention" }, + ]) { + const f = fixture(true); + f.host.sync.update(scenario.patch as never); + f.state.render(); + assert.equal(f.root.querySelectorAll(".mod-cta").length, 1, f.text()); + assert.ok(button(f.root, scenario.action)); + assert.match(f.root.querySelector(".mdbase-sync-heading")!.textContent!, new RegExp(scenario.label)); + assert.doesNotMatch(f.text(), /Up to date|Sync now/); + f.dom.window.close(); + } +}); + +test("a stale reviewed plan cannot be applied before refreshing the newest changes", () => { + const f = fixture(true); + f.state.mirrorPreview = { + phase: "incremental", plan: { actions: [{ command: "delete_local" }], issues: [], summary: { blocking_issues: 0 } }, + entries: [{ path: "old.md", direction: "download", action: "delete", detail: "Delete old file" }], collisions: [], local_issues: [], + }; + f.host.sync.reportProblem(Object.assign(new Error("Plan changed"), { code: "stale_mirror_plan" })); + f.state.render(); + assert.equal(f.root.querySelectorAll(".mod-cta").length, 1, f.text()); + assert.ok(button(f.root, "Review newest changes")); + assert.doesNotMatch(f.text(), /Sync 1 change|Refresh review/); + f.dom.window.close(); +}); + test("enrollment exposes only essential controls but retains the upload warning and advanced options", () => { const f = fixture(); f.state.render();