diff --git a/docs/sync-ux-acceptance.md b/docs/sync-ux-acceptance.md index 0bc70fa..3e166f7 100644 --- a/docs/sync-ux-acceptance.md +++ b/docs/sync-ux-acceptance.md @@ -23,6 +23,6 @@ node scripts/test-sync-layout.cjs after-layout `MDBASE_UX_PLAYWRIGHT` can be omitted if Playwright is already resolvable. It is not a plugin runtime dependency. -The audit captures 23 states at 1100px and 390px, in dark and light themes: healthy, long excluded-folder scope, local file issue, offline, sign-in, copied device, paused, unexpected failure, progress, first-sync review, deletion-burst review, rebuild, unresolved conflict (both versions present, local absent, or hosted absent), pinned conflict history, enrollment, and local upload, plus five sync problems viewed from Issues (where mobile needs an in-workspace indicator). Desktop sidebars are collapsed for realistic narrow panes. Assertions reject horizontal overflow, hidden sync problems when viewing another destination, and primary/dismiss targets below 44px in narrow panes. Long, unbroken paths are intentional. `*-checks.json` records the measured bounds; the command exits nonzero on a regression. +The audit captures 24 states at 1100px and 390px, in dark and light themes: healthy, long excluded-folder scope, local file issue, offline, sign-in, copied device, paused, unexpected failure, progress, first-sync review, deletion-burst review, rebuild, unresolved conflict (both versions present, local absent, hosted absent, or active sync), pinned conflict history, enrollment, and local upload, plus five sync problems viewed from Issues (where mobile needs an in-workspace indicator). Desktop sidebars are collapsed for realistic narrow panes. Assertions reject horizontal overflow, hidden sync problems when viewing another destination, conflict decisions enabled while sync is active, and primary/dismiss targets below 44px in narrow panes. Long, unbroken paths are intentional. `*-checks.json` records the measured bounds; the command exits nonzero on a regression. Review the PNGs as well as the assertions. Diff panels may scroll horizontally within their own surface; the workspace itself must not. Stop the isolated instance after testing and discard its app/profile/vault. Injected profile state is ephemeral and must never be saved as real credentials. diff --git a/main.js b/main.js index 15b8aa2..9c49ce9 100644 --- a/main.js +++ b/main.js @@ -3,31 +3,31 @@ THIS IS A GENERATED/BUNDLED FILE BY ESBUILD if you want to view the source, please visit the github repository of this plugin */ -var eE=Object.create;var Ma=Object.defineProperty;var tE=Object.getOwnPropertyDescriptor;var rE=Object.getOwnPropertyNames;var nE=Object.getPrototypeOf,iE=Object.prototype.hasOwnProperty;var cy=(r,e)=>()=>(r&&(e=r(r=0)),e);var k=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),ly=(r,e)=>{for(var t in e)Ma(r,t,{get:e[t],enumerable:!0})},dy=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of rE(e))!iE.call(r,i)&&i!==t&&Ma(r,i,{get:()=>e[i],enumerable:!(n=tE(e,i))||n.enumerable});return r};var Wn=(r,e,t)=>(t=r!=null?eE(nE(r)):{},dy(e||!r||!r.__esModule?Ma(t,"default",{value:r,enumerable:!0}):t,r)),sE=r=>dy(Ma({},"__esModule",{value:!0}),r);var qs=k(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 Jn=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=Jn;var Lt=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 Jn&&(t[n.str]=(t[n.str]||0)+1),t),{})}};se._Code=Lt;se.nil=new Lt("");function py(r,...e){let t=[r[0]],n=0;for(;n{"use strict";Object.defineProperty(ft,"__esModule",{value:!0});ft.ValueScope=ft.ValueScopeName=ft.Scope=ft.varKinds=ft.UsedValueState=void 0;var ut=qs(),Ud=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},Oa;(function(r){r[r.Started=0]="Started",r[r.Completed=1]="Completed"})(Oa||(ft.UsedValueState=Oa={}));ft.varKinds={const:new ut.Name("const"),let:new ut.Name("let"),var:new ut.Name("var")};var Da=class{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t}toName(e){return e instanceof ut.Name?e:this.name(e)}name(e){return new ut.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}}};ft.Scope=Da;var Na=class extends ut.Name{constructor(e,t){super(t),this.prefix=e}setValue(e,{property:t,itemIndex:n}){this.value=e,this.scopePath=(0,ut._)`.${new ut.Name(t)}[${n}]`}};ft.ValueScopeName=Na;var wE=(0,ut._)`\n`,Vd=class extends Da{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?wE:ut.nil}}get(){return this._scope}name(e){return new Na(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,ut._)`${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=ut.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,Oa.Started);let u=t(l);if(u){let d=this.opts.es5?ft.varKinds.var:ft.varKinds.const;s=(0,ut._)`${s}${d} ${l} = ${u};${this.opts._n}`}else if(u=i?.(l))s=(0,ut._)`${s}${u}${this.opts._n}`;else throw new Ud(l);c.set(l,Oa.Completed)})}return s}};ft.ValueScope=Vd});var U=k(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(),Xt=Hd(),ln=qs();Object.defineProperty(Y,"_",{enumerable:!0,get:function(){return ln._}});Object.defineProperty(Y,"str",{enumerable:!0,get:function(){return ln.str}});Object.defineProperty(Y,"strConcat",{enumerable:!0,get:function(){return ln.strConcat}});Object.defineProperty(Y,"nil",{enumerable:!0,get:function(){return ln.nil}});Object.defineProperty(Y,"getProperty",{enumerable:!0,get:function(){return ln.getProperty}});Object.defineProperty(Y,"stringify",{enumerable:!0,get:function(){return ln.stringify}});Object.defineProperty(Y,"regexpCode",{enumerable:!0,get:function(){return ln.regexpCode}});Object.defineProperty(Y,"Name",{enumerable:!0,get:function(){return ln.Name}});var qa=Hd();Object.defineProperty(Y,"Scope",{enumerable:!0,get:function(){return qa.Scope}});Object.defineProperty(Y,"ValueScope",{enumerable:!0,get:function(){return qa.ValueScope}});Object.defineProperty(Y,"ValueScopeName",{enumerable:!0,get:function(){return qa.ValueScopeName}});Object.defineProperty(Y,"varKinds",{enumerable:!0,get:function(){return qa.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 jr=class{optimizeNodes(){return this}optimizeNames(e,t){return this}},zd=class extends jr{constructor(e,t,n){super(),this.varKind=e,this.name=t,this.rhs=n}render({es5:e,_n:t}){let n=e?Xt.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:{}}},La=class extends jr{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 ja(e,this.rhs)}},Kd=class extends La{constructor(e,t,n,i){super(e,n,i),this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Wd=class extends jr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Gd=class extends jr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Jd=class extends jr{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Yd=class extends jr{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 jr{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)||(_E(e,s.names),n.splice(i,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>Qn(e,t.names),{})}},qr=class extends Bs{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Xd=class extends Bs{},Ci=class extends qr{};Ci.kind="else";var Yn=class r extends qr{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(my(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 ja(e,this.condition),this.else&&Qn(e,this.else.names),e}};Yn.kind="if";var Xn=class extends qr{};Xn.kind="for";var Qd=class extends Xn{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 Qn(super.names,this.iteration.names)}},Zd=class extends Xn{constructor(e,t,n,i){super(),this.varKind=e,this.name=t,this.from=n,this.to=i}render(e){let t=e.es5?Xt.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=ja(super.names,this.from);return ja(e,this.to)}},Fa=class extends Xn{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 Qn(super.names,this.iterable.names)}},Us=class extends qr{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 eu=class extends qr{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&&Qn(e,this.catch.names),this.finally&&Qn(e,this.finally.names),e}},Hs=class extends qr{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};Hs.kind="catch";var zs=class extends qr{render(e){return"finally"+super.render(e)}};zs.kind="finally";var tu=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?` -`:""},this._extScope=e,this._scope=new Xt.Scope({parent:e}),this._nodes=[new Xd]}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 zd(e,s,n)),s}const(e,t,n){return this._def(Xt.varKinds.const,e,t,n)}let(e,t,n){return this._def(Xt.varKinds.let,e,t,n)}var(e,t,n){return this._def(Xt.varKinds.var,e,t,n)}assign(e,t,n){return this._leafNode(new La(e,t,n))}add(e,t){return this._leafNode(new Kd(e,Y.operators.ADD,t))}code(e){return typeof e=="function"?e():e!==re.nil&&this._leafNode(new Yd(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 Yn(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 Yn(e))}else(){return this._elseNode(new Ci)}endIf(){return this._endBlockNode(Yn,Ci)}_for(e,t){return this._blockNode(e),t&&this.code(t).endFor(),this}for(e,t){return this._for(new Qd(e),t)}forRange(e,t,n,i,s=this.opts.es5?Xt.varKinds.var:Xt.varKinds.let){let o=this._scope.toName(e);return this._for(new Zd(s,o,t,n),()=>i(o))}forOf(e,t,n,i=Xt.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 Fa("of",i,s,t),()=>n(s))}forIn(e,t,n,i=this.opts.es5?Xt.varKinds.var:Xt.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 Fa("in",i,s,t),()=>n(s))}endFor(){return this._endBlockNode(Xn)}label(e){return this._leafNode(new Wd(e))}break(e){return this._leafNode(new Gd(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 eu;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 Jd(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 Yn))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=tu;function Qn(r,e){for(let t in e)r[t]=(r[t]||0)+(e[t]||0);return r}function ja(r,e){return e instanceof re._CodeOrName?Qn(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 _E(r,e){for(let t in e)r[t]=(r[t]||0)-(e[t]||0)}function my(r){return typeof r=="boolean"||typeof r=="number"||r===null?!r:(0,re._)`!${ru(r)}`}Y.not=my;var SE=yy(Y.operators.AND);function xE(...r){return r.reduce(SE)}Y.and=xE;var $E=yy(Y.operators.OR);function EE(...r){return r.reduce($E)}Y.or=EE;function yy(r){return(e,t)=>e===re.nil?t:t===re.nil?e:(0,re._)`${ru(e)} ${r} ${ru(t)}`}function ru(r){return r instanceof re.Name?r:(0,re._)`(${r})`}});var Q=k(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(),kE=qs();function AE(r){let e={};for(let t of r)e[t]=!0;return e}X.toHash=AE;function PE(r,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(vy(r,e),!wy(e,r.self.RULES.all))}X.alwaysValidSchema=PE;function vy(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]||xy(r,`unknown keyword: "${s}"`)}X.checkUnknownRules=vy;function wy(r,e){if(typeof r=="boolean")return!r;for(let t in r)if(e[t])return!0;return!1}X.schemaHasRules=wy;function CE(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=CE;function ME({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=ME;function RE(r){return _y(decodeURIComponent(r))}X.unescapeFragment=RE;function TE(r){return encodeURIComponent(iu(r))}X.escapeFragment=TE;function iu(r){return typeof r=="number"?`${r}`:r.replace(/~/g,"~0").replace(/\//g,"~1")}X.escapeJsonPointer=iu;function _y(r){return r.replace(/~1/g,"/").replace(/~0/g,"~")}X.unescapeJsonPointer=_y;function IE(r,e){if(Array.isArray(r))for(let t of r)e(t);else e(r)}X.eachItem=IE;function gy({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:gy({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} || {}`),su(r,t,e))}),mergeValues:(r,e)=>r===!0?!0:{...r,...e},resultToName:Sy}),items:gy({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 Sy(r,e){if(e===!0)return r.var("props",!0);let t=r.var("props",(0,de._)`{}`);return e!==void 0&&su(r,t,e),t}X.evaluatedPropsToName=Sy;function su(r,e,t){Object.keys(t).forEach(n=>r.assign((0,de._)`${e}${(0,de.getProperty)(n)}`,!0))}X.setEvaluated=su;var by={};function OE(r,e){return r.scopeValue("func",{ref:e,code:by[e.code]||(by[e.code]=new kE._Code(e.code))})}X.useFunc=OE;var nu;(function(r){r[r.Num=0]="Num",r[r.Str=1]="Str"})(nu||(X.Type=nu={}));function DE(r,e,t){if(r instanceof de.Name){let n=e===nu.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():"/"+iu(r)}X.getErrorPath=DE;function xy(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=xy});var Ft=k(ou=>{"use strict";Object.defineProperty(ou,"__esModule",{value:!0});var He=U(),NE={data:new He.Name("data"),valCxt:new He.Name("valCxt"),instancePath:new He.Name("instancePath"),parentData:new He.Name("parentData"),parentDataProperty:new He.Name("parentDataProperty"),rootData:new He.Name("rootData"),dynamicAnchors:new He.Name("dynamicAnchors"),vErrors:new He.Name("vErrors"),errors:new He.Name("errors"),this:new He.Name("this"),self:new He.Name("self"),scope:new He.Name("scope"),json:new He.Name("json"),jsonPos:new He.Name("jsonPos"),jsonLen:new He.Name("jsonLen"),jsonPart:new He.Name("jsonPart")};ou.default=NE});var Ks=k(ze=>{"use strict";Object.defineProperty(ze,"__esModule",{value:!0});ze.extendErrors=ze.resetErrorsCount=ze.reportExtraError=ze.reportError=ze.keyword$DataError=ze.keywordError=void 0;var ie=U(),Ba=Q(),rt=Ft();ze.keywordError={message:({keyword:r})=>(0,ie.str)`must pass "${r}" keyword validation`};ze.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 LE(r,e=ze.keywordError,t,n){let{it:i}=r,{gen:s,compositeRule:o,allErrors:a}=i,c=ky(r,e,t);n??(o||a)?$y(s,c):Ey(i,(0,ie._)`[${c}]`)}ze.reportError=LE;function FE(r,e=ze.keywordError,t){let{it:n}=r,{gen:i,compositeRule:s,allErrors:o}=n,a=ky(r,e,t);$y(i,a),s||o||Ey(n,rt.default.vErrors)}ze.reportExtraError=FE;function jE(r,e){r.assign(rt.default.errors,e),r.if((0,ie._)`${rt.default.vErrors} !== null`,()=>r.if(e,()=>r.assign((0,ie._)`${rt.default.vErrors}.length`,e),()=>r.assign(rt.default.vErrors,null)))}ze.resetErrorsCount=jE;function qE({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,rt.default.errors,a=>{r.const(o,(0,ie._)`${rt.default.vErrors}[${a}]`),r.if((0,ie._)`${o}.instancePath === undefined`,()=>r.assign((0,ie._)`${o}.instancePath`,(0,ie.strConcat)(rt.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))})}ze.extendErrors=qE;function $y(r,e){let t=r.const("err",e);r.if((0,ie._)`${rt.default.vErrors} === null`,()=>r.assign(rt.default.vErrors,(0,ie._)`[${t}]`),(0,ie._)`${rt.default.vErrors}.push(${t})`),r.code((0,ie._)`${rt.default.errors}++`)}function Ey(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 Zn={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 ky(r,e,t){let{createErrors:n}=r.it;return n===!1?(0,ie._)`{}`:BE(r,e,t)}function BE(r,e,t={}){let{gen:n,it:i}=r,s=[UE(i,t),VE(r,t)];return HE(r,e,s),n.object(...s)}function UE({errorPath:r},{instancePath:e}){let t=e?(0,ie.str)`${r}${(0,Ba.getErrorPath)(e,Ba.Type.Str)}`:r;return[rt.default.instancePath,(0,ie.strConcat)(rt.default.instancePath,t)]}function VE({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,Ba.getErrorPath)(t,Ba.Type.Str)}`),[Zn.schemaPath,i]}function HE(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([Zn.keyword,i],[Zn.params,typeof e=="function"?e(r):e||(0,ie._)`{}`]),c.messages&&n.push([Zn.message,typeof t=="function"?t(r):t]),c.verbose&&n.push([Zn.schema,o],[Zn.parentSchema,(0,ie._)`${u}${d}`],[rt.default.data,s]),l&&n.push([Zn.propertyName,l])}});var Py=k(Ri=>{"use strict";Object.defineProperty(Ri,"__esModule",{value:!0});Ri.boolOrEmptySchema=Ri.topBoolOrEmptySchema=void 0;var zE=Ks(),KE=U(),WE=Ft(),GE={message:"boolean schema is false"};function JE(r){let{gen:e,schema:t,validateName:n}=r;t===!1?Ay(r,!1):typeof t=="object"&&t.$async===!0?e.return(WE.default.data):(e.assign((0,KE._)`${n}.errors`,null),e.return(!0))}Ri.topBoolOrEmptySchema=JE;function YE(r,e){let{gen:t,schema:n}=r;n===!1?(t.var(e,!1),Ay(r)):t.var(e,!0)}Ri.boolOrEmptySchema=YE;function Ay(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,zE.reportError)(i,GE,void 0,e)}});var au=k(Ti=>{"use strict";Object.defineProperty(Ti,"__esModule",{value:!0});Ti.getRules=Ti.isJSONType=void 0;var XE=["string","number","integer","boolean","null","object","array"],QE=new Set(XE);function ZE(r){return typeof r=="string"&&QE.has(r)}Ti.isJSONType=ZE;function ek(){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:{}}}Ti.getRules=ek});var cu=k(dn=>{"use strict";Object.defineProperty(dn,"__esModule",{value:!0});dn.shouldUseRule=dn.shouldUseGroup=dn.schemaHasRulesForType=void 0;function tk({schema:r,self:e},t){let n=e.RULES.types[t];return n&&n!==!0&&Cy(r,n)}dn.schemaHasRulesForType=tk;function Cy(r,e){return e.rules.some(t=>My(r,t))}dn.shouldUseGroup=Cy;function My(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))}dn.shouldUseRule=My});var Ws=k(Ke=>{"use strict";Object.defineProperty(Ke,"__esModule",{value:!0});Ke.reportTypeError=Ke.checkDataTypes=Ke.checkDataType=Ke.coerceAndCheckDataType=Ke.getJSONTypes=Ke.getSchemaTypes=Ke.DataType=void 0;var rk=au(),nk=cu(),ik=Ks(),z=U(),Ry=Q(),Ii;(function(r){r[r.Correct=0]="Correct",r[r.Wrong=1]="Wrong"})(Ii||(Ke.DataType=Ii={}));function sk(r){let e=Ty(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}Ke.getSchemaTypes=sk;function Ty(r){let e=Array.isArray(r)?r:r?[r]:[];if(e.every(rk.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}Ke.getJSONTypes=Ty;function ok(r,e){let{gen:t,data:n,opts:i}=r,s=ak(e,i.coerceTypes),o=e.length>0&&!(s.length===0&&e.length===1&&(0,nk.schemaHasRulesForType)(r,e[0]));if(o){let a=du(e,n,i.strictNumbers,Ii.Wrong);t.if(a,()=>{s.length?ck(r,e,s):uu(r)})}return o}Ke.coerceAndCheckDataType=ok;var Iy=new Set(["string","number","integer","boolean","null"]);function ak(r,e){return e?r.filter(t=>Iy.has(t)||e==="array"&&t==="array"):[]}function ck(r,e,t){let{gen:n,data:i,opts:s}=r,o=n.let("dataType",(0,z._)`typeof ${i}`),a=n.let("coerced",(0,z._)`undefined`);s.coerceTypes==="array"&&n.if((0,z._)`${o} == 'object' && Array.isArray(${i}) && ${i}.length == 1`,()=>n.assign(i,(0,z._)`${i}[0]`).assign(o,(0,z._)`typeof ${i}`).if(du(e,i,s.strictNumbers),()=>n.assign(a,i))),n.if((0,z._)`${a} !== undefined`);for(let l of t)(Iy.has(l)||l==="array"&&s.coerceTypes==="array")&&c(l);n.else(),uu(r),n.endIf(),n.if((0,z._)`${a} !== undefined`,()=>{n.assign(i,a),lk(r,a)});function c(l){switch(l){case"string":n.elseIf((0,z._)`${o} == "number" || ${o} == "boolean"`).assign(a,(0,z._)`"" + ${i}`).elseIf((0,z._)`${i} === null`).assign(a,(0,z._)`""`);return;case"number":n.elseIf((0,z._)`${o} == "boolean" || ${i} === null +var eE=Object.create;var Ma=Object.defineProperty;var tE=Object.getOwnPropertyDescriptor;var rE=Object.getOwnPropertyNames;var nE=Object.getPrototypeOf,iE=Object.prototype.hasOwnProperty;var cy=(r,e)=>()=>(r&&(e=r(r=0)),e);var k=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),ly=(r,e)=>{for(var t in e)Ma(r,t,{get:e[t],enumerable:!0})},dy=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of rE(e))!iE.call(r,i)&&i!==t&&Ma(r,i,{get:()=>e[i],enumerable:!(n=tE(e,i))||n.enumerable});return r};var Wn=(r,e,t)=>(t=r!=null?eE(nE(r)):{},dy(e||!r||!r.__esModule?Ma(t,"default",{value:r,enumerable:!0}):t,r)),sE=r=>dy(Ma({},"__esModule",{value:!0}),r);var qs=k(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 Jn=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=Jn;var Nt=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 Jn&&(t[n.str]=(t[n.str]||0)+1),t),{})}};se._Code=Nt;se.nil=new Nt("");function py(r,...e){let t=[r[0]],n=0;for(;n{"use strict";Object.defineProperty(ft,"__esModule",{value:!0});ft.ValueScope=ft.ValueScopeName=ft.Scope=ft.varKinds=ft.UsedValueState=void 0;var ut=qs(),Ud=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},Oa;(function(r){r[r.Started=0]="Started",r[r.Completed=1]="Completed"})(Oa||(ft.UsedValueState=Oa={}));ft.varKinds={const:new ut.Name("const"),let:new ut.Name("let"),var:new ut.Name("var")};var Da=class{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t}toName(e){return e instanceof ut.Name?e:this.name(e)}name(e){return new ut.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}}};ft.Scope=Da;var La=class extends ut.Name{constructor(e,t){super(t),this.prefix=e}setValue(e,{property:t,itemIndex:n}){this.value=e,this.scopePath=(0,ut._)`.${new ut.Name(t)}[${n}]`}};ft.ValueScopeName=La;var wE=(0,ut._)`\n`,Vd=class extends Da{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?wE:ut.nil}}get(){return this._scope}name(e){return new La(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,ut._)`${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=ut.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,Oa.Started);let u=t(l);if(u){let d=this.opts.es5?ft.varKinds.var:ft.varKinds.const;s=(0,ut._)`${s}${d} ${l} = ${u};${this.opts._n}`}else if(u=i?.(l))s=(0,ut._)`${s}${u}${this.opts._n}`;else throw new Ud(l);c.set(l,Oa.Completed)})}return s}};ft.ValueScope=Vd});var U=k(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(),Xt=Hd(),ln=qs();Object.defineProperty(Y,"_",{enumerable:!0,get:function(){return ln._}});Object.defineProperty(Y,"str",{enumerable:!0,get:function(){return ln.str}});Object.defineProperty(Y,"strConcat",{enumerable:!0,get:function(){return ln.strConcat}});Object.defineProperty(Y,"nil",{enumerable:!0,get:function(){return ln.nil}});Object.defineProperty(Y,"getProperty",{enumerable:!0,get:function(){return ln.getProperty}});Object.defineProperty(Y,"stringify",{enumerable:!0,get:function(){return ln.stringify}});Object.defineProperty(Y,"regexpCode",{enumerable:!0,get:function(){return ln.regexpCode}});Object.defineProperty(Y,"Name",{enumerable:!0,get:function(){return ln.Name}});var qa=Hd();Object.defineProperty(Y,"Scope",{enumerable:!0,get:function(){return qa.Scope}});Object.defineProperty(Y,"ValueScope",{enumerable:!0,get:function(){return qa.ValueScope}});Object.defineProperty(Y,"ValueScopeName",{enumerable:!0,get:function(){return qa.ValueScopeName}});Object.defineProperty(Y,"varKinds",{enumerable:!0,get:function(){return qa.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 jr=class{optimizeNodes(){return this}optimizeNames(e,t){return this}},zd=class extends jr{constructor(e,t,n){super(),this.varKind=e,this.name=t,this.rhs=n}render({es5:e,_n:t}){let n=e?Xt.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:{}}},Na=class extends jr{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 ja(e,this.rhs)}},Kd=class extends Na{constructor(e,t,n,i){super(e,n,i),this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Wd=class extends jr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Gd=class extends jr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Jd=class extends jr{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Yd=class extends jr{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 jr{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)||(_E(e,s.names),n.splice(i,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>Qn(e,t.names),{})}},qr=class extends Bs{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Xd=class extends Bs{},Ci=class extends qr{};Ci.kind="else";var Yn=class r extends qr{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(my(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 ja(e,this.condition),this.else&&Qn(e,this.else.names),e}};Yn.kind="if";var Xn=class extends qr{};Xn.kind="for";var Qd=class extends Xn{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 Qn(super.names,this.iteration.names)}},Zd=class extends Xn{constructor(e,t,n,i){super(),this.varKind=e,this.name=t,this.from=n,this.to=i}render(e){let t=e.es5?Xt.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=ja(super.names,this.from);return ja(e,this.to)}},Fa=class extends Xn{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 Qn(super.names,this.iterable.names)}},Us=class extends qr{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 eu=class extends qr{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&&Qn(e,this.catch.names),this.finally&&Qn(e,this.finally.names),e}},Hs=class extends qr{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};Hs.kind="catch";var zs=class extends qr{render(e){return"finally"+super.render(e)}};zs.kind="finally";var tu=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?` +`:""},this._extScope=e,this._scope=new Xt.Scope({parent:e}),this._nodes=[new Xd]}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 zd(e,s,n)),s}const(e,t,n){return this._def(Xt.varKinds.const,e,t,n)}let(e,t,n){return this._def(Xt.varKinds.let,e,t,n)}var(e,t,n){return this._def(Xt.varKinds.var,e,t,n)}assign(e,t,n){return this._leafNode(new Na(e,t,n))}add(e,t){return this._leafNode(new Kd(e,Y.operators.ADD,t))}code(e){return typeof e=="function"?e():e!==re.nil&&this._leafNode(new Yd(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 Yn(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 Yn(e))}else(){return this._elseNode(new Ci)}endIf(){return this._endBlockNode(Yn,Ci)}_for(e,t){return this._blockNode(e),t&&this.code(t).endFor(),this}for(e,t){return this._for(new Qd(e),t)}forRange(e,t,n,i,s=this.opts.es5?Xt.varKinds.var:Xt.varKinds.let){let o=this._scope.toName(e);return this._for(new Zd(s,o,t,n),()=>i(o))}forOf(e,t,n,i=Xt.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 Fa("of",i,s,t),()=>n(s))}forIn(e,t,n,i=this.opts.es5?Xt.varKinds.var:Xt.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 Fa("in",i,s,t),()=>n(s))}endFor(){return this._endBlockNode(Xn)}label(e){return this._leafNode(new Wd(e))}break(e){return this._leafNode(new Gd(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 eu;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 Jd(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 Yn))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=tu;function Qn(r,e){for(let t in e)r[t]=(r[t]||0)+(e[t]||0);return r}function ja(r,e){return e instanceof re._CodeOrName?Qn(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 _E(r,e){for(let t in e)r[t]=(r[t]||0)-(e[t]||0)}function my(r){return typeof r=="boolean"||typeof r=="number"||r===null?!r:(0,re._)`!${ru(r)}`}Y.not=my;var SE=yy(Y.operators.AND);function xE(...r){return r.reduce(SE)}Y.and=xE;var $E=yy(Y.operators.OR);function EE(...r){return r.reduce($E)}Y.or=EE;function yy(r){return(e,t)=>e===re.nil?t:t===re.nil?e:(0,re._)`${ru(e)} ${r} ${ru(t)}`}function ru(r){return r instanceof re.Name?r:(0,re._)`(${r})`}});var Q=k(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(),kE=qs();function AE(r){let e={};for(let t of r)e[t]=!0;return e}X.toHash=AE;function PE(r,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(vy(r,e),!wy(e,r.self.RULES.all))}X.alwaysValidSchema=PE;function vy(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]||xy(r,`unknown keyword: "${s}"`)}X.checkUnknownRules=vy;function wy(r,e){if(typeof r=="boolean")return!r;for(let t in r)if(e[t])return!0;return!1}X.schemaHasRules=wy;function CE(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=CE;function ME({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=ME;function RE(r){return _y(decodeURIComponent(r))}X.unescapeFragment=RE;function TE(r){return encodeURIComponent(iu(r))}X.escapeFragment=TE;function iu(r){return typeof r=="number"?`${r}`:r.replace(/~/g,"~0").replace(/\//g,"~1")}X.escapeJsonPointer=iu;function _y(r){return r.replace(/~1/g,"/").replace(/~0/g,"~")}X.unescapeJsonPointer=_y;function IE(r,e){if(Array.isArray(r))for(let t of r)e(t);else e(r)}X.eachItem=IE;function gy({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:gy({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} || {}`),su(r,t,e))}),mergeValues:(r,e)=>r===!0?!0:{...r,...e},resultToName:Sy}),items:gy({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 Sy(r,e){if(e===!0)return r.var("props",!0);let t=r.var("props",(0,de._)`{}`);return e!==void 0&&su(r,t,e),t}X.evaluatedPropsToName=Sy;function su(r,e,t){Object.keys(t).forEach(n=>r.assign((0,de._)`${e}${(0,de.getProperty)(n)}`,!0))}X.setEvaluated=su;var by={};function OE(r,e){return r.scopeValue("func",{ref:e,code:by[e.code]||(by[e.code]=new kE._Code(e.code))})}X.useFunc=OE;var nu;(function(r){r[r.Num=0]="Num",r[r.Str=1]="Str"})(nu||(X.Type=nu={}));function DE(r,e,t){if(r instanceof de.Name){let n=e===nu.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():"/"+iu(r)}X.getErrorPath=DE;function xy(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=xy});var Ft=k(ou=>{"use strict";Object.defineProperty(ou,"__esModule",{value:!0});var He=U(),LE={data:new He.Name("data"),valCxt:new He.Name("valCxt"),instancePath:new He.Name("instancePath"),parentData:new He.Name("parentData"),parentDataProperty:new He.Name("parentDataProperty"),rootData:new He.Name("rootData"),dynamicAnchors:new He.Name("dynamicAnchors"),vErrors:new He.Name("vErrors"),errors:new He.Name("errors"),this:new He.Name("this"),self:new He.Name("self"),scope:new He.Name("scope"),json:new He.Name("json"),jsonPos:new He.Name("jsonPos"),jsonLen:new He.Name("jsonLen"),jsonPart:new He.Name("jsonPart")};ou.default=LE});var Ks=k(ze=>{"use strict";Object.defineProperty(ze,"__esModule",{value:!0});ze.extendErrors=ze.resetErrorsCount=ze.reportExtraError=ze.reportError=ze.keyword$DataError=ze.keywordError=void 0;var ie=U(),Ba=Q(),rt=Ft();ze.keywordError={message:({keyword:r})=>(0,ie.str)`must pass "${r}" keyword validation`};ze.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=ze.keywordError,t,n){let{it:i}=r,{gen:s,compositeRule:o,allErrors:a}=i,c=ky(r,e,t);n??(o||a)?$y(s,c):Ey(i,(0,ie._)`[${c}]`)}ze.reportError=NE;function FE(r,e=ze.keywordError,t){let{it:n}=r,{gen:i,compositeRule:s,allErrors:o}=n,a=ky(r,e,t);$y(i,a),s||o||Ey(n,rt.default.vErrors)}ze.reportExtraError=FE;function jE(r,e){r.assign(rt.default.errors,e),r.if((0,ie._)`${rt.default.vErrors} !== null`,()=>r.if(e,()=>r.assign((0,ie._)`${rt.default.vErrors}.length`,e),()=>r.assign(rt.default.vErrors,null)))}ze.resetErrorsCount=jE;function qE({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,rt.default.errors,a=>{r.const(o,(0,ie._)`${rt.default.vErrors}[${a}]`),r.if((0,ie._)`${o}.instancePath === undefined`,()=>r.assign((0,ie._)`${o}.instancePath`,(0,ie.strConcat)(rt.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))})}ze.extendErrors=qE;function $y(r,e){let t=r.const("err",e);r.if((0,ie._)`${rt.default.vErrors} === null`,()=>r.assign(rt.default.vErrors,(0,ie._)`[${t}]`),(0,ie._)`${rt.default.vErrors}.push(${t})`),r.code((0,ie._)`${rt.default.errors}++`)}function Ey(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 Zn={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 ky(r,e,t){let{createErrors:n}=r.it;return n===!1?(0,ie._)`{}`:BE(r,e,t)}function BE(r,e,t={}){let{gen:n,it:i}=r,s=[UE(i,t),VE(r,t)];return HE(r,e,s),n.object(...s)}function UE({errorPath:r},{instancePath:e}){let t=e?(0,ie.str)`${r}${(0,Ba.getErrorPath)(e,Ba.Type.Str)}`:r;return[rt.default.instancePath,(0,ie.strConcat)(rt.default.instancePath,t)]}function VE({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,Ba.getErrorPath)(t,Ba.Type.Str)}`),[Zn.schemaPath,i]}function HE(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([Zn.keyword,i],[Zn.params,typeof e=="function"?e(r):e||(0,ie._)`{}`]),c.messages&&n.push([Zn.message,typeof t=="function"?t(r):t]),c.verbose&&n.push([Zn.schema,o],[Zn.parentSchema,(0,ie._)`${u}${d}`],[rt.default.data,s]),l&&n.push([Zn.propertyName,l])}});var Py=k(Ri=>{"use strict";Object.defineProperty(Ri,"__esModule",{value:!0});Ri.boolOrEmptySchema=Ri.topBoolOrEmptySchema=void 0;var zE=Ks(),KE=U(),WE=Ft(),GE={message:"boolean schema is false"};function JE(r){let{gen:e,schema:t,validateName:n}=r;t===!1?Ay(r,!1):typeof t=="object"&&t.$async===!0?e.return(WE.default.data):(e.assign((0,KE._)`${n}.errors`,null),e.return(!0))}Ri.topBoolOrEmptySchema=JE;function YE(r,e){let{gen:t,schema:n}=r;n===!1?(t.var(e,!1),Ay(r)):t.var(e,!0)}Ri.boolOrEmptySchema=YE;function Ay(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,zE.reportError)(i,GE,void 0,e)}});var au=k(Ti=>{"use strict";Object.defineProperty(Ti,"__esModule",{value:!0});Ti.getRules=Ti.isJSONType=void 0;var XE=["string","number","integer","boolean","null","object","array"],QE=new Set(XE);function ZE(r){return typeof r=="string"&&QE.has(r)}Ti.isJSONType=ZE;function ek(){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:{}}}Ti.getRules=ek});var cu=k(dn=>{"use strict";Object.defineProperty(dn,"__esModule",{value:!0});dn.shouldUseRule=dn.shouldUseGroup=dn.schemaHasRulesForType=void 0;function tk({schema:r,self:e},t){let n=e.RULES.types[t];return n&&n!==!0&&Cy(r,n)}dn.schemaHasRulesForType=tk;function Cy(r,e){return e.rules.some(t=>My(r,t))}dn.shouldUseGroup=Cy;function My(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))}dn.shouldUseRule=My});var Ws=k(Ke=>{"use strict";Object.defineProperty(Ke,"__esModule",{value:!0});Ke.reportTypeError=Ke.checkDataTypes=Ke.checkDataType=Ke.coerceAndCheckDataType=Ke.getJSONTypes=Ke.getSchemaTypes=Ke.DataType=void 0;var rk=au(),nk=cu(),ik=Ks(),z=U(),Ry=Q(),Ii;(function(r){r[r.Correct=0]="Correct",r[r.Wrong=1]="Wrong"})(Ii||(Ke.DataType=Ii={}));function sk(r){let e=Ty(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}Ke.getSchemaTypes=sk;function Ty(r){let e=Array.isArray(r)?r:r?[r]:[];if(e.every(rk.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}Ke.getJSONTypes=Ty;function ok(r,e){let{gen:t,data:n,opts:i}=r,s=ak(e,i.coerceTypes),o=e.length>0&&!(s.length===0&&e.length===1&&(0,nk.schemaHasRulesForType)(r,e[0]));if(o){let a=du(e,n,i.strictNumbers,Ii.Wrong);t.if(a,()=>{s.length?ck(r,e,s):uu(r)})}return o}Ke.coerceAndCheckDataType=ok;var Iy=new Set(["string","number","integer","boolean","null"]);function ak(r,e){return e?r.filter(t=>Iy.has(t)||e==="array"&&t==="array"):[]}function ck(r,e,t){let{gen:n,data:i,opts:s}=r,o=n.let("dataType",(0,z._)`typeof ${i}`),a=n.let("coerced",(0,z._)`undefined`);s.coerceTypes==="array"&&n.if((0,z._)`${o} == 'object' && Array.isArray(${i}) && ${i}.length == 1`,()=>n.assign(i,(0,z._)`${i}[0]`).assign(o,(0,z._)`typeof ${i}`).if(du(e,i,s.strictNumbers),()=>n.assign(a,i))),n.if((0,z._)`${a} !== undefined`);for(let l of t)(Iy.has(l)||l==="array"&&s.coerceTypes==="array")&&c(l);n.else(),uu(r),n.endIf(),n.if((0,z._)`${a} !== undefined`,()=>{n.assign(i,a),lk(r,a)});function c(l){switch(l){case"string":n.elseIf((0,z._)`${o} == "number" || ${o} == "boolean"`).assign(a,(0,z._)`"" + ${i}`).elseIf((0,z._)`${i} === null`).assign(a,(0,z._)`""`);return;case"number":n.elseIf((0,z._)`${o} == "boolean" || ${i} === null || (${o} == "string" && ${i} && ${i} == +${i})`).assign(a,(0,z._)`+${i}`);return;case"integer":n.elseIf((0,z._)`${o} === "boolean" || ${i} === null || (${o} === "string" && ${i} && ${i} == +${i} && !(${i} % 1))`).assign(a,(0,z._)`+${i}`);return;case"boolean":n.elseIf((0,z._)`${i} === "false" || ${i} === 0 || ${i} === null`).assign(a,!1).elseIf((0,z._)`${i} === "true" || ${i} === 1`).assign(a,!0);return;case"null":n.elseIf((0,z._)`${i} === "" || ${i} === 0 || ${i} === false`),n.assign(a,null);return;case"array":n.elseIf((0,z._)`${o} === "string" || ${o} === "number" - || ${o} === "boolean" || ${i} === null`).assign(a,(0,z._)`[${i}]`)}}}function lk({gen:r,parentData:e,parentDataProperty:t},n){r.if((0,z._)`${e} !== undefined`,()=>r.assign((0,z._)`${e}[${t}]`,n))}function lu(r,e,t,n=Ii.Correct){let i=n===Ii.Correct?z.operators.EQ:z.operators.NEQ,s;switch(r){case"null":return(0,z._)`${e} ${i} null`;case"array":s=(0,z._)`Array.isArray(${e})`;break;case"object":s=(0,z._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=o((0,z._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=o();break;default:return(0,z._)`typeof ${e} ${i} ${r}`}return n===Ii.Correct?s:(0,z.not)(s);function o(a=z.nil){return(0,z.and)((0,z._)`typeof ${e} == "number"`,a,t?(0,z._)`isFinite(${e})`:z.nil)}}Ke.checkDataType=lu;function du(r,e,t,n){if(r.length===1)return lu(r[0],e,t,n);let i,s=(0,Ry.toHash)(r);if(s.array&&s.object){let o=(0,z._)`typeof ${e} != "object"`;i=s.null?o:(0,z._)`!${e} || ${o}`,delete s.null,delete s.array,delete s.object}else i=z.nil;s.number&&delete s.integer;for(let o in s)i=(0,z.and)(i,lu(o,e,t,n));return i}Ke.checkDataTypes=du;var dk={message:({schema:r})=>`must be ${r}`,params:({schema:r,schemaValue:e})=>typeof r=="string"?(0,z._)`{type: ${r}}`:(0,z._)`{type: ${e}}`};function uu(r){let e=uk(r);(0,ik.reportError)(e,dk)}Ke.reportTypeError=uu;function uk(r){let{gen:e,data:t,schema:n}=r,i=(0,Ry.schemaRefOrVal)(r,n,"type");return{gen:e,keyword:"type",data:t,schema:n.type,schemaCode:i,schemaValue:i,parentSchema:n,params:{},it:r}}});var Dy=k(Ua=>{"use strict";Object.defineProperty(Ua,"__esModule",{value:!0});Ua.assignDefaults=void 0;var Oi=U(),fk=Q();function pk(r,e){let{properties:t,items:n}=r.schema;if(e==="object"&&t)for(let i in t)Oy(r,i,t[i].default);else e==="array"&&Array.isArray(n)&&n.forEach((i,s)=>Oy(r,s,i.default))}Ua.assignDefaults=pk;function Oy(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,fk.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 jt=k(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(),fu=Q(),un=Ft(),hk=Q();function mk(r,e){let{gen:t,data:n,it:i}=r;t.if(hu(t,n,e,i.opts.ownProperties),()=>{r.setParams({missingProperty:(0,me._)`${e}`},!0),r.error()})}le.checkReportMissingProp=mk;function yk({gen:r,data:e,it:{opts:t}},n,i){return(0,me.or)(...n.map(s=>(0,me.and)(hu(r,e,s,t.ownProperties),(0,me._)`${i} = ${s}`)))}le.checkMissingProp=yk;function gk(r,e){r.setParams({missingProperty:e},!0),r.error()}le.reportMissingProp=gk;function Ny(r){return r.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,me._)`Object.prototype.hasOwnProperty`})}le.hasPropFunc=Ny;function pu(r,e,t){return(0,me._)`${Ny(r)}.call(${e}, ${t})`}le.isOwnProperty=pu;function bk(r,e,t,n){let i=(0,me._)`${e}${(0,me.getProperty)(t)} !== undefined`;return n?(0,me._)`${i} && ${pu(r,e,t)}`:i}le.propertyInData=bk;function hu(r,e,t,n){let i=(0,me._)`${e}${(0,me.getProperty)(t)} === undefined`;return n?(0,me.or)(i,(0,me.not)(pu(r,e,t))):i}le.noPropertyInData=hu;function Ly(r){return r?Object.keys(r).filter(e=>e!=="__proto__"):[]}le.allSchemaProperties=Ly;function vk(r,e){return Ly(e).filter(t=>!(0,fu.alwaysValidSchema)(r,e[t]))}le.schemaProperties=vk;function wk({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=[[un.default.instancePath,(0,me.strConcat)(un.default.instancePath,s)],[un.default.parentData,o.parentData],[un.default.parentDataProperty,o.parentDataProperty],[un.default.rootData,un.default.rootData]];o.opts.dynamicRef&&d.push([un.default.dynamicAnchors,un.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=wk;var _k=(0,me._)`new RegExp`;function Sk({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"?_k:(0,hk.useFunc)(r,i)}(${t}, ${n})`})}le.usePattern=Sk;function xk(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:fu.Type.Num},s),e.if((0,me.not)(s),a)})}}le.validateArray=xk;function $k(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,fu.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=$k});var qy=k(vr=>{"use strict";Object.defineProperty(vr,"__esModule",{value:!0});vr.validateKeywordUsage=vr.validSchemaType=vr.funcKeywordCode=vr.macroKeywordCode=void 0;var nt=U(),ei=Ft(),Ek=jt(),kk=Ks();function Ak(r,e){let{gen:t,keyword:n,schema:i,parentSchema:s,it:o}=r,a=e.macro.call(o.self,i,s,o),c=jy(t,n,a);o.opts.validateSchema!==!1&&o.self.validateSchema(a,!0);let l=t.name("valid");r.subschema({schema:a,schemaPath:nt.nil,errSchemaPath:`${o.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},l),r.pass(l,()=>r.error(!0))}vr.macroKeywordCode=Ak;function Pk(r,e){var t;let{gen:n,keyword:i,schema:s,parentSchema:o,$data:a,it:c}=r;Mk(c,e);let l=!a&&e.compile?e.compile.call(c.self,s,o,c):e.validate,u=jy(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&&Fy(r),y(()=>r.error());else{let g=e.async?p():h();e.modifying&&Fy(r),y(()=>Ck(r,g))}}function p(){let g=n.let("ruleErrs",null);return n.try(()=>m((0,nt._)`await `),b=>n.assign(d,!1).if((0,nt._)`${b} instanceof ${c.ValidationError}`,()=>n.assign(g,(0,nt._)`${b}.errors`),()=>n.throw(b))),g}function h(){let g=(0,nt._)`${u}.errors`;return n.assign(g,null),m(nt.nil),g}function m(g=e.async?(0,nt._)`await `:nt.nil){let b=c.opts.passContext?ei.default.this:ei.default.self,v=!("compile"in e&&!a||e.schema===!1);n.assign(d,(0,nt._)`${g}${(0,Ek.callValidateCode)(r,u,b,v)}`,e.modifying)}function y(g){var b;n.if((0,nt.not)((b=e.valid)!==null&&b!==void 0?b:d),g)}}vr.funcKeywordCode=Pk;function Fy(r){let{gen:e,data:t,it:n}=r;e.if(n.parentData,()=>e.assign(t,(0,nt._)`${n.parentData}[${n.parentDataProperty}]`))}function Ck(r,e){let{gen:t}=r;t.if((0,nt._)`Array.isArray(${e})`,()=>{t.assign(ei.default.vErrors,(0,nt._)`${ei.default.vErrors} === null ? ${e} : ${ei.default.vErrors}.concat(${e})`).assign(ei.default.errors,(0,nt._)`${ei.default.vErrors}.length`),(0,kk.extendErrors)(r)},()=>r.error())}function Mk({schemaEnv:r},e){if(e.async&&!r.$async)throw new Error("async keyword in sync schema")}function jy(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,nt.stringify)(t)})}function Rk(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")}vr.validSchemaType=Rk;function Tk({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)}}vr.validateKeywordUsage=Tk});var Uy=k(fn=>{"use strict";Object.defineProperty(fn,"__esModule",{value:!0});fn.extendSubschemaMode=fn.extendSubschemaData=fn.getSubschema=void 0;var wr=U(),By=Q();function Ik(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,wr._)`${r.schemaPath}${(0,wr.getProperty)(e)}`,errSchemaPath:`${r.errSchemaPath}/${e}`}:{schema:a[t],schemaPath:(0,wr._)`${r.schemaPath}${(0,wr.getProperty)(e)}${(0,wr.getProperty)(t)}`,errSchemaPath:`${r.errSchemaPath}/${e}/${(0,By.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')}fn.getSubschema=Ik;function Ok(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,wr._)`${e.data}${(0,wr.getProperty)(t)}`,!0);c(f),r.errorPath=(0,wr.str)`${l}${(0,By.getErrorPath)(t,n,d.jsPropertySyntax)}`,r.parentDataProperty=(0,wr._)`${t}`,r.dataPathArr=[...u,r.parentDataProperty]}if(i!==void 0){let l=i instanceof wr.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]}}fn.extendSubschemaData=Ok;function Dk(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}fn.extendSubschemaMode=Dk});var mu=k((Oj,Vy)=>{"use strict";Vy.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 zy=k((Dj,Hy)=>{"use strict";var pn=Hy.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(){};Va(e,n,i,r,"",r)};pn.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};pn.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};pn.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};pn.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 Va(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 pn.arrayKeywords)for(var f=0;f{"use strict";Object.defineProperty(pt,"__esModule",{value:!0});pt.getSchemaRefs=pt.resolveUrl=pt.normalizeId=pt._getFullPath=pt.getFullPath=pt.inlineRef=void 0;var Lk=Q(),Fk=mu(),jk=zy(),qk=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function Bk(r,e=!0){return typeof r=="boolean"?!0:e===!0?!yu(r):e?Ky(r)<=e:!1}pt.inlineRef=Bk;var Uk=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function yu(r){for(let e in r){if(Uk.has(e))return!0;let t=r[e];if(Array.isArray(t)&&t.some(yu)||typeof t=="object"&&yu(t))return!0}return!1}function Ky(r){let e=0;for(let t in r){if(t==="$ref")return 1/0;if(e++,!qk.has(t)&&(typeof r[t]=="object"&&(0,Lk.eachItem)(r[t],n=>e+=Ky(n)),e===1/0))return 1/0}return e}function Wy(r,e="",t){t!==!1&&(e=Di(e));let n=r.parse(e);return Gy(r,n)}pt.getFullPath=Wy;function Gy(r,e){return r.serialize(e).split("#")[0]+"#"}pt._getFullPath=Gy;var Vk=/#\/?$/;function Di(r){return r?r.replace(Vk,""):""}pt.normalizeId=Di;function Hk(r,e,t){return t=Di(t),r.resolve(e,t)}pt.resolveUrl=Hk;var zk=/^[a-z_][-a-z0-9._]*$/i;function Kk(r,e){if(typeof r=="boolean")return{};let{schemaId:t,uriResolver:n}=this.opts,i=Di(r[t]||e),s={"":i},o=Wy(n,i,!1),a={},c=new Set;return jk(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(!zk.test(v))throw new Error(`invalid anchor "${v}"`);g.call(this,`#${v}`)}}}),a;function l(d,f,p){if(f!==void 0&&!Fk(d,f))throw u(p)}function u(d){return new Error(`reference "${d}" resolves to more than one schema`)}}pt.getSchemaRefs=Kk});var Ni=k(hn=>{"use strict";Object.defineProperty(hn,"__esModule",{value:!0});hn.getData=hn.KeywordCxt=hn.validateFunctionCode=void 0;var Zy=Py(),Jy=Ws(),bu=cu(),Ha=Ws(),Wk=Dy(),Ys=qy(),gu=Uy(),j=U(),B=Ft(),Gk=Gs(),Br=Q(),Js=Ks();function Jk(r){if(rg(r)&&(ng(r),tg(r))){Qk(r);return}eg(r,()=>(0,Zy.topBoolOrEmptySchema)(r))}hn.validateFunctionCode=Jk;function eg({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"; ${Yy(t,i)}`),Xk(r,i),r.code(s)}):r.func(e,(0,j._)`${B.default.data}, ${Yk(i)}`,n.$async,()=>r.code(Yy(t,i)).code(s))}function Yk(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 Xk(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 Qk(r){let{schema:e,opts:t,gen:n}=r;eg(r,()=>{t.$comment&&e.$comment&&sg(r),nA(r),n.let(B.default.vErrors,null),n.let(B.default.errors,0),t.unevaluated&&Zk(r),ig(r),oA(r)})}function Zk(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 Yy(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 eA(r,e){if(rg(r)&&(ng(r),tg(r))){tA(r,e);return}(0,Zy.boolOrEmptySchema)(r,e)}function tg({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 rg(r){return typeof r.schema!="boolean"}function tA(r,e){let{schema:t,gen:n,opts:i}=r;i.$comment&&t.$comment&&sg(r),iA(r),sA(r);let s=n.const("_errs",B.default.errors);ig(r,s),n.var(e,(0,j._)`${s} === ${B.default.errors}`)}function ng(r){(0,Br.checkUnknownRules)(r),rA(r)}function ig(r,e){if(r.opts.jtd)return Xy(r,[],!1,e);let t=(0,Jy.getSchemaTypes)(r.schema),n=(0,Jy.coerceAndCheckDataType)(r,t);Xy(r,t,!n,e)}function rA(r){let{schema:e,errSchemaPath:t,opts:n,self:i}=r;e.$ref&&n.ignoreKeywordsWithRef&&(0,Br.schemaHasRulesButRef)(e,i.RULES)&&i.logger.warn(`$ref: keywords ignored in schema at path "${t}"`)}function nA(r){let{schema:e,opts:t}=r;e.default!==void 0&&t.useDefaults&&t.strictSchema&&(0,Br.checkStrictMode)(r,"default is ignored in the schema root")}function iA(r){let e=r.schema[r.opts.schemaId];e&&(r.baseId=(0,Gk.resolveUrl)(r.opts.uriResolver,r.baseId,e))}function sA(r){if(r.schema.$async&&!r.schemaEnv.$async)throw new Error("async schema in sync schema")}function sg({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 oA(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&&aA(r),e.return((0,j._)`${B.default.errors} === 0`))}function aA({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 Xy(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,Br.schemaHasRulesButRef)(s,u))){i.block(()=>ag(r,"$ref",u.all.$ref.definition));return}c.jtd||cA(r,e),i.block(()=>{for(let f of u.rules)d(f);d(u.post)});function d(f){(0,bu.shouldUseGroup)(s,f)&&(f.type?(i.if((0,Ha.checkDataType)(f.type,o,c.strictNumbers)),Qy(r,f),e.length===1&&e[0]===f.type&&t&&(i.else(),(0,Ha.reportTypeError)(r)),i.endIf()):Qy(r,f),a||i.if((0,j._)`${B.default.errors} === ${n||0}`))}}function Qy(r,e){let{gen:t,schema:n,opts:{useDefaults:i}}=r;i&&(0,Wk.assignDefaults)(r,e.type),t.block(()=>{for(let s of e.rules)(0,bu.shouldUseRule)(n,s)&&ag(r,s.keyword,s.definition,e.type)})}function cA(r,e){r.schemaEnv.meta||!r.opts.strictTypes||(lA(r,e),r.opts.allowUnionTypes||dA(r,e),uA(r,r.dataTypes))}function lA(r,e){if(e.length){if(!r.dataTypes.length){r.dataTypes=e;return}e.forEach(t=>{og(r.dataTypes,t)||vu(r,`type "${t}" not allowed by context "${r.dataTypes.join(",")}"`)}),pA(r,e)}}function dA(r,e){e.length>1&&!(e.length===2&&e.includes("null"))&&vu(r,"use allowUnionTypes to allow union type keyword")}function uA(r,e){let t=r.self.RULES.all;for(let n in t){let i=t[n];if(typeof i=="object"&&(0,bu.shouldUseRule)(r.schema,i)){let{type:s}=i.definition;s.length&&!s.some(o=>fA(e,o))&&vu(r,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function fA(r,e){return r.includes(e)||e==="number"&&r.includes("integer")}function og(r,e){return r.includes(e)||e==="integer"&&r.includes("number")}function pA(r,e){let t=[];for(let n of r.dataTypes)og(e,n)?t.push(n):e.includes("integer")&&n==="number"&&t.push("integer");r.dataTypes=t}function vu(r,e){let t=r.schemaEnv.baseId+r.errSchemaPath;e+=` at "${t}" (strictTypes)`,(0,Br.checkStrictMode)(r,e,r.opts.strictTypes)}var za=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,Br.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",cg(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,Ha.checkDataTypes)(c,t,s.opts.strictNumbers,Ha.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,gu.getSubschema)(this.it,e);(0,gu.extendSubschemaData)(n,this.it,e),(0,gu.extendSubschemaMode)(n,e);let i={...this.it,...n,items:void 0,props:void 0};return eA(i,t),i}mergeEvaluated(e,t){let{it:n,gen:i}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=Br.mergeEvaluated.props(i,e.props,n.props,t)),n.items!==!0&&e.items!==void 0&&(n.items=Br.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}};hn.KeywordCxt=za;function ag(r,e,t,n){let i=new za(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 hA=/^\/(?:[^~]|~0|~1)*$/,mA=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function cg(r,{dataLevel:e,dataNames:t,dataPathArr:n}){let i,s;if(r==="")return B.default.rootData;if(r[0]==="/"){if(!hA.test(r))throw new Error(`Invalid JSON-pointer: ${r}`);i=r,s=B.default.rootData}else{let l=mA.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,Br.unescapeJsonPointer)(l))}`,o=(0,j._)`${o} && ${s}`);return o;function c(l,u){return`Cannot access ${l} ${u} levels up, current level is ${e}`}}hn.getData=cg});var Xs=k(_u=>{"use strict";Object.defineProperty(_u,"__esModule",{value:!0});var wu=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};_u.default=wu});var Li=k($u=>{"use strict";Object.defineProperty($u,"__esModule",{value:!0});var Su=Gs(),xu=class extends Error{constructor(e,t,n,i){super(i||`can't resolve reference ${n} from id ${t}`),this.missingRef=(0,Su.resolveUrl)(e,t,n),this.missingSchema=(0,Su.normalizeId)((0,Su.getFullPath)(e,this.missingRef))}};$u.default=xu});var Qs=k(qt=>{"use strict";Object.defineProperty(qt,"__esModule",{value:!0});qt.resolveSchema=qt.getCompilingSchema=qt.resolveRef=qt.compileSchema=qt.SchemaEnv=void 0;var Qt=U(),yA=Xs(),ti=Ft(),Zt=Gs(),lg=Q(),gA=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,Zt.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};qt.SchemaEnv=Fi;function ku(r){let e=dg.call(this,r);if(e)return e;let t=(0,Zt.getFullPath)(this.opts.uriResolver,r.root.baseId),{es5:n,lines:i}=this.opts.code,{ownProperties:s}=this.opts,o=new Qt.CodeGen(this.scope,{es5:n,lines:i,ownProperties:s}),a;r.$async&&(a=o.scopeValue("Error",{ref:yA.default,code:(0,Qt._)`require("ajv/dist/runtime/validation_error").default`}));let c=o.scopeName("validate");r.validateName=c;let l={gen:o,allErrors:this.opts.allErrors,data:ti.default.data,parentData:ti.default.parentData,parentDataProperty:ti.default.parentDataProperty,dataNames:[ti.default.data],dataPathArr:[Qt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:o.scopeValue("schema",this.opts.code.source===!0?{ref:r.schema,code:(0,Qt.stringify)(r.schema)}:{ref:r.schema}),validateName:c,ValidationError:a,schema:r.schema,schemaEnv:r,rootId:t,baseId:r.baseId||t,schemaPath:Qt.nil,errSchemaPath:r.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Qt._)`""`,opts:this.opts,self:this},u;try{this._compilations.add(r),(0,gA.validateFunctionCode)(l),o.optimize(this.opts.code.optimize);let d=o.toString();u=`${o.scopeRefs(ti.default.scope)}return ${d}`,this.opts.code.process&&(u=this.opts.code.process(u,r));let p=new Function(`${ti.default.self}`,`${ti.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 Qt.Name?void 0:h,items:m instanceof Qt.Name?void 0:m,dynamicProps:h instanceof Qt.Name,dynamicItems:m instanceof Qt.Name},p.source&&(p.source.evaluated=(0,Qt.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)}}qt.compileSchema=ku;function bA(r,e,t){var n;t=(0,Zt.resolveUrl)(this.opts.uriResolver,e,t);let i=r.refs[t];if(i)return i;let s=_A.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]=vA.call(this,s)}qt.resolveRef=bA;function vA(r){return(0,Zt.inlineRef)(r.schema,this.opts.inlineRefs)?r.schema:r.validate?r:ku.call(this,r)}function dg(r){for(let e of this._compilations)if(wA(e,r))return e}qt.getCompilingSchema=dg;function wA(r,e){return r.schema===e.schema&&r.root===e.root&&r.baseId===e.baseId}function _A(r,e){let t;for(;typeof(t=this.refs[e])=="string";)e=t;return t||this.schemas[e]||Ka.call(this,r,e)}function Ka(r,e){let t=this.opts.uriResolver.parse(e),n=(0,Zt._getFullPath)(this.opts.uriResolver,t),i=(0,Zt.getFullPath)(this.opts.uriResolver,r.baseId,void 0);if(Object.keys(r.schema).length>0&&n===i)return Eu.call(this,t,r);let s=(0,Zt.normalizeId)(n),o=this.refs[s]||this.schemas[s];if(typeof o=="string"){let a=Ka.call(this,r,o);return typeof a?.schema!="object"?void 0:Eu.call(this,t,a)}if(typeof o?.schema=="object"){if(o.validate||ku.call(this,o),s===(0,Zt.normalizeId)(e)){let{schema:a}=o,{schemaId:c}=this.opts,l=a[c];return l&&(i=(0,Zt.resolveUrl)(this.opts.uriResolver,i,l)),new Fi({schema:a,schemaId:c,root:r,baseId:i})}return Eu.call(this,t,o)}}qt.resolveSchema=Ka;var SA=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Eu(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,lg.unescapeFragment)(a)];if(c===void 0)return;t=c;let l=typeof t=="object"&&t[this.opts.schemaId];!SA.has(a)&&l&&(e=(0,Zt.resolveUrl)(this.opts.uriResolver,e,l))}let s;if(typeof t!="boolean"&&t.$ref&&!(0,lg.schemaHasRulesButRef)(t,this.RULES)){let a=(0,Zt.resolveUrl)(this.opts.uriResolver,e,t.$ref);s=Ka.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 ug=k((Bj,xA)=>{xA.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 Tu=k((Uj,bg)=>{"use strict";var $A=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Pu=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),EA=RegExp.prototype.test.bind(/^\d*$/u),ri=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),Cu=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),pg=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u),Mu=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u),kA=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u),ht=new Array(256);{let r="0123456789ABCDEF";for(let e=0;e<256;e++)ht[e]="%"+r[e>>4]+r[e&15]}function We(r){return r<2048?ht[192|r>>6]+ht[128|r&63]:r<65536?ht[224|r>>12]+ht[128|r>>6&63]+ht[128|r&63]:ht[240|r>>18]+ht[128|r>>12&63]+ht[128|r>>6&63]+ht[128|r&63]}function AA(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 PA=RegExp.prototype.test.bind(/^[\dA-Fa-f]{1,4}$/),CA=RegExp.prototype.test.bind(/^[vV][\dA-Fa-f]+\.[A-Za-z\d\-._~!$&'()*+,;=:]+$/),MA=RegExp.prototype.test.bind(/^[A-Za-z\d\-._~]$/),RA=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function TA(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 IA(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;aNA[n])}function mg(r,e=!1){if(r.indexOf("%")===-1)return r;let t="";for(let n=0;n57343)e+=We(i);else if(i<=56319&&t+1=56320&&s<=57343?(e+=We(65536+(i-55296<<10)+(s-56320)),t++):e+=We(65533)}else e+=We(65533)}}return e}function qA(r,e=!1){let t="",n=e&&r[0]!=="/";for(let i=0;i57343)t+=We(o);else if(o<=56319&&i+1=56320&&a<=57343?(t+=We(65536+(o-55296<<10)+(a-56320)),i++):t+=We(65533)}else t+=We(65533)}}return t}function Ru(r,e){let t="";for(let n=0;n57343)t+=We(s);else if(s<=56319&&n+1=56320&&o<=57343?(t+=We(65536+(s-55296<<10)+(o-56320)),n++):t+=We(65533)}else t+=We(65533)}}return t}function yg(r){return Ru(r,kA)}function BA(r){return Ru(r,Mu)}function UA(r){return Ru(r,Mu)}function gg(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 VA(r){let e="";for(let t=0;t57343)e+=We(i);else if(i<=56319&&t+1=56320&&s<=57343?(e+=We(65536+(i-55296<<10)+(s-56320)),t++):e+=We(65533)}else e+=We(65533)}}return e}function HA(r){let e="";for(let t=0;t{"use strict";var{isUUID:KA}=Tu(),WA=/^([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-./:;=@]|%[\da-f]{2})+)$/iu,GA=["http","https","ws","wss","urn","urn:uuid"];function JA(r){return GA.indexOf(r)!==-1}function Iu(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 vg(r){return r.host||(r.error=r.error||"HTTP URIs must have a host."),r}function wg(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 YA(r){return r.secure=Iu(r),r.resourceName=(r.path||"/")+(r.query?"?"+r.query:""),r.path=void 0,r.query=void 0,r}function XA(r){if((r.port===(Iu(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 QA(r,e){if(!r.path)return r.error="URN can not be parsed",r;let t=r.path.match(WA);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=Ou(i);r.path=void 0,s&&(r=s.parse(r,e))}else r.error=r.error||"URN can not be parsed.";return r}function ZA(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=Ou(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 eP(r,e){let t=r;return t.uuid=t.nss,t.nss=void 0,!e.tolerant&&(!t.uuid||!KA(t.uuid))&&(t.error=t.error||"UUID is not valid."),t}function tP(r){let e=r;return e.nss=(r.uuid||"").toLowerCase(),e}var _g={scheme:"http",domainHost:!0,parse:vg,serialize:wg},rP={scheme:"https",domainHost:_g.domainHost,parse:vg,serialize:wg},Wa={scheme:"ws",domainHost:!0,parse:YA,serialize:XA},nP={scheme:"wss",domainHost:Wa.domainHost,parse:Wa.parse,serialize:Wa.serialize},iP={scheme:"urn",parse:QA,serialize:ZA,skipNormalize:!0},sP={scheme:"urn:uuid",parse:eP,serialize:tP,skipNormalize:!0},Ga={http:_g,https:rP,ws:Wa,wss:nP,urn:iP,"urn:uuid":sP};Object.setPrototypeOf(Ga,null);function Ou(r){return r&&(Ga[r]||Ga[r.toLowerCase()])||void 0}Sg.exports={wsIsSecure:Iu,SCHEMES:Ga,isValidSchemeName:JA,getSchemeHandler:Ou}});var Lg=k((Hj,Xa)=>{"use strict";var{normalizeIPv6:Pg,removeDotSegments:eo,recomposeAuthority:oP,normalizePercentEncoding:Cg,normalizePathEncoding:aP,serializePathEncoding:$g,normalizeQueryFragmentEncoding:Eg,encodeQuery:cP,encodeFragment:lP,reescapeHostDelimiters:dP,isIPv4:Mg,nonSimpleDomain:uP}=Tu(),{SCHEMES:Rg,getSchemeHandler:Du}=xg(),Tg=/^[A-Za-z][A-Za-z0-9+.-]*$/u,Ig="URI scheme is malformed.";function kg(r){let e=unescape(String(r));if(!Tg.test(e))throw new TypeError(Ig);return e}function fP(r,e){return typeof r=="string"?r=wP(r,e):typeof r=="object"&&(r=Ya(ni(r,e),e)),r}function pP(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}=Ja(r,n),{parsed:u,malformedAuthorityOrPort:d,malformedPercentEncoding:f,malformedSchemeSpecific:p,malformedHost:h,malformedScheme:m}=Ja(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=Og(i,u,n,!0),g=Du(t&&t.scheme||y.scheme),b=y.host,v=b!==void 0&&b!==""&&(Mg(b)||Pg(b).isIPV6);Dg(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,ni(y,n)}function Og(r,e,t,n){let i={};return n||(r=Ya(ni(r,t),t),e=Ya(ni(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 hP(r,e,t){let n=Ag(r,t),i=Ag(e,t);return n!==void 0&&i!==void 0&&n===i}function ni(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=kg(t.scheme));let s=Du(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=Cg(t.path):t.path=$g(t.path,a)),n.reference!=="suffix"&&t.scheme&&(t.scheme=kg(t.scheme),i.push(t.scheme,":"));let c=oP(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=$g(l,!0)),c===void 0&&l[0]==="/"&&l[1]==="/"&&(l="/%2F"+l.slice(2)),i.push(l)}return t.query!==void 0&&i.push("?",cP(t.query)),t.fragment!==void 0&&i.push("#",lP(t.fragment)),i.join("")}var mP=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,yP=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,gP=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function bP(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 Nu(r){return r[0]==="["&&r[r.length-1]==="]"}function vP(r){let e=r[4];return Zs(r[3])||e!==void 0&&!Nu(e)&&Zs(e)||Zs(r[6])||Zs(r[7])||Zs(r[8])}function Dg(r,e,t,n){if(!e.unicodeSupport&&(!t||!t.unicodeSupport)&&r.host&&!Nu(r.host)&&(e.domainHost||t&&t.domainHost)&&n===!1&&uP(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 Ja(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(yP);d!==null&&d[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",i=!0);let f=r.match(gP);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(mP);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);Tg.test(y)?n.scheme=y.toLowerCase():(n.error=n.error||Ig,l=!0)}s=vP(p),s&&(n.error=n.error||"URI contains malformed percent-encoding."),isNaN(n.port)&&(n.port=p[5]);let h=bP(n,p);if(h!==void 0&&(n.error=n.error||h,i=!0),n.host)if(Mg(n.host)===!1){let g=Nu(n.host),b=n.host.indexOf("[")!==-1||n.host.indexOf("]")!==-1,v=Pg(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=Du(t.scheme||n.scheme);if(c||(a=Dg(n,t,m,u)),!m||m&&!m.skipNormalize){if(r.indexOf("%")!==-1&&n.host!==void 0&&!c){let y=u?n.host:Cg(n.host,!0);n.host=dP(y,u)}n.path&&(n.path=aP(n.path)),n.query&&(n.query=Eg(n.query)),n.fragment&&(n.fragment=Eg(n.fragment))}m&&m.parse&&(m.parse(n,t),m===Rg.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 Ya(r,e){return Ja(r,e).parsed}function wP(r,e){return Ng(r,e).normalized}function Ng(r,e){let{parsed:t,malformedAuthorityOrPort:n,malformedPercentEncoding:i,malformedSchemeSpecific:s,malformedHost:o,malformedScheme:a}=Ja(r,e);return{normalized:n||i||s||o||a?r:ni(t,e),malformedAuthorityOrPort:n,malformedPercentEncoding:i,malformedSchemeSpecific:s,malformedHost:o,malformedScheme:a}}function Ag(r,e){if(typeof r!="string"&&typeof r!="object")return;let t;try{t=typeof r=="string"?r:ni(r,e)}catch{return}let{normalized:n,malformedAuthorityOrPort:i,malformedPercentEncoding:s,malformedSchemeSpecific:o,malformedHost:a,malformedScheme:c}=Ng(t,e);return i||s||o||a||c?void 0:n}var Lu={SCHEMES:Rg,normalize:fP,resolve:pP,resolveComponent:Og,equal:hP,serialize:ni,parse:Ya};Xa.exports=Lu;Xa.exports.default=Lu;Xa.exports.fastUri=Lu});var jg=k(Fu=>{"use strict";Object.defineProperty(Fu,"__esModule",{value:!0});var Fg=Lg();Fg.code='require("ajv/dist/runtime/uri").default';Fu.default=Fg});var Bu=k(Fe=>{"use strict";Object.defineProperty(Fe,"__esModule",{value:!0});Fe.CodeGen=Fe.Name=Fe.nil=Fe.stringify=Fe.str=Fe._=Fe.KeywordCxt=void 0;var _P=Ni();Object.defineProperty(Fe,"KeywordCxt",{enumerable:!0,get:function(){return _P.KeywordCxt}});var ji=U();Object.defineProperty(Fe,"_",{enumerable:!0,get:function(){return ji._}});Object.defineProperty(Fe,"str",{enumerable:!0,get:function(){return ji.str}});Object.defineProperty(Fe,"stringify",{enumerable:!0,get:function(){return ji.stringify}});Object.defineProperty(Fe,"nil",{enumerable:!0,get:function(){return ji.nil}});Object.defineProperty(Fe,"Name",{enumerable:!0,get:function(){return ji.Name}});Object.defineProperty(Fe,"CodeGen",{enumerable:!0,get:function(){return ji.CodeGen}});var SP=Xs(),Hg=Li(),xP=au(),to=Qs(),$P=U(),ro=Gs(),Qa=Ws(),qu=Q(),qg=ug(),EP=jg(),zg=(r,e)=>new RegExp(r,e);zg.code="new RegExp";var kP=["removeAdditional","useDefaults","coerceTypes"],AP=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),PP={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."},CP={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Bg=200;function MP(r){var e,t,n,i,s,o,a,c,l,u,d,f,p,h,m,y,g,b,v,S,_,E,A,x,R;let $=r.strict,q=(e=r.code)===null||e===void 0?void 0:e.optimize,M=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:zg,P=(i=r.uriResolver)!==null&&i!==void 0?i:EP.default;return{strictSchema:(o=(s=r.strictSchema)!==null&&s!==void 0?s:$)!==null&&o!==void 0?o:!0,strictNumbers:(c=(a=r.strictNumbers)!==null&&a!==void 0?a:$)!==null&&c!==void 0?c:!0,strictTypes:(u=(l=r.strictTypes)!==null&&l!==void 0?l:$)!==null&&u!==void 0?u:"log",strictTuples:(f=(d=r.strictTuples)!==null&&d!==void 0?d:$)!==null&&f!==void 0?f:"log",strictRequired:(h=(p=r.strictRequired)!==null&&p!==void 0?p:$)!==null&&h!==void 0?h:!1,code:r.code?{...r.code,optimize:M,regExp:V}:{optimize:M,regExp:V},loopRequired:(m=r.loopRequired)!==null&&m!==void 0?m:Bg,loopEnum:(y=r.loopEnum)!==null&&y!==void 0?y:Bg,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:(A=r.validateFormats)!==null&&A!==void 0?A:!0,unicodeRegExp:(x=r.unicodeRegExp)!==null&&x!==void 0?x:!0,int32range:(R=r.int32range)!==null&&R!==void 0?R:!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,...MP(e)};let{es5:t,lines:n}=this.opts.code;this.scope=new $P.ValueScope({scope:{},prefixes:AP,es5:t,lines:n}),this.logger=NP(e.logger);let i=e.validateFormats;e.validateFormats=!1,this.RULES=(0,xP.getRules)(),Ug.call(this,PP,e,"NOT SUPPORTED"),Ug.call(this,CP,e,"DEPRECATED","warn"),this._metaOpts=OP.call(this),e.formats&&TP.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&IP.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),RP.call(this),e.validateFormats=i}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:t,schemaId:n}=this.opts,i=qg;n==="id"&&(i={...qg},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 Hg.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=Vg.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=Vg.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(FP.call(this,n,t),!t)return(0,qu.eachItem)(n,s=>ju.call(this,s)),this;qP.call(this,t);let i={...t,type:(0,Qa.getJSONTypes)(t.type),schemaType:(0,Qa.getJSONTypes)(t.schemaType)};return(0,qu.eachItem)(n,i.type.length===0?s=>ju.call(this,s,i):s=>i.type.forEach(o=>ju.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]=Kg(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=SP.default;no.MissingRefError=Hg.default;Fe.default=no;function Ug(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 Vg(r){return r=(0,ro.normalizeId)(r),this.schemas[r]||this.refs[r]}function RP(){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 IP(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 OP(){let r={...this.opts};for(let e of kP)delete r[e];return r}var DP={log(){},warn(){},error(){}};function NP(r){if(r===!1)return DP;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 LP=/^[a-z_$][a-z0-9_$:-]*$/i;function FP(r,e){let{RULES:t}=this;if((0,qu.eachItem)(r,n=>{if(t.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!LP.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 ju(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,Qa.getJSONTypes)(e.type),schemaType:(0,Qa.getJSONTypes)(e.schemaType)}};e.before?jP.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 jP(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 qP(r){let{metaSchema:e}=r;e!==void 0&&(r.$data&&this.opts.$data&&(e=Kg(e)),r.validateSchema=this.compile(e,!0))}var BP={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Kg(r){return{anyOf:[r,BP]}}});var Wg=k(Uu=>{"use strict";Object.defineProperty(Uu,"__esModule",{value:!0});var UP={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Uu.default=UP});var tc=k(ii=>{"use strict";Object.defineProperty(ii,"__esModule",{value:!0});ii.callRef=ii.getValidate=void 0;var VP=Li(),Gg=jt(),mt=U(),qi=Ft(),Jg=Qs(),Za=Q(),HP={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=Jg.resolveRef.call(c,l,i,t);if(u===void 0)throw new VP.default(n.opts.uriResolver,i,t);if(u instanceof Jg.SchemaEnv)return f(u);return p(u);function d(){if(s===l)return ec(r,o,s,s.$async);let h=e.scopeValue("root",{ref:l});return ec(r,(0,mt._)`${h}.validate`,l,l.$async)}function f(h){let m=Yg(r,h);ec(r,m,h,h.$async)}function p(h){let m=e.scopeValue("schema",a.code.source===!0?{ref:h,code:(0,mt.stringify)(h)}:{ref:h}),y=e.name("valid"),g=r.subschema({schema:h,dataTypes:[],schemaPath:mt.nil,topSchemaRef:m,errSchemaPath:t},y);r.mergeEvaluated(g),r.ok(y)}}};function Yg(r,e){let{gen:t}=r;return e.validate?t.scopeValue("validate",{ref:e.validate}):(0,mt._)`${t.scopeValue("wrapper",{ref:e})}.validate`}ii.getValidate=Yg;function ec(r,e,t,n){let{gen:i,it:s}=r,{allErrors:o,schemaEnv:a,opts:c}=s,l=c.passContext?qi.default.this:mt.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,mt._)`await ${(0,Gg.callValidateCode)(r,e,l)}`),p(e),o||i.assign(h,!0)},m=>{i.if((0,mt._)`!(${m} instanceof ${s.ValidationError})`,()=>i.throw(m)),f(m),o||i.assign(h,!1)}),r.ok(h)}function d(){r.result((0,Gg.callValidateCode)(r,e,l),()=>p(e),()=>f(e))}function f(h){let m=(0,mt._)`${h}.errors`;i.assign(qi.default.vErrors,(0,mt._)`${qi.default.vErrors} === null ? ${m} : ${qi.default.vErrors}.concat(${m})`),i.assign(qi.default.errors,(0,mt._)`${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=Za.mergeEvaluated.props(i,y.props,s.props));else{let g=i.var("props",(0,mt._)`${h}.evaluated.props`);s.props=Za.mergeEvaluated.props(i,g,s.props,mt.Name)}if(s.items!==!0)if(y&&!y.dynamicItems)y.items!==void 0&&(s.items=Za.mergeEvaluated.items(i,y.items,s.items));else{let g=i.var("items",(0,mt._)`${h}.evaluated.items`);s.items=Za.mergeEvaluated.items(i,g,s.items,mt.Name)}}}ii.callRef=ec;ii.default=HP});var Hu=k(Vu=>{"use strict";Object.defineProperty(Vu,"__esModule",{value:!0});var zP=Wg(),KP=tc(),WP=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",zP.default,KP.default];Vu.default=WP});var Xg=k(zu=>{"use strict";Object.defineProperty(zu,"__esModule",{value:!0});var rc=U(),mn=rc.operators,nc={maximum:{okStr:"<=",ok:mn.LTE,fail:mn.GT},minimum:{okStr:">=",ok:mn.GTE,fail:mn.LT},exclusiveMaximum:{okStr:"<",ok:mn.LT,fail:mn.GTE},exclusiveMinimum:{okStr:">",ok:mn.GT,fail:mn.LTE}},GP={message:({keyword:r,schemaCode:e})=>(0,rc.str)`must be ${nc[r].okStr} ${e}`,params:({keyword:r,schemaCode:e})=>(0,rc._)`{comparison: ${nc[r].okStr}, limit: ${e}}`},JP={keyword:Object.keys(nc),type:"number",schemaType:"number",$data:!0,error:GP,code(r){let{keyword:e,data:t,schemaCode:n}=r;r.fail$data((0,rc._)`${t} ${nc[e].fail} ${n} || isNaN(${t})`)}};zu.default=JP});var Qg=k(Ku=>{"use strict";Object.defineProperty(Ku,"__esModule",{value:!0});var io=U(),YP={message:({schemaCode:r})=>(0,io.str)`must be multiple of ${r}`,params:({schemaCode:r})=>(0,io._)`{multipleOf: ${r}}`},XP={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:YP,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}))`)}};Ku.default=XP});var eb=k(Wu=>{"use strict";Object.defineProperty(Wu,"__esModule",{value:!0});function Zg(r){let e=r.length,t=0,n=0,i;for(;n=55296&&i<=56319&&n{"use strict";Object.defineProperty(Gu,"__esModule",{value:!0});var si=U(),QP=Q(),ZP=eb(),eC={message({keyword:r,schemaCode:e}){let t=r==="maxLength"?"more":"fewer";return(0,si.str)`must NOT have ${t} than ${e} characters`},params:({schemaCode:r})=>(0,si._)`{limit: ${r}}`},tC={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:eC,code(r){let{keyword:e,data:t,schemaCode:n,it:i}=r,s=e==="maxLength"?si.operators.GT:si.operators.LT,o=i.opts.unicode===!1?(0,si._)`${t}.length`:(0,si._)`${(0,QP.useFunc)(r.gen,ZP.default)}(${t})`;r.fail$data((0,si._)`${o} ${s} ${n}`)}};Gu.default=tC});var rb=k(Ju=>{"use strict";Object.defineProperty(Ju,"__esModule",{value:!0});var rC=jt(),nC=Q(),Bi=U(),iC={message:({schemaCode:r})=>(0,Bi.str)`must match pattern "${r}"`,params:({schemaCode:r})=>(0,Bi._)`{pattern: ${r}}`},sC={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:iC,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,nC.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,rC.usePattern)(r,i);r.fail$data((0,Bi._)`!${c}.test(${t})`)}}};Ju.default=sC});var nb=k(Yu=>{"use strict";Object.defineProperty(Yu,"__esModule",{value:!0});var so=U(),oC={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}}`},aC={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:oC,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}`)}};Yu.default=aC});var ib=k(Xu=>{"use strict";Object.defineProperty(Xu,"__esModule",{value:!0});var oo=jt(),ao=U(),cC=Q(),lC={message:({params:{missingProperty:r}})=>(0,ao.str)`must have required property '${r}'`,params:({params:{missingProperty:r}})=>(0,ao._)`{missingProperty: ${r}}`},dC={keyword:"required",type:"object",schemaType:"array",$data:!0,error:lC,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,cC.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)}}};Xu.default=dC});var sb=k(Qu=>{"use strict";Object.defineProperty(Qu,"__esModule",{value:!0});var co=U(),uC={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}}`},fC={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:uC,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}`)}};Qu.default=fC});var ic=k(Zu=>{"use strict";Object.defineProperty(Zu,"__esModule",{value:!0});var ob=mu();ob.code='require("ajv/dist/runtime/equal").default';Zu.default=ob});var ab=k(tf=>{"use strict";Object.defineProperty(tf,"__esModule",{value:!0});var ef=Ws(),je=U(),pC=Q(),hC=ic(),mC={message:({params:{i:r,j:e}})=>(0,je.str)`must NOT have duplicate items (items ## ${e} and ${r} are identical)`,params:({params:{i:r,j:e}})=>(0,je._)`{i: ${r}, j: ${e}}`},yC={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:mC,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,ef.getSchemaTypes)(s.items):[];r.block$data(c,u,(0,je._)`${o} === false`),r.ok(c);function u(){let h=e.let("i",(0,je._)`${t}.length`),m=e.let("j");r.setParams({i:h,j:m}),e.assign(c,!0),e.if((0,je._)`${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,ef.checkDataTypes)(l,y,a.opts.strictNumbers,ef.DataType.Wrong),b=e.const("indices",(0,je._)`{}`);e.for((0,je._)`;${h}--;`,()=>{e.let(y,(0,je._)`${t}[${h}]`),e.if(g,(0,je._)`continue`),l.length>1&&e.if((0,je._)`typeof ${y} == "string"`,(0,je._)`${y} += "_"`),e.if((0,je._)`typeof ${b}[${y}] == "number"`,()=>{e.assign(m,(0,je._)`${b}[${y}]`),r.error(),e.assign(c,!1).break()}).code((0,je._)`${b}[${y}] = ${h}`)})}function p(h,m){let y=(0,pC.useFunc)(e,hC.default),g=e.name("outer");e.label(g).for((0,je._)`;${h}--;`,()=>e.for((0,je._)`${m} = ${h}; ${m}--;`,()=>e.if((0,je._)`${y}(${t}[${h}], ${t}[${m}])`,()=>{r.error(),e.assign(c,!1).break(g)})))}}};tf.default=yC});var cb=k(nf=>{"use strict";Object.defineProperty(nf,"__esModule",{value:!0});var rf=U(),gC=Q(),bC=ic(),vC={message:"must be equal to constant",params:({schemaCode:r})=>(0,rf._)`{allowedValue: ${r}}`},wC={keyword:"const",$data:!0,error:vC,code(r){let{gen:e,data:t,$data:n,schemaCode:i,schema:s}=r;n||s&&typeof s=="object"?r.fail$data((0,rf._)`!${(0,gC.useFunc)(e,bC.default)}(${t}, ${i})`):r.fail((0,rf._)`${s} !== ${t}`)}};nf.default=wC});var lb=k(sf=>{"use strict";Object.defineProperty(sf,"__esModule",{value:!0});var lo=U(),_C=Q(),SC=ic(),xC={message:"must be equal to one of the allowed values",params:({schemaCode:r})=>(0,lo._)`{allowedValues: ${r}}`},$C={keyword:"enum",schemaType:"array",$data:!0,error:xC,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,_C.useFunc)(e,SC.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}`}}};sf.default=$C});var af=k(of=>{"use strict";Object.defineProperty(of,"__esModule",{value:!0});var EC=Xg(),kC=Qg(),AC=tb(),PC=rb(),CC=nb(),MC=ib(),RC=sb(),TC=ab(),IC=cb(),OC=lb(),DC=[EC.default,kC.default,AC.default,PC.default,CC.default,MC.default,RC.default,TC.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},IC.default,OC.default];of.default=DC});var lf=k(uo=>{"use strict";Object.defineProperty(uo,"__esModule",{value:!0});uo.validateAdditionalItems=void 0;var oi=U(),cf=Q(),NC={message:({params:{len:r}})=>(0,oi.str)`must NOT have more than ${r} items`,params:({params:{len:r}})=>(0,oi._)`{limit: ${r}}`},LC={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:NC,code(r){let{parentSchema:e,it:t}=r,{items:n}=e;if(!Array.isArray(n)){(0,cf.checkStrictMode)(t,'"additionalItems" is ignored when "items" is not an array of schemas');return}db(r,n)}};function db(r,e){let{gen:t,schema:n,data:i,keyword:s,it:o}=r;o.items=!0;let a=t.const("len",(0,oi._)`${i}.length`);if(n===!1)r.setParams({len:e.length}),r.pass((0,oi._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,cf.alwaysValidSchema)(o,n)){let l=t.var("valid",(0,oi._)`${a} <= ${e.length}`);t.if((0,oi.not)(l),()=>c(l)),r.ok(l)}function c(l){t.forRange("i",e.length,a,u=>{r.subschema({keyword:s,dataProp:u,dataPropType:cf.Type.Num},l),o.allErrors||t.if((0,oi.not)(l),()=>t.break())})}}uo.validateAdditionalItems=db;uo.default=LC});var df=k(fo=>{"use strict";Object.defineProperty(fo,"__esModule",{value:!0});fo.validateTuple=void 0;var ub=U(),sc=Q(),FC=jt(),jC={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(r){let{schema:e,it:t}=r;if(Array.isArray(e))return fb(r,"additionalItems",e);t.items=!0,!(0,sc.alwaysValidSchema)(t,e)&&r.ok((0,FC.validateArray)(r))}};function fb(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=sc.mergeEvaluated.items(n,t.length,a.items));let c=n.name("valid"),l=n.const("len",(0,ub._)`${s}.length`);t.forEach((d,f)=>{(0,sc.alwaysValidSchema)(a,d)||(n.if((0,ub._)`${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,sc.checkStrictMode)(a,y,f.strictTuples)}}}fo.validateTuple=fb;fo.default=jC});var pb=k(uf=>{"use strict";Object.defineProperty(uf,"__esModule",{value:!0});var qC=df(),BC={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:r=>(0,qC.validateTuple)(r,"items")};uf.default=BC});var mb=k(ff=>{"use strict";Object.defineProperty(ff,"__esModule",{value:!0});var hb=U(),UC=Q(),VC=jt(),HC=lf(),zC={message:({params:{len:r}})=>(0,hb.str)`must NOT have more than ${r} items`,params:({params:{len:r}})=>(0,hb._)`{limit: ${r}}`},KC={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:zC,code(r){let{schema:e,parentSchema:t,it:n}=r,{prefixItems:i}=t;n.items=!0,!(0,UC.alwaysValidSchema)(n,e)&&(i?(0,HC.validateAdditionalItems)(r,i):r.ok((0,VC.validateArray)(r)))}};ff.default=KC});var yb=k(pf=>{"use strict";Object.defineProperty(pf,"__esModule",{value:!0});var Bt=U(),oc=Q(),WC={message:({params:{min:r,max:e}})=>e===void 0?(0,Bt.str)`must contain at least ${r} valid item(s)`:(0,Bt.str)`must contain at least ${r} and no more than ${e} valid item(s)`,params:({params:{min:r,max:e}})=>e===void 0?(0,Bt._)`{minContains: ${r}}`:(0,Bt._)`{minContains: ${r}, maxContains: ${e}}`},GC={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:WC,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,Bt._)`${i}.length`);if(r.setParams({min:o,max:a}),a===void 0&&o===0){(0,oc.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&o>a){(0,oc.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),r.fail();return}if((0,oc.alwaysValidSchema)(s,t)){let m=(0,Bt._)`${u} >= ${o}`;a!==void 0&&(m=(0,Bt._)`${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,Bt._)`${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:oc.Type.Num,compositeRule:!0},m),y()})}function h(m){e.code((0,Bt._)`${m}++`),a===void 0?e.if((0,Bt._)`${m} >= ${o}`,()=>e.assign(d,!0).break()):(e.if((0,Bt._)`${m} > ${a}`,()=>e.assign(d,!1).break()),o===1?e.assign(d,!0):e.if((0,Bt._)`${m} >= ${o}`,()=>e.assign(d,!0)))}}};pf.default=GC});var ac=k(_r=>{"use strict";Object.defineProperty(_r,"__esModule",{value:!0});_r.validateSchemaDeps=_r.validatePropertyDeps=_r.error=void 0;var hf=U(),JC=Q(),po=jt();_r.error={message:({params:{property:r,depsCount:e,deps:t}})=>{let n=e===1?"property":"properties";return(0,hf.str)`must have ${n} ${t} when property ${r} is present`},params:({params:{property:r,depsCount:e,deps:t,missingProperty:n}})=>(0,hf._)`{property: ${r}, + || ${o} === "boolean" || ${i} === null`).assign(a,(0,z._)`[${i}]`)}}}function lk({gen:r,parentData:e,parentDataProperty:t},n){r.if((0,z._)`${e} !== undefined`,()=>r.assign((0,z._)`${e}[${t}]`,n))}function lu(r,e,t,n=Ii.Correct){let i=n===Ii.Correct?z.operators.EQ:z.operators.NEQ,s;switch(r){case"null":return(0,z._)`${e} ${i} null`;case"array":s=(0,z._)`Array.isArray(${e})`;break;case"object":s=(0,z._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=o((0,z._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=o();break;default:return(0,z._)`typeof ${e} ${i} ${r}`}return n===Ii.Correct?s:(0,z.not)(s);function o(a=z.nil){return(0,z.and)((0,z._)`typeof ${e} == "number"`,a,t?(0,z._)`isFinite(${e})`:z.nil)}}Ke.checkDataType=lu;function du(r,e,t,n){if(r.length===1)return lu(r[0],e,t,n);let i,s=(0,Ry.toHash)(r);if(s.array&&s.object){let o=(0,z._)`typeof ${e} != "object"`;i=s.null?o:(0,z._)`!${e} || ${o}`,delete s.null,delete s.array,delete s.object}else i=z.nil;s.number&&delete s.integer;for(let o in s)i=(0,z.and)(i,lu(o,e,t,n));return i}Ke.checkDataTypes=du;var dk={message:({schema:r})=>`must be ${r}`,params:({schema:r,schemaValue:e})=>typeof r=="string"?(0,z._)`{type: ${r}}`:(0,z._)`{type: ${e}}`};function uu(r){let e=uk(r);(0,ik.reportError)(e,dk)}Ke.reportTypeError=uu;function uk(r){let{gen:e,data:t,schema:n}=r,i=(0,Ry.schemaRefOrVal)(r,n,"type");return{gen:e,keyword:"type",data:t,schema:n.type,schemaCode:i,schemaValue:i,parentSchema:n,params:{},it:r}}});var Dy=k(Ua=>{"use strict";Object.defineProperty(Ua,"__esModule",{value:!0});Ua.assignDefaults=void 0;var Oi=U(),fk=Q();function pk(r,e){let{properties:t,items:n}=r.schema;if(e==="object"&&t)for(let i in t)Oy(r,i,t[i].default);else e==="array"&&Array.isArray(n)&&n.forEach((i,s)=>Oy(r,s,i.default))}Ua.assignDefaults=pk;function Oy(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,fk.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 jt=k(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(),fu=Q(),un=Ft(),hk=Q();function mk(r,e){let{gen:t,data:n,it:i}=r;t.if(hu(t,n,e,i.opts.ownProperties),()=>{r.setParams({missingProperty:(0,me._)`${e}`},!0),r.error()})}le.checkReportMissingProp=mk;function yk({gen:r,data:e,it:{opts:t}},n,i){return(0,me.or)(...n.map(s=>(0,me.and)(hu(r,e,s,t.ownProperties),(0,me._)`${i} = ${s}`)))}le.checkMissingProp=yk;function gk(r,e){r.setParams({missingProperty:e},!0),r.error()}le.reportMissingProp=gk;function Ly(r){return r.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,me._)`Object.prototype.hasOwnProperty`})}le.hasPropFunc=Ly;function pu(r,e,t){return(0,me._)`${Ly(r)}.call(${e}, ${t})`}le.isOwnProperty=pu;function bk(r,e,t,n){let i=(0,me._)`${e}${(0,me.getProperty)(t)} !== undefined`;return n?(0,me._)`${i} && ${pu(r,e,t)}`:i}le.propertyInData=bk;function hu(r,e,t,n){let i=(0,me._)`${e}${(0,me.getProperty)(t)} === undefined`;return n?(0,me.or)(i,(0,me.not)(pu(r,e,t))):i}le.noPropertyInData=hu;function Ny(r){return r?Object.keys(r).filter(e=>e!=="__proto__"):[]}le.allSchemaProperties=Ny;function vk(r,e){return Ny(e).filter(t=>!(0,fu.alwaysValidSchema)(r,e[t]))}le.schemaProperties=vk;function wk({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=[[un.default.instancePath,(0,me.strConcat)(un.default.instancePath,s)],[un.default.parentData,o.parentData],[un.default.parentDataProperty,o.parentDataProperty],[un.default.rootData,un.default.rootData]];o.opts.dynamicRef&&d.push([un.default.dynamicAnchors,un.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=wk;var _k=(0,me._)`new RegExp`;function Sk({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"?_k:(0,hk.useFunc)(r,i)}(${t}, ${n})`})}le.usePattern=Sk;function xk(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:fu.Type.Num},s),e.if((0,me.not)(s),a)})}}le.validateArray=xk;function $k(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,fu.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=$k});var qy=k(vr=>{"use strict";Object.defineProperty(vr,"__esModule",{value:!0});vr.validateKeywordUsage=vr.validSchemaType=vr.funcKeywordCode=vr.macroKeywordCode=void 0;var nt=U(),ei=Ft(),Ek=jt(),kk=Ks();function Ak(r,e){let{gen:t,keyword:n,schema:i,parentSchema:s,it:o}=r,a=e.macro.call(o.self,i,s,o),c=jy(t,n,a);o.opts.validateSchema!==!1&&o.self.validateSchema(a,!0);let l=t.name("valid");r.subschema({schema:a,schemaPath:nt.nil,errSchemaPath:`${o.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},l),r.pass(l,()=>r.error(!0))}vr.macroKeywordCode=Ak;function Pk(r,e){var t;let{gen:n,keyword:i,schema:s,parentSchema:o,$data:a,it:c}=r;Mk(c,e);let l=!a&&e.compile?e.compile.call(c.self,s,o,c):e.validate,u=jy(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&&Fy(r),y(()=>r.error());else{let g=e.async?p():h();e.modifying&&Fy(r),y(()=>Ck(r,g))}}function p(){let g=n.let("ruleErrs",null);return n.try(()=>m((0,nt._)`await `),b=>n.assign(d,!1).if((0,nt._)`${b} instanceof ${c.ValidationError}`,()=>n.assign(g,(0,nt._)`${b}.errors`),()=>n.throw(b))),g}function h(){let g=(0,nt._)`${u}.errors`;return n.assign(g,null),m(nt.nil),g}function m(g=e.async?(0,nt._)`await `:nt.nil){let b=c.opts.passContext?ei.default.this:ei.default.self,v=!("compile"in e&&!a||e.schema===!1);n.assign(d,(0,nt._)`${g}${(0,Ek.callValidateCode)(r,u,b,v)}`,e.modifying)}function y(g){var b;n.if((0,nt.not)((b=e.valid)!==null&&b!==void 0?b:d),g)}}vr.funcKeywordCode=Pk;function Fy(r){let{gen:e,data:t,it:n}=r;e.if(n.parentData,()=>e.assign(t,(0,nt._)`${n.parentData}[${n.parentDataProperty}]`))}function Ck(r,e){let{gen:t}=r;t.if((0,nt._)`Array.isArray(${e})`,()=>{t.assign(ei.default.vErrors,(0,nt._)`${ei.default.vErrors} === null ? ${e} : ${ei.default.vErrors}.concat(${e})`).assign(ei.default.errors,(0,nt._)`${ei.default.vErrors}.length`),(0,kk.extendErrors)(r)},()=>r.error())}function Mk({schemaEnv:r},e){if(e.async&&!r.$async)throw new Error("async keyword in sync schema")}function jy(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,nt.stringify)(t)})}function Rk(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")}vr.validSchemaType=Rk;function Tk({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)}}vr.validateKeywordUsage=Tk});var Uy=k(fn=>{"use strict";Object.defineProperty(fn,"__esModule",{value:!0});fn.extendSubschemaMode=fn.extendSubschemaData=fn.getSubschema=void 0;var wr=U(),By=Q();function Ik(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,wr._)`${r.schemaPath}${(0,wr.getProperty)(e)}`,errSchemaPath:`${r.errSchemaPath}/${e}`}:{schema:a[t],schemaPath:(0,wr._)`${r.schemaPath}${(0,wr.getProperty)(e)}${(0,wr.getProperty)(t)}`,errSchemaPath:`${r.errSchemaPath}/${e}/${(0,By.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')}fn.getSubschema=Ik;function Ok(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,wr._)`${e.data}${(0,wr.getProperty)(t)}`,!0);c(f),r.errorPath=(0,wr.str)`${l}${(0,By.getErrorPath)(t,n,d.jsPropertySyntax)}`,r.parentDataProperty=(0,wr._)`${t}`,r.dataPathArr=[...u,r.parentDataProperty]}if(i!==void 0){let l=i instanceof wr.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]}}fn.extendSubschemaData=Ok;function Dk(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}fn.extendSubschemaMode=Dk});var mu=k((Oj,Vy)=>{"use strict";Vy.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 zy=k((Dj,Hy)=>{"use strict";var pn=Hy.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(){};Va(e,n,i,r,"",r)};pn.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};pn.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};pn.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};pn.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 Va(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 pn.arrayKeywords)for(var f=0;f{"use strict";Object.defineProperty(pt,"__esModule",{value:!0});pt.getSchemaRefs=pt.resolveUrl=pt.normalizeId=pt._getFullPath=pt.getFullPath=pt.inlineRef=void 0;var Nk=Q(),Fk=mu(),jk=zy(),qk=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function Bk(r,e=!0){return typeof r=="boolean"?!0:e===!0?!yu(r):e?Ky(r)<=e:!1}pt.inlineRef=Bk;var Uk=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function yu(r){for(let e in r){if(Uk.has(e))return!0;let t=r[e];if(Array.isArray(t)&&t.some(yu)||typeof t=="object"&&yu(t))return!0}return!1}function Ky(r){let e=0;for(let t in r){if(t==="$ref")return 1/0;if(e++,!qk.has(t)&&(typeof r[t]=="object"&&(0,Nk.eachItem)(r[t],n=>e+=Ky(n)),e===1/0))return 1/0}return e}function Wy(r,e="",t){t!==!1&&(e=Di(e));let n=r.parse(e);return Gy(r,n)}pt.getFullPath=Wy;function Gy(r,e){return r.serialize(e).split("#")[0]+"#"}pt._getFullPath=Gy;var Vk=/#\/?$/;function Di(r){return r?r.replace(Vk,""):""}pt.normalizeId=Di;function Hk(r,e,t){return t=Di(t),r.resolve(e,t)}pt.resolveUrl=Hk;var zk=/^[a-z_][-a-z0-9._]*$/i;function Kk(r,e){if(typeof r=="boolean")return{};let{schemaId:t,uriResolver:n}=this.opts,i=Di(r[t]||e),s={"":i},o=Wy(n,i,!1),a={},c=new Set;return jk(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(!zk.test(v))throw new Error(`invalid anchor "${v}"`);g.call(this,`#${v}`)}}}),a;function l(d,f,p){if(f!==void 0&&!Fk(d,f))throw u(p)}function u(d){return new Error(`reference "${d}" resolves to more than one schema`)}}pt.getSchemaRefs=Kk});var Li=k(hn=>{"use strict";Object.defineProperty(hn,"__esModule",{value:!0});hn.getData=hn.KeywordCxt=hn.validateFunctionCode=void 0;var Zy=Py(),Jy=Ws(),bu=cu(),Ha=Ws(),Wk=Dy(),Ys=qy(),gu=Uy(),j=U(),B=Ft(),Gk=Gs(),Br=Q(),Js=Ks();function Jk(r){if(rg(r)&&(ng(r),tg(r))){Qk(r);return}eg(r,()=>(0,Zy.topBoolOrEmptySchema)(r))}hn.validateFunctionCode=Jk;function eg({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"; ${Yy(t,i)}`),Xk(r,i),r.code(s)}):r.func(e,(0,j._)`${B.default.data}, ${Yk(i)}`,n.$async,()=>r.code(Yy(t,i)).code(s))}function Yk(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 Xk(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 Qk(r){let{schema:e,opts:t,gen:n}=r;eg(r,()=>{t.$comment&&e.$comment&&sg(r),nA(r),n.let(B.default.vErrors,null),n.let(B.default.errors,0),t.unevaluated&&Zk(r),ig(r),oA(r)})}function Zk(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 Yy(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 eA(r,e){if(rg(r)&&(ng(r),tg(r))){tA(r,e);return}(0,Zy.boolOrEmptySchema)(r,e)}function tg({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 rg(r){return typeof r.schema!="boolean"}function tA(r,e){let{schema:t,gen:n,opts:i}=r;i.$comment&&t.$comment&&sg(r),iA(r),sA(r);let s=n.const("_errs",B.default.errors);ig(r,s),n.var(e,(0,j._)`${s} === ${B.default.errors}`)}function ng(r){(0,Br.checkUnknownRules)(r),rA(r)}function ig(r,e){if(r.opts.jtd)return Xy(r,[],!1,e);let t=(0,Jy.getSchemaTypes)(r.schema),n=(0,Jy.coerceAndCheckDataType)(r,t);Xy(r,t,!n,e)}function rA(r){let{schema:e,errSchemaPath:t,opts:n,self:i}=r;e.$ref&&n.ignoreKeywordsWithRef&&(0,Br.schemaHasRulesButRef)(e,i.RULES)&&i.logger.warn(`$ref: keywords ignored in schema at path "${t}"`)}function nA(r){let{schema:e,opts:t}=r;e.default!==void 0&&t.useDefaults&&t.strictSchema&&(0,Br.checkStrictMode)(r,"default is ignored in the schema root")}function iA(r){let e=r.schema[r.opts.schemaId];e&&(r.baseId=(0,Gk.resolveUrl)(r.opts.uriResolver,r.baseId,e))}function sA(r){if(r.schema.$async&&!r.schemaEnv.$async)throw new Error("async schema in sync schema")}function sg({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 oA(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&&aA(r),e.return((0,j._)`${B.default.errors} === 0`))}function aA({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 Xy(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,Br.schemaHasRulesButRef)(s,u))){i.block(()=>ag(r,"$ref",u.all.$ref.definition));return}c.jtd||cA(r,e),i.block(()=>{for(let f of u.rules)d(f);d(u.post)});function d(f){(0,bu.shouldUseGroup)(s,f)&&(f.type?(i.if((0,Ha.checkDataType)(f.type,o,c.strictNumbers)),Qy(r,f),e.length===1&&e[0]===f.type&&t&&(i.else(),(0,Ha.reportTypeError)(r)),i.endIf()):Qy(r,f),a||i.if((0,j._)`${B.default.errors} === ${n||0}`))}}function Qy(r,e){let{gen:t,schema:n,opts:{useDefaults:i}}=r;i&&(0,Wk.assignDefaults)(r,e.type),t.block(()=>{for(let s of e.rules)(0,bu.shouldUseRule)(n,s)&&ag(r,s.keyword,s.definition,e.type)})}function cA(r,e){r.schemaEnv.meta||!r.opts.strictTypes||(lA(r,e),r.opts.allowUnionTypes||dA(r,e),uA(r,r.dataTypes))}function lA(r,e){if(e.length){if(!r.dataTypes.length){r.dataTypes=e;return}e.forEach(t=>{og(r.dataTypes,t)||vu(r,`type "${t}" not allowed by context "${r.dataTypes.join(",")}"`)}),pA(r,e)}}function dA(r,e){e.length>1&&!(e.length===2&&e.includes("null"))&&vu(r,"use allowUnionTypes to allow union type keyword")}function uA(r,e){let t=r.self.RULES.all;for(let n in t){let i=t[n];if(typeof i=="object"&&(0,bu.shouldUseRule)(r.schema,i)){let{type:s}=i.definition;s.length&&!s.some(o=>fA(e,o))&&vu(r,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function fA(r,e){return r.includes(e)||e==="number"&&r.includes("integer")}function og(r,e){return r.includes(e)||e==="integer"&&r.includes("number")}function pA(r,e){let t=[];for(let n of r.dataTypes)og(e,n)?t.push(n):e.includes("integer")&&n==="number"&&t.push("integer");r.dataTypes=t}function vu(r,e){let t=r.schemaEnv.baseId+r.errSchemaPath;e+=` at "${t}" (strictTypes)`,(0,Br.checkStrictMode)(r,e,r.opts.strictTypes)}var za=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,Br.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",cg(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,Ha.checkDataTypes)(c,t,s.opts.strictNumbers,Ha.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,gu.getSubschema)(this.it,e);(0,gu.extendSubschemaData)(n,this.it,e),(0,gu.extendSubschemaMode)(n,e);let i={...this.it,...n,items:void 0,props:void 0};return eA(i,t),i}mergeEvaluated(e,t){let{it:n,gen:i}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=Br.mergeEvaluated.props(i,e.props,n.props,t)),n.items!==!0&&e.items!==void 0&&(n.items=Br.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}};hn.KeywordCxt=za;function ag(r,e,t,n){let i=new za(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 hA=/^\/(?:[^~]|~0|~1)*$/,mA=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function cg(r,{dataLevel:e,dataNames:t,dataPathArr:n}){let i,s;if(r==="")return B.default.rootData;if(r[0]==="/"){if(!hA.test(r))throw new Error(`Invalid JSON-pointer: ${r}`);i=r,s=B.default.rootData}else{let l=mA.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,Br.unescapeJsonPointer)(l))}`,o=(0,j._)`${o} && ${s}`);return o;function c(l,u){return`Cannot access ${l} ${u} levels up, current level is ${e}`}}hn.getData=cg});var Xs=k(_u=>{"use strict";Object.defineProperty(_u,"__esModule",{value:!0});var wu=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};_u.default=wu});var Ni=k($u=>{"use strict";Object.defineProperty($u,"__esModule",{value:!0});var Su=Gs(),xu=class extends Error{constructor(e,t,n,i){super(i||`can't resolve reference ${n} from id ${t}`),this.missingRef=(0,Su.resolveUrl)(e,t,n),this.missingSchema=(0,Su.normalizeId)((0,Su.getFullPath)(e,this.missingRef))}};$u.default=xu});var Qs=k(qt=>{"use strict";Object.defineProperty(qt,"__esModule",{value:!0});qt.resolveSchema=qt.getCompilingSchema=qt.resolveRef=qt.compileSchema=qt.SchemaEnv=void 0;var Qt=U(),yA=Xs(),ti=Ft(),Zt=Gs(),lg=Q(),gA=Li(),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,Zt.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};qt.SchemaEnv=Fi;function ku(r){let e=dg.call(this,r);if(e)return e;let t=(0,Zt.getFullPath)(this.opts.uriResolver,r.root.baseId),{es5:n,lines:i}=this.opts.code,{ownProperties:s}=this.opts,o=new Qt.CodeGen(this.scope,{es5:n,lines:i,ownProperties:s}),a;r.$async&&(a=o.scopeValue("Error",{ref:yA.default,code:(0,Qt._)`require("ajv/dist/runtime/validation_error").default`}));let c=o.scopeName("validate");r.validateName=c;let l={gen:o,allErrors:this.opts.allErrors,data:ti.default.data,parentData:ti.default.parentData,parentDataProperty:ti.default.parentDataProperty,dataNames:[ti.default.data],dataPathArr:[Qt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:o.scopeValue("schema",this.opts.code.source===!0?{ref:r.schema,code:(0,Qt.stringify)(r.schema)}:{ref:r.schema}),validateName:c,ValidationError:a,schema:r.schema,schemaEnv:r,rootId:t,baseId:r.baseId||t,schemaPath:Qt.nil,errSchemaPath:r.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Qt._)`""`,opts:this.opts,self:this},u;try{this._compilations.add(r),(0,gA.validateFunctionCode)(l),o.optimize(this.opts.code.optimize);let d=o.toString();u=`${o.scopeRefs(ti.default.scope)}return ${d}`,this.opts.code.process&&(u=this.opts.code.process(u,r));let p=new Function(`${ti.default.self}`,`${ti.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 Qt.Name?void 0:h,items:m instanceof Qt.Name?void 0:m,dynamicProps:h instanceof Qt.Name,dynamicItems:m instanceof Qt.Name},p.source&&(p.source.evaluated=(0,Qt.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)}}qt.compileSchema=ku;function bA(r,e,t){var n;t=(0,Zt.resolveUrl)(this.opts.uriResolver,e,t);let i=r.refs[t];if(i)return i;let s=_A.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]=vA.call(this,s)}qt.resolveRef=bA;function vA(r){return(0,Zt.inlineRef)(r.schema,this.opts.inlineRefs)?r.schema:r.validate?r:ku.call(this,r)}function dg(r){for(let e of this._compilations)if(wA(e,r))return e}qt.getCompilingSchema=dg;function wA(r,e){return r.schema===e.schema&&r.root===e.root&&r.baseId===e.baseId}function _A(r,e){let t;for(;typeof(t=this.refs[e])=="string";)e=t;return t||this.schemas[e]||Ka.call(this,r,e)}function Ka(r,e){let t=this.opts.uriResolver.parse(e),n=(0,Zt._getFullPath)(this.opts.uriResolver,t),i=(0,Zt.getFullPath)(this.opts.uriResolver,r.baseId,void 0);if(Object.keys(r.schema).length>0&&n===i)return Eu.call(this,t,r);let s=(0,Zt.normalizeId)(n),o=this.refs[s]||this.schemas[s];if(typeof o=="string"){let a=Ka.call(this,r,o);return typeof a?.schema!="object"?void 0:Eu.call(this,t,a)}if(typeof o?.schema=="object"){if(o.validate||ku.call(this,o),s===(0,Zt.normalizeId)(e)){let{schema:a}=o,{schemaId:c}=this.opts,l=a[c];return l&&(i=(0,Zt.resolveUrl)(this.opts.uriResolver,i,l)),new Fi({schema:a,schemaId:c,root:r,baseId:i})}return Eu.call(this,t,o)}}qt.resolveSchema=Ka;var SA=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Eu(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,lg.unescapeFragment)(a)];if(c===void 0)return;t=c;let l=typeof t=="object"&&t[this.opts.schemaId];!SA.has(a)&&l&&(e=(0,Zt.resolveUrl)(this.opts.uriResolver,e,l))}let s;if(typeof t!="boolean"&&t.$ref&&!(0,lg.schemaHasRulesButRef)(t,this.RULES)){let a=(0,Zt.resolveUrl)(this.opts.uriResolver,e,t.$ref);s=Ka.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 ug=k((Bj,xA)=>{xA.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 Tu=k((Uj,bg)=>{"use strict";var $A=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Pu=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),EA=RegExp.prototype.test.bind(/^\d*$/u),ri=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),Cu=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),pg=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u),Mu=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u),kA=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u),ht=new Array(256);{let r="0123456789ABCDEF";for(let e=0;e<256;e++)ht[e]="%"+r[e>>4]+r[e&15]}function We(r){return r<2048?ht[192|r>>6]+ht[128|r&63]:r<65536?ht[224|r>>12]+ht[128|r>>6&63]+ht[128|r&63]:ht[240|r>>18]+ht[128|r>>12&63]+ht[128|r>>6&63]+ht[128|r&63]}function AA(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 PA=RegExp.prototype.test.bind(/^[\dA-Fa-f]{1,4}$/),CA=RegExp.prototype.test.bind(/^[vV][\dA-Fa-f]+\.[A-Za-z\d\-._~!$&'()*+,;=:]+$/),MA=RegExp.prototype.test.bind(/^[A-Za-z\d\-._~]$/),RA=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function TA(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 IA(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;aLA[n])}function mg(r,e=!1){if(r.indexOf("%")===-1)return r;let t="";for(let n=0;n57343)e+=We(i);else if(i<=56319&&t+1=56320&&s<=57343?(e+=We(65536+(i-55296<<10)+(s-56320)),t++):e+=We(65533)}else e+=We(65533)}}return e}function qA(r,e=!1){let t="",n=e&&r[0]!=="/";for(let i=0;i57343)t+=We(o);else if(o<=56319&&i+1=56320&&a<=57343?(t+=We(65536+(o-55296<<10)+(a-56320)),i++):t+=We(65533)}else t+=We(65533)}}return t}function Ru(r,e){let t="";for(let n=0;n57343)t+=We(s);else if(s<=56319&&n+1=56320&&o<=57343?(t+=We(65536+(s-55296<<10)+(o-56320)),n++):t+=We(65533)}else t+=We(65533)}}return t}function yg(r){return Ru(r,kA)}function BA(r){return Ru(r,Mu)}function UA(r){return Ru(r,Mu)}function gg(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 VA(r){let e="";for(let t=0;t57343)e+=We(i);else if(i<=56319&&t+1=56320&&s<=57343?(e+=We(65536+(i-55296<<10)+(s-56320)),t++):e+=We(65533)}else e+=We(65533)}}return e}function HA(r){let e="";for(let t=0;t{"use strict";var{isUUID:KA}=Tu(),WA=/^([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-./:;=@]|%[\da-f]{2})+)$/iu,GA=["http","https","ws","wss","urn","urn:uuid"];function JA(r){return GA.indexOf(r)!==-1}function Iu(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 vg(r){return r.host||(r.error=r.error||"HTTP URIs must have a host."),r}function wg(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 YA(r){return r.secure=Iu(r),r.resourceName=(r.path||"/")+(r.query?"?"+r.query:""),r.path=void 0,r.query=void 0,r}function XA(r){if((r.port===(Iu(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 QA(r,e){if(!r.path)return r.error="URN can not be parsed",r;let t=r.path.match(WA);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=Ou(i);r.path=void 0,s&&(r=s.parse(r,e))}else r.error=r.error||"URN can not be parsed.";return r}function ZA(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=Ou(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 eP(r,e){let t=r;return t.uuid=t.nss,t.nss=void 0,!e.tolerant&&(!t.uuid||!KA(t.uuid))&&(t.error=t.error||"UUID is not valid."),t}function tP(r){let e=r;return e.nss=(r.uuid||"").toLowerCase(),e}var _g={scheme:"http",domainHost:!0,parse:vg,serialize:wg},rP={scheme:"https",domainHost:_g.domainHost,parse:vg,serialize:wg},Wa={scheme:"ws",domainHost:!0,parse:YA,serialize:XA},nP={scheme:"wss",domainHost:Wa.domainHost,parse:Wa.parse,serialize:Wa.serialize},iP={scheme:"urn",parse:QA,serialize:ZA,skipNormalize:!0},sP={scheme:"urn:uuid",parse:eP,serialize:tP,skipNormalize:!0},Ga={http:_g,https:rP,ws:Wa,wss:nP,urn:iP,"urn:uuid":sP};Object.setPrototypeOf(Ga,null);function Ou(r){return r&&(Ga[r]||Ga[r.toLowerCase()])||void 0}Sg.exports={wsIsSecure:Iu,SCHEMES:Ga,isValidSchemeName:JA,getSchemeHandler:Ou}});var Ng=k((Hj,Xa)=>{"use strict";var{normalizeIPv6:Pg,removeDotSegments:eo,recomposeAuthority:oP,normalizePercentEncoding:Cg,normalizePathEncoding:aP,serializePathEncoding:$g,normalizeQueryFragmentEncoding:Eg,encodeQuery:cP,encodeFragment:lP,reescapeHostDelimiters:dP,isIPv4:Mg,nonSimpleDomain:uP}=Tu(),{SCHEMES:Rg,getSchemeHandler:Du}=xg(),Tg=/^[A-Za-z][A-Za-z0-9+.-]*$/u,Ig="URI scheme is malformed.";function kg(r){let e=unescape(String(r));if(!Tg.test(e))throw new TypeError(Ig);return e}function fP(r,e){return typeof r=="string"?r=wP(r,e):typeof r=="object"&&(r=Ya(ni(r,e),e)),r}function pP(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}=Ja(r,n),{parsed:u,malformedAuthorityOrPort:d,malformedPercentEncoding:f,malformedSchemeSpecific:p,malformedHost:h,malformedScheme:m}=Ja(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=Og(i,u,n,!0),g=Du(t&&t.scheme||y.scheme),b=y.host,v=b!==void 0&&b!==""&&(Mg(b)||Pg(b).isIPV6);Dg(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,ni(y,n)}function Og(r,e,t,n){let i={};return n||(r=Ya(ni(r,t),t),e=Ya(ni(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 hP(r,e,t){let n=Ag(r,t),i=Ag(e,t);return n!==void 0&&i!==void 0&&n===i}function ni(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=kg(t.scheme));let s=Du(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=Cg(t.path):t.path=$g(t.path,a)),n.reference!=="suffix"&&t.scheme&&(t.scheme=kg(t.scheme),i.push(t.scheme,":"));let c=oP(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=$g(l,!0)),c===void 0&&l[0]==="/"&&l[1]==="/"&&(l="/%2F"+l.slice(2)),i.push(l)}return t.query!==void 0&&i.push("?",cP(t.query)),t.fragment!==void 0&&i.push("#",lP(t.fragment)),i.join("")}var mP=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,yP=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,gP=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function bP(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 Lu(r){return r[0]==="["&&r[r.length-1]==="]"}function vP(r){let e=r[4];return Zs(r[3])||e!==void 0&&!Lu(e)&&Zs(e)||Zs(r[6])||Zs(r[7])||Zs(r[8])}function Dg(r,e,t,n){if(!e.unicodeSupport&&(!t||!t.unicodeSupport)&&r.host&&!Lu(r.host)&&(e.domainHost||t&&t.domainHost)&&n===!1&&uP(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 Ja(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(yP);d!==null&&d[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",i=!0);let f=r.match(gP);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(mP);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);Tg.test(y)?n.scheme=y.toLowerCase():(n.error=n.error||Ig,l=!0)}s=vP(p),s&&(n.error=n.error||"URI contains malformed percent-encoding."),isNaN(n.port)&&(n.port=p[5]);let h=bP(n,p);if(h!==void 0&&(n.error=n.error||h,i=!0),n.host)if(Mg(n.host)===!1){let g=Lu(n.host),b=n.host.indexOf("[")!==-1||n.host.indexOf("]")!==-1,v=Pg(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=Du(t.scheme||n.scheme);if(c||(a=Dg(n,t,m,u)),!m||m&&!m.skipNormalize){if(r.indexOf("%")!==-1&&n.host!==void 0&&!c){let y=u?n.host:Cg(n.host,!0);n.host=dP(y,u)}n.path&&(n.path=aP(n.path)),n.query&&(n.query=Eg(n.query)),n.fragment&&(n.fragment=Eg(n.fragment))}m&&m.parse&&(m.parse(n,t),m===Rg.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 Ya(r,e){return Ja(r,e).parsed}function wP(r,e){return Lg(r,e).normalized}function Lg(r,e){let{parsed:t,malformedAuthorityOrPort:n,malformedPercentEncoding:i,malformedSchemeSpecific:s,malformedHost:o,malformedScheme:a}=Ja(r,e);return{normalized:n||i||s||o||a?r:ni(t,e),malformedAuthorityOrPort:n,malformedPercentEncoding:i,malformedSchemeSpecific:s,malformedHost:o,malformedScheme:a}}function Ag(r,e){if(typeof r!="string"&&typeof r!="object")return;let t;try{t=typeof r=="string"?r:ni(r,e)}catch{return}let{normalized:n,malformedAuthorityOrPort:i,malformedPercentEncoding:s,malformedSchemeSpecific:o,malformedHost:a,malformedScheme:c}=Lg(t,e);return i||s||o||a||c?void 0:n}var Nu={SCHEMES:Rg,normalize:fP,resolve:pP,resolveComponent:Og,equal:hP,serialize:ni,parse:Ya};Xa.exports=Nu;Xa.exports.default=Nu;Xa.exports.fastUri=Nu});var jg=k(Fu=>{"use strict";Object.defineProperty(Fu,"__esModule",{value:!0});var Fg=Ng();Fg.code='require("ajv/dist/runtime/uri").default';Fu.default=Fg});var Bu=k(Fe=>{"use strict";Object.defineProperty(Fe,"__esModule",{value:!0});Fe.CodeGen=Fe.Name=Fe.nil=Fe.stringify=Fe.str=Fe._=Fe.KeywordCxt=void 0;var _P=Li();Object.defineProperty(Fe,"KeywordCxt",{enumerable:!0,get:function(){return _P.KeywordCxt}});var ji=U();Object.defineProperty(Fe,"_",{enumerable:!0,get:function(){return ji._}});Object.defineProperty(Fe,"str",{enumerable:!0,get:function(){return ji.str}});Object.defineProperty(Fe,"stringify",{enumerable:!0,get:function(){return ji.stringify}});Object.defineProperty(Fe,"nil",{enumerable:!0,get:function(){return ji.nil}});Object.defineProperty(Fe,"Name",{enumerable:!0,get:function(){return ji.Name}});Object.defineProperty(Fe,"CodeGen",{enumerable:!0,get:function(){return ji.CodeGen}});var SP=Xs(),Hg=Ni(),xP=au(),to=Qs(),$P=U(),ro=Gs(),Qa=Ws(),qu=Q(),qg=ug(),EP=jg(),zg=(r,e)=>new RegExp(r,e);zg.code="new RegExp";var kP=["removeAdditional","useDefaults","coerceTypes"],AP=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),PP={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."},CP={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Bg=200;function MP(r){var e,t,n,i,s,o,a,c,l,u,d,f,p,h,m,y,g,b,v,S,_,E,A,x,R;let $=r.strict,q=(e=r.code)===null||e===void 0?void 0:e.optimize,M=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:zg,P=(i=r.uriResolver)!==null&&i!==void 0?i:EP.default;return{strictSchema:(o=(s=r.strictSchema)!==null&&s!==void 0?s:$)!==null&&o!==void 0?o:!0,strictNumbers:(c=(a=r.strictNumbers)!==null&&a!==void 0?a:$)!==null&&c!==void 0?c:!0,strictTypes:(u=(l=r.strictTypes)!==null&&l!==void 0?l:$)!==null&&u!==void 0?u:"log",strictTuples:(f=(d=r.strictTuples)!==null&&d!==void 0?d:$)!==null&&f!==void 0?f:"log",strictRequired:(h=(p=r.strictRequired)!==null&&p!==void 0?p:$)!==null&&h!==void 0?h:!1,code:r.code?{...r.code,optimize:M,regExp:V}:{optimize:M,regExp:V},loopRequired:(m=r.loopRequired)!==null&&m!==void 0?m:Bg,loopEnum:(y=r.loopEnum)!==null&&y!==void 0?y:Bg,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:(A=r.validateFormats)!==null&&A!==void 0?A:!0,unicodeRegExp:(x=r.unicodeRegExp)!==null&&x!==void 0?x:!0,int32range:(R=r.int32range)!==null&&R!==void 0?R:!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,...MP(e)};let{es5:t,lines:n}=this.opts.code;this.scope=new $P.ValueScope({scope:{},prefixes:AP,es5:t,lines:n}),this.logger=LP(e.logger);let i=e.validateFormats;e.validateFormats=!1,this.RULES=(0,xP.getRules)(),Ug.call(this,PP,e,"NOT SUPPORTED"),Ug.call(this,CP,e,"DEPRECATED","warn"),this._metaOpts=OP.call(this),e.formats&&TP.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&IP.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),RP.call(this),e.validateFormats=i}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:t,schemaId:n}=this.opts,i=qg;n==="id"&&(i={...qg},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 Hg.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=Vg.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=Vg.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(FP.call(this,n,t),!t)return(0,qu.eachItem)(n,s=>ju.call(this,s)),this;qP.call(this,t);let i={...t,type:(0,Qa.getJSONTypes)(t.type),schemaType:(0,Qa.getJSONTypes)(t.schemaType)};return(0,qu.eachItem)(n,i.type.length===0?s=>ju.call(this,s,i):s=>i.type.forEach(o=>ju.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]=Kg(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=SP.default;no.MissingRefError=Hg.default;Fe.default=no;function Ug(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 Vg(r){return r=(0,ro.normalizeId)(r),this.schemas[r]||this.refs[r]}function RP(){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 IP(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 OP(){let r={...this.opts};for(let e of kP)delete r[e];return r}var DP={log(){},warn(){},error(){}};function LP(r){if(r===!1)return DP;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 FP(r,e){let{RULES:t}=this;if((0,qu.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 ju(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,Qa.getJSONTypes)(e.type),schemaType:(0,Qa.getJSONTypes)(e.schemaType)}};e.before?jP.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 jP(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 qP(r){let{metaSchema:e}=r;e!==void 0&&(r.$data&&this.opts.$data&&(e=Kg(e)),r.validateSchema=this.compile(e,!0))}var BP={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Kg(r){return{anyOf:[r,BP]}}});var Wg=k(Uu=>{"use strict";Object.defineProperty(Uu,"__esModule",{value:!0});var UP={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Uu.default=UP});var tc=k(ii=>{"use strict";Object.defineProperty(ii,"__esModule",{value:!0});ii.callRef=ii.getValidate=void 0;var VP=Ni(),Gg=jt(),mt=U(),qi=Ft(),Jg=Qs(),Za=Q(),HP={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=Jg.resolveRef.call(c,l,i,t);if(u===void 0)throw new VP.default(n.opts.uriResolver,i,t);if(u instanceof Jg.SchemaEnv)return f(u);return p(u);function d(){if(s===l)return ec(r,o,s,s.$async);let h=e.scopeValue("root",{ref:l});return ec(r,(0,mt._)`${h}.validate`,l,l.$async)}function f(h){let m=Yg(r,h);ec(r,m,h,h.$async)}function p(h){let m=e.scopeValue("schema",a.code.source===!0?{ref:h,code:(0,mt.stringify)(h)}:{ref:h}),y=e.name("valid"),g=r.subschema({schema:h,dataTypes:[],schemaPath:mt.nil,topSchemaRef:m,errSchemaPath:t},y);r.mergeEvaluated(g),r.ok(y)}}};function Yg(r,e){let{gen:t}=r;return e.validate?t.scopeValue("validate",{ref:e.validate}):(0,mt._)`${t.scopeValue("wrapper",{ref:e})}.validate`}ii.getValidate=Yg;function ec(r,e,t,n){let{gen:i,it:s}=r,{allErrors:o,schemaEnv:a,opts:c}=s,l=c.passContext?qi.default.this:mt.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,mt._)`await ${(0,Gg.callValidateCode)(r,e,l)}`),p(e),o||i.assign(h,!0)},m=>{i.if((0,mt._)`!(${m} instanceof ${s.ValidationError})`,()=>i.throw(m)),f(m),o||i.assign(h,!1)}),r.ok(h)}function d(){r.result((0,Gg.callValidateCode)(r,e,l),()=>p(e),()=>f(e))}function f(h){let m=(0,mt._)`${h}.errors`;i.assign(qi.default.vErrors,(0,mt._)`${qi.default.vErrors} === null ? ${m} : ${qi.default.vErrors}.concat(${m})`),i.assign(qi.default.errors,(0,mt._)`${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=Za.mergeEvaluated.props(i,y.props,s.props));else{let g=i.var("props",(0,mt._)`${h}.evaluated.props`);s.props=Za.mergeEvaluated.props(i,g,s.props,mt.Name)}if(s.items!==!0)if(y&&!y.dynamicItems)y.items!==void 0&&(s.items=Za.mergeEvaluated.items(i,y.items,s.items));else{let g=i.var("items",(0,mt._)`${h}.evaluated.items`);s.items=Za.mergeEvaluated.items(i,g,s.items,mt.Name)}}}ii.callRef=ec;ii.default=HP});var Hu=k(Vu=>{"use strict";Object.defineProperty(Vu,"__esModule",{value:!0});var zP=Wg(),KP=tc(),WP=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",zP.default,KP.default];Vu.default=WP});var Xg=k(zu=>{"use strict";Object.defineProperty(zu,"__esModule",{value:!0});var rc=U(),mn=rc.operators,nc={maximum:{okStr:"<=",ok:mn.LTE,fail:mn.GT},minimum:{okStr:">=",ok:mn.GTE,fail:mn.LT},exclusiveMaximum:{okStr:"<",ok:mn.LT,fail:mn.GTE},exclusiveMinimum:{okStr:">",ok:mn.GT,fail:mn.LTE}},GP={message:({keyword:r,schemaCode:e})=>(0,rc.str)`must be ${nc[r].okStr} ${e}`,params:({keyword:r,schemaCode:e})=>(0,rc._)`{comparison: ${nc[r].okStr}, limit: ${e}}`},JP={keyword:Object.keys(nc),type:"number",schemaType:"number",$data:!0,error:GP,code(r){let{keyword:e,data:t,schemaCode:n}=r;r.fail$data((0,rc._)`${t} ${nc[e].fail} ${n} || isNaN(${t})`)}};zu.default=JP});var Qg=k(Ku=>{"use strict";Object.defineProperty(Ku,"__esModule",{value:!0});var io=U(),YP={message:({schemaCode:r})=>(0,io.str)`must be multiple of ${r}`,params:({schemaCode:r})=>(0,io._)`{multipleOf: ${r}}`},XP={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:YP,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}))`)}};Ku.default=XP});var eb=k(Wu=>{"use strict";Object.defineProperty(Wu,"__esModule",{value:!0});function Zg(r){let e=r.length,t=0,n=0,i;for(;n=55296&&i<=56319&&n{"use strict";Object.defineProperty(Gu,"__esModule",{value:!0});var si=U(),QP=Q(),ZP=eb(),eC={message({keyword:r,schemaCode:e}){let t=r==="maxLength"?"more":"fewer";return(0,si.str)`must NOT have ${t} than ${e} characters`},params:({schemaCode:r})=>(0,si._)`{limit: ${r}}`},tC={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:eC,code(r){let{keyword:e,data:t,schemaCode:n,it:i}=r,s=e==="maxLength"?si.operators.GT:si.operators.LT,o=i.opts.unicode===!1?(0,si._)`${t}.length`:(0,si._)`${(0,QP.useFunc)(r.gen,ZP.default)}(${t})`;r.fail$data((0,si._)`${o} ${s} ${n}`)}};Gu.default=tC});var rb=k(Ju=>{"use strict";Object.defineProperty(Ju,"__esModule",{value:!0});var rC=jt(),nC=Q(),Bi=U(),iC={message:({schemaCode:r})=>(0,Bi.str)`must match pattern "${r}"`,params:({schemaCode:r})=>(0,Bi._)`{pattern: ${r}}`},sC={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:iC,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,nC.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,rC.usePattern)(r,i);r.fail$data((0,Bi._)`!${c}.test(${t})`)}}};Ju.default=sC});var nb=k(Yu=>{"use strict";Object.defineProperty(Yu,"__esModule",{value:!0});var so=U(),oC={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}}`},aC={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:oC,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}`)}};Yu.default=aC});var ib=k(Xu=>{"use strict";Object.defineProperty(Xu,"__esModule",{value:!0});var oo=jt(),ao=U(),cC=Q(),lC={message:({params:{missingProperty:r}})=>(0,ao.str)`must have required property '${r}'`,params:({params:{missingProperty:r}})=>(0,ao._)`{missingProperty: ${r}}`},dC={keyword:"required",type:"object",schemaType:"array",$data:!0,error:lC,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,cC.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)}}};Xu.default=dC});var sb=k(Qu=>{"use strict";Object.defineProperty(Qu,"__esModule",{value:!0});var co=U(),uC={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}}`},fC={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:uC,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}`)}};Qu.default=fC});var ic=k(Zu=>{"use strict";Object.defineProperty(Zu,"__esModule",{value:!0});var ob=mu();ob.code='require("ajv/dist/runtime/equal").default';Zu.default=ob});var ab=k(tf=>{"use strict";Object.defineProperty(tf,"__esModule",{value:!0});var ef=Ws(),je=U(),pC=Q(),hC=ic(),mC={message:({params:{i:r,j:e}})=>(0,je.str)`must NOT have duplicate items (items ## ${e} and ${r} are identical)`,params:({params:{i:r,j:e}})=>(0,je._)`{i: ${r}, j: ${e}}`},yC={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:mC,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,ef.getSchemaTypes)(s.items):[];r.block$data(c,u,(0,je._)`${o} === false`),r.ok(c);function u(){let h=e.let("i",(0,je._)`${t}.length`),m=e.let("j");r.setParams({i:h,j:m}),e.assign(c,!0),e.if((0,je._)`${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,ef.checkDataTypes)(l,y,a.opts.strictNumbers,ef.DataType.Wrong),b=e.const("indices",(0,je._)`{}`);e.for((0,je._)`;${h}--;`,()=>{e.let(y,(0,je._)`${t}[${h}]`),e.if(g,(0,je._)`continue`),l.length>1&&e.if((0,je._)`typeof ${y} == "string"`,(0,je._)`${y} += "_"`),e.if((0,je._)`typeof ${b}[${y}] == "number"`,()=>{e.assign(m,(0,je._)`${b}[${y}]`),r.error(),e.assign(c,!1).break()}).code((0,je._)`${b}[${y}] = ${h}`)})}function p(h,m){let y=(0,pC.useFunc)(e,hC.default),g=e.name("outer");e.label(g).for((0,je._)`;${h}--;`,()=>e.for((0,je._)`${m} = ${h}; ${m}--;`,()=>e.if((0,je._)`${y}(${t}[${h}], ${t}[${m}])`,()=>{r.error(),e.assign(c,!1).break(g)})))}}};tf.default=yC});var cb=k(nf=>{"use strict";Object.defineProperty(nf,"__esModule",{value:!0});var rf=U(),gC=Q(),bC=ic(),vC={message:"must be equal to constant",params:({schemaCode:r})=>(0,rf._)`{allowedValue: ${r}}`},wC={keyword:"const",$data:!0,error:vC,code(r){let{gen:e,data:t,$data:n,schemaCode:i,schema:s}=r;n||s&&typeof s=="object"?r.fail$data((0,rf._)`!${(0,gC.useFunc)(e,bC.default)}(${t}, ${i})`):r.fail((0,rf._)`${s} !== ${t}`)}};nf.default=wC});var lb=k(sf=>{"use strict";Object.defineProperty(sf,"__esModule",{value:!0});var lo=U(),_C=Q(),SC=ic(),xC={message:"must be equal to one of the allowed values",params:({schemaCode:r})=>(0,lo._)`{allowedValues: ${r}}`},$C={keyword:"enum",schemaType:"array",$data:!0,error:xC,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,_C.useFunc)(e,SC.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}`}}};sf.default=$C});var af=k(of=>{"use strict";Object.defineProperty(of,"__esModule",{value:!0});var EC=Xg(),kC=Qg(),AC=tb(),PC=rb(),CC=nb(),MC=ib(),RC=sb(),TC=ab(),IC=cb(),OC=lb(),DC=[EC.default,kC.default,AC.default,PC.default,CC.default,MC.default,RC.default,TC.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},IC.default,OC.default];of.default=DC});var lf=k(uo=>{"use strict";Object.defineProperty(uo,"__esModule",{value:!0});uo.validateAdditionalItems=void 0;var oi=U(),cf=Q(),LC={message:({params:{len:r}})=>(0,oi.str)`must NOT have more than ${r} items`,params:({params:{len:r}})=>(0,oi._)`{limit: ${r}}`},NC={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:LC,code(r){let{parentSchema:e,it:t}=r,{items:n}=e;if(!Array.isArray(n)){(0,cf.checkStrictMode)(t,'"additionalItems" is ignored when "items" is not an array of schemas');return}db(r,n)}};function db(r,e){let{gen:t,schema:n,data:i,keyword:s,it:o}=r;o.items=!0;let a=t.const("len",(0,oi._)`${i}.length`);if(n===!1)r.setParams({len:e.length}),r.pass((0,oi._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,cf.alwaysValidSchema)(o,n)){let l=t.var("valid",(0,oi._)`${a} <= ${e.length}`);t.if((0,oi.not)(l),()=>c(l)),r.ok(l)}function c(l){t.forRange("i",e.length,a,u=>{r.subschema({keyword:s,dataProp:u,dataPropType:cf.Type.Num},l),o.allErrors||t.if((0,oi.not)(l),()=>t.break())})}}uo.validateAdditionalItems=db;uo.default=NC});var df=k(fo=>{"use strict";Object.defineProperty(fo,"__esModule",{value:!0});fo.validateTuple=void 0;var ub=U(),sc=Q(),FC=jt(),jC={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(r){let{schema:e,it:t}=r;if(Array.isArray(e))return fb(r,"additionalItems",e);t.items=!0,!(0,sc.alwaysValidSchema)(t,e)&&r.ok((0,FC.validateArray)(r))}};function fb(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=sc.mergeEvaluated.items(n,t.length,a.items));let c=n.name("valid"),l=n.const("len",(0,ub._)`${s}.length`);t.forEach((d,f)=>{(0,sc.alwaysValidSchema)(a,d)||(n.if((0,ub._)`${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,sc.checkStrictMode)(a,y,f.strictTuples)}}}fo.validateTuple=fb;fo.default=jC});var pb=k(uf=>{"use strict";Object.defineProperty(uf,"__esModule",{value:!0});var qC=df(),BC={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:r=>(0,qC.validateTuple)(r,"items")};uf.default=BC});var mb=k(ff=>{"use strict";Object.defineProperty(ff,"__esModule",{value:!0});var hb=U(),UC=Q(),VC=jt(),HC=lf(),zC={message:({params:{len:r}})=>(0,hb.str)`must NOT have more than ${r} items`,params:({params:{len:r}})=>(0,hb._)`{limit: ${r}}`},KC={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:zC,code(r){let{schema:e,parentSchema:t,it:n}=r,{prefixItems:i}=t;n.items=!0,!(0,UC.alwaysValidSchema)(n,e)&&(i?(0,HC.validateAdditionalItems)(r,i):r.ok((0,VC.validateArray)(r)))}};ff.default=KC});var yb=k(pf=>{"use strict";Object.defineProperty(pf,"__esModule",{value:!0});var Bt=U(),oc=Q(),WC={message:({params:{min:r,max:e}})=>e===void 0?(0,Bt.str)`must contain at least ${r} valid item(s)`:(0,Bt.str)`must contain at least ${r} and no more than ${e} valid item(s)`,params:({params:{min:r,max:e}})=>e===void 0?(0,Bt._)`{minContains: ${r}}`:(0,Bt._)`{minContains: ${r}, maxContains: ${e}}`},GC={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:WC,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,Bt._)`${i}.length`);if(r.setParams({min:o,max:a}),a===void 0&&o===0){(0,oc.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&o>a){(0,oc.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),r.fail();return}if((0,oc.alwaysValidSchema)(s,t)){let m=(0,Bt._)`${u} >= ${o}`;a!==void 0&&(m=(0,Bt._)`${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,Bt._)`${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:oc.Type.Num,compositeRule:!0},m),y()})}function h(m){e.code((0,Bt._)`${m}++`),a===void 0?e.if((0,Bt._)`${m} >= ${o}`,()=>e.assign(d,!0).break()):(e.if((0,Bt._)`${m} > ${a}`,()=>e.assign(d,!1).break()),o===1?e.assign(d,!0):e.if((0,Bt._)`${m} >= ${o}`,()=>e.assign(d,!0)))}}};pf.default=GC});var ac=k(_r=>{"use strict";Object.defineProperty(_r,"__esModule",{value:!0});_r.validateSchemaDeps=_r.validatePropertyDeps=_r.error=void 0;var hf=U(),JC=Q(),po=jt();_r.error={message:({params:{property:r,depsCount:e,deps:t}})=>{let n=e===1?"property":"properties";return(0,hf.str)`must have ${n} ${t} when property ${r} is present`},params:({params:{property:r,depsCount:e,deps:t,missingProperty:n}})=>(0,hf._)`{property: ${r}, missingProperty: ${n}, depsCount: ${e}, - deps: ${t}}`};var YC={keyword:"dependencies",type:"object",schemaType:"object",error:_r.error,code(r){let[e,t]=XC(r);gb(r,e),bb(r,t)}};function XC({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 gb(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,hf._)`${c} && (${(0,po.checkMissingProp)(r,a,s)})`),(0,po.reportMissingProp)(r,s),t.else())}}_r.validatePropertyDeps=gb;function bb(r,e=r.schema){let{gen:t,data:n,keyword:i,it:s}=r,o=t.name("valid");for(let a in e)(0,JC.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))}_r.validateSchemaDeps=bb;_r.default=YC});var wb=k(mf=>{"use strict";Object.defineProperty(mf,"__esModule",{value:!0});var vb=U(),QC=Q(),ZC={message:"property name must be valid",params:({params:r})=>(0,vb._)`{propertyName: ${r.propertyName}}`},eM={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:ZC,code(r){let{gen:e,schema:t,data:n,it:i}=r;if((0,QC.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,vb.not)(s),()=>{r.error(!0),i.allErrors||e.break()})}),r.ok(s)}};mf.default=eM});var gf=k(yf=>{"use strict";Object.defineProperty(yf,"__esModule",{value:!0});var cc=jt(),er=U(),tM=Ft(),lc=Q(),rM={message:"must NOT have additional properties",params:({params:r})=>(0,er._)`{additionalProperty: ${r.additionalProperty}}`},nM={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:rM,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,lc.alwaysValidSchema)(o,t))return;let l=(0,cc.allSchemaProperties)(n.properties),u=(0,cc.allSchemaProperties)(n.patternProperties);d(),r.ok((0,er._)`${s} === ${tM.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,lc.schemaRefOrVal)(o,n.properties,"properties");g=(0,cc.isOwnProperty)(e,b,y)}else l.length?g=(0,er.or)(...l.map(b=>(0,er._)`${y} === ${b}`)):g=er.nil;return u.length&&(g=(0,er.or)(g,...u.map(b=>(0,er._)`${(0,cc.usePattern)(r,b)}.test(${y})`))),(0,er.not)(g)}function p(y){e.code((0,er._)`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,lc.alwaysValidSchema)(o,t)){let g=e.name("valid");c.removeAdditional==="failing"?(m(y,g,!1),e.if((0,er.not)(g),()=>{r.reset(),p(y)})):(m(y,g),a||e.if((0,er.not)(g),()=>e.break()))}}function m(y,g,b){let v={keyword:"additionalProperties",dataProp:y,dataPropType:lc.Type.Str};b===!1&&Object.assign(v,{compositeRule:!0,createErrors:!1,allErrors:!1}),r.subschema(v,g)}}};yf.default=nM});var xb=k(vf=>{"use strict";Object.defineProperty(vf,"__esModule",{value:!0});var iM=Ni(),_b=jt(),bf=Q(),Sb=gf(),sM={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&&Sb.default.code(new iM.KeywordCxt(s,Sb.default,"additionalProperties"));let o=(0,_b.allSchemaProperties)(t);for(let d of o)s.definedProperties.add(d);s.opts.unevaluated&&o.length&&s.props!==!0&&(s.props=bf.mergeEvaluated.props(e,(0,bf.toHash)(o),s.props));let a=o.filter(d=>!(0,bf.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,_b.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)}}};vf.default=sM});var Ab=k(wf=>{"use strict";Object.defineProperty(wf,"__esModule",{value:!0});var $b=jt(),dc=U(),Eb=Q(),kb=Q(),oM={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,$b.allSchemaProperties)(t),c=a.filter(m=>(0,Eb.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 dc.Name)&&(s.props=(0,kb.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,Eb.checkStrictMode)(s,`property ${y} matches pattern ${m} (use allowMatchingProperties)`)}function h(m){e.forIn("key",n,y=>{e.if((0,dc._)`${(0,$b.usePattern)(r,m)}.test(${y})`,()=>{let g=c.includes(m);g||r.subschema({keyword:"patternProperties",schemaProp:m,dataProp:y,dataPropType:kb.Type.Str},u),s.opts.unevaluated&&d!==!0?e.assign((0,dc._)`${d}[${y}]`,!0):!g&&!s.allErrors&&e.if((0,dc.not)(u),()=>e.break())})})}}};wf.default=oM});var Pb=k(_f=>{"use strict";Object.defineProperty(_f,"__esModule",{value:!0});var aM=Q(),cM={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(r){let{gen:e,schema:t,it:n}=r;if((0,aM.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"}};_f.default=cM});var Cb=k(Sf=>{"use strict";Object.defineProperty(Sf,"__esModule",{value:!0});var lM=jt(),dM={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:lM.validateUnion,error:{message:"must match a schema in anyOf"}};Sf.default=dM});var Mb=k(xf=>{"use strict";Object.defineProperty(xf,"__esModule",{value:!0});var uc=U(),uM=Q(),fM={message:"must match exactly one schema in oneOf",params:({params:r})=>(0,uc._)`{passingSchemas: ${r.passing}}`},pM={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:fM,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,uM.alwaysValidSchema)(i,u)?e.var(c,!0):f=r.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,uc._)`${c} && ${o}`).assign(o,!1).assign(a,(0,uc._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(o,!0),e.assign(a,d),f&&r.mergeEvaluated(f,uc.Name)})})}}};xf.default=pM});var Rb=k($f=>{"use strict";Object.defineProperty($f,"__esModule",{value:!0});var hM=Q(),mM={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,hM.alwaysValidSchema)(n,s))return;let a=r.subschema({keyword:"allOf",schemaProp:o},i);r.ok(i),r.mergeEvaluated(a)})}};$f.default=mM});var Ob=k(Ef=>{"use strict";Object.defineProperty(Ef,"__esModule",{value:!0});var fc=U(),Ib=Q(),yM={message:({params:r})=>(0,fc.str)`must match "${r.ifClause}" schema`,params:({params:r})=>(0,fc._)`{failingKeyword: ${r.ifClause}}`},gM={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:yM,code(r){let{gen:e,parentSchema:t,it:n}=r;t.then===void 0&&t.else===void 0&&(0,Ib.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let i=Tb(n,"then"),s=Tb(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,fc.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,fc._)`${u}`):r.setParams({ifClause:u})}}}};function Tb(r,e){let t=r.schema[e];return t!==void 0&&!(0,Ib.alwaysValidSchema)(r,t)}Ef.default=gM});var Db=k(kf=>{"use strict";Object.defineProperty(kf,"__esModule",{value:!0});var bM=Q(),vM={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:r,parentSchema:e,it:t}){e.if===void 0&&(0,bM.checkStrictMode)(t,`"${r}" without "if" is ignored`)}};kf.default=vM});var Pf=k(Af=>{"use strict";Object.defineProperty(Af,"__esModule",{value:!0});var wM=lf(),_M=pb(),SM=df(),xM=mb(),$M=yb(),EM=ac(),kM=wb(),AM=gf(),PM=xb(),CM=Ab(),MM=Pb(),RM=Cb(),TM=Mb(),IM=Rb(),OM=Ob(),DM=Db();function NM(r=!1){let e=[MM.default,RM.default,TM.default,IM.default,OM.default,DM.default,kM.default,AM.default,EM.default,PM.default,CM.default];return r?e.push(_M.default,xM.default):e.push(wM.default,SM.default),e.push($M.default),e}Af.default=NM});var Mf=k(ho=>{"use strict";Object.defineProperty(ho,"__esModule",{value:!0});ho.dynamicAnchor=void 0;var Cf=U(),LM=Ft(),Nb=Qs(),FM=tc(),jM={keyword:"$dynamicAnchor",schemaType:"string",code:r=>Lb(r,r.schema)};function Lb(r,e){let{gen:t,it:n}=r;n.schemaEnv.root.dynamicAnchors[e]=!0;let i=(0,Cf._)`${LM.default.dynamicAnchors}${(0,Cf.getProperty)(e)}`,s=n.errSchemaPath==="#"?n.validateName:qM(r);t.if((0,Cf._)`!${i}`,()=>t.assign(i,s))}ho.dynamicAnchor=Lb;function qM(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 Nb.SchemaEnv({schema:t,schemaId:c,root:i,baseId:s,localRefs:o,meta:a});return Nb.compileSchema.call(n,l),(0,FM.getValidate)(r,l)}ho.default=jM});var Rf=k(mo=>{"use strict";Object.defineProperty(mo,"__esModule",{value:!0});mo.dynamicRef=void 0;var Fb=U(),BM=Ft(),jb=tc(),UM={keyword:"$dynamicRef",schemaType:"string",code:r=>qb(r,r.schema)};function qb(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,Fb._)`${BM.default.dynamicAnchors}${(0,Fb.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,jb.callRef)(r,c),t.let(l,!0)}):()=>(0,jb.callRef)(r,c)}}mo.dynamicRef=qb;mo.default=UM});var Bb=k(Tf=>{"use strict";Object.defineProperty(Tf,"__esModule",{value:!0});var VM=Mf(),HM=Q(),zM={keyword:"$recursiveAnchor",schemaType:"boolean",code(r){r.schema?(0,VM.dynamicAnchor)(r,""):(0,HM.checkStrictMode)(r.it,"$recursiveAnchor: false is ignored")}};Tf.default=zM});var Ub=k(If=>{"use strict";Object.defineProperty(If,"__esModule",{value:!0});var KM=Rf(),WM={keyword:"$recursiveRef",schemaType:"string",code:r=>(0,KM.dynamicRef)(r,r.schema)};If.default=WM});var Vb=k(Of=>{"use strict";Object.defineProperty(Of,"__esModule",{value:!0});var GM=Mf(),JM=Rf(),YM=Bb(),XM=Ub(),QM=[GM.default,JM.default,YM.default,XM.default];Of.default=QM});var zb=k(Df=>{"use strict";Object.defineProperty(Df,"__esModule",{value:!0});var Hb=ac(),ZM={keyword:"dependentRequired",type:"object",schemaType:"object",error:Hb.error,code:r=>(0,Hb.validatePropertyDeps)(r)};Df.default=ZM});var Kb=k(Nf=>{"use strict";Object.defineProperty(Nf,"__esModule",{value:!0});var e1=ac(),t1={keyword:"dependentSchemas",type:"object",schemaType:"object",code:r=>(0,e1.validateSchemaDeps)(r)};Nf.default=t1});var Wb=k(Lf=>{"use strict";Object.defineProperty(Lf,"__esModule",{value:!0});var r1=Q(),n1={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword:r,parentSchema:e,it:t}){e.contains===void 0&&(0,r1.checkStrictMode)(t,`"${r}" without "contains" is ignored`)}};Lf.default=n1});var Gb=k(Ff=>{"use strict";Object.defineProperty(Ff,"__esModule",{value:!0});var i1=zb(),s1=Kb(),o1=Wb(),a1=[i1.default,s1.default,o1.default];Ff.default=a1});var Yb=k(jf=>{"use strict";Object.defineProperty(jf,"__esModule",{value:!0});var yn=U(),Jb=Q(),c1=Ft(),l1={message:"must NOT have unevaluated properties",params:({params:r})=>(0,yn._)`{unevaluatedProperty: ${r.unevaluatedProperty}}`},d1={keyword:"unevaluatedProperties",type:"object",schemaType:["boolean","object"],trackErrors:!0,error:l1,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 yn.Name?e.if((0,yn._)`${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,yn._)`${i} === ${c1.default.errors}`);function c(d){if(t===!1){r.setParams({unevaluatedProperty:d}),r.error(),o||e.break();return}if(!(0,Jb.alwaysValidSchema)(s,t)){let f=e.name("valid");r.subschema({keyword:"unevaluatedProperties",dataProp:d,dataPropType:Jb.Type.Str},f),o||e.if((0,yn.not)(f),()=>e.break())}}function l(d,f){return(0,yn._)`!${d} || !${d}[${f}]`}function u(d,f){let p=[];for(let h in d)d[h]===!0&&p.push((0,yn._)`${f} !== ${h}`);return(0,yn.and)(...p)}}};jf.default=d1});var Qb=k(qf=>{"use strict";Object.defineProperty(qf,"__esModule",{value:!0});var ai=U(),Xb=Q(),u1={message:({params:{len:r}})=>(0,ai.str)`must NOT have more than ${r} items`,params:({params:{len:r}})=>(0,ai._)`{limit: ${r}}`},f1={keyword:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error:u1,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,ai._)`${n}.length`);if(t===!1)r.setParams({len:s}),r.fail((0,ai._)`${o} > ${s}`);else if(typeof t=="object"&&!(0,Xb.alwaysValidSchema)(i,t)){let c=e.var("valid",(0,ai._)`${o} <= ${s}`);e.if((0,ai.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:Xb.Type.Num},c),i.allErrors||e.if((0,ai.not)(c),()=>e.break())})}}};qf.default=f1});var Zb=k(Bf=>{"use strict";Object.defineProperty(Bf,"__esModule",{value:!0});var p1=Yb(),h1=Qb(),m1=[p1.default,h1.default];Bf.default=m1});var ev=k(Uf=>{"use strict";Object.defineProperty(Uf,"__esModule",{value:!0});var xe=U(),y1={message:({schemaCode:r})=>(0,xe.str)`must match format "${r}"`,params:({schemaCode:r})=>(0,xe._)`{format: ${r}}`},g1={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:y1,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,xe._)`${h}[${o}]`),y=t.let("fType"),g=t.let("format");t.if((0,xe._)`typeof ${m} == "object" && !(${m} instanceof RegExp)`,()=>t.assign(y,(0,xe._)`${m}.type || "string"`).assign(g,(0,xe._)`${m}.validate`),()=>t.assign(y,(0,xe._)`"string"`).assign(g,m)),r.fail$data((0,xe.or)(b(),v()));function b(){return c.strictSchema===!1?xe.nil:(0,xe._)`${o} && !${g}`}function v(){let S=u.$async?(0,xe._)`(${m}.async ? await ${g}(${n}) : ${g}(${n}))`:(0,xe._)`${g}(${n})`,_=(0,xe._)`(typeof ${g} == "function" ? ${S} : ${g}.test(${n}))`;return(0,xe._)`${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,xe.regexpCode)(_):c.code.formats?(0,xe._)`${c.code.formats}${(0,xe.getProperty)(s)}`:void 0,A=t.scopeValue("formats",{key:s,ref:_,code:E});return typeof _=="object"&&!(_ instanceof RegExp)?[_.type||"string",_.validate,(0,xe._)`${A}.validate`]:["string",_,A]}function S(){if(typeof h=="object"&&!(h instanceof RegExp)&&h.async){if(!u.$async)throw new Error("async format in sync schema");return(0,xe._)`await ${g}(${n})`}return typeof y=="function"?(0,xe._)`${g}(${n})`:(0,xe._)`${g}.test(${n})`}}}};Uf.default=g1});var Hf=k(Vf=>{"use strict";Object.defineProperty(Vf,"__esModule",{value:!0});var b1=ev(),v1=[b1.default];Vf.default=v1});var zf=k(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 rv=k(Kf=>{"use strict";Object.defineProperty(Kf,"__esModule",{value:!0});var w1=Hu(),_1=af(),S1=Pf(),x1=Vb(),$1=Gb(),E1=Zb(),k1=Hf(),tv=zf(),A1=[x1.default,w1.default,_1.default,(0,S1.default)(!0),k1.default,tv.metadataVocabulary,tv.contentVocabulary,$1.default,E1.default];Kf.default=A1});var iv=k(pc=>{"use strict";Object.defineProperty(pc,"__esModule",{value:!0});pc.DiscrError=void 0;var nv;(function(r){r.Tag="tag",r.Mapping="mapping"})(nv||(pc.DiscrError=nv={}))});var Jf=k(Gf=>{"use strict";Object.defineProperty(Gf,"__esModule",{value:!0});var Vi=U(),Wf=iv(),sv=Qs(),P1=Li(),C1=Q(),M1={message:({params:{discrError:r,tagName:e}})=>r===Wf.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}}`},R1={keyword:"discriminator",type:"object",schemaType:"object",error:M1,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:Wf.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:Wf.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{T1.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 av=k((zq,I1)=>{I1.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 cv=k((Kq,O1)=>{O1.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 lv=k((Wq,D1)=>{D1.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 dv=k((Gq,N1)=>{N1.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 uv=k((Jq,L1)=>{L1.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 fv=k((Yq,F1)=>{F1.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 pv=k((Xq,j1)=>{j1.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 hv=k(Yf=>{"use strict";Object.defineProperty(Yf,"__esModule",{value:!0});var q1=ov(),B1=av(),U1=cv(),V1=lv(),H1=dv(),z1=uv(),K1=fv(),W1=pv(),G1=["/properties"];function J1(r){return[q1,B1,U1,V1,H1,e(this,z1),K1,e(this,W1)].forEach(t=>this.addMetaSchema(t,void 0,!1)),this;function e(t,n){return r?t.$dataMetaSchema(n,G1):n}}Yf.default=J1});var Zf=k((ye,Qf)=>{"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 Y1=Bu(),X1=rv(),Q1=Jf(),Z1=hv(),Xf="https://json-schema.org/draft/2020-12/schema",Hi=class extends Y1.default{constructor(e={}){super({...e,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){super._addVocabularies(),X1.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(Q1.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data:e,meta:t}=this.opts;t&&(Z1.default.call(this,e),this.refs["http://json-schema.org/schema"]=Xf)}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Xf)?Xf:void 0)}};ye.Ajv2020=Hi;Qf.exports=ye=Hi;Qf.exports.Ajv2020=Hi;Object.defineProperty(ye,"__esModule",{value:!0});ye.default=Hi;var eR=Ni();Object.defineProperty(ye,"KeywordCxt",{enumerable:!0,get:function(){return eR.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 tR=Xs();Object.defineProperty(ye,"ValidationError",{enumerable:!0,get:function(){return tR.default}});var rR=Li();Object.defineProperty(ye,"MissingRefError",{enumerable:!0,get:function(){return rR.default}})});var Sv=k(xr=>{"use strict";Object.defineProperty(xr,"__esModule",{value:!0});xr.formatNames=xr.fastFormats=xr.fullFormats=void 0;function Sr(r,e){return{validate:r,compare:e}}xr.fullFormats={date:Sr(bv,np),time:Sr(tp(!0),ip),"date-time":Sr(mv(!0),wv),"iso-time":Sr(tp(),vv),"iso-date-time":Sr(mv(),_v),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:cR,"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:mR,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:lR,int32:{type:"number",validate:fR},int64:{type:"number",validate:pR},float:{type:"number",validate:gv},double:{type:"number",validate:gv},password:!0,binary:!0};xr.fastFormats={...xr.fullFormats,date:Sr(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,np),time:Sr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,ip),"date-time":Sr(/^\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,wv),"iso-time":Sr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,vv),"iso-date-time":Sr(/^\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,_v),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};xr.formatNames=Object.keys(xr.fullFormats);function nR(r){return r%4===0&&(r%100!==0||r%400===0)}var iR=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,sR=[0,31,28,31,30,31,30,31,31,30,31,30,31];function bv(r){let e=iR.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&&nR(t)?29:sR[n])}function np(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 ip(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 vv(r,e){if(!(r&&e))return;let t=ep.exec(r),n=ep.exec(e);if(t&&n)return r=t[1]+t[2]+t[3],e=n[1]+n[2]+n[3],r>e?1:r=dR}function pR(r){return Number.isInteger(r)}function gv(){return!0}var hR=/[^\\]\\Z/;function mR(r){if(hR.test(r))return!1;try{return new RegExp(r),!0}catch{return!1}}});var $v=k(sp=>{"use strict";Object.defineProperty(sp,"__esModule",{value:!0});var yR=Hu(),gR=af(),bR=Pf(),vR=Hf(),xv=zf(),wR=[yR.default,gR.default,(0,bR.default)(),vR.default,xv.metadataVocabulary,xv.contentVocabulary];sp.default=wR});var Ev=k((tB,_R)=>{_R.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 Av=k((ge,op)=>{"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 SR=Bu(),xR=$v(),$R=Jf(),kv=Ev(),ER=["/properties"],hc="http://json-schema.org/draft-07/schema",Ki=class extends SR.default{_addVocabularies(){super._addVocabularies(),xR.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword($R.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(kv,ER):kv;this.addMetaSchema(e,hc,!1),this.refs["http://json-schema.org/schema"]=hc}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(hc)?hc:void 0)}};ge.Ajv=Ki;op.exports=ge=Ki;op.exports.Ajv=Ki;Object.defineProperty(ge,"__esModule",{value:!0});ge.default=Ki;var kR=Ni();Object.defineProperty(ge,"KeywordCxt",{enumerable:!0,get:function(){return kR.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 AR=Xs();Object.defineProperty(ge,"ValidationError",{enumerable:!0,get:function(){return AR.default}});var PR=Li();Object.defineProperty(ge,"MissingRefError",{enumerable:!0,get:function(){return PR.default}})});var Pv=k(Gi=>{"use strict";Object.defineProperty(Gi,"__esModule",{value:!0});Gi.formatLimitDefinition=void 0;var CR=Av(),tr=U(),gn=tr.operators,mc={formatMaximum:{okStr:"<=",ok:gn.LTE,fail:gn.GT},formatMinimum:{okStr:">=",ok:gn.GTE,fail:gn.LT},formatExclusiveMaximum:{okStr:"<",ok:gn.LT,fail:gn.GTE},formatExclusiveMinimum:{okStr:">",ok:gn.GT,fail:gn.LTE}},MR={message:({keyword:r,schemaCode:e})=>(0,tr.str)`should be ${mc[r].okStr} ${e}`,params:({keyword:r,schemaCode:e})=>(0,tr._)`{comparison: ${mc[r].okStr}, limit: ${e}}`};Gi.formatLimitDefinition={keyword:Object.keys(mc),type:"string",schemaType:"string",$data:!0,error:MR,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 CR.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,tr._)`${f}[${c.schemaCode}]`);r.fail$data((0,tr.or)((0,tr._)`typeof ${p} != "object"`,(0,tr._)`${p} instanceof RegExp`,(0,tr._)`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,tr._)`${o.code.formats}${(0,tr.getProperty)(f)}`:void 0});r.fail$data(d(h))}function d(f){return(0,tr._)`${f}.compare(${t}, ${n}) ${mc[i].fail} 0`}},dependencies:["format"]};var RR=r=>(r.addKeyword(Gi.formatLimitDefinition),r);Gi.default=RR});var lp=k((yo,Rv)=>{"use strict";Object.defineProperty(yo,"__esModule",{value:!0});var Ji=Sv(),TR=Pv(),ap=U(),Cv=new ap.Name("fullFormats"),IR=new ap.Name("fastFormats"),cp=(r,e={keywords:!0})=>{if(Array.isArray(e))return Mv(r,e,Ji.fullFormats,Cv),r;let[t,n]=e.mode==="fast"?[Ji.fastFormats,IR]:[Ji.fullFormats,Cv],i=e.formats||Ji.formatNames;return Mv(r,i,t,n),e.keywords&&(0,TR.default)(r),r};cp.get=(r,e="full")=>{let n=(e==="fast"?Ji.fastFormats:Ji.fullFormats)[r];if(!n)throw new Error(`Unknown format "${r}"`);return n};function Mv(r,e,t,n){var i,s;(i=(s=r.opts.code).formats)!==null&&i!==void 0||(s.formats=(0,ap._)`require("ajv-formats/dist/formats").${n}`);for(let o of e)r.addFormat(o,t[o])}Rv.exports=yo=cp;Object.defineProperty(yo,"__esModule",{value:!0});yo.default=cp});var go=k((nB,Nv)=>{"use strict";var Tv="[^\\\\/]",OR="(?=.)",Iv="[^/]",dp="(?:\\/|$)",Ov="(?:^|\\/)",up=`\\.{1,2}${dp}`,DR="(?!\\.)",NR=`(?!${Ov}${up})`,LR=`(?!\\.{0,1}${dp})`,FR=`(?!${up})`,jR="[^.\\/]",qR=`${Iv}*?`,BR="/",Dv={DOT_LITERAL:"\\.",PLUS_LITERAL:"\\+",QMARK_LITERAL:"\\?",SLASH_LITERAL:"\\/",ONE_CHAR:OR,QMARK:Iv,END_ANCHOR:dp,DOTS_SLASH:up,NO_DOT:DR,NO_DOTS:NR,NO_DOT_SLASH:LR,NO_DOTS_SLASH:FR,QMARK_NO_DOT:jR,STAR:qR,START_ANCHOR:Ov,SEP:BR},UR={...Dv,SLASH_LITERAL:"[\\\\/]",QMARK:Tv,STAR:`${Tv}*?`,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:"\\"},VR={__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"};Nv.exports={DEFAULT_MAX_EXTGLOB_RECURSION:0,MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:VR,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?UR:Dv}}});var bo=k(yt=>{"use strict";var{REGEX_BACKSLASH:HR,REGEX_REMOVE_BACKSLASH:zR,REGEX_SPECIAL_CHARS:KR,REGEX_SPECIAL_CHARS_GLOBAL:WR}=go();yt.isObject=r=>r!==null&&typeof r=="object"&&!Array.isArray(r);yt.hasRegexChars=r=>KR.test(r);yt.isRegexChar=r=>r.length===1&&yt.hasRegexChars(r);yt.escapeRegex=r=>r.replace(WR,"\\$1");yt.toPosixSlashes=r=>r.replace(HR,"/");yt.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};yt.removeBackslashes=r=>r.replace(zR,e=>e==="\\"?"":e);yt.escapeLast=(r,e,t)=>{let n=r.lastIndexOf(e,t);return n===-1?r:r[n-1]==="\\"?yt.escapeLast(r,e,n-1):`${r.slice(0,n)}\\${r.slice(n)}`};yt.removePrefix=(r,e={})=>{let t=r;return t.startsWith("./")&&(t=t.slice(2),e.prefix="./"),t};yt.wrapOutput=(r,e={},t={})=>{let n=t.contains?"":"^",i=t.contains?"":"$",s=`${n}(?:${r})${i}`;return e.negated===!0&&(s=`(?:^(?!${s}).*$)`),s};yt.basename=(r,{windows:e}={})=>{let t=r.split(e?/[\\/]/:"/"),n=t[t.length-1];return n===""?t[t.length-2]:n}});var Hv=k((sB,Vv)=>{"use strict";var Lv=bo(),{CHAR_ASTERISK:fp,CHAR_AT:GR,CHAR_BACKWARD_SLASH:Yi,CHAR_COMMA:JR,CHAR_DOT:pp,CHAR_EXCLAMATION_MARK:hp,CHAR_FORWARD_SLASH:Uv,CHAR_LEFT_CURLY_BRACE:mp,CHAR_LEFT_PARENTHESES:yc,CHAR_LEFT_SQUARE_BRACKET:YR,CHAR_PLUS:XR,CHAR_QUESTION_MARK:Fv,CHAR_RIGHT_CURLY_BRACE:QR,CHAR_RIGHT_PARENTHESES:jv,CHAR_RIGHT_SQUARE_BRACKET:ZR}=go(),qv=r=>r===Uv||r===Yi,Bv=r=>{r.isPrefix!==!0&&(r.depth=r.isGlobstar?1/0:1)},eT=(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,A,x,R={value:"",depth:0,isGlob:!1},$=()=>l>=n,q=()=>c.charCodeAt(l+1),M=()=>(A=x,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&&qv(V.charCodeAt(V.length-1))&&(V=V.slice(0,-1)),t.unescape===!0&&(C&&(C=Lv.removeBackslashes(C)),V&&b===!0&&(V=Lv.removeBackslashes(V)));let Ve={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&&(Ve.maxDepth=0,qv(x)||o.push(R),Ve.tokens=o),t.parts===!0||t.tokens===!0){let ce;for(let Ae=0;Ae=u&&(a.push(zn),ce=Ns)}let dt=ce!==void 0?ce+1:u,kt=r.slice(dt);a.push(kt),t.tokens&&ce&&ce+1{"use strict";var vo=go(),At=bo(),{MAX_LENGTH:gc,POSIX_REGEX_SOURCE:tT,REGEX_NON_SPECIAL_CHARS:rT,REGEX_SPECIAL_CHARS_BACKREF:nT,REPLACEMENTS:zv}=vo,iT=(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=>At.escapeRegex(i)).join("..")}return t},Xi=(r,e)=>`Missing ${r}: "${e}" - use "\\\\${e}" to match literal characters`,Kv=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},sT=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},gp=r=>{let e=r.trim(),t=!0;for(;t===!0;)t=!1,/^@\([^\\()[\]{}|]+\)$/.test(e)&&(e=e.slice(2,-1),t=!0);if(sT(e))return e.replace(/\\(.)/g,"$1")},oT=r=>{let e=r.map(gp).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}}}}},aT=r=>`${r.length===1?At.escapeRegex(r[0]):`[${r.map(t=>At.escapeRegex(t)).join("")}]`}*`,cT=r=>{let e=0,t=[];for(;eo.trim());if(i.length!==1)return;let s=gp(i[0]);if(!s||s.length!==1)return;t.push(s),e+=n.end+1}if(!(t.length<1))return t},lT=r=>{let e=0,t=r.trim(),n=yp(t);for(;n;)e++,t=n.body.trim(),n=yp(t);return e},dT=(r,e)=>{if(e.maxExtglobRecursion===!1)return{risky:!1};let t=typeof e.maxExtglobRecursion=="number"?e.maxExtglobRecursion:vo.DEFAULT_MAX_EXTGLOB_RECURSION,n=Kv(r).map(a=>a.trim());if(n.length>1&&(n.some(a=>a==="")||n.some(a=>/^[*?]+$/.test(a))||oT(n)))return{risky:!0};let i=[],s=!1,o=!0;for(let a of n){let c=cT(a);if(c){s=!0,i.push(...c);continue}let l=gp(a);if(l&&l.length===1){i.push(l);continue}if(o=!1,lT(a)>t)return{risky:!0}}return s?o?{risky:!0,safeOutput:aT([...new Set(i)])}:{risky:!0}:{risky:!1}},bp=(r,e)=>{if(typeof r!="string")throw new TypeError("Expected a string");r=zv[r]||r;let t={...e},n=typeof t.maxLength=="number"?Math.min(gc,t.maxLength):gc,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}).)*?)`,A=t.dot?"":m,x=t.dot?b:v,R=t.bash===!0?E(t):S;t.capture&&(R=`(${R})`),typeof t.noext=="boolean"&&(t.noextglob=t.noext);let $={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=At.removePrefix(r,$),i=r.length;let q=[],M=[],V=[],P=s,C,Ve=()=>$.index===i-1,ce=$.peek=(I=1)=>r[$.index+I],dt=$.advance=()=>r[++$.index]||"",kt=()=>r.slice($.index+1),Ae=(I="",ve=0)=>{$.consumed+=I,$.index+=ve},ki=I=>{$.output+=I.output!=null?I.output:I.value,Ae(I.value)},Ns=()=>{let I=1;for(;ce()==="!"&&(ce(2)!=="("||ce(3)==="?");)dt(),$.start++,I++;return I%2===0?!1:($.negated=!0,$.start++,!0)},zn=I=>{$[I]++,V.push(I)},cn=I=>{$[I]--,V.pop()},Z=I=>{if(P.type==="globstar"){let ve=$.braces>0&&(I.type==="comma"||I.type==="brace"),T=I.extglob===!0||q.length&&(I.type==="pipe"||I.type==="paren");I.type!=="slash"&&I.type!=="paren"&&!ve&&!T&&($.output=$.output.slice(0,-P.output.length),P.type="star",P.value="*",P.output=R,$.output+=P.output)}if(q.length&&I.type!=="paren"&&(q[q.length-1].inner+=I.value),(I.value||I.output)&&ki(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},Ca=(I,ve)=>{let T={...l[ve],conditions:1,inner:""};T.prev=P,T.parens=$.parens,T.output=$.output,T.startIndex=$.index,T.tokensIndex=o.length;let ee=(t.capture?"(":"")+T.open;zn("parens"),Z({type:I,value:ve,output:$.output?"":p}),Z({type:"paren",extglob:!0,value:dt(),output:ee}),q.push(T)},Z$=I=>{let ve=r.slice(I.startIndex,$.index+1),T=r.slice(I.startIndex+2,$.index),ee=dT(T,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,gr=o[I.tokensIndex];gr.type="text",gr.value=ve,gr.output=ue||At.escapeRegex(ve);for(let Kn=I.tokensIndex+1;Kn1&&I.inner.includes("/")&&(ue=E(t)),(ue!==R||Ve()||/^\)+$/.test(kt()))&&(he=I.close=`)$))${ue}`),I.inner.includes("*")&&(Pe=kt())&&/^\.[^\\/.]+$/.test(Pe)){let gr=bp(Pe,{...e,fastpaths:!1}).output;he=I.close=`)${gr})${ue})`}I.prev.type==="bos"&&($.negatedExtglob=!0)}Z({type:"paren",extglob:!0,value:C,output:he}),cn("parens")};if(t.fastpaths!==!1&&!/(^[*!]|[/()[\]{}"])/.test(r)){let I=!1,ve=r.replace(nT,(T,ee,he,Pe,ue,gr)=>Pe==="\\"?(I=!0,T):Pe==="?"?ee?ee+Pe+(ue?b.repeat(ue.length):""):gr===0?x+(ue?b.repeat(ue.length):""):b.repeat(he.length):Pe==="."?u.repeat(he.length):Pe==="*"?ee?ee+Pe+(ue?R:""):R:ee?T:`\\${T}`);return I===!0&&(t.unescape===!0?ve=ve.replace(/\\/g,""):ve=ve.replace(/\\+/g,T=>T.length%2===0?"\\\\":T?"\\":"")),ve===r&&t.contains===!0?($.output=r,$):($.output=At.wrapOutput(ve,$,e),$)}for(;!Ve();){if(C=dt(),C==="\0")continue;if(C==="\\"){let T=ce();if(T==="/"&&t.bash!==!0||T==="."||T===";")continue;if(!T){C+="\\",Z({type:"text",value:C});continue}let ee=/^\\+/.exec(kt()),he=0;if(ee&&ee[0].length>2&&(he=ee[0].length,$.index+=he,he%2!==0&&(C+="\\")),t.unescape===!0?C=dt():C+=dt(),$.brackets===0){Z({type:"text",value:C});continue}}if($.brackets>0&&(C!=="]"||P.value==="["||P.value==="[^")){if(t.posix!==!1&&C===":"){let T=P.value.slice(1);if(T.includes("[")&&(P.posix=!0,T.includes(":"))){let ee=P.value.lastIndexOf("["),he=P.value.slice(0,ee),Pe=P.value.slice(ee+2),ue=tT[Pe];if(ue){P.value=he+ue,$.backtrack=!0,dt(),!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,ki({value:C});continue}if($.quotes===1&&C!=='"'){C=At.escapeRegex(C),P.value+=C,ki({value:C});continue}if(C==='"'){$.quotes=$.quotes===1?0:1,t.keepQuotes===!0&&Z({type:"text",value:C});continue}if(C==="("){zn("parens"),Z({type:"paren",value:C});continue}if(C===")"){if($.parens===0&&t.strictBrackets===!0)throw new SyntaxError(Xi("opening","("));let T=q[q.length-1];if(T&&$.parens===T.parens+1){Z$(q.pop());continue}Z({type:"paren",value:C,output:$.parens?")":"\\)"}),cn("parens");continue}if(C==="["){if(t.nobracket===!0||!kt().includes("]")){if(t.nobracket!==!0&&t.strictBrackets===!0)throw new SyntaxError(Xi("closing","]"));C=`\\${C}`}else zn("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($.brackets===0){if(t.strictBrackets===!0)throw new SyntaxError(Xi("opening","["));Z({type:"text",value:C,output:`\\${C}`});continue}cn("brackets");let T=P.value.slice(1);if(P.posix!==!0&&T[0]==="^"&&!T.includes("/")&&(C=`/${C}`),P.value+=C,ki({value:C}),t.literalBrackets===!1||At.hasRegexChars(T))continue;let ee=At.escapeRegex(P.value);if($.output=$.output.slice(0,-P.value.length),t.literalBrackets===!0){$.output+=ee,P.value=ee;continue}P.value=`(${a}${ee}|${P.value})`,$.output+=P.value;continue}if(C==="{"&&t.nobrace!==!0){zn("braces");let T={type:"brace",value:C,output:"(",outputIndex:$.output.length,tokensIndex:$.tokens.length};M.push(T),Z(T);continue}if(C==="}"){let T=M[M.length-1];if(t.nobrace===!0||!T){Z({type:"text",value:C,output:C});continue}let ee=")";if(T.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=iT(Pe,t),$.backtrack=!0}if(T.comma!==!0&&T.dots!==!0){let he=$.output.slice(0,T.outputIndex),Pe=$.tokens.slice(T.tokensIndex);T.value=T.output="\\{",C=ee="\\}",$.output=he;for(let ue of Pe)$.output+=ue.output||ue.value}Z({type:"brace",value:C,output:ee}),cn("braces"),M.pop();continue}if(C==="|"){q.length>0&&q[q.length-1].conditions++,Z({type:"text",value:C});continue}if(C===","){let T=C,ee=M[M.length-1];ee&&V[V.length-1]==="braces"&&(ee.comma=!0,T="|"),Z({type:"comma",value:C,output:T});continue}if(C==="/"){if(P.type==="dot"&&$.index===$.start+1){$.start=$.index+1,$.consumed="",$.output="",o.pop(),P=s;continue}Z({type:"slash",value:C,output:f});continue}if(C==="."){if($.braces>0&&P.type==="dot"){P.value==="."&&(P.output=u);let T=M[M.length-1];P.type="dots",P.output+=C,P.value+=C,T.dots=!0;continue}if($.braces+$.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)!=="?"){Ca("qmark",C);continue}if(P&&P.type==="paren"){let ee=ce(),he=C;(P.value==="("&&!/[!=<:]/.test(ee)||ee==="<"&&!/<([!=]|\w+>)/.test(kt()))&&(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)))){Ca("negate",C);continue}if(t.nonegate!==!0&&$.index===0){Ns();continue}}if(C==="+"){if(t.noextglob!==!0&&ce()==="("&&ce(2)!=="?"){Ca("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")||$.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 T=rT.exec(kt());T&&(C+=T[0],$.index+=T[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=R,$.backtrack=!0,$.globstar=!0,Ae(C);continue}let I=kt();if(t.noextglob!==!0&&/^\([^?]/.test(I)){Ca("star",C);continue}if(P.type==="star"){if(t.noglobstar===!0){Ae(C);continue}let T=P.prev,ee=T.prev,he=T.type==="slash"||T.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=$.braces>0&&(T.type==="comma"||T.type==="brace"),gr=q.length&&(T.type==="pipe"||T.type==="paren");if(!he&&T.type!=="paren"&&!ue&&!gr){Z({type:"star",value:C,output:""});continue}for(;I.slice(0,3)==="/**";){let Ai=r[$.index+4];if(Ai&&Ai!=="/")break;I=I.slice(3),Ae("/**",3)}let Kn=Ve()||$.parens>0&&I===")".repeat($.parens)&&!q.some(Ai=>Ai.type==="negate");if(T.type==="bos"&&Ve()){P.type="globstar",P.value+=C,P.output=E(t),$.output=P.output,$.globstar=!0,Ae(C);continue}if(T.type==="slash"&&T.prev.type!=="bos"&&!Pe&&Kn){$.output=$.output.slice(0,-(T.output+P.output).length),T.output=`(?:${T.output}`,P.type="globstar",P.output=E(t)+(t.strictSlashes?")":"|$)"),P.value+=C,$.globstar=!0,$.output+=T.output+P.output,Ae(C);continue}if(T.type==="slash"&&T.prev.type!=="bos"&&I[0]==="/"){let Ai=I[1]!==void 0?"|$":"";$.output=$.output.slice(0,-(T.output+P.output).length),T.output=`(?:${T.output}`,P.type="globstar",P.output=`${E(t)}${f}|${f}${Ai})`,P.value+=C,$.output+=T.output+P.output,$.globstar=!0,Ae(C+dt()),Z({type:"slash",value:"/",output:""});continue}if(T.type==="bos"&&I[0]==="/"){P.type="globstar",P.value+=C,P.output=`(?:^|${f}|${E(t)}${f})`,$.output=P.output,$.globstar=!0,Ae(C+dt()),Z({type:"slash",value:"/",output:""});continue}$.output=$.output.slice(0,-P.output.length),P.type="globstar",P.output=E(t),P.value+=C,$.output+=P.output,$.globstar=!0,Ae(C);continue}let ve={type:"star",value:C,output:R};if(t.bash===!0){ve.output=".*?",(P.type==="bos"||P.type==="slash")&&(ve.output=A+ve.output),Z(ve);continue}if(P&&(P.type==="bracket"||P.type==="paren")&&t.regex===!0){ve.output=C,Z(ve);continue}($.index===$.start||P.type==="slash"||P.type==="dot")&&(P.type==="dot"?($.output+=y,P.output+=y):t.dot===!0?($.output+=g,P.output+=g):($.output+=A,P.output+=A),ce()!=="*"&&($.output+=p,P.output+=p)),Z(ve)}for(;$.brackets>0;){if(t.strictBrackets===!0)throw new SyntaxError(Xi("closing","]"));$.output=At.escapeLast($.output,"["),cn("brackets")}for(;$.parens>0;){if(t.strictBrackets===!0)throw new SyntaxError(Xi("closing",")"));$.output=At.escapeLast($.output,"("),cn("parens")}for(;$.braces>0;){if(t.strictBrackets===!0)throw new SyntaxError(Xi("closing","}"));$.output=At.escapeLast($.output,"{"),cn("braces")}if(t.strictSlashes!==!0&&(P.type==="star"||P.type==="bracket")&&Z({type:"maybe_slash",value:"",output:`${f}?`}),$.backtrack===!0){$.output="";for(let I of $.tokens)$.output+=I.output!=null?I.output:I.value,I.suffix&&($.output+=I.suffix)}return $};bp.fastpaths=(r,e)=>{let t={...e},n=typeof t.maxLength=="number"?Math.min(gc,t.maxLength):gc,i=r.length;if(i>n)throw new SyntaxError(`Input length: ${i}, exceeds maximum allowed length: ${n}`);r=zv[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=A=>A.noglobstar===!0?b:`(${y}(?:(?!${p}${A.dot?c:s}).)*?)`,S=A=>{switch(A){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 x=/^(.*?)\.(\w+)$/.exec(A);if(!x)return;let R=S(x[1]);return R?R+s+x[2]:void 0}}},_=At.removePrefix(r,g),E=S(_);return E&&t.strictSlashes!==!0&&(E+=`${o}?`),E};Wv.exports=bp});var Xv=k((aB,Yv)=>{"use strict";var uT=Hv(),vp=Gv(),Jv=bo(),fT=go(),pT=r=>r&&typeof r=="object"&&!Array.isArray(r),$e=(r,e,t=!1)=>{if(Array.isArray(r)){let u=r.map(f=>$e(f,e,t));return f=>{for(let p of u){let h=p(f);if(h)return h}return!1}}let n=pT(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?$e.compileRe(r,e):$e.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=$e(i.ignore,u,t)}let l=(u,d=!1)=>{let{isMatch:f,match:p,output:h}=$e.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};$e.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?Jv.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=$e.matchBase(r,e,t,i):a=e.exec(c)),{isMatch:!!a,match:a,output:c}};$e.matchBase=(r,e,t,n=t&&t.windows)=>(e instanceof RegExp?e:$e.makeRe(e,t)).test(Jv.basename(r,{windows:n}));$e.isMatch=(r,e,t)=>$e(e,t)(r);$e.parse=(r,e)=>Array.isArray(r)?r.map(t=>$e.parse(t,e)):vp(r,{...e,fastpaths:!1});$e.scan=(r,e)=>uT(r,e);$e.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=$e.toRegex(a,e);return n===!0&&(c.state=r),c};$e.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=vp.fastpaths(r,e)),i.output||(i=vp(r,e)),$e.compileRe(i,e,t,n)};$e.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/$^/}};$e.constants=fT;Yv.exports=$e});var wp=k((cB,ew)=>{"use strict";var Qv=Xv(),hT=bo();function Zv(r,e,t=!1){return e&&(e.windows===null||e.windows===void 0)&&(e={...e,windows:hT.isWindows()}),Qv(r,e,t)}Object.assign(Zv,Qv);ew.exports=Zv});function _p(r,e){return mT(e.split("/"),r.split("/"))}function mT(r,e){let t=0,n=0,i=-1,s=0;for(;t=0)n=i+1,t=++s;else return!1;for(;e[n]==="**";)n++;return n===e.length}function yT(r,e){let t=[...r],n=bT([...e]),i=0,s=0,o=-1,a=0;for(;i=0)s=o+1,i=++a;else return!1;for(;n[s]==="*";)s++;return s===n.length}function gT(r,e){if(r===void 0)return!1;if(typeof r=="string")return r==="?"||r===e;let t=wo(e);return r.ranges.some(([n,i])=>n<=t&&t<=i)!==r.negated}function bT(r){let e=[];for(let t=0;t{});var gw={};ly(gw,{MdbasePathError:()=>So,applyReadDefaults:()=>zT,buildInitialFrontmatter:()=>Dp,buildTypeTemplate:()=>Op,buildUniqueNotePath:()=>Lp,coerceFieldInput:()=>xc,createNoteFromType:()=>JT,createTypeDefinition:()=>KT,ensureCollectionInitialized:()=>xo,fieldsFromV03Schema:()=>vn,formatMarkdown:()=>gt,getPromptFields:()=>Np,getTopLevelFieldFromIssuePath:()=>Fp,getTypesForFile:()=>Ge,isExcluded:()=>bt,loadContractDefinitions:()=>Mp,loadMdbaseConfig:()=>ci,loadTypeDefinitions:()=>Cp,normalizeSafeRelativePath:()=>bn,parseFrontmatter:()=>Me,readCollectionRecords:()=>Pp,resolveFilenameForType:()=>hw,resolveFolderForType:()=>pw,schemaFromV03Fields:()=>Zi,slugify:()=>kp,v03TypeDefFromFrontmatter:()=>_c,validateCollection:()=>Ip,validateFile:()=>Sc,validateRecordAgainstType:()=>es});function _T(){return _o||(_o=new nw.Ajv2020({allErrors:!0,strict:!1,allowUnionTypes:!0}),(0,iw.default)(_o),_o)}function K(r){return!!r&&typeof r=="object"&&!Array.isArray(r)}function Ne(r){return JSON.parse(JSON.stringify(r))}function ST(r){if(r===!0)return!0;if(r===!1)return!1;if(r==="warn")return"warn"}function Sp(r){return Array.isArray(r)?`[${r.map(e=>Sp(e)).join(",")}]`:K(r)?`{${Object.keys(r).sort().map(t=>`${JSON.stringify(t)}:${Sp(r[t])}`).join(",")}}`:JSON.stringify(r)}function xT(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 $T(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:Ne(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?{...Ne(a.fields),...Ne(o.fields)}:Ne(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 sw(r){let e=(0,oe.normalizePath)(r),t=e.lastIndexOf("/");return t>=0?e.slice(0,t):""}function ow(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 aw(r){return/^[a-z][a-z0-9+.-]*:\/\//i.test(r)}function cw(r,e,t){let n=ow(t);if(!n||aw(n))return null;let i=new Set,s=(0,oe.normalizePath)(n);i.add(s),s.endsWith(".md")||i.add(`${s}.md`);let o=sw(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 ET(r,e,t){return aw(ow(t))||cw(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&&!K(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 gt(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 YC={keyword:"dependencies",type:"object",schemaType:"object",error:_r.error,code(r){let[e,t]=XC(r);gb(r,e),bb(r,t)}};function XC({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 gb(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,hf._)`${c} && (${(0,po.checkMissingProp)(r,a,s)})`),(0,po.reportMissingProp)(r,s),t.else())}}_r.validatePropertyDeps=gb;function bb(r,e=r.schema){let{gen:t,data:n,keyword:i,it:s}=r,o=t.name("valid");for(let a in e)(0,JC.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))}_r.validateSchemaDeps=bb;_r.default=YC});var wb=k(mf=>{"use strict";Object.defineProperty(mf,"__esModule",{value:!0});var vb=U(),QC=Q(),ZC={message:"property name must be valid",params:({params:r})=>(0,vb._)`{propertyName: ${r.propertyName}}`},eM={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:ZC,code(r){let{gen:e,schema:t,data:n,it:i}=r;if((0,QC.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,vb.not)(s),()=>{r.error(!0),i.allErrors||e.break()})}),r.ok(s)}};mf.default=eM});var gf=k(yf=>{"use strict";Object.defineProperty(yf,"__esModule",{value:!0});var cc=jt(),er=U(),tM=Ft(),lc=Q(),rM={message:"must NOT have additional properties",params:({params:r})=>(0,er._)`{additionalProperty: ${r.additionalProperty}}`},nM={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:rM,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,lc.alwaysValidSchema)(o,t))return;let l=(0,cc.allSchemaProperties)(n.properties),u=(0,cc.allSchemaProperties)(n.patternProperties);d(),r.ok((0,er._)`${s} === ${tM.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,lc.schemaRefOrVal)(o,n.properties,"properties");g=(0,cc.isOwnProperty)(e,b,y)}else l.length?g=(0,er.or)(...l.map(b=>(0,er._)`${y} === ${b}`)):g=er.nil;return u.length&&(g=(0,er.or)(g,...u.map(b=>(0,er._)`${(0,cc.usePattern)(r,b)}.test(${y})`))),(0,er.not)(g)}function p(y){e.code((0,er._)`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,lc.alwaysValidSchema)(o,t)){let g=e.name("valid");c.removeAdditional==="failing"?(m(y,g,!1),e.if((0,er.not)(g),()=>{r.reset(),p(y)})):(m(y,g),a||e.if((0,er.not)(g),()=>e.break()))}}function m(y,g,b){let v={keyword:"additionalProperties",dataProp:y,dataPropType:lc.Type.Str};b===!1&&Object.assign(v,{compositeRule:!0,createErrors:!1,allErrors:!1}),r.subschema(v,g)}}};yf.default=nM});var xb=k(vf=>{"use strict";Object.defineProperty(vf,"__esModule",{value:!0});var iM=Li(),_b=jt(),bf=Q(),Sb=gf(),sM={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&&Sb.default.code(new iM.KeywordCxt(s,Sb.default,"additionalProperties"));let o=(0,_b.allSchemaProperties)(t);for(let d of o)s.definedProperties.add(d);s.opts.unevaluated&&o.length&&s.props!==!0&&(s.props=bf.mergeEvaluated.props(e,(0,bf.toHash)(o),s.props));let a=o.filter(d=>!(0,bf.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,_b.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)}}};vf.default=sM});var Ab=k(wf=>{"use strict";Object.defineProperty(wf,"__esModule",{value:!0});var $b=jt(),dc=U(),Eb=Q(),kb=Q(),oM={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,$b.allSchemaProperties)(t),c=a.filter(m=>(0,Eb.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 dc.Name)&&(s.props=(0,kb.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,Eb.checkStrictMode)(s,`property ${y} matches pattern ${m} (use allowMatchingProperties)`)}function h(m){e.forIn("key",n,y=>{e.if((0,dc._)`${(0,$b.usePattern)(r,m)}.test(${y})`,()=>{let g=c.includes(m);g||r.subschema({keyword:"patternProperties",schemaProp:m,dataProp:y,dataPropType:kb.Type.Str},u),s.opts.unevaluated&&d!==!0?e.assign((0,dc._)`${d}[${y}]`,!0):!g&&!s.allErrors&&e.if((0,dc.not)(u),()=>e.break())})})}}};wf.default=oM});var Pb=k(_f=>{"use strict";Object.defineProperty(_f,"__esModule",{value:!0});var aM=Q(),cM={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(r){let{gen:e,schema:t,it:n}=r;if((0,aM.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"}};_f.default=cM});var Cb=k(Sf=>{"use strict";Object.defineProperty(Sf,"__esModule",{value:!0});var lM=jt(),dM={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:lM.validateUnion,error:{message:"must match a schema in anyOf"}};Sf.default=dM});var Mb=k(xf=>{"use strict";Object.defineProperty(xf,"__esModule",{value:!0});var uc=U(),uM=Q(),fM={message:"must match exactly one schema in oneOf",params:({params:r})=>(0,uc._)`{passingSchemas: ${r.passing}}`},pM={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:fM,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,uM.alwaysValidSchema)(i,u)?e.var(c,!0):f=r.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,uc._)`${c} && ${o}`).assign(o,!1).assign(a,(0,uc._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(o,!0),e.assign(a,d),f&&r.mergeEvaluated(f,uc.Name)})})}}};xf.default=pM});var Rb=k($f=>{"use strict";Object.defineProperty($f,"__esModule",{value:!0});var hM=Q(),mM={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,hM.alwaysValidSchema)(n,s))return;let a=r.subschema({keyword:"allOf",schemaProp:o},i);r.ok(i),r.mergeEvaluated(a)})}};$f.default=mM});var Ob=k(Ef=>{"use strict";Object.defineProperty(Ef,"__esModule",{value:!0});var fc=U(),Ib=Q(),yM={message:({params:r})=>(0,fc.str)`must match "${r.ifClause}" schema`,params:({params:r})=>(0,fc._)`{failingKeyword: ${r.ifClause}}`},gM={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:yM,code(r){let{gen:e,parentSchema:t,it:n}=r;t.then===void 0&&t.else===void 0&&(0,Ib.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let i=Tb(n,"then"),s=Tb(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,fc.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,fc._)`${u}`):r.setParams({ifClause:u})}}}};function Tb(r,e){let t=r.schema[e];return t!==void 0&&!(0,Ib.alwaysValidSchema)(r,t)}Ef.default=gM});var Db=k(kf=>{"use strict";Object.defineProperty(kf,"__esModule",{value:!0});var bM=Q(),vM={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:r,parentSchema:e,it:t}){e.if===void 0&&(0,bM.checkStrictMode)(t,`"${r}" without "if" is ignored`)}};kf.default=vM});var Pf=k(Af=>{"use strict";Object.defineProperty(Af,"__esModule",{value:!0});var wM=lf(),_M=pb(),SM=df(),xM=mb(),$M=yb(),EM=ac(),kM=wb(),AM=gf(),PM=xb(),CM=Ab(),MM=Pb(),RM=Cb(),TM=Mb(),IM=Rb(),OM=Ob(),DM=Db();function LM(r=!1){let e=[MM.default,RM.default,TM.default,IM.default,OM.default,DM.default,kM.default,AM.default,EM.default,PM.default,CM.default];return r?e.push(_M.default,xM.default):e.push(wM.default,SM.default),e.push($M.default),e}Af.default=LM});var Mf=k(ho=>{"use strict";Object.defineProperty(ho,"__esModule",{value:!0});ho.dynamicAnchor=void 0;var Cf=U(),NM=Ft(),Lb=Qs(),FM=tc(),jM={keyword:"$dynamicAnchor",schemaType:"string",code:r=>Nb(r,r.schema)};function Nb(r,e){let{gen:t,it:n}=r;n.schemaEnv.root.dynamicAnchors[e]=!0;let i=(0,Cf._)`${NM.default.dynamicAnchors}${(0,Cf.getProperty)(e)}`,s=n.errSchemaPath==="#"?n.validateName:qM(r);t.if((0,Cf._)`!${i}`,()=>t.assign(i,s))}ho.dynamicAnchor=Nb;function qM(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 Lb.SchemaEnv({schema:t,schemaId:c,root:i,baseId:s,localRefs:o,meta:a});return Lb.compileSchema.call(n,l),(0,FM.getValidate)(r,l)}ho.default=jM});var Rf=k(mo=>{"use strict";Object.defineProperty(mo,"__esModule",{value:!0});mo.dynamicRef=void 0;var Fb=U(),BM=Ft(),jb=tc(),UM={keyword:"$dynamicRef",schemaType:"string",code:r=>qb(r,r.schema)};function qb(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,Fb._)`${BM.default.dynamicAnchors}${(0,Fb.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,jb.callRef)(r,c),t.let(l,!0)}):()=>(0,jb.callRef)(r,c)}}mo.dynamicRef=qb;mo.default=UM});var Bb=k(Tf=>{"use strict";Object.defineProperty(Tf,"__esModule",{value:!0});var VM=Mf(),HM=Q(),zM={keyword:"$recursiveAnchor",schemaType:"boolean",code(r){r.schema?(0,VM.dynamicAnchor)(r,""):(0,HM.checkStrictMode)(r.it,"$recursiveAnchor: false is ignored")}};Tf.default=zM});var Ub=k(If=>{"use strict";Object.defineProperty(If,"__esModule",{value:!0});var KM=Rf(),WM={keyword:"$recursiveRef",schemaType:"string",code:r=>(0,KM.dynamicRef)(r,r.schema)};If.default=WM});var Vb=k(Of=>{"use strict";Object.defineProperty(Of,"__esModule",{value:!0});var GM=Mf(),JM=Rf(),YM=Bb(),XM=Ub(),QM=[GM.default,JM.default,YM.default,XM.default];Of.default=QM});var zb=k(Df=>{"use strict";Object.defineProperty(Df,"__esModule",{value:!0});var Hb=ac(),ZM={keyword:"dependentRequired",type:"object",schemaType:"object",error:Hb.error,code:r=>(0,Hb.validatePropertyDeps)(r)};Df.default=ZM});var Kb=k(Lf=>{"use strict";Object.defineProperty(Lf,"__esModule",{value:!0});var e1=ac(),t1={keyword:"dependentSchemas",type:"object",schemaType:"object",code:r=>(0,e1.validateSchemaDeps)(r)};Lf.default=t1});var Wb=k(Nf=>{"use strict";Object.defineProperty(Nf,"__esModule",{value:!0});var r1=Q(),n1={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword:r,parentSchema:e,it:t}){e.contains===void 0&&(0,r1.checkStrictMode)(t,`"${r}" without "contains" is ignored`)}};Nf.default=n1});var Gb=k(Ff=>{"use strict";Object.defineProperty(Ff,"__esModule",{value:!0});var i1=zb(),s1=Kb(),o1=Wb(),a1=[i1.default,s1.default,o1.default];Ff.default=a1});var Yb=k(jf=>{"use strict";Object.defineProperty(jf,"__esModule",{value:!0});var yn=U(),Jb=Q(),c1=Ft(),l1={message:"must NOT have unevaluated properties",params:({params:r})=>(0,yn._)`{unevaluatedProperty: ${r.unevaluatedProperty}}`},d1={keyword:"unevaluatedProperties",type:"object",schemaType:["boolean","object"],trackErrors:!0,error:l1,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 yn.Name?e.if((0,yn._)`${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,yn._)`${i} === ${c1.default.errors}`);function c(d){if(t===!1){r.setParams({unevaluatedProperty:d}),r.error(),o||e.break();return}if(!(0,Jb.alwaysValidSchema)(s,t)){let f=e.name("valid");r.subschema({keyword:"unevaluatedProperties",dataProp:d,dataPropType:Jb.Type.Str},f),o||e.if((0,yn.not)(f),()=>e.break())}}function l(d,f){return(0,yn._)`!${d} || !${d}[${f}]`}function u(d,f){let p=[];for(let h in d)d[h]===!0&&p.push((0,yn._)`${f} !== ${h}`);return(0,yn.and)(...p)}}};jf.default=d1});var Qb=k(qf=>{"use strict";Object.defineProperty(qf,"__esModule",{value:!0});var ai=U(),Xb=Q(),u1={message:({params:{len:r}})=>(0,ai.str)`must NOT have more than ${r} items`,params:({params:{len:r}})=>(0,ai._)`{limit: ${r}}`},f1={keyword:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error:u1,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,ai._)`${n}.length`);if(t===!1)r.setParams({len:s}),r.fail((0,ai._)`${o} > ${s}`);else if(typeof t=="object"&&!(0,Xb.alwaysValidSchema)(i,t)){let c=e.var("valid",(0,ai._)`${o} <= ${s}`);e.if((0,ai.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:Xb.Type.Num},c),i.allErrors||e.if((0,ai.not)(c),()=>e.break())})}}};qf.default=f1});var Zb=k(Bf=>{"use strict";Object.defineProperty(Bf,"__esModule",{value:!0});var p1=Yb(),h1=Qb(),m1=[p1.default,h1.default];Bf.default=m1});var ev=k(Uf=>{"use strict";Object.defineProperty(Uf,"__esModule",{value:!0});var xe=U(),y1={message:({schemaCode:r})=>(0,xe.str)`must match format "${r}"`,params:({schemaCode:r})=>(0,xe._)`{format: ${r}}`},g1={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:y1,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,xe._)`${h}[${o}]`),y=t.let("fType"),g=t.let("format");t.if((0,xe._)`typeof ${m} == "object" && !(${m} instanceof RegExp)`,()=>t.assign(y,(0,xe._)`${m}.type || "string"`).assign(g,(0,xe._)`${m}.validate`),()=>t.assign(y,(0,xe._)`"string"`).assign(g,m)),r.fail$data((0,xe.or)(b(),v()));function b(){return c.strictSchema===!1?xe.nil:(0,xe._)`${o} && !${g}`}function v(){let S=u.$async?(0,xe._)`(${m}.async ? await ${g}(${n}) : ${g}(${n}))`:(0,xe._)`${g}(${n})`,_=(0,xe._)`(typeof ${g} == "function" ? ${S} : ${g}.test(${n}))`;return(0,xe._)`${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,xe.regexpCode)(_):c.code.formats?(0,xe._)`${c.code.formats}${(0,xe.getProperty)(s)}`:void 0,A=t.scopeValue("formats",{key:s,ref:_,code:E});return typeof _=="object"&&!(_ instanceof RegExp)?[_.type||"string",_.validate,(0,xe._)`${A}.validate`]:["string",_,A]}function S(){if(typeof h=="object"&&!(h instanceof RegExp)&&h.async){if(!u.$async)throw new Error("async format in sync schema");return(0,xe._)`await ${g}(${n})`}return typeof y=="function"?(0,xe._)`${g}(${n})`:(0,xe._)`${g}.test(${n})`}}}};Uf.default=g1});var Hf=k(Vf=>{"use strict";Object.defineProperty(Vf,"__esModule",{value:!0});var b1=ev(),v1=[b1.default];Vf.default=v1});var zf=k(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 rv=k(Kf=>{"use strict";Object.defineProperty(Kf,"__esModule",{value:!0});var w1=Hu(),_1=af(),S1=Pf(),x1=Vb(),$1=Gb(),E1=Zb(),k1=Hf(),tv=zf(),A1=[x1.default,w1.default,_1.default,(0,S1.default)(!0),k1.default,tv.metadataVocabulary,tv.contentVocabulary,$1.default,E1.default];Kf.default=A1});var iv=k(pc=>{"use strict";Object.defineProperty(pc,"__esModule",{value:!0});pc.DiscrError=void 0;var nv;(function(r){r.Tag="tag",r.Mapping="mapping"})(nv||(pc.DiscrError=nv={}))});var Jf=k(Gf=>{"use strict";Object.defineProperty(Gf,"__esModule",{value:!0});var Vi=U(),Wf=iv(),sv=Qs(),P1=Ni(),C1=Q(),M1={message:({params:{discrError:r,tagName:e}})=>r===Wf.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}}`},R1={keyword:"discriminator",type:"object",schemaType:"object",error:M1,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:Wf.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:Wf.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{T1.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 av=k((zq,I1)=>{I1.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 cv=k((Kq,O1)=>{O1.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 lv=k((Wq,D1)=>{D1.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 dv=k((Gq,L1)=>{L1.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 uv=k((Jq,N1)=>{N1.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 fv=k((Yq,F1)=>{F1.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 pv=k((Xq,j1)=>{j1.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 hv=k(Yf=>{"use strict";Object.defineProperty(Yf,"__esModule",{value:!0});var q1=ov(),B1=av(),U1=cv(),V1=lv(),H1=dv(),z1=uv(),K1=fv(),W1=pv(),G1=["/properties"];function J1(r){return[q1,B1,U1,V1,H1,e(this,z1),K1,e(this,W1)].forEach(t=>this.addMetaSchema(t,void 0,!1)),this;function e(t,n){return r?t.$dataMetaSchema(n,G1):n}}Yf.default=J1});var Zf=k((ye,Qf)=>{"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 Y1=Bu(),X1=rv(),Q1=Jf(),Z1=hv(),Xf="https://json-schema.org/draft/2020-12/schema",Hi=class extends Y1.default{constructor(e={}){super({...e,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){super._addVocabularies(),X1.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(Q1.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data:e,meta:t}=this.opts;t&&(Z1.default.call(this,e),this.refs["http://json-schema.org/schema"]=Xf)}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Xf)?Xf:void 0)}};ye.Ajv2020=Hi;Qf.exports=ye=Hi;Qf.exports.Ajv2020=Hi;Object.defineProperty(ye,"__esModule",{value:!0});ye.default=Hi;var eR=Li();Object.defineProperty(ye,"KeywordCxt",{enumerable:!0,get:function(){return eR.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 tR=Xs();Object.defineProperty(ye,"ValidationError",{enumerable:!0,get:function(){return tR.default}});var rR=Ni();Object.defineProperty(ye,"MissingRefError",{enumerable:!0,get:function(){return rR.default}})});var Sv=k(xr=>{"use strict";Object.defineProperty(xr,"__esModule",{value:!0});xr.formatNames=xr.fastFormats=xr.fullFormats=void 0;function Sr(r,e){return{validate:r,compare:e}}xr.fullFormats={date:Sr(bv,np),time:Sr(tp(!0),ip),"date-time":Sr(mv(!0),wv),"iso-time":Sr(tp(),vv),"iso-date-time":Sr(mv(),_v),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:cR,"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:mR,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:lR,int32:{type:"number",validate:fR},int64:{type:"number",validate:pR},float:{type:"number",validate:gv},double:{type:"number",validate:gv},password:!0,binary:!0};xr.fastFormats={...xr.fullFormats,date:Sr(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,np),time:Sr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,ip),"date-time":Sr(/^\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,wv),"iso-time":Sr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,vv),"iso-date-time":Sr(/^\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,_v),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};xr.formatNames=Object.keys(xr.fullFormats);function nR(r){return r%4===0&&(r%100!==0||r%400===0)}var iR=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,sR=[0,31,28,31,30,31,30,31,31,30,31,30,31];function bv(r){let e=iR.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&&nR(t)?29:sR[n])}function np(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 ip(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 vv(r,e){if(!(r&&e))return;let t=ep.exec(r),n=ep.exec(e);if(t&&n)return r=t[1]+t[2]+t[3],e=n[1]+n[2]+n[3],r>e?1:r=dR}function pR(r){return Number.isInteger(r)}function gv(){return!0}var hR=/[^\\]\\Z/;function mR(r){if(hR.test(r))return!1;try{return new RegExp(r),!0}catch{return!1}}});var $v=k(sp=>{"use strict";Object.defineProperty(sp,"__esModule",{value:!0});var yR=Hu(),gR=af(),bR=Pf(),vR=Hf(),xv=zf(),wR=[yR.default,gR.default,(0,bR.default)(),vR.default,xv.metadataVocabulary,xv.contentVocabulary];sp.default=wR});var Ev=k((tB,_R)=>{_R.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 Av=k((ge,op)=>{"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 SR=Bu(),xR=$v(),$R=Jf(),kv=Ev(),ER=["/properties"],hc="http://json-schema.org/draft-07/schema",Ki=class extends SR.default{_addVocabularies(){super._addVocabularies(),xR.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword($R.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(kv,ER):kv;this.addMetaSchema(e,hc,!1),this.refs["http://json-schema.org/schema"]=hc}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(hc)?hc:void 0)}};ge.Ajv=Ki;op.exports=ge=Ki;op.exports.Ajv=Ki;Object.defineProperty(ge,"__esModule",{value:!0});ge.default=Ki;var kR=Li();Object.defineProperty(ge,"KeywordCxt",{enumerable:!0,get:function(){return kR.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 AR=Xs();Object.defineProperty(ge,"ValidationError",{enumerable:!0,get:function(){return AR.default}});var PR=Ni();Object.defineProperty(ge,"MissingRefError",{enumerable:!0,get:function(){return PR.default}})});var Pv=k(Gi=>{"use strict";Object.defineProperty(Gi,"__esModule",{value:!0});Gi.formatLimitDefinition=void 0;var CR=Av(),tr=U(),gn=tr.operators,mc={formatMaximum:{okStr:"<=",ok:gn.LTE,fail:gn.GT},formatMinimum:{okStr:">=",ok:gn.GTE,fail:gn.LT},formatExclusiveMaximum:{okStr:"<",ok:gn.LT,fail:gn.GTE},formatExclusiveMinimum:{okStr:">",ok:gn.GT,fail:gn.LTE}},MR={message:({keyword:r,schemaCode:e})=>(0,tr.str)`should be ${mc[r].okStr} ${e}`,params:({keyword:r,schemaCode:e})=>(0,tr._)`{comparison: ${mc[r].okStr}, limit: ${e}}`};Gi.formatLimitDefinition={keyword:Object.keys(mc),type:"string",schemaType:"string",$data:!0,error:MR,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 CR.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,tr._)`${f}[${c.schemaCode}]`);r.fail$data((0,tr.or)((0,tr._)`typeof ${p} != "object"`,(0,tr._)`${p} instanceof RegExp`,(0,tr._)`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,tr._)`${o.code.formats}${(0,tr.getProperty)(f)}`:void 0});r.fail$data(d(h))}function d(f){return(0,tr._)`${f}.compare(${t}, ${n}) ${mc[i].fail} 0`}},dependencies:["format"]};var RR=r=>(r.addKeyword(Gi.formatLimitDefinition),r);Gi.default=RR});var lp=k((yo,Rv)=>{"use strict";Object.defineProperty(yo,"__esModule",{value:!0});var Ji=Sv(),TR=Pv(),ap=U(),Cv=new ap.Name("fullFormats"),IR=new ap.Name("fastFormats"),cp=(r,e={keywords:!0})=>{if(Array.isArray(e))return Mv(r,e,Ji.fullFormats,Cv),r;let[t,n]=e.mode==="fast"?[Ji.fastFormats,IR]:[Ji.fullFormats,Cv],i=e.formats||Ji.formatNames;return Mv(r,i,t,n),e.keywords&&(0,TR.default)(r),r};cp.get=(r,e="full")=>{let n=(e==="fast"?Ji.fastFormats:Ji.fullFormats)[r];if(!n)throw new Error(`Unknown format "${r}"`);return n};function Mv(r,e,t,n){var i,s;(i=(s=r.opts.code).formats)!==null&&i!==void 0||(s.formats=(0,ap._)`require("ajv-formats/dist/formats").${n}`);for(let o of e)r.addFormat(o,t[o])}Rv.exports=yo=cp;Object.defineProperty(yo,"__esModule",{value:!0});yo.default=cp});var go=k((nB,Lv)=>{"use strict";var Tv="[^\\\\/]",OR="(?=.)",Iv="[^/]",dp="(?:\\/|$)",Ov="(?:^|\\/)",up=`\\.{1,2}${dp}`,DR="(?!\\.)",LR=`(?!${Ov}${up})`,NR=`(?!\\.{0,1}${dp})`,FR=`(?!${up})`,jR="[^.\\/]",qR=`${Iv}*?`,BR="/",Dv={DOT_LITERAL:"\\.",PLUS_LITERAL:"\\+",QMARK_LITERAL:"\\?",SLASH_LITERAL:"\\/",ONE_CHAR:OR,QMARK:Iv,END_ANCHOR:dp,DOTS_SLASH:up,NO_DOT:DR,NO_DOTS:LR,NO_DOT_SLASH:NR,NO_DOTS_SLASH:FR,QMARK_NO_DOT:jR,STAR:qR,START_ANCHOR:Ov,SEP:BR},UR={...Dv,SLASH_LITERAL:"[\\\\/]",QMARK:Tv,STAR:`${Tv}*?`,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:"\\"},VR={__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"};Lv.exports={DEFAULT_MAX_EXTGLOB_RECURSION:0,MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:VR,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?UR:Dv}}});var bo=k(yt=>{"use strict";var{REGEX_BACKSLASH:HR,REGEX_REMOVE_BACKSLASH:zR,REGEX_SPECIAL_CHARS:KR,REGEX_SPECIAL_CHARS_GLOBAL:WR}=go();yt.isObject=r=>r!==null&&typeof r=="object"&&!Array.isArray(r);yt.hasRegexChars=r=>KR.test(r);yt.isRegexChar=r=>r.length===1&&yt.hasRegexChars(r);yt.escapeRegex=r=>r.replace(WR,"\\$1");yt.toPosixSlashes=r=>r.replace(HR,"/");yt.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};yt.removeBackslashes=r=>r.replace(zR,e=>e==="\\"?"":e);yt.escapeLast=(r,e,t)=>{let n=r.lastIndexOf(e,t);return n===-1?r:r[n-1]==="\\"?yt.escapeLast(r,e,n-1):`${r.slice(0,n)}\\${r.slice(n)}`};yt.removePrefix=(r,e={})=>{let t=r;return t.startsWith("./")&&(t=t.slice(2),e.prefix="./"),t};yt.wrapOutput=(r,e={},t={})=>{let n=t.contains?"":"^",i=t.contains?"":"$",s=`${n}(?:${r})${i}`;return e.negated===!0&&(s=`(?:^(?!${s}).*$)`),s};yt.basename=(r,{windows:e}={})=>{let t=r.split(e?/[\\/]/:"/"),n=t[t.length-1];return n===""?t[t.length-2]:n}});var Hv=k((sB,Vv)=>{"use strict";var Nv=bo(),{CHAR_ASTERISK:fp,CHAR_AT:GR,CHAR_BACKWARD_SLASH:Yi,CHAR_COMMA:JR,CHAR_DOT:pp,CHAR_EXCLAMATION_MARK:hp,CHAR_FORWARD_SLASH:Uv,CHAR_LEFT_CURLY_BRACE:mp,CHAR_LEFT_PARENTHESES:yc,CHAR_LEFT_SQUARE_BRACKET:YR,CHAR_PLUS:XR,CHAR_QUESTION_MARK:Fv,CHAR_RIGHT_CURLY_BRACE:QR,CHAR_RIGHT_PARENTHESES:jv,CHAR_RIGHT_SQUARE_BRACKET:ZR}=go(),qv=r=>r===Uv||r===Yi,Bv=r=>{r.isPrefix!==!0&&(r.depth=r.isGlobstar?1/0:1)},eT=(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,A,x,R={value:"",depth:0,isGlob:!1},$=()=>l>=n,q=()=>c.charCodeAt(l+1),M=()=>(A=x,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&&qv(V.charCodeAt(V.length-1))&&(V=V.slice(0,-1)),t.unescape===!0&&(C&&(C=Nv.removeBackslashes(C)),V&&b===!0&&(V=Nv.removeBackslashes(V)));let Ve={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&&(Ve.maxDepth=0,qv(x)||o.push(R),Ve.tokens=o),t.parts===!0||t.tokens===!0){let ce;for(let Ce=0;Ce=u&&(a.push(zn),ce=Ls)}let dt=ce!==void 0?ce+1:u,kt=r.slice(dt);a.push(kt),t.tokens&&ce&&ce+1{"use strict";var vo=go(),At=bo(),{MAX_LENGTH:gc,POSIX_REGEX_SOURCE:tT,REGEX_NON_SPECIAL_CHARS:rT,REGEX_SPECIAL_CHARS_BACKREF:nT,REPLACEMENTS:zv}=vo,iT=(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=>At.escapeRegex(i)).join("..")}return t},Xi=(r,e)=>`Missing ${r}: "${e}" - use "\\\\${e}" to match literal characters`,Kv=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},sT=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},gp=r=>{let e=r.trim(),t=!0;for(;t===!0;)t=!1,/^@\([^\\()[\]{}|]+\)$/.test(e)&&(e=e.slice(2,-1),t=!0);if(sT(e))return e.replace(/\\(.)/g,"$1")},oT=r=>{let e=r.map(gp).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}}}}},aT=r=>`${r.length===1?At.escapeRegex(r[0]):`[${r.map(t=>At.escapeRegex(t)).join("")}]`}*`,cT=r=>{let e=0,t=[];for(;eo.trim());if(i.length!==1)return;let s=gp(i[0]);if(!s||s.length!==1)return;t.push(s),e+=n.end+1}if(!(t.length<1))return t},lT=r=>{let e=0,t=r.trim(),n=yp(t);for(;n;)e++,t=n.body.trim(),n=yp(t);return e},dT=(r,e)=>{if(e.maxExtglobRecursion===!1)return{risky:!1};let t=typeof e.maxExtglobRecursion=="number"?e.maxExtglobRecursion:vo.DEFAULT_MAX_EXTGLOB_RECURSION,n=Kv(r).map(a=>a.trim());if(n.length>1&&(n.some(a=>a==="")||n.some(a=>/^[*?]+$/.test(a))||oT(n)))return{risky:!0};let i=[],s=!1,o=!0;for(let a of n){let c=cT(a);if(c){s=!0,i.push(...c);continue}let l=gp(a);if(l&&l.length===1){i.push(l);continue}if(o=!1,lT(a)>t)return{risky:!0}}return s?o?{risky:!0,safeOutput:aT([...new Set(i)])}:{risky:!0}:{risky:!1}},bp=(r,e)=>{if(typeof r!="string")throw new TypeError("Expected a string");r=zv[r]||r;let t={...e},n=typeof t.maxLength=="number"?Math.min(gc,t.maxLength):gc,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}).)*?)`,A=t.dot?"":m,x=t.dot?b:v,R=t.bash===!0?E(t):S;t.capture&&(R=`(${R})`),typeof t.noext=="boolean"&&(t.noextglob=t.noext);let $={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=At.removePrefix(r,$),i=r.length;let q=[],M=[],V=[],P=s,C,Ve=()=>$.index===i-1,ce=$.peek=(I=1)=>r[$.index+I],dt=$.advance=()=>r[++$.index]||"",kt=()=>r.slice($.index+1),Ce=(I="",ve=0)=>{$.consumed+=I,$.index+=ve},ki=I=>{$.output+=I.output!=null?I.output:I.value,Ce(I.value)},Ls=()=>{let I=1;for(;ce()==="!"&&(ce(2)!=="("||ce(3)==="?");)dt(),$.start++,I++;return I%2===0?!1:($.negated=!0,$.start++,!0)},zn=I=>{$[I]++,V.push(I)},cn=I=>{$[I]--,V.pop()},Z=I=>{if(P.type==="globstar"){let ve=$.braces>0&&(I.type==="comma"||I.type==="brace"),T=I.extglob===!0||q.length&&(I.type==="pipe"||I.type==="paren");I.type!=="slash"&&I.type!=="paren"&&!ve&&!T&&($.output=$.output.slice(0,-P.output.length),P.type="star",P.value="*",P.output=R,$.output+=P.output)}if(q.length&&I.type!=="paren"&&(q[q.length-1].inner+=I.value),(I.value||I.output)&&ki(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},Ca=(I,ve)=>{let T={...l[ve],conditions:1,inner:""};T.prev=P,T.parens=$.parens,T.output=$.output,T.startIndex=$.index,T.tokensIndex=o.length;let ee=(t.capture?"(":"")+T.open;zn("parens"),Z({type:I,value:ve,output:$.output?"":p}),Z({type:"paren",extglob:!0,value:dt(),output:ee}),q.push(T)},Z$=I=>{let ve=r.slice(I.startIndex,$.index+1),T=r.slice(I.startIndex+2,$.index),ee=dT(T,t);if((I.type==="plus"||I.type==="star")&&ee.risky){let fe=ee.safeOutput?(I.output?"":p)+(t.capture?`(${ee.safeOutput})`:ee.safeOutput):void 0,gr=o[I.tokensIndex];gr.type="text",gr.value=ve,gr.output=fe||At.escapeRegex(ve);for(let Kn=I.tokensIndex+1;Kn1&&I.inner.includes("/")&&(fe=E(t)),(fe!==R||Ve()||/^\)+$/.test(kt()))&&(he=I.close=`)$))${fe}`),I.inner.includes("*")&&(Me=kt())&&/^\.[^\\/.]+$/.test(Me)){let gr=bp(Me,{...e,fastpaths:!1}).output;he=I.close=`)${gr})${fe})`}I.prev.type==="bos"&&($.negatedExtglob=!0)}Z({type:"paren",extglob:!0,value:C,output:he}),cn("parens")};if(t.fastpaths!==!1&&!/(^[*!]|[/()[\]{}"])/.test(r)){let I=!1,ve=r.replace(nT,(T,ee,he,Me,fe,gr)=>Me==="\\"?(I=!0,T):Me==="?"?ee?ee+Me+(fe?b.repeat(fe.length):""):gr===0?x+(fe?b.repeat(fe.length):""):b.repeat(he.length):Me==="."?u.repeat(he.length):Me==="*"?ee?ee+Me+(fe?R:""):R:ee?T:`\\${T}`);return I===!0&&(t.unescape===!0?ve=ve.replace(/\\/g,""):ve=ve.replace(/\\+/g,T=>T.length%2===0?"\\\\":T?"\\":"")),ve===r&&t.contains===!0?($.output=r,$):($.output=At.wrapOutput(ve,$,e),$)}for(;!Ve();){if(C=dt(),C==="\0")continue;if(C==="\\"){let T=ce();if(T==="/"&&t.bash!==!0||T==="."||T===";")continue;if(!T){C+="\\",Z({type:"text",value:C});continue}let ee=/^\\+/.exec(kt()),he=0;if(ee&&ee[0].length>2&&(he=ee[0].length,$.index+=he,he%2!==0&&(C+="\\")),t.unescape===!0?C=dt():C+=dt(),$.brackets===0){Z({type:"text",value:C});continue}}if($.brackets>0&&(C!=="]"||P.value==="["||P.value==="[^")){if(t.posix!==!1&&C===":"){let T=P.value.slice(1);if(T.includes("[")&&(P.posix=!0,T.includes(":"))){let ee=P.value.lastIndexOf("["),he=P.value.slice(0,ee),Me=P.value.slice(ee+2),fe=tT[Me];if(fe){P.value=he+fe,$.backtrack=!0,dt(),!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,ki({value:C});continue}if($.quotes===1&&C!=='"'){C=At.escapeRegex(C),P.value+=C,ki({value:C});continue}if(C==='"'){$.quotes=$.quotes===1?0:1,t.keepQuotes===!0&&Z({type:"text",value:C});continue}if(C==="("){zn("parens"),Z({type:"paren",value:C});continue}if(C===")"){if($.parens===0&&t.strictBrackets===!0)throw new SyntaxError(Xi("opening","("));let T=q[q.length-1];if(T&&$.parens===T.parens+1){Z$(q.pop());continue}Z({type:"paren",value:C,output:$.parens?")":"\\)"}),cn("parens");continue}if(C==="["){if(t.nobracket===!0||!kt().includes("]")){if(t.nobracket!==!0&&t.strictBrackets===!0)throw new SyntaxError(Xi("closing","]"));C=`\\${C}`}else zn("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($.brackets===0){if(t.strictBrackets===!0)throw new SyntaxError(Xi("opening","["));Z({type:"text",value:C,output:`\\${C}`});continue}cn("brackets");let T=P.value.slice(1);if(P.posix!==!0&&T[0]==="^"&&!T.includes("/")&&(C=`/${C}`),P.value+=C,ki({value:C}),t.literalBrackets===!1||At.hasRegexChars(T))continue;let ee=At.escapeRegex(P.value);if($.output=$.output.slice(0,-P.value.length),t.literalBrackets===!0){$.output+=ee,P.value=ee;continue}P.value=`(${a}${ee}|${P.value})`,$.output+=P.value;continue}if(C==="{"&&t.nobrace!==!0){zn("braces");let T={type:"brace",value:C,output:"(",outputIndex:$.output.length,tokensIndex:$.tokens.length};M.push(T),Z(T);continue}if(C==="}"){let T=M[M.length-1];if(t.nobrace===!0||!T){Z({type:"text",value:C,output:C});continue}let ee=")";if(T.dots===!0){let he=o.slice(),Me=[];for(let fe=he.length-1;fe>=0&&(o.pop(),he[fe].type!=="brace");fe--)he[fe].type!=="dots"&&Me.unshift(he[fe].value);ee=iT(Me,t),$.backtrack=!0}if(T.comma!==!0&&T.dots!==!0){let he=$.output.slice(0,T.outputIndex),Me=$.tokens.slice(T.tokensIndex);T.value=T.output="\\{",C=ee="\\}",$.output=he;for(let fe of Me)$.output+=fe.output||fe.value}Z({type:"brace",value:C,output:ee}),cn("braces"),M.pop();continue}if(C==="|"){q.length>0&&q[q.length-1].conditions++,Z({type:"text",value:C});continue}if(C===","){let T=C,ee=M[M.length-1];ee&&V[V.length-1]==="braces"&&(ee.comma=!0,T="|"),Z({type:"comma",value:C,output:T});continue}if(C==="/"){if(P.type==="dot"&&$.index===$.start+1){$.start=$.index+1,$.consumed="",$.output="",o.pop(),P=s;continue}Z({type:"slash",value:C,output:f});continue}if(C==="."){if($.braces>0&&P.type==="dot"){P.value==="."&&(P.output=u);let T=M[M.length-1];P.type="dots",P.output+=C,P.value+=C,T.dots=!0;continue}if($.braces+$.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)!=="?"){Ca("qmark",C);continue}if(P&&P.type==="paren"){let ee=ce(),he=C;(P.value==="("&&!/[!=<:]/.test(ee)||ee==="<"&&!/<([!=]|\w+>)/.test(kt()))&&(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)))){Ca("negate",C);continue}if(t.nonegate!==!0&&$.index===0){Ls();continue}}if(C==="+"){if(t.noextglob!==!0&&ce()==="("&&ce(2)!=="?"){Ca("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")||$.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 T=rT.exec(kt());T&&(C+=T[0],$.index+=T[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=R,$.backtrack=!0,$.globstar=!0,Ce(C);continue}let I=kt();if(t.noextglob!==!0&&/^\([^?]/.test(I)){Ca("star",C);continue}if(P.type==="star"){if(t.noglobstar===!0){Ce(C);continue}let T=P.prev,ee=T.prev,he=T.type==="slash"||T.type==="bos",Me=ee&&(ee.type==="star"||ee.type==="globstar");if(t.bash===!0&&(!he||I[0]&&I[0]!=="/")){Z({type:"star",value:C,output:""});continue}let fe=$.braces>0&&(T.type==="comma"||T.type==="brace"),gr=q.length&&(T.type==="pipe"||T.type==="paren");if(!he&&T.type!=="paren"&&!fe&&!gr){Z({type:"star",value:C,output:""});continue}for(;I.slice(0,3)==="/**";){let Ai=r[$.index+4];if(Ai&&Ai!=="/")break;I=I.slice(3),Ce("/**",3)}let Kn=Ve()||$.parens>0&&I===")".repeat($.parens)&&!q.some(Ai=>Ai.type==="negate");if(T.type==="bos"&&Ve()){P.type="globstar",P.value+=C,P.output=E(t),$.output=P.output,$.globstar=!0,Ce(C);continue}if(T.type==="slash"&&T.prev.type!=="bos"&&!Me&&Kn){$.output=$.output.slice(0,-(T.output+P.output).length),T.output=`(?:${T.output}`,P.type="globstar",P.output=E(t)+(t.strictSlashes?")":"|$)"),P.value+=C,$.globstar=!0,$.output+=T.output+P.output,Ce(C);continue}if(T.type==="slash"&&T.prev.type!=="bos"&&I[0]==="/"){let Ai=I[1]!==void 0?"|$":"";$.output=$.output.slice(0,-(T.output+P.output).length),T.output=`(?:${T.output}`,P.type="globstar",P.output=`${E(t)}${f}|${f}${Ai})`,P.value+=C,$.output+=T.output+P.output,$.globstar=!0,Ce(C+dt()),Z({type:"slash",value:"/",output:""});continue}if(T.type==="bos"&&I[0]==="/"){P.type="globstar",P.value+=C,P.output=`(?:^|${f}|${E(t)}${f})`,$.output=P.output,$.globstar=!0,Ce(C+dt()),Z({type:"slash",value:"/",output:""});continue}$.output=$.output.slice(0,-P.output.length),P.type="globstar",P.output=E(t),P.value+=C,$.output+=P.output,$.globstar=!0,Ce(C);continue}let ve={type:"star",value:C,output:R};if(t.bash===!0){ve.output=".*?",(P.type==="bos"||P.type==="slash")&&(ve.output=A+ve.output),Z(ve);continue}if(P&&(P.type==="bracket"||P.type==="paren")&&t.regex===!0){ve.output=C,Z(ve);continue}($.index===$.start||P.type==="slash"||P.type==="dot")&&(P.type==="dot"?($.output+=y,P.output+=y):t.dot===!0?($.output+=g,P.output+=g):($.output+=A,P.output+=A),ce()!=="*"&&($.output+=p,P.output+=p)),Z(ve)}for(;$.brackets>0;){if(t.strictBrackets===!0)throw new SyntaxError(Xi("closing","]"));$.output=At.escapeLast($.output,"["),cn("brackets")}for(;$.parens>0;){if(t.strictBrackets===!0)throw new SyntaxError(Xi("closing",")"));$.output=At.escapeLast($.output,"("),cn("parens")}for(;$.braces>0;){if(t.strictBrackets===!0)throw new SyntaxError(Xi("closing","}"));$.output=At.escapeLast($.output,"{"),cn("braces")}if(t.strictSlashes!==!0&&(P.type==="star"||P.type==="bracket")&&Z({type:"maybe_slash",value:"",output:`${f}?`}),$.backtrack===!0){$.output="";for(let I of $.tokens)$.output+=I.output!=null?I.output:I.value,I.suffix&&($.output+=I.suffix)}return $};bp.fastpaths=(r,e)=>{let t={...e},n=typeof t.maxLength=="number"?Math.min(gc,t.maxLength):gc,i=r.length;if(i>n)throw new SyntaxError(`Input length: ${i}, exceeds maximum allowed length: ${n}`);r=zv[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=A=>A.noglobstar===!0?b:`(${y}(?:(?!${p}${A.dot?c:s}).)*?)`,S=A=>{switch(A){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 x=/^(.*?)\.(\w+)$/.exec(A);if(!x)return;let R=S(x[1]);return R?R+s+x[2]:void 0}}},_=At.removePrefix(r,g),E=S(_);return E&&t.strictSlashes!==!0&&(E+=`${o}?`),E};Wv.exports=bp});var Xv=k((aB,Yv)=>{"use strict";var uT=Hv(),vp=Gv(),Jv=bo(),fT=go(),pT=r=>r&&typeof r=="object"&&!Array.isArray(r),$e=(r,e,t=!1)=>{if(Array.isArray(r)){let u=r.map(f=>$e(f,e,t));return f=>{for(let p of u){let h=p(f);if(h)return h}return!1}}let n=pT(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?$e.compileRe(r,e):$e.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=$e(i.ignore,u,t)}let l=(u,d=!1)=>{let{isMatch:f,match:p,output:h}=$e.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};$e.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?Jv.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=$e.matchBase(r,e,t,i):a=e.exec(c)),{isMatch:!!a,match:a,output:c}};$e.matchBase=(r,e,t,n=t&&t.windows)=>(e instanceof RegExp?e:$e.makeRe(e,t)).test(Jv.basename(r,{windows:n}));$e.isMatch=(r,e,t)=>$e(e,t)(r);$e.parse=(r,e)=>Array.isArray(r)?r.map(t=>$e.parse(t,e)):vp(r,{...e,fastpaths:!1});$e.scan=(r,e)=>uT(r,e);$e.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=$e.toRegex(a,e);return n===!0&&(c.state=r),c};$e.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=vp.fastpaths(r,e)),i.output||(i=vp(r,e)),$e.compileRe(i,e,t,n)};$e.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/$^/}};$e.constants=fT;Yv.exports=$e});var wp=k((cB,ew)=>{"use strict";var Qv=Xv(),hT=bo();function Zv(r,e,t=!1){return e&&(e.windows===null||e.windows===void 0)&&(e={...e,windows:hT.isWindows()}),Qv(r,e,t)}Object.assign(Zv,Qv);ew.exports=Zv});function _p(r,e){return mT(e.split("/"),r.split("/"))}function mT(r,e){let t=0,n=0,i=-1,s=0;for(;t=0)n=i+1,t=++s;else return!1;for(;e[n]==="**";)n++;return n===e.length}function yT(r,e){let t=[...r],n=bT([...e]),i=0,s=0,o=-1,a=0;for(;i=0)s=o+1,i=++a;else return!1;for(;n[s]==="*";)s++;return s===n.length}function gT(r,e){if(r===void 0)return!1;if(typeof r=="string")return r==="?"||r===e;let t=wo(e);return r.ranges.some(([n,i])=>n<=t&&t<=i)!==r.negated}function bT(r){let e=[];for(let t=0;t{});var gw={};ly(gw,{MdbasePathError:()=>So,applyReadDefaults:()=>zT,buildInitialFrontmatter:()=>Dp,buildTypeTemplate:()=>Op,buildUniqueNotePath:()=>Np,coerceFieldInput:()=>xc,createNoteFromType:()=>JT,createTypeDefinition:()=>KT,ensureCollectionInitialized:()=>xo,fieldsFromV03Schema:()=>vn,formatMarkdown:()=>gt,getPromptFields:()=>Lp,getTopLevelFieldFromIssuePath:()=>Fp,getTypesForFile:()=>Ge,isExcluded:()=>bt,loadContractDefinitions:()=>Mp,loadMdbaseConfig:()=>ci,loadTypeDefinitions:()=>Cp,normalizeSafeRelativePath:()=>bn,parseFrontmatter:()=>Te,readCollectionRecords:()=>Pp,resolveFilenameForType:()=>hw,resolveFolderForType:()=>pw,schemaFromV03Fields:()=>Zi,slugify:()=>kp,v03TypeDefFromFrontmatter:()=>_c,validateCollection:()=>Ip,validateFile:()=>Sc,validateRecordAgainstType:()=>es});function _T(){return _o||(_o=new nw.Ajv2020({allErrors:!0,strict:!1,allowUnionTypes:!0}),(0,iw.default)(_o),_o)}function K(r){return!!r&&typeof r=="object"&&!Array.isArray(r)}function Le(r){return JSON.parse(JSON.stringify(r))}function ST(r){if(r===!0)return!0;if(r===!1)return!1;if(r==="warn")return"warn"}function Sp(r){return Array.isArray(r)?`[${r.map(e=>Sp(e)).join(",")}]`:K(r)?`{${Object.keys(r).sort().map(t=>`${JSON.stringify(t)}:${Sp(r[t])}`).join(",")}}`:JSON.stringify(r)}function xT(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 $T(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:Le(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?{...Le(a.fields),...Le(o.fields)}:Le(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 sw(r){let e=(0,oe.normalizePath)(r),t=e.lastIndexOf("/");return t>=0?e.slice(0,t):""}function ow(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 aw(r){return/^[a-z][a-z0-9+.-]*:\/\//i.test(r)}function cw(r,e,t){let n=ow(t);if(!n||aw(n))return null;let i=new Set,s=(0,oe.normalizePath)(n);i.add(s),s.endsWith(".md")||i.add(`${s}.md`);let o=sw(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 ET(r,e,t){return aw(ow(t))||cw(r,e,t)!==null}function Te(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&&!K(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 gt(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 ci(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(!K(n))return null;let i=K(n.settings)?n.settings:{},s=K(n.runtime)?n.runtime:void 0;return{spec_version:typeof n.spec_version=="string"?n.spec_version:Ur.spec_version,name:typeof n.name=="string"?n.name:Ur.name,description:typeof n.description=="string"?n.description:Ur.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:Ur.settings.types_folder,contracts_folder:typeof i.contracts_folder=="string"?i.contracts_folder:Ur.settings.contracts_folder,explicit_type_keys:Array.isArray(i.explicit_type_keys)?i.explicit_type_keys.filter(o=>typeof o=="string"):[...Ur.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"):Tp(n.spec_version)?[]:[...wT]}}}catch{return null}}async function xo(r,e={}){let t=[];if(!(r.getAbstractFileByPath("mdbase.yaml")instanceof oe.TFile)){let l=(0,oe.stringifyYaml)(Ur).trimEnd()+` -`;await r.create("mdbase.yaml",l),t.push("mdbase.yaml")}let i=await ci(r)??Ur,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=Op("note",void 0,i.spec_version);await r.create(a,l),t.push(a)}return{created:t}}function lw(r,e){let t=K(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=Ne(t.enum)):n==="array"?(i.type="list",i.items=lw(t.items,!1)):n==="object"?(i.type="object",i.fields=vn(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=Ne(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 vn(r){let e=K(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,lw(i,t.has(n))]))}function dw(r,e){let t={...Ne(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=Ne(r.values??[]),delete t.format,i(),s();else if(n==="list")t.type="array",delete t.enum,delete t.format,i(),t.items=dw(r.items??{type:"any"},K(t.items)?t.items:{});else if(n==="object"){t.type="object",delete t.enum,delete t.format,s();let c=Zi(r.fields??{},K(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=Ne(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 Zi(r,e={},t=!1){let n=K(e.properties)?e.properties:{},i=Object.create(null),s=[];for(let[a,c]of Object.entries(r))i[a]=dw(c,K(n[a])?n[a]:{}),c.required===!0&&s.push(a);let o={...Ne(e),type:"object",properties:i,additionalProperties:!t};return s.length>0?o.required=s:delete o.required,o}function uw(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(K(t)&&i in t)t=t[i];else return}return t}async function fw(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=sw(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=uw(l,i);return K(u)?u:null}catch{return null}}function _c(r,e,t){let n=K(r.collection)?Ne(r.collection):void 0,i=vn(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:K(r.match)?r.match:void 0,fields:i,filePath:e,specProfile:"v0.3",schema:Ne(t),collection:n,originalFrontmatter:Ne(r)}}async function Pp(r,e){let t=[],n=performance.now();for(let i of r.getMarkdownFiles()){if(performance.now()-n>=8&&(await new Promise(o=>setTimeout(o,0)),n=performance.now()),bt(i.path,e))continue;let s=Me(await r.cachedRead(i));s.error||t.push({path:i.path,frontmatter:s.frontmatter})}return t}function es(r,e,t){let n=[];return yw(r,e,t,n),n}async function Cp(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"||!K(a.schema))continue;let u=a.schema,d=K(u.value)?u.value:null;if(!d&&typeof u.ref=="string"&&(d=await fw(r,i.path,u.ref)),!d)continue;t.set(a.name,_c(a,i.path,d));continue}if(!K(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))K(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:ST(a.strict),match:K(a.match)?a.match:void 0,fields:l,filePath:i.path,specProfile:"v0.2",originalFrontmatter:Ne(a)})}return $T(t)}async function Mp(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=K(o.record_schema)?o.record_schema:{},c=K(o.binding_schema)?o.binding_schema:void 0,l=await rw(r,i.path,a);if(!l)continue;let u=c?await rw(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 rw(r,e,t){return K(t.value)?Ne(t.value):typeof t.ref!="string"?null:fw(r,e,t.ref)}function kT(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 Rp(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 bn(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 AT(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 pw(r,e){if(r.path_pattern){let t=(0,oe.normalizePath)(Rp(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?AT(r.match.path_glob):""}function hw(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)(Rp(r.filename_pattern,e)),c=(o.split("/").pop()??o).replace(/\.md$/i,"").trim();if(c.length>0)return`${kp(c)}.md`}return`${kp(s)}.md`}function Qi(r){return Array.isArray(r)?`[${r.map(Qi).join(",")}]`:K(r)?`{${Object.keys(r).sort().map(e=>`${JSON.stringify(e)}:${Qi(r[e])}`).join(",")}}`:JSON.stringify(r)}function PT(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(!K(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 bc(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 CT(r,e,t,n){let i=(s,o)=>Qi(s)===Qi(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 bc(r.value,t,(s,o)=>s>o);case"gte":return bc(r.value,t,(s,o)=>s>=o);case"lt":return bc(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 wc(r,e,t){if("and"in r)return Array.isArray(r.and)&&r.and.every(n=>K(n)&&wc(n,e,t));if("or"in r)return Array.isArray(r.or)&&r.or.some(n=>K(n)&&wc(n,e,t));if("not"in r)return K(r.not)&&!wc(r.not,e,t);for(let[n,i]of Object.entries(r)){let s=PT(e,n);if(!K(i)){if(!s.present||Qi(s.value)!==Qi(i))return!1;continue}for(let[o,a]of Object.entries(i))if(!CT(s,o,a,t))return!1}return!0}function Ge(r,e,t,n){let i=kT(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"&&!VT(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&&K(c.where)&&(l=wc(c.where,e,t.spec_version)),l&&typeof c.where=="string"&&(l=!1),l&&s.push(o)}return s}function mw(r){return r==null||typeof r=="string"&&r.trim().length===0}function MT(r){return/^\d{4}-\d{2}-\d{2}$/.test(r)}function RT(r){return/^\d{2}:\d{2}(:\d{2})?$/.test(r)}function TT(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 Ut(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=TT(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 xp(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":Ut(r,e,t,n,i);return;case"string":if(typeof r!="string"){a("a string");return}Ut(r,e,t,n,i);return;case"integer":if(typeof r!="number"||!Number.isInteger(r)){a("an integer");return}Ut(r,e,t,n,i);return;case"number":if(typeof r!="number"||Number.isNaN(r)){a("a number");return}Ut(r,e,t,n,i);return;case"boolean":typeof r!="boolean"&&a("a boolean");return;case"date":if(typeof r!="string"||!MT(r)){a("a date (YYYY-MM-DD)");return}Ut(r,e,t,n,i);return;case"datetime":if(typeof r!="string"||Number.isNaN(Date.parse(r))){a("a datetime string");return}Ut(r,e,t,n,i);return;case"time":if(typeof r!="string"||!RT(r)){a("a time string (HH:MM)");return}Ut(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}Ut(r,e,t,n,i);return}case"list":{if(!Array.isArray(r)){a("a list");return}Ut(r,e,t,n,i),e.items&&r.forEach((c,l)=>{xp(c,e.items,`${t}[${l}]`,n,i,s)});return}case"object":{if(!K(r)){a("an object");return}if(e.fields&&K(e.fields))for(let[c,l]of Object.entries(e.fields)){if(!K(l))continue;let u=l,d=`${t}.${c}`,f=r[c];if(u.required&&mw(f)){Ce(i,n,"error","missing_required",`Missing required field '${d}'`,d);continue}xp(f,u,d,n,i,s)}return}case"link":{if(typeof r!="string"&&!K(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||!ET(s,n,c))&&Ce(i,n,"error","missing_link_target",`Field '${t}' references a missing note`,t)}return}case"tags":if(typeof r=="string"){Ut(r,e,t,n,i);return}if(Array.isArray(r)&&r.every(c=>typeof c=="string")){Ut(r,e,t,n,i);return}a("a tag string or list of strings");return;default:Ut(r,e,t,n,i);return}}function IT(r){return r.replace(/^\//,"").split("/").filter(Boolean).map(t=>t.replace(/~1/g,"/").replace(/~0/g,"~")).join(".")||void 0}function OT(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}`:K(r)?"an object":r===void 0?"missing":JSON.stringify(r)??"unknown"}function vc(r,e){return`${r} ${e}${r===1?"":"s"}`}function LT(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=>DT[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 ${vc(typeof t=="string"?t.length:0,"character")}; limit is ${String(i.limit)}`;case"minLength":return`${s} is ${vc(typeof t=="string"?t.length:0,"character")}; needs at least ${String(i.limit)}`;case"maxItems":return`${s} has ${vc(Array.isArray(t)?t.length:0,"item")}; limit is ${String(i.limit)}`;case"minItems":return`${s} has ${vc(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 ${NT[String(i.format)]??String(i.format)}`;default:return`${s}: ${r.message??"invalid value"}`}}function FT(r,e,t,n={}){let i=r.params,s=IT(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_${OT(r.keyword)}`,l=uw(n,r.instancePath);return{path:e,code:c,message:LT(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 Ep(r){if(Array.isArray(r)){for(let e of r){let t=Ep(e);if(t)return t}return null}if(!K(r))return null;if(typeof r.$ref=="string"&&!r.$ref.startsWith("#"))return r.$ref;for(let e of Object.values(r)){let t=Ep(e);if(t)return t}return null}function jT(r,e,t,n){if(!t.schema)return;let i=Ep(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=_T().compile(t.schema);if(s(e))return;for(let o of s.errors??[])n.push(FT(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 qT(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=cw(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));Ge(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 yw(r,e,t,n,i){if(t.specProfile==="v0.3"){jT(r,e,t,n);return}for(let[s,o]of Object.entries(t.fields)){if(!K(o))continue;let a=o,c=e[s];if(a.required&&mw(c)){Ce(n,r,"error","missing_required",`Missing required field '${s}' for type '${t.name}'`,s);continue}xp(c,a,s,r,n,i)}}function BT(r){let e=new Set;for(let t of r)for(let n of Object.keys(t.fields))e.add(n);return e}function UT(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 bt(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(Tp(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=>_p(s,t))}if(e.settings.include_subfolders===!1&&t.includes("/"))return!0;for(let i of e.settings.exclude)if((0,Ap.default)(i,{dot:!0,matchBase:!i.includes("/")})(t)||!i.includes("*")&&!i.includes("?")&&!i.includes("/")&&t.startsWith(`${i}/`))return!0;return!1}function Tp(r){return typeof r=="string"&&r.startsWith("0.3.")}function VT(r,e,t){return Tp(t.spec_version)?_p(r,e):(0,Ap.default)(r,{dot:!0})(e)}async function Sc(r,e,t,n){if(bt(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=Ge(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)yw(e.path,a,f,i,r),f.specProfile==="v0.3"&&await qT(r,e.path,a,f,t,n,i);let d=t.spec_version.startsWith("0.3.")?!1:UT(l,t);if(d!==!1){let f=BT(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 HT(r,e,t,n={}){let i=new Map;for(let o of r.getMarkdownFiles()){if(bt(o.path,e))continue;n.signal?.throwIfAborted();let a=await r.cachedRead(o),c=Me(a);if(c.error)continue;let u=Ge(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(!K(p))continue;let h=p;if(h.unique!==!0)continue;let m=c.frontmatter[f];if(m==null)continue;let y=Sp(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 zT(r,e){let t=Ne(r);for(let n of e)for(let[i,s]of Object.entries(n.collection?.read_defaults??{}))i in t||(t[i]=Ne(s));return t}async function Ip(r,e,t,n={}){let i=[],s=r.getMarkdownFiles().filter(a=>!bt(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 Sc(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 HT(r,e,t,n);return n.signal?.throwIfAborted(),i.push(...o),i}function Op(r,e,t=Ur.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()}),`${gt(i,`# ${r} +`;await r.create("mdbase.yaml",l),t.push("mdbase.yaml")}let i=await ci(r)??Ur,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=Op("note",void 0,i.spec_version);await r.create(a,l),t.push(a)}return{created:t}}function lw(r,e){let t=K(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=Le(t.enum)):n==="array"?(i.type="list",i.items=lw(t.items,!1)):n==="object"?(i.type="object",i.fields=vn(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=Le(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 vn(r){let e=K(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,lw(i,t.has(n))]))}function dw(r,e){let t={...Le(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=Le(r.values??[]),delete t.format,i(),s();else if(n==="list")t.type="array",delete t.enum,delete t.format,i(),t.items=dw(r.items??{type:"any"},K(t.items)?t.items:{});else if(n==="object"){t.type="object",delete t.enum,delete t.format,s();let c=Zi(r.fields??{},K(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=Le(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 Zi(r,e={},t=!1){let n=K(e.properties)?e.properties:{},i=Object.create(null),s=[];for(let[a,c]of Object.entries(r))i[a]=dw(c,K(n[a])?n[a]:{}),c.required===!0&&s.push(a);let o={...Le(e),type:"object",properties:i,additionalProperties:!t};return s.length>0?o.required=s:delete o.required,o}function uw(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(K(t)&&i in t)t=t[i];else return}return t}async function fw(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=sw(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=uw(l,i);return K(u)?u:null}catch{return null}}function _c(r,e,t){let n=K(r.collection)?Le(r.collection):void 0,i=vn(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:K(r.match)?r.match:void 0,fields:i,filePath:e,specProfile:"v0.3",schema:Le(t),collection:n,originalFrontmatter:Le(r)}}async function Pp(r,e){let t=[],n=performance.now();for(let i of r.getMarkdownFiles()){if(performance.now()-n>=8&&(await new Promise(o=>setTimeout(o,0)),n=performance.now()),bt(i.path,e))continue;let s=Te(await r.cachedRead(i));s.error||t.push({path:i.path,frontmatter:s.frontmatter})}return t}function es(r,e,t){let n=[];return yw(r,e,t,n),n}async function Cp(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=Te(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"||!K(a.schema))continue;let u=a.schema,d=K(u.value)?u.value:null;if(!d&&typeof u.ref=="string"&&(d=await fw(r,i.path,u.ref)),!d)continue;t.set(a.name,_c(a,i.path,d));continue}if(!K(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))K(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:ST(a.strict),match:K(a.match)?a.match:void 0,fields:l,filePath:i.path,specProfile:"v0.2",originalFrontmatter:Le(a)})}return $T(t)}async function Mp(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=Te(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=K(o.record_schema)?o.record_schema:{},c=K(o.binding_schema)?o.binding_schema:void 0,l=await rw(r,i.path,a);if(!l)continue;let u=c?await rw(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 rw(r,e,t){return K(t.value)?Le(t.value):typeof t.ref!="string"?null:fw(r,e,t.ref)}function kT(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 Rp(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 bn(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 AT(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 pw(r,e){if(r.path_pattern){let t=(0,oe.normalizePath)(Rp(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?AT(r.match.path_glob):""}function hw(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)(Rp(r.filename_pattern,e)),c=(o.split("/").pop()??o).replace(/\.md$/i,"").trim();if(c.length>0)return`${kp(c)}.md`}return`${kp(s)}.md`}function Qi(r){return Array.isArray(r)?`[${r.map(Qi).join(",")}]`:K(r)?`{${Object.keys(r).sort().map(e=>`${JSON.stringify(e)}:${Qi(r[e])}`).join(",")}}`:JSON.stringify(r)}function PT(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(!K(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 bc(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 CT(r,e,t,n){let i=(s,o)=>Qi(s)===Qi(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 bc(r.value,t,(s,o)=>s>o);case"gte":return bc(r.value,t,(s,o)=>s>=o);case"lt":return bc(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 wc(r,e,t){if("and"in r)return Array.isArray(r.and)&&r.and.every(n=>K(n)&&wc(n,e,t));if("or"in r)return Array.isArray(r.or)&&r.or.some(n=>K(n)&&wc(n,e,t));if("not"in r)return K(r.not)&&!wc(r.not,e,t);for(let[n,i]of Object.entries(r)){let s=PT(e,n);if(!K(i)){if(!s.present||Qi(s.value)!==Qi(i))return!1;continue}for(let[o,a]of Object.entries(i))if(!CT(s,o,a,t))return!1}return!0}function Ge(r,e,t,n){let i=kT(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"&&!VT(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&&K(c.where)&&(l=wc(c.where,e,t.spec_version)),l&&typeof c.where=="string"&&(l=!1),l&&s.push(o)}return s}function mw(r){return r==null||typeof r=="string"&&r.trim().length===0}function MT(r){return/^\d{4}-\d{2}-\d{2}$/.test(r)}function RT(r){return/^\d{2}:\d{2}(:\d{2})?$/.test(r)}function TT(r){return typeof r=="string"||Array.isArray(r)?r.length:null}function Re(r,e,t,n,i,s){r.push({path:e,code:n,message:i,severity:t,field:s})}function Ut(r,e,t,n,i){typeof r=="number"&&(typeof e.min=="number"&&re.max&&Re(i,n,"error","above_max",`'${t}' is ${r}; must be at most ${e.max}`,t));let s=TT(r);if(s!=null&&(typeof e.min_length=="number"&&se.max_length&&Re(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)||Re(i,n,"error","pattern_mismatch",`'${t}' is ${$p(r)}; does not match /${e.pattern}/`,t)}catch(o){Re(i,n,"warn","invalid_pattern",`Field '${t}' has invalid regex pattern: ${o instanceof Error?o.message:String(o)}`,t)}}function xp(r,e,t,n,i,s){let o=e.type??"any";if(r==null)return;e.deprecated===!0&&Re(i,n,"warn","deprecated_field",`Field '${t}' is marked deprecated`,t);let a=c=>{Re(i,n,"error","invalid_type",`Field '${t}' expected ${c}`,t)};switch(o){case"any":Ut(r,e,t,n,i);return;case"string":if(typeof r!="string"){a("a string");return}Ut(r,e,t,n,i);return;case"integer":if(typeof r!="number"||!Number.isInteger(r)){a("an integer");return}Ut(r,e,t,n,i);return;case"number":if(typeof r!="number"||Number.isNaN(r)){a("a number");return}Ut(r,e,t,n,i);return;case"boolean":typeof r!="boolean"&&a("a boolean");return;case"date":if(typeof r!="string"||!MT(r)){a("a date (YYYY-MM-DD)");return}Ut(r,e,t,n,i);return;case"datetime":if(typeof r!="string"||Number.isNaN(Date.parse(r))){a("a datetime string");return}Ut(r,e,t,n,i);return;case"time":if(typeof r!="string"||!RT(r)){a("a time string (HH:MM)");return}Ut(r,e,t,n,i);return;case"enum":{let c=Array.isArray(e.values)?e.values:[];if(!c.includes(r)){Re(i,n,"error","invalid_enum",`Field '${t}' must be one of: ${c.map(l=>String(l)).join(", ")}`,t);return}Ut(r,e,t,n,i);return}case"list":{if(!Array.isArray(r)){a("a list");return}Ut(r,e,t,n,i),e.items&&r.forEach((c,l)=>{xp(c,e.items,`${t}[${l}]`,n,i,s)});return}case"object":{if(!K(r)){a("an object");return}if(e.fields&&K(e.fields))for(let[c,l]of Object.entries(e.fields)){if(!K(l))continue;let u=l,d=`${t}.${c}`,f=r[c];if(u.required&&mw(f)){Re(i,n,"error","missing_required",`Missing required field '${d}'`,d);continue}xp(f,u,d,n,i,s)}return}case"link":{if(typeof r!="string"&&!K(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||!ET(s,n,c))&&Re(i,n,"error","missing_link_target",`Field '${t}' references a missing note`,t)}return}case"tags":if(typeof r=="string"){Ut(r,e,t,n,i);return}if(Array.isArray(r)&&r.every(c=>typeof c=="string")){Ut(r,e,t,n,i);return}a("a tag string or list of strings");return;default:Ut(r,e,t,n,i);return}}function IT(r){return r.replace(/^\//,"").split("/").filter(Boolean).map(t=>t.replace(/~1/g,"/").replace(/~0/g,"~")).join(".")||void 0}function OT(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}`:K(r)?"an object":r===void 0?"missing":JSON.stringify(r)??"unknown"}function vc(r,e){return`${r} ${e}${r===1?"":"s"}`}function NT(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=>DT[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 ${vc(typeof t=="string"?t.length:0,"character")}; limit is ${String(i.limit)}`;case"minLength":return`${s} is ${vc(typeof t=="string"?t.length:0,"character")}; needs at least ${String(i.limit)}`;case"maxItems":return`${s} has ${vc(Array.isArray(t)?t.length:0,"item")}; limit is ${String(i.limit)}`;case"minItems":return`${s} has ${vc(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 ${LT[String(i.format)]??String(i.format)}`;default:return`${s}: ${r.message??"invalid value"}`}}function FT(r,e,t,n={}){let i=r.params,s=IT(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_${OT(r.keyword)}`,l=uw(n,r.instancePath);return{path:e,code:c,message:NT(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 Ep(r){if(Array.isArray(r)){for(let e of r){let t=Ep(e);if(t)return t}return null}if(!K(r))return null;if(typeof r.$ref=="string"&&!r.$ref.startsWith("#"))return r.$ref;for(let e of Object.values(r)){let t=Ep(e);if(t)return t}return null}function jT(r,e,t,n){if(!t.schema)return;let i=Ep(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=_T().compile(t.schema);if(s(e))return;for(let o of s.errors??[])n.push(FT(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 qT(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=cw(r,e,d);if(!f&&c.validate_exists===!0){Re(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=Te(await r.cachedRead(f));Ge(f.path,p.frontmatter,i,s).includes(c.target_type)||Re(o,e,"error","link_wrong_type",`Field '${a}' must reference type '${c.target_type}'`,a)}}}}function yw(r,e,t,n,i){if(t.specProfile==="v0.3"){jT(r,e,t,n);return}for(let[s,o]of Object.entries(t.fields)){if(!K(o))continue;let a=o,c=e[s];if(a.required&&mw(c)){Re(n,r,"error","missing_required",`Missing required field '${s}' for type '${t.name}'`,s);continue}xp(c,a,s,r,n,i)}}function BT(r){let e=new Set;for(let t of r)for(let n of Object.keys(t.fields))e.add(n);return e}function UT(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 bt(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(Tp(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=>_p(s,t))}if(e.settings.include_subfolders===!1&&t.includes("/"))return!0;for(let i of e.settings.exclude)if((0,Ap.default)(i,{dot:!0,matchBase:!i.includes("/")})(t)||!i.includes("*")&&!i.includes("?")&&!i.includes("/")&&t.startsWith(`${i}/`))return!0;return!1}function Tp(r){return typeof r=="string"&&r.startsWith("0.3.")}function VT(r,e,t){return Tp(t.spec_version)?_p(r,e):(0,Ap.default)(r,{dot:!0})(e)}async function Sc(r,e,t,n){if(bt(e.path,t))return[];let i=[],s=await r.cachedRead(e),o=Te(s);if(o.error)return Re(i,e.path,"error","invalid_frontmatter",o.error),i;let a=o.frontmatter,c=Ge(e.path,a,t,n);if(c.length===0)return Re(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&&Re(i,e.path,"error","unknown_type",`Resolved types are not defined: ${u.join(", ")}`),l.length===0)return i;for(let f of l)yw(e.path,a,f,i,r),f.specProfile==="v0.3"&&await qT(r,e.path,a,f,t,n,i);let d=t.spec_version.startsWith("0.3.")?!1:UT(l,t);if(d!==!1){let f=BT(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)||Re(i,e.path,h,"unknown_field",`Unknown field '${m}' in strict mode`,m)}return i}async function HT(r,e,t,n={}){let i=new Map;for(let o of r.getMarkdownFiles()){if(bt(o.path,e))continue;n.signal?.throwIfAborted();let a=await r.cachedRead(o),c=Te(a);if(c.error)continue;let u=Ge(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(!K(p))continue;let h=p;if(h.unique!==!0)continue;let m=c.frontmatter[f];if(m==null)continue;let y=Sp(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(", ");Re(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 zT(r,e){let t=Le(r);for(let n of e)for(let[i,s]of Object.entries(n.collection?.read_defaults??{}))i in t||(t[i]=Le(s));return t}async function Ip(r,e,t,n={}){let i=[],s=r.getMarkdownFiles().filter(a=>!bt(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 Sc(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 HT(r,e,t,n);return n.signal?.throwIfAborted(),i.push(...o),i}function Op(r,e,t=Ur.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()}),`${gt(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()}),`${gt(n,`# ${r} Type definition for ${r}.`)} -`}async function KT(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=Op(i,n,e.spec_version);return await r.create(s,o),s}function Dp(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(!K(s))continue;let o=s;o.default!==void 0&&(t[i]=Ne(o.default))}return t}function Np(r,e){let t=[];for(let[n,i]of Object.entries(r.fields)){if(!K(i))continue;let s=i;s.computed||s.required&&e[n]===void 0&&t.push([n,s])}return t}function xc(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=>xc(s,e.items)):i}case"object":{let i=(0,oe.parseYaml)(t);if(!K(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 kp(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 WT(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 GT(r,e){if(!r.path_pattern||r.path_pattern.trim().length===0)return null;let t=(0,oe.normalizePath)(Rp(r.path_pattern,e));return t.endsWith(".md")?t:null}async function Lp(r,e,t){let n=GT(e,t),i=pw(e,t),s=n?n.split("/").pop()??n:hw(e,t),o=bn(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 JT(r,e,t,n=""){let i=bn(e),s=i.lastIndexOf("/");if(s>0&&await WT(r,i.slice(0,s)),await r.adapter.exists(i))throw new Error(`File already exists: ${i}`);let o=`${gt(t,n)} -`;return r.create(i,o)}function Fp(r){return xT(r)}var oe,nw,iw,Ap,So,Ur,wT,_o,DT,NT,Vt=cy(()=>{oe=require("obsidian"),nw=Wn(Zf(),1),iw=Wn(lp(),1),Ap=Wn(wp(),1);tw();So=class extends Error{constructor(t,n){super(n);this.code=t;this.name="MdbasePathError"}},Ur={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:[]}},wT=["_types",".obsidian",".git","node_modules",".trash",".mdbase"],_o=null;DT={string:"text",integer:"a whole number",number:"a number",boolean:"true or false",array:"a list",object:"an object",null:"empty"},NT={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 is=k((CB,Cw)=>{"use strict";var iI="2.0.0",sI=Number.MAX_SAFE_INTEGER||9007199254740991,oI=16,aI=250,cI=["major","premajor","minor","preminor","patch","prepatch","prerelease"];Cw.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:oI,MAX_SAFE_BUILD_LENGTH:aI,MAX_SAFE_INTEGER:sI,RELEASE_TYPES:cI,SEMVER_SPEC_VERSION:iI,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var Eo=k((MB,Mw)=>{"use strict";var lI=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...r)=>console.error("SEMVER",...r):()=>{};Mw.exports=lI});var ss=k((Er,Rw)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:Kp,MAX_SAFE_BUILD_LENGTH:dI,MAX_LENGTH:uI}=is(),fI=Eo();Er=Rw.exports={};var pI=Er.re=[],hI=Er.safeRe=[],D=Er.src=[],mI=Er.safeSrc=[],N=Er.t={},yI=0,Wp="[a-zA-Z0-9-]",gI=[["\\s",1],["\\d",uI],[Wp,dI]],bI=r=>{for(let[e,t]of gI)r=r.split(`${e}*`).join(`${e}{0,${t}}`).split(`${e}+`).join(`${e}{1,${t}}`);return r},H=(r,e,t)=>{let n=bI(e),i=yI++;fI(r,i,e),N[r]=i,D[i]=e,mI[i]=n,pI[i]=new RegExp(e,t?"g":void 0),hI[i]=new RegExp(n,t?"g":void 0)};H("NUMERICIDENTIFIER","0|[1-9]\\d*");H("NUMERICIDENTIFIERLOOSE","\\d+");H("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${Wp}*`);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",`${Wp}+`);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,${Kp}})(?:\\.(\\d{1,${Kp}}))?(?:\\.(\\d{1,${Kp}}))?`);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);Er.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);Er.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);Er.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 Mc=k((RB,Tw)=>{"use strict";var vI=Object.freeze({loose:!0}),wI=Object.freeze({}),_I=r=>r?typeof r!="object"?vI:r:wI;Tw.exports=_I});var Gp=k((TB,Dw)=>{"use strict";var Iw=/^[0-9]+$/,Ow=(r,e)=>{if(typeof r=="number"&&typeof e=="number")return r===e?0:rOw(e,r);Dw.exports={compareIdentifiers:Ow,rcompareIdentifiers:SI}});var qe=k((IB,Lw)=>{"use strict";var Rc=Eo(),{MAX_LENGTH:Nw,MAX_SAFE_INTEGER:Tc}=is(),{safeRe:Ic,t:Oc}=ss(),xI=Mc(),{compareIdentifiers:Jp}=Gp(),$I=(r,e)=>{let t=e.split(".");if(t.length>r.length)return!1;for(let n=0;nNw)throw new TypeError(`version is longer than ${Nw} characters`);Rc("SemVer",e,t),this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease;let n=e.trim().match(t.loose?Ic[Oc.LOOSE]:Ic[Oc.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(Rc("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 Jp(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(Rc("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 Jp(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?Ic[Oc.PRERELEASELOOSE]:Ic[Oc.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]),$I(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}};Lw.exports=Yp});var _n=k((OB,jw)=>{"use strict";var Fw=qe(),EI=(r,e,t=!1)=>{if(r instanceof Fw)return r;try{return new Fw(r,e)}catch(n){if(!t)return null;throw n}};jw.exports=EI});var Bw=k((DB,qw)=>{"use strict";var kI=_n(),AI=(r,e)=>{let t=kI(r,e);return t?t.version:null};qw.exports=AI});var Vw=k((NB,Uw)=>{"use strict";var PI=_n(),CI=(r,e)=>{let t=PI(r.trim().replace(/^[=v]+/,""),e);return t?t.version:null};Uw.exports=CI});var Kw=k((LB,zw)=>{"use strict";var Hw=qe(),MI=(r,e,t,n,i)=>{typeof t=="string"&&(i=n,n=t,t=void 0);try{return new Hw(r instanceof Hw?r.version:r,t).inc(e,n,i).version}catch{return null}};zw.exports=MI});var Jw=k((FB,Gw)=>{"use strict";var Ww=_n(),RI=(r,e)=>{let t=Ww(r,null,!0),n=Ww(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"};Gw.exports=RI});var Xw=k((jB,Yw)=>{"use strict";var TI=qe(),II=(r,e)=>new TI(r,e).major;Yw.exports=II});var Zw=k((qB,Qw)=>{"use strict";var OI=qe(),DI=(r,e)=>new OI(r,e).minor;Qw.exports=DI});var t_=k((BB,e_)=>{"use strict";var NI=qe(),LI=(r,e)=>new NI(r,e).patch;e_.exports=LI});var n_=k((UB,r_)=>{"use strict";var FI=_n(),jI=(r,e)=>{let t=FI(r,e);return t&&t.prerelease.length?t.prerelease:null};r_.exports=jI});var Ht=k((VB,s_)=>{"use strict";var i_=qe(),qI=(r,e,t)=>new i_(r,t).compare(new i_(e,t));s_.exports=qI});var a_=k((HB,o_)=>{"use strict";var BI=Ht(),UI=(r,e,t)=>BI(e,r,t);o_.exports=UI});var l_=k((zB,c_)=>{"use strict";var VI=Ht(),HI=(r,e)=>VI(r,e,!0);c_.exports=HI});var Dc=k((KB,u_)=>{"use strict";var d_=qe(),zI=(r,e,t)=>{let n=new d_(r,t),i=new d_(e,t);return n.compare(i)||n.compareBuild(i)};u_.exports=zI});var p_=k((WB,f_)=>{"use strict";var KI=Dc(),WI=(r,e)=>r.sort((t,n)=>KI(t,n,e));f_.exports=WI});var m_=k((GB,h_)=>{"use strict";var GI=Dc(),JI=(r,e)=>r.sort((t,n)=>GI(n,t,e));h_.exports=JI});var ko=k((JB,y_)=>{"use strict";var YI=Ht(),XI=(r,e,t)=>YI(r,e,t)>0;y_.exports=XI});var Nc=k((YB,g_)=>{"use strict";var QI=Ht(),ZI=(r,e,t)=>QI(r,e,t)<0;g_.exports=ZI});var Xp=k((XB,b_)=>{"use strict";var eO=Ht(),tO=(r,e,t)=>eO(r,e,t)===0;b_.exports=tO});var Qp=k((QB,v_)=>{"use strict";var rO=Ht(),nO=(r,e,t)=>rO(r,e,t)!==0;v_.exports=nO});var Lc=k((ZB,w_)=>{"use strict";var iO=Ht(),sO=(r,e,t)=>iO(r,e,t)>=0;w_.exports=sO});var Fc=k((eU,__)=>{"use strict";var oO=Ht(),aO=(r,e,t)=>oO(r,e,t)<=0;__.exports=aO});var Zp=k((tU,S_)=>{"use strict";var cO=Xp(),lO=Qp(),dO=ko(),uO=Lc(),fO=Nc(),pO=Fc(),hO=(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 cO(r,t,n);case"!=":return lO(r,t,n);case">":return dO(r,t,n);case">=":return uO(r,t,n);case"<":return fO(r,t,n);case"<=":return pO(r,t,n);default:throw new TypeError(`Invalid operator: ${e}`)}};S_.exports=hO});var $_=k((rU,x_)=>{"use strict";var mO=qe(),yO=_n(),{safeRe:jc,t:qc}=ss(),gO=(r,e)=>{if(r instanceof mO)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?jc[qc.COERCEFULL]:jc[qc.COERCE]);else{let c=e.includePrerelease?jc[qc.COERCERTLFULL]:jc[qc.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 yO(`${n}.${i}.${s}${o}${a}`,e)};x_.exports=gO});var k_=k((nU,E_)=>{"use strict";var bO=_n(),vO=is(),wO=qe(),_O=(r,e,t)=>{if(!vO.RELEASE_TYPES.includes(e))return null;let n=SO(r,t);return n&&xO(n,e)},SO=(r,e)=>{let t=r instanceof wO?r.version:r;return bO(t,e)},xO=(r,e)=>{if($O(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()},$O=r=>r.startsWith("pre");E_.exports=_O});var P_=k((iU,A_)=>{"use strict";var eh=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}};A_.exports=eh});var zt=k((sU,T_)=>{"use strict";var EO=/\s+/g,th=class r{constructor(e,t){if(t=AO(t),e instanceof r)return e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease?e:new r(e.raw,t);if(e instanceof rh)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(EO," "),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=>!M_(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&&NO(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(DO,"");let n=((this.options.includePrerelease&&IO)|(this.options.loose&&OO))+":"+e,i=C_.get(n);if(i)return i;let s=this.options.loose,o=s?st[Be.HYPHENRANGELOOSE]:st[Be.HYPHENRANGE];e=e.replace(o,WO(this.options.includePrerelease)),be("hyphen replace",e),e=e.replace(st[Be.COMPARATORTRIM],MO),be("comparator trim",e),e=e.replace(st[Be.TILDETRIM],RO),be("tilde trim",e),e=e.replace(st[Be.CARETTRIM],TO),be("caret trim",e);let a=e.split(" ").map(d=>LO(d,this.options)).join(" ").split(/\s+/).map(d=>KO(d,this.options));s&&(a=a.filter(d=>(be("loose invalid filter",d,this.options),!!d.match(st[Be.COMPARATORLOOSE])))),be("range list",a);let c=new Map,l=a.map(d=>new rh(d,this.options));for(let d of l){if(M_(d))return[d];c.set(d.value,d)}c.size>1&&c.has("")&&c.delete("");let u=[...c.values()];return C_.set(n,u),u}intersects(e,t){if(!(e instanceof r))throw new TypeError("a Range is required");return this.set.some(n=>R_(n,t)&&e.set.some(i=>R_(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 PO(e,this.options)}catch{return!1}for(let t=0;tr.value==="<0.0.0-0",NO=r=>r.value==="",R_=(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},LO=(r,e)=>(r=r.replace(st[Be.BUILD],""),be("comp",r,e),r=BO(r,e),be("caret",r),r=jO(r,e),be("tildes",r),r=VO(r,e),be("xrange",r),r=zO(r,e),be("stars",r),r),Re=r=>!r||r.toLowerCase()==="x"||r==="*",FO=(r,e,t)=>Re(r)&&!Re(e)||Re(e)&&t&&!Re(t),jO=(r,e)=>r.trim().split(/\s+/).map(t=>qO(t,e)).join(" "),qO=(r,e)=>{let t=e.loose?st[Be.TILDELOOSE]:st[Be.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 Re(s)?l="":Re(o)?l=`>=${s}.0.0${n} <${+s+1}.0.0-0`:Re(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})},BO=(r,e)=>r.trim().split(/\s+/).map(t=>UO(t,e)).join(" "),UO=(r,e)=>{be("caret",r,e);let t=e.loose?st[Be.CARETLOOSE]:st[Be.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 Re(s)?l="":Re(o)?l=`>=${s}.0.0${n} <${+s+1}.0.0-0`:Re(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})},VO=(r,e)=>(be("replaceXRanges",r,e),r.split(/\s+/).map(t=>HO(t,e)).join(" ")),HO=(r,e)=>{r=r.trim();let t=e.loose?st[Be.XRANGELOOSE]:st[Be.XRANGE];return r.replace(t,(n,i,s,o,a,c)=>{if(be("xRange",r,n,i,s,o,a,c),FO(s,o,a))return r;let l=Re(s),u=l||Re(o),d=u||Re(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})},zO=(r,e)=>(be("replaceStars",r,e),r.trim().replace(st[Be.STAR],"")),KO=(r,e)=>(be("replaceGTE0",r,e),r.trim().replace(st[e.includePrerelease?Be.GTE0PRE:Be.GTE0],"")),WO=r=>(e,t,n,i,s,o,a,c,l,u,d,f)=>(Re(n)?t="":Re(i)?t=`>=${n}.0.0${r?"-0":""}`:Re(s)?t=`>=${n}.${i}.0${r?"-0":""}`:o?t=`>=${t}`:t=`>=${t}${r?"-0":""}`,Re(l)?c="":Re(u)?c=`<${+l+1}.0.0-0`:Re(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()),GO=(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 Ao=k((oU,F_)=>{"use strict";var Po=Symbol("SemVer ANY"),sh=class r{static get ANY(){return Po}constructor(e,t){if(t=I_(t),e instanceof r){if(e.loose===!!t.loose)return e;e=e.value}e=e.trim().split(/\s+/).join(" "),ih("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,ih("comp",this)}parse(e){let t=this.options.loose?O_[D_.COMPARATORLOOSE]:O_[D_.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 N_(n[2],this.options.loose):this.semver=Po}toString(){return this.value}test(e){if(ih("Comparator.test",e,this.options.loose),this.semver===Po||e===Po)return!0;if(typeof e=="string")try{e=new N_(e,this.options)}catch{return!1}return nh(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 L_(e.value,t).test(this.value):e.operator===""?e.value===""?!0:new L_(this.value,t).test(e.semver):(t=I_(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("=")||nh(this.semver,"<",e.semver,t)&&this.operator.startsWith(">")&&e.operator.startsWith("<")||nh(this.semver,">",e.semver,t)&&this.operator.startsWith("<")&&e.operator.startsWith(">")))}};F_.exports=sh;var I_=Mc(),{safeRe:O_,t:D_}=ss(),nh=Zp(),ih=Eo(),N_=qe(),L_=zt()});var Co=k((aU,j_)=>{"use strict";var JO=zt(),YO=(r,e,t)=>{try{e=new JO(e,t)}catch{return!1}return e.test(r)};j_.exports=YO});var B_=k((cU,q_)=>{"use strict";var XO=zt(),QO=(r,e)=>new XO(r,e).set.map(t=>t.map(n=>n.value).join(" ").trim().split(" "));q_.exports=QO});var V_=k((lU,U_)=>{"use strict";var ZO=qe(),eD=zt(),tD=(r,e,t)=>{let n=null,i=null,s=null;try{s=new eD(e,t)}catch{return null}return r.forEach(o=>{s.test(o)&&(!n||i.compare(o)===-1)&&(n=o,i=new ZO(n,t))}),n};U_.exports=tD});var z_=k((dU,H_)=>{"use strict";var rD=qe(),nD=zt(),iD=(r,e,t)=>{let n=null,i=null,s=null;try{s=new nD(e,t)}catch{return null}return r.forEach(o=>{s.test(o)&&(!n||i.compare(o)===1)&&(n=o,i=new rD(n,t))}),n};H_.exports=iD});var G_=k((uU,W_)=>{"use strict";var oh=qe(),sD=zt(),K_=ko(),oD=(r,e)=>{r=new sD(r,e);let t=new oh("0.0.0");if(r.test(t)||(t=new oh("0.0.0-0"),r.test(t)))return t;t=null;for(let n=0;n{let a=new oh(o.semver.version);switch(o.operator){case">":a.prerelease.length===0?a.patch++:a.prerelease.push(0),a.raw=a.format();case"":case">=":(!s||K_(a,s))&&(s=a);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${o.operator}`)}}),s&&(!t||K_(t,s))&&(t=s)}return t&&r.test(t)?t:null};W_.exports=oD});var Y_=k((fU,J_)=>{"use strict";var aD=zt(),cD=(r,e)=>{try{return new aD(r,e).range||"*"}catch{return null}};J_.exports=cD});var Bc=k((pU,e0)=>{"use strict";var lD=qe(),Z_=Ao(),{ANY:dD}=Z_,uD=zt(),fD=Co(),X_=ko(),Q_=Nc(),pD=Fc(),hD=Lc(),mD=(r,e,t,n)=>{r=new lD(r,n),e=new uD(e,n);let i,s,o,a,c;switch(t){case">":i=X_,s=pD,o=Q_,a=">",c=">=";break;case"<":i=Q_,s=hD,o=X_,a="<",c="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(fD(r,e,n))return!1;for(let l=0;l{p.semver===dD&&(p=new Z_(">=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};e0.exports=mD});var r0=k((hU,t0)=>{"use strict";var yD=Bc(),gD=(r,e,t)=>yD(r,e,">",t);t0.exports=gD});var i0=k((mU,n0)=>{"use strict";var bD=Bc(),vD=(r,e,t)=>bD(r,e,"<",t);n0.exports=vD});var a0=k((yU,o0)=>{"use strict";var s0=zt(),wD=(r,e,t)=>(r=new s0(r,t),e=new s0(e,t),r.intersects(e,t));o0.exports=wD});var l0=k((gU,c0)=>{"use strict";var _D=Co(),SD=Ht();c0.exports=(r,e,t)=>{let n=[],i=null,s=null,o=r.sort((u,d)=>SD(u,d,t));for(let u of o)_D(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 d0=zt(),lh=Ao(),{ANY:ah}=lh,ch=Co(),dh=Ht(),xD=(r,e,t={})=>{if(r===e)return!0;r=new d0(r,t),e=new d0(e,t);let n=!1;e:for(let i of r.set){for(let s of e.set){let o=ED(i,s,t);if(n=n||o!==null,o)continue e}if(n)return!1}return!0},$D=[new lh(">=0.0.0-0")],u0=[new lh(">=0.0.0")],ED=(r,e,t)=>{if(r===e)return!0;if(r.length===1&&r[0].semver===ah){if(e.length===1&&e[0].semver===ah)return!0;t.includePrerelease?r=$D:r=u0}if(e.length===1&&e[0].semver===ah){if(t.includePrerelease)return!0;e=u0}let n=new Set,i,s;for(let p of r)p.operator===">"||p.operator===">="?i=f0(i,p,t):p.operator==="<"||p.operator==="<="?s=p0(s,p,t):n.add(p.semver);if(n.size>1)return null;let o;if(i&&s){if(o=dh(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&&!ch(p,String(i),t)||s&&!ch(p,String(s),t))return null;for(let h of e)if(!ch(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=f0(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=p0(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)},f0=(r,e,t)=>{if(!r)return e;let n=dh(r.semver,e.semver,t);return n>0?r:n<0||e.operator===">"&&r.operator===">="?e:r},p0=(r,e,t)=>{if(!r)return e;let n=dh(r.semver,e.semver,t);return n<0?r:n>0||e.operator==="<"&&r.operator==="<="?e:r};h0.exports=xD});var v0=k((vU,b0)=>{"use strict";var uh=ss(),y0=is(),kD=qe(),g0=Gp(),AD=_n(),PD=Bw(),CD=Vw(),MD=Kw(),RD=Jw(),TD=Xw(),ID=Zw(),OD=t_(),DD=n_(),ND=Ht(),LD=a_(),FD=l_(),jD=Dc(),qD=p_(),BD=m_(),UD=ko(),VD=Nc(),HD=Xp(),zD=Qp(),KD=Lc(),WD=Fc(),GD=Zp(),JD=$_(),YD=k_(),XD=Ao(),QD=zt(),ZD=Co(),eN=B_(),tN=V_(),rN=z_(),nN=G_(),iN=Y_(),sN=Bc(),oN=r0(),aN=i0(),cN=a0(),lN=l0(),dN=m0();b0.exports={parse:AD,valid:PD,clean:CD,inc:MD,diff:RD,major:TD,minor:ID,patch:OD,prerelease:DD,compare:ND,rcompare:LD,compareLoose:FD,compareBuild:jD,sort:qD,rsort:BD,gt:UD,lt:VD,eq:HD,neq:zD,gte:KD,lte:WD,cmp:GD,coerce:JD,truncate:YD,Comparator:XD,Range:QD,satisfies:ZD,toComparators:eN,maxSatisfying:tN,minSatisfying:rN,minVersion:nN,validRange:iN,outside:sN,gtr:oN,ltr:aN,intersects:cN,simplifyRange:lN,subset:dN,SemVer:kD,re:uh.re,src:uh.src,tokens:uh.t,SEMVER_SPEC_VERSION:y0.SEMVER_SPEC_VERSION,RELEASE_TYPES:y0.RELEASE_TYPES,compareIdentifiers:g0.compareIdentifiers,rcompareIdentifiers:g0.rcompareIdentifiers}});var mj={};ly(mj,{default:()=>Dd});module.exports=sE(mj);var Nt=require("obsidian"),Ld="https://mdbase.dev/contracts/catalog.json",Ls="mdbase.lock.yaml",Fr=".mdbase/obsidian-pack-install.json";function br(r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("Invalid contract catalog or type pack.");return r}function Yt(r){if(typeof r!="string"||!r)throw new Error("Missing catalog field.");return r}function fy(r){let e=Yt(r);if(!/^sha256:[a-f0-9]{64}$/.test(e))throw new Error("Invalid pack digest.");return e}function Ra(r){let e=Yt(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 Fd(r){return Array.isArray(r)?`[${r.map(Fd).join(",")}]`:r&&typeof r=="object"?`{${Object.entries(r).sort(([e],[t])=>et?1:0).map(([e,t])=>`${JSON.stringify(e)}:${Fd(t)}`).join(",")}}`:JSON.stringify(r)}function oE(r){let e=new URL(Yt(r),Ld);if(e.origin!==new URL(Ld).origin||!e.pathname.startsWith("/contracts/"))throw new Error("Pack artifacts must come from the first-party contract catalog.");return e.href}async function aE(){let r=await(0,Nt.requestUrl)({url:Ld,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=br(r.json);if(e.catalog_version!==2||!Array.isArray(e.packs))throw new Error("Unsupported contract catalog.");return e.packs.map(t=>{let n=br(t),i=br(n.display),s=br(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:Yt(n.id),version:Yt(n.version),digest:fy(n.digest),provision:oE(n.provision),resource_count:Number(n.resource_count),display:{name:Yt(i.name),summary:Yt(i.summary)},installation:{visibility:Yt(s.visibility),recommendation:Yt(s.recommendation),primary_type:s.primary_type==null?null:Yt(s.primary_type),...typeof s.caution=="string"?{caution:s.caution}:{}}}})}async function Gn(r,e){let t=r.vault.getAbstractFileByPath(e);if(t&&!(t instanceof Nt.TFile))throw new Error(`A folder occupies ${e}.`);return t instanceof Nt.TFile?r.vault.read(t):null}async function uy(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 cE(r,e){let t=await(0,Nt.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 lE(r,e,JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(t.arrayBuffer)))}async function lE(r,e,t){let n=br(t),i=br(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=br(m),g=Ra(y.source);if(s.has(g))throw new Error("Duplicate pack source.");let b=Yt(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 Gn(r,Ls),u=l?(0,Nt.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(Fd(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=br(m),g=Ra(y.source),b=Ra(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),_=fy(y.digest);if(!S||await Pi(S)!==_)throw new Error(`Resource digest mismatch: ${g}`);if(u.packs.some(R=>R.id!==e.id&&R.resources.some($=>$.mode==="managed"&&$.target===b)))throw new Error(`${b} belongs to another installed pack.`);let E=await Gn(r,b),A=d?.resources.find(R=>R.target===b);if(y.mode==="managed"&&E!==null&&await Pi(E)!==_)throw new Error(`${b} already exists with different contents. Nothing was overwritten.`);let x=E===null&&!(y.mode==="seed"&&A)?"create":y.mode==="seed"?"preserve":"unchanged";a.push({path:b,before:E,after:S,action:x}),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 jd(r){if(!await r.vault.adapter.exists(Fr))return;let e=br(JSON.parse(await r.vault.adapter.read(Fr)));if(!Array.isArray(e.created))throw new Error("Invalid pack recovery journal.");if(await Gn(r,Ls)===e.lockAfter){await r.vault.adapter.remove(Fr);return}for(let t of[...e.created].reverse()){let n=br(t),i=Ra(n.path),s=r.vault.getAbstractFileByPath(i);if(s instanceof Nt.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(Fr)}var Nd=new WeakSet;async function dE(r,e,t,n){if(Nd.has(r))throw new Error("Another contract pack is installing. Wait for it to finish.");Nd.add(r);try{await uE(r,e,t,n)}finally{Nd.delete(r)}}async function uE(r,e,t,n){if(t(),await r.vault.adapter.exists(Fr))throw new Error("Recover the previous pack installation before trying again.");if(await Gn(r,Ls)!==e.lockBefore)throw new Error("Pack lock changed. Review again.");for(let s of e.files)if(await Gn(r,s.path)!==s.before)throw new Error(`${s.path} changed. Review again.`);await uy(r,Fr);let i={lockAfter:e.lockAfter,created:[]};await r.vault.adapter.write(Fr,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 uy(r,c.path),await Gn(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(Fr,JSON.stringify(i)),await r.vault.create(c.path,c.after),await Gn(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 Nt.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(Fr)}catch(s){throw await jd(r),s}}var Ta=class extends Nt.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 aE();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,cE(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,dE(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 Ia=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 it=require("obsidian");var bw=require("obsidian");Vt();function YT(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 bw.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=Dp(n,i)}onOpen(){this.titleEl.setText(`New ${this.type.name}`),this.contentEl.addClass("mdbase-create-note");let t=Np(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)]:xc(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 Lp(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=YT(this.pathInput.value);if(bt(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?es(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}};Vt();var ts=require("obsidian");var jp=class extends ts.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 qp(r,e){return new Promise(t=>{new jp(r,e,i=>{if(i.type==="selected"){t(i.typeDef);return}t(null)}).open()})}var Ec=class extends ts.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())}},kc=class extends ts.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 ts.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 vw(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||QT(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 ZT(r)}),r.addCommand({id:"mdbase-create-note-from-type",name:"Create note from type",callback:()=>void Bp(r)}),r.addCommand({id:"mdbase-validate-current-note",name:"Validate current note",checkCallback:n=>{let i=e.workspace.getActiveFile();return!(i instanceof it.TFile)||i.extension!=="md"?!1:(n||eI(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||XT(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 it.TFile)||!t()||n.addItem(s=>s.setTitle("Sync history").setIcon("history").onClick(()=>r.openNoteSyncHistory(i.path)))}))}async function XT(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 it.Notice(`Review before syncing: ${i.join(", ").toLowerCase()||"changes need attention"}.`),await r.openWorkspace("sync")}else e==="busy"?new it.Notice("A sync is already running."):e==="paused"?new it.Notice("Sync is paused."):e==="failed"?new it.Notice(n?.message??(t||"Sync failed.")):t&&new it.Notice(t)}async function QT(r){r.connectSync.assertLocalAuthorityWritable();let{created:e}=await xo(r.app.vault,{seedNoteType:!1});r.invalidateSchemaCache(),new it.Notice(e.length?`Initialized mdbase collection: ${e.join(", ")}`:"mdbase collection already initialized.")}async function ZT(r){let e=await r.requireConfigAndTypes();if(!e)return;if(e.types.size===0){new it.Notice("No type definitions found.");return}let t=r.app.workspace.getActiveFile(),n=[];if(t instanceof it.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=Ge(t.path,a.frontmatter,e.config,e.types).flatMap(c=>e.types.get(c)??[]))}}let i=n.length===1?n[0]:await qp(r.app,n.length?n:[...e.types.values()]);if(!i)return;await(await r.openWorkspace("types")).editType(i.filePath)}async function eI(r,e){let t=await r.validateFileAndStore(e,"manual");if(t.length===0){new it.Notice("No issues in current note.");return}new it.Notice(`Found ${t.length} issue${t.length===1?"":"s"} in current note.`),(await r.openWorkspace("issues")).showIssuesForPath(e.path)}async function Bp(r,e){r.connectSync.assertLocalAuthorityWritable();let t=await r.requireConfigAndTypes();if(!t)return;if(t.types.size===0){new it.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 qp(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(()=>(Vt(),gw)),a=await o(r.app.vault,i,s);await r.app.workspace.getLeaf(!0).openFile(a),await r.validateFileAndStore(a,"manual")}).open()}var ww=require("obsidian");Vt();function Up(r,e){let t=Me(r);if(t.error)throw new Error(`Invalid frontmatter: ${t.error}`);return tI(t.frontmatter,e)?{content:`--- +`}async function KT(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=Op(i,n,e.spec_version);return await r.create(s,o),s}function Dp(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(!K(s))continue;let o=s;o.default!==void 0&&(t[i]=Le(o.default))}return t}function Lp(r,e){let t=[];for(let[n,i]of Object.entries(r.fields)){if(!K(i))continue;let s=i;s.computed||s.required&&e[n]===void 0&&t.push([n,s])}return t}function xc(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=>xc(s,e.items)):i}case"object":{let i=(0,oe.parseYaml)(t);if(!K(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 kp(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 WT(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 GT(r,e){if(!r.path_pattern||r.path_pattern.trim().length===0)return null;let t=(0,oe.normalizePath)(Rp(r.path_pattern,e));return t.endsWith(".md")?t:null}async function Np(r,e,t){let n=GT(e,t),i=pw(e,t),s=n?n.split("/").pop()??n:hw(e,t),o=bn(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 JT(r,e,t,n=""){let i=bn(e),s=i.lastIndexOf("/");if(s>0&&await WT(r,i.slice(0,s)),await r.adapter.exists(i))throw new Error(`File already exists: ${i}`);let o=`${gt(t,n)} +`;return r.create(i,o)}function Fp(r){return xT(r)}var oe,nw,iw,Ap,So,Ur,wT,_o,DT,LT,Vt=cy(()=>{oe=require("obsidian"),nw=Wn(Zf(),1),iw=Wn(lp(),1),Ap=Wn(wp(),1);tw();So=class extends Error{constructor(t,n){super(n);this.code=t;this.name="MdbasePathError"}},Ur={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:[]}},wT=["_types",".obsidian",".git","node_modules",".trash",".mdbase"],_o=null;DT={string:"text",integer:"a whole number",number:"a number",boolean:"true or false",array:"a list",object:"an object",null:"empty"},LT={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 is=k((CB,Cw)=>{"use strict";var iI="2.0.0",sI=Number.MAX_SAFE_INTEGER||9007199254740991,oI=16,aI=250,cI=["major","premajor","minor","preminor","patch","prepatch","prerelease"];Cw.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:oI,MAX_SAFE_BUILD_LENGTH:aI,MAX_SAFE_INTEGER:sI,RELEASE_TYPES:cI,SEMVER_SPEC_VERSION:iI,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var Eo=k((MB,Mw)=>{"use strict";var lI=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...r)=>console.error("SEMVER",...r):()=>{};Mw.exports=lI});var ss=k((Er,Rw)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:Kp,MAX_SAFE_BUILD_LENGTH:dI,MAX_LENGTH:uI}=is(),fI=Eo();Er=Rw.exports={};var pI=Er.re=[],hI=Er.safeRe=[],D=Er.src=[],mI=Er.safeSrc=[],L=Er.t={},yI=0,Wp="[a-zA-Z0-9-]",gI=[["\\s",1],["\\d",uI],[Wp,dI]],bI=r=>{for(let[e,t]of gI)r=r.split(`${e}*`).join(`${e}{0,${t}}`).split(`${e}+`).join(`${e}{1,${t}}`);return r},H=(r,e,t)=>{let n=bI(e),i=yI++;fI(r,i,e),L[r]=i,D[i]=e,mI[i]=n,pI[i]=new RegExp(e,t?"g":void 0),hI[i]=new RegExp(n,t?"g":void 0)};H("NUMERICIDENTIFIER","0|[1-9]\\d*");H("NUMERICIDENTIFIERLOOSE","\\d+");H("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${Wp}*`);H("MAINVERSION",`(${D[L.NUMERICIDENTIFIER]})\\.(${D[L.NUMERICIDENTIFIER]})\\.(${D[L.NUMERICIDENTIFIER]})`);H("MAINVERSIONLOOSE",`(${D[L.NUMERICIDENTIFIERLOOSE]})\\.(${D[L.NUMERICIDENTIFIERLOOSE]})\\.(${D[L.NUMERICIDENTIFIERLOOSE]})`);H("PRERELEASEIDENTIFIER",`(?:${D[L.NONNUMERICIDENTIFIER]}|${D[L.NUMERICIDENTIFIER]})`);H("PRERELEASEIDENTIFIERLOOSE",`(?:${D[L.NONNUMERICIDENTIFIER]}|${D[L.NUMERICIDENTIFIERLOOSE]})`);H("PRERELEASE",`(?:-(${D[L.PRERELEASEIDENTIFIER]}(?:\\.${D[L.PRERELEASEIDENTIFIER]})*))`);H("PRERELEASELOOSE",`(?:-?(${D[L.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${D[L.PRERELEASEIDENTIFIERLOOSE]})*))`);H("BUILDIDENTIFIER",`${Wp}+`);H("BUILD",`(?:\\+(${D[L.BUILDIDENTIFIER]}(?:\\.${D[L.BUILDIDENTIFIER]})*))`);H("FULLPLAIN",`v?${D[L.MAINVERSION]}${D[L.PRERELEASE]}?${D[L.BUILD]}?`);H("FULL",`^${D[L.FULLPLAIN]}$`);H("LOOSEPLAIN",`[v=\\s]*${D[L.MAINVERSIONLOOSE]}${D[L.PRERELEASELOOSE]}?${D[L.BUILD]}?`);H("LOOSE",`^${D[L.LOOSEPLAIN]}$`);H("GTLT","((?:<|>)?=?)");H("XRANGEIDENTIFIERLOOSE",`${D[L.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);H("XRANGEIDENTIFIER",`${D[L.NUMERICIDENTIFIER]}|x|X|\\*`);H("XRANGEPLAIN",`[v=\\s]*(${D[L.XRANGEIDENTIFIER]})(?:\\.(${D[L.XRANGEIDENTIFIER]})(?:\\.(${D[L.XRANGEIDENTIFIER]})(?:${D[L.PRERELEASE]})?${D[L.BUILD]}?)?)?`);H("XRANGEPLAINLOOSE",`[v=\\s]*(${D[L.XRANGEIDENTIFIERLOOSE]})(?:\\.(${D[L.XRANGEIDENTIFIERLOOSE]})(?:\\.(${D[L.XRANGEIDENTIFIERLOOSE]})(?:${D[L.PRERELEASELOOSE]})?${D[L.BUILD]}?)?)?`);H("XRANGE",`^${D[L.GTLT]}\\s*${D[L.XRANGEPLAIN]}$`);H("XRANGELOOSE",`^${D[L.GTLT]}\\s*${D[L.XRANGEPLAINLOOSE]}$`);H("COERCEPLAIN",`(^|[^\\d])(\\d{1,${Kp}})(?:\\.(\\d{1,${Kp}}))?(?:\\.(\\d{1,${Kp}}))?`);H("COERCE",`${D[L.COERCEPLAIN]}(?:$|[^\\d])`);H("COERCEFULL",D[L.COERCEPLAIN]+`(?:${D[L.PRERELEASE]})?(?:${D[L.BUILD]})?(?:$|[^\\d])`);H("COERCERTL",D[L.COERCE],!0);H("COERCERTLFULL",D[L.COERCEFULL],!0);H("LONETILDE","(?:~>?)");H("TILDETRIM",`(\\s*)${D[L.LONETILDE]}\\s+`,!0);Er.tildeTrimReplace="$1~";H("TILDE",`^${D[L.LONETILDE]}${D[L.XRANGEPLAIN]}$`);H("TILDELOOSE",`^${D[L.LONETILDE]}${D[L.XRANGEPLAINLOOSE]}$`);H("LONECARET","(?:\\^)");H("CARETTRIM",`(\\s*)${D[L.LONECARET]}\\s+`,!0);Er.caretTrimReplace="$1^";H("CARET",`^${D[L.LONECARET]}${D[L.XRANGEPLAIN]}$`);H("CARETLOOSE",`^${D[L.LONECARET]}${D[L.XRANGEPLAINLOOSE]}$`);H("COMPARATORLOOSE",`^${D[L.GTLT]}\\s*(${D[L.LOOSEPLAIN]})$|^$`);H("COMPARATOR",`^${D[L.GTLT]}\\s*(${D[L.FULLPLAIN]})$|^$`);H("COMPARATORTRIM",`(\\s*)${D[L.GTLT]}\\s*(${D[L.LOOSEPLAIN]}|${D[L.XRANGEPLAIN]})`,!0);Er.comparatorTrimReplace="$1$2$3";H("HYPHENRANGE",`^\\s*(${D[L.XRANGEPLAIN]})\\s+-\\s+(${D[L.XRANGEPLAIN]})\\s*$`);H("HYPHENRANGELOOSE",`^\\s*(${D[L.XRANGEPLAINLOOSE]})\\s+-\\s+(${D[L.XRANGEPLAINLOOSE]})\\s*$`);H("STAR","(<|>)?=?\\s*\\*");H("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");H("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")});var Mc=k((RB,Tw)=>{"use strict";var vI=Object.freeze({loose:!0}),wI=Object.freeze({}),_I=r=>r?typeof r!="object"?vI:r:wI;Tw.exports=_I});var Gp=k((TB,Dw)=>{"use strict";var Iw=/^[0-9]+$/,Ow=(r,e)=>{if(typeof r=="number"&&typeof e=="number")return r===e?0:rOw(e,r);Dw.exports={compareIdentifiers:Ow,rcompareIdentifiers:SI}});var qe=k((IB,Nw)=>{"use strict";var Rc=Eo(),{MAX_LENGTH:Lw,MAX_SAFE_INTEGER:Tc}=is(),{safeRe:Ic,t:Oc}=ss(),xI=Mc(),{compareIdentifiers:Jp}=Gp(),$I=(r,e)=>{let t=e.split(".");if(t.length>r.length)return!1;for(let n=0;nLw)throw new TypeError(`version is longer than ${Lw} characters`);Rc("SemVer",e,t),this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease;let n=e.trim().match(t.loose?Ic[Oc.LOOSE]:Ic[Oc.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(Rc("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 Jp(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(Rc("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 Jp(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?Ic[Oc.PRERELEASELOOSE]:Ic[Oc.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]),$I(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}};Nw.exports=Yp});var _n=k((OB,jw)=>{"use strict";var Fw=qe(),EI=(r,e,t=!1)=>{if(r instanceof Fw)return r;try{return new Fw(r,e)}catch(n){if(!t)return null;throw n}};jw.exports=EI});var Bw=k((DB,qw)=>{"use strict";var kI=_n(),AI=(r,e)=>{let t=kI(r,e);return t?t.version:null};qw.exports=AI});var Vw=k((LB,Uw)=>{"use strict";var PI=_n(),CI=(r,e)=>{let t=PI(r.trim().replace(/^[=v]+/,""),e);return t?t.version:null};Uw.exports=CI});var Kw=k((NB,zw)=>{"use strict";var Hw=qe(),MI=(r,e,t,n,i)=>{typeof t=="string"&&(i=n,n=t,t=void 0);try{return new Hw(r instanceof Hw?r.version:r,t).inc(e,n,i).version}catch{return null}};zw.exports=MI});var Jw=k((FB,Gw)=>{"use strict";var Ww=_n(),RI=(r,e)=>{let t=Ww(r,null,!0),n=Ww(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"};Gw.exports=RI});var Xw=k((jB,Yw)=>{"use strict";var TI=qe(),II=(r,e)=>new TI(r,e).major;Yw.exports=II});var Zw=k((qB,Qw)=>{"use strict";var OI=qe(),DI=(r,e)=>new OI(r,e).minor;Qw.exports=DI});var t_=k((BB,e_)=>{"use strict";var LI=qe(),NI=(r,e)=>new LI(r,e).patch;e_.exports=NI});var n_=k((UB,r_)=>{"use strict";var FI=_n(),jI=(r,e)=>{let t=FI(r,e);return t&&t.prerelease.length?t.prerelease:null};r_.exports=jI});var Ht=k((VB,s_)=>{"use strict";var i_=qe(),qI=(r,e,t)=>new i_(r,t).compare(new i_(e,t));s_.exports=qI});var a_=k((HB,o_)=>{"use strict";var BI=Ht(),UI=(r,e,t)=>BI(e,r,t);o_.exports=UI});var l_=k((zB,c_)=>{"use strict";var VI=Ht(),HI=(r,e)=>VI(r,e,!0);c_.exports=HI});var Dc=k((KB,u_)=>{"use strict";var d_=qe(),zI=(r,e,t)=>{let n=new d_(r,t),i=new d_(e,t);return n.compare(i)||n.compareBuild(i)};u_.exports=zI});var p_=k((WB,f_)=>{"use strict";var KI=Dc(),WI=(r,e)=>r.sort((t,n)=>KI(t,n,e));f_.exports=WI});var m_=k((GB,h_)=>{"use strict";var GI=Dc(),JI=(r,e)=>r.sort((t,n)=>GI(n,t,e));h_.exports=JI});var ko=k((JB,y_)=>{"use strict";var YI=Ht(),XI=(r,e,t)=>YI(r,e,t)>0;y_.exports=XI});var Lc=k((YB,g_)=>{"use strict";var QI=Ht(),ZI=(r,e,t)=>QI(r,e,t)<0;g_.exports=ZI});var Xp=k((XB,b_)=>{"use strict";var eO=Ht(),tO=(r,e,t)=>eO(r,e,t)===0;b_.exports=tO});var Qp=k((QB,v_)=>{"use strict";var rO=Ht(),nO=(r,e,t)=>rO(r,e,t)!==0;v_.exports=nO});var Nc=k((ZB,w_)=>{"use strict";var iO=Ht(),sO=(r,e,t)=>iO(r,e,t)>=0;w_.exports=sO});var Fc=k((eU,__)=>{"use strict";var oO=Ht(),aO=(r,e,t)=>oO(r,e,t)<=0;__.exports=aO});var Zp=k((tU,S_)=>{"use strict";var cO=Xp(),lO=Qp(),dO=ko(),uO=Nc(),fO=Lc(),pO=Fc(),hO=(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 cO(r,t,n);case"!=":return lO(r,t,n);case">":return dO(r,t,n);case">=":return uO(r,t,n);case"<":return fO(r,t,n);case"<=":return pO(r,t,n);default:throw new TypeError(`Invalid operator: ${e}`)}};S_.exports=hO});var $_=k((rU,x_)=>{"use strict";var mO=qe(),yO=_n(),{safeRe:jc,t:qc}=ss(),gO=(r,e)=>{if(r instanceof mO)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?jc[qc.COERCEFULL]:jc[qc.COERCE]);else{let c=e.includePrerelease?jc[qc.COERCERTLFULL]:jc[qc.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 yO(`${n}.${i}.${s}${o}${a}`,e)};x_.exports=gO});var k_=k((nU,E_)=>{"use strict";var bO=_n(),vO=is(),wO=qe(),_O=(r,e,t)=>{if(!vO.RELEASE_TYPES.includes(e))return null;let n=SO(r,t);return n&&xO(n,e)},SO=(r,e)=>{let t=r instanceof wO?r.version:r;return bO(t,e)},xO=(r,e)=>{if($O(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()},$O=r=>r.startsWith("pre");E_.exports=_O});var P_=k((iU,A_)=>{"use strict";var eh=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}};A_.exports=eh});var zt=k((sU,T_)=>{"use strict";var EO=/\s+/g,th=class r{constructor(e,t){if(t=AO(t),e instanceof r)return e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease?e:new r(e.raw,t);if(e instanceof rh)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(EO," "),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=>!M_(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&&LO(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(DO,"");let n=((this.options.includePrerelease&&IO)|(this.options.loose&&OO))+":"+e,i=C_.get(n);if(i)return i;let s=this.options.loose,o=s?st[Be.HYPHENRANGELOOSE]:st[Be.HYPHENRANGE];e=e.replace(o,WO(this.options.includePrerelease)),be("hyphen replace",e),e=e.replace(st[Be.COMPARATORTRIM],MO),be("comparator trim",e),e=e.replace(st[Be.TILDETRIM],RO),be("tilde trim",e),e=e.replace(st[Be.CARETTRIM],TO),be("caret trim",e);let a=e.split(" ").map(d=>NO(d,this.options)).join(" ").split(/\s+/).map(d=>KO(d,this.options));s&&(a=a.filter(d=>(be("loose invalid filter",d,this.options),!!d.match(st[Be.COMPARATORLOOSE])))),be("range list",a);let c=new Map,l=a.map(d=>new rh(d,this.options));for(let d of l){if(M_(d))return[d];c.set(d.value,d)}c.size>1&&c.has("")&&c.delete("");let u=[...c.values()];return C_.set(n,u),u}intersects(e,t){if(!(e instanceof r))throw new TypeError("a Range is required");return this.set.some(n=>R_(n,t)&&e.set.some(i=>R_(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 PO(e,this.options)}catch{return!1}for(let t=0;tr.value==="<0.0.0-0",LO=r=>r.value==="",R_=(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},NO=(r,e)=>(r=r.replace(st[Be.BUILD],""),be("comp",r,e),r=BO(r,e),be("caret",r),r=jO(r,e),be("tildes",r),r=VO(r,e),be("xrange",r),r=zO(r,e),be("stars",r),r),Ie=r=>!r||r.toLowerCase()==="x"||r==="*",FO=(r,e,t)=>Ie(r)&&!Ie(e)||Ie(e)&&t&&!Ie(t),jO=(r,e)=>r.trim().split(/\s+/).map(t=>qO(t,e)).join(" "),qO=(r,e)=>{let t=e.loose?st[Be.TILDELOOSE]:st[Be.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 Ie(s)?l="":Ie(o)?l=`>=${s}.0.0${n} <${+s+1}.0.0-0`:Ie(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})},BO=(r,e)=>r.trim().split(/\s+/).map(t=>UO(t,e)).join(" "),UO=(r,e)=>{be("caret",r,e);let t=e.loose?st[Be.CARETLOOSE]:st[Be.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 Ie(s)?l="":Ie(o)?l=`>=${s}.0.0${n} <${+s+1}.0.0-0`:Ie(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})},VO=(r,e)=>(be("replaceXRanges",r,e),r.split(/\s+/).map(t=>HO(t,e)).join(" ")),HO=(r,e)=>{r=r.trim();let t=e.loose?st[Be.XRANGELOOSE]:st[Be.XRANGE];return r.replace(t,(n,i,s,o,a,c)=>{if(be("xRange",r,n,i,s,o,a,c),FO(s,o,a))return r;let l=Ie(s),u=l||Ie(o),d=u||Ie(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})},zO=(r,e)=>(be("replaceStars",r,e),r.trim().replace(st[Be.STAR],"")),KO=(r,e)=>(be("replaceGTE0",r,e),r.trim().replace(st[e.includePrerelease?Be.GTE0PRE:Be.GTE0],"")),WO=r=>(e,t,n,i,s,o,a,c,l,u,d,f)=>(Ie(n)?t="":Ie(i)?t=`>=${n}.0.0${r?"-0":""}`:Ie(s)?t=`>=${n}.${i}.0${r?"-0":""}`:o?t=`>=${t}`:t=`>=${t}${r?"-0":""}`,Ie(l)?c="":Ie(u)?c=`<${+l+1}.0.0-0`:Ie(d)?c=`<${l}.${+u+1}.0-0`:f?c=`<=${l}.${u}.${d}-${f}`:r?c=`<${l}.${u}.${+d+1}-0`:c=`<=${c}`,`${t} ${c}`.trim()),GO=(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 Ao=k((oU,F_)=>{"use strict";var Po=Symbol("SemVer ANY"),sh=class r{static get ANY(){return Po}constructor(e,t){if(t=I_(t),e instanceof r){if(e.loose===!!t.loose)return e;e=e.value}e=e.trim().split(/\s+/).join(" "),ih("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,ih("comp",this)}parse(e){let t=this.options.loose?O_[D_.COMPARATORLOOSE]:O_[D_.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 L_(n[2],this.options.loose):this.semver=Po}toString(){return this.value}test(e){if(ih("Comparator.test",e,this.options.loose),this.semver===Po||e===Po)return!0;if(typeof e=="string")try{e=new L_(e,this.options)}catch{return!1}return nh(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 N_(e.value,t).test(this.value):e.operator===""?e.value===""?!0:new N_(this.value,t).test(e.semver):(t=I_(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("=")||nh(this.semver,"<",e.semver,t)&&this.operator.startsWith(">")&&e.operator.startsWith("<")||nh(this.semver,">",e.semver,t)&&this.operator.startsWith("<")&&e.operator.startsWith(">")))}};F_.exports=sh;var I_=Mc(),{safeRe:O_,t:D_}=ss(),nh=Zp(),ih=Eo(),L_=qe(),N_=zt()});var Co=k((aU,j_)=>{"use strict";var JO=zt(),YO=(r,e,t)=>{try{e=new JO(e,t)}catch{return!1}return e.test(r)};j_.exports=YO});var B_=k((cU,q_)=>{"use strict";var XO=zt(),QO=(r,e)=>new XO(r,e).set.map(t=>t.map(n=>n.value).join(" ").trim().split(" "));q_.exports=QO});var V_=k((lU,U_)=>{"use strict";var ZO=qe(),eD=zt(),tD=(r,e,t)=>{let n=null,i=null,s=null;try{s=new eD(e,t)}catch{return null}return r.forEach(o=>{s.test(o)&&(!n||i.compare(o)===-1)&&(n=o,i=new ZO(n,t))}),n};U_.exports=tD});var z_=k((dU,H_)=>{"use strict";var rD=qe(),nD=zt(),iD=(r,e,t)=>{let n=null,i=null,s=null;try{s=new nD(e,t)}catch{return null}return r.forEach(o=>{s.test(o)&&(!n||i.compare(o)===1)&&(n=o,i=new rD(n,t))}),n};H_.exports=iD});var G_=k((uU,W_)=>{"use strict";var oh=qe(),sD=zt(),K_=ko(),oD=(r,e)=>{r=new sD(r,e);let t=new oh("0.0.0");if(r.test(t)||(t=new oh("0.0.0-0"),r.test(t)))return t;t=null;for(let n=0;n{let a=new oh(o.semver.version);switch(o.operator){case">":a.prerelease.length===0?a.patch++:a.prerelease.push(0),a.raw=a.format();case"":case">=":(!s||K_(a,s))&&(s=a);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${o.operator}`)}}),s&&(!t||K_(t,s))&&(t=s)}return t&&r.test(t)?t:null};W_.exports=oD});var Y_=k((fU,J_)=>{"use strict";var aD=zt(),cD=(r,e)=>{try{return new aD(r,e).range||"*"}catch{return null}};J_.exports=cD});var Bc=k((pU,e0)=>{"use strict";var lD=qe(),Z_=Ao(),{ANY:dD}=Z_,uD=zt(),fD=Co(),X_=ko(),Q_=Lc(),pD=Fc(),hD=Nc(),mD=(r,e,t,n)=>{r=new lD(r,n),e=new uD(e,n);let i,s,o,a,c;switch(t){case">":i=X_,s=pD,o=Q_,a=">",c=">=";break;case"<":i=Q_,s=hD,o=X_,a="<",c="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(fD(r,e,n))return!1;for(let l=0;l{p.semver===dD&&(p=new Z_(">=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};e0.exports=mD});var r0=k((hU,t0)=>{"use strict";var yD=Bc(),gD=(r,e,t)=>yD(r,e,">",t);t0.exports=gD});var i0=k((mU,n0)=>{"use strict";var bD=Bc(),vD=(r,e,t)=>bD(r,e,"<",t);n0.exports=vD});var a0=k((yU,o0)=>{"use strict";var s0=zt(),wD=(r,e,t)=>(r=new s0(r,t),e=new s0(e,t),r.intersects(e,t));o0.exports=wD});var l0=k((gU,c0)=>{"use strict";var _D=Co(),SD=Ht();c0.exports=(r,e,t)=>{let n=[],i=null,s=null,o=r.sort((u,d)=>SD(u,d,t));for(let u of o)_D(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 d0=zt(),lh=Ao(),{ANY:ah}=lh,ch=Co(),dh=Ht(),xD=(r,e,t={})=>{if(r===e)return!0;r=new d0(r,t),e=new d0(e,t);let n=!1;e:for(let i of r.set){for(let s of e.set){let o=ED(i,s,t);if(n=n||o!==null,o)continue e}if(n)return!1}return!0},$D=[new lh(">=0.0.0-0")],u0=[new lh(">=0.0.0")],ED=(r,e,t)=>{if(r===e)return!0;if(r.length===1&&r[0].semver===ah){if(e.length===1&&e[0].semver===ah)return!0;t.includePrerelease?r=$D:r=u0}if(e.length===1&&e[0].semver===ah){if(t.includePrerelease)return!0;e=u0}let n=new Set,i,s;for(let p of r)p.operator===">"||p.operator===">="?i=f0(i,p,t):p.operator==="<"||p.operator==="<="?s=p0(s,p,t):n.add(p.semver);if(n.size>1)return null;let o;if(i&&s){if(o=dh(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&&!ch(p,String(i),t)||s&&!ch(p,String(s),t))return null;for(let h of e)if(!ch(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=f0(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=p0(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)},f0=(r,e,t)=>{if(!r)return e;let n=dh(r.semver,e.semver,t);return n>0?r:n<0||e.operator===">"&&r.operator===">="?e:r},p0=(r,e,t)=>{if(!r)return e;let n=dh(r.semver,e.semver,t);return n<0?r:n>0||e.operator==="<"&&r.operator==="<="?e:r};h0.exports=xD});var v0=k((vU,b0)=>{"use strict";var uh=ss(),y0=is(),kD=qe(),g0=Gp(),AD=_n(),PD=Bw(),CD=Vw(),MD=Kw(),RD=Jw(),TD=Xw(),ID=Zw(),OD=t_(),DD=n_(),LD=Ht(),ND=a_(),FD=l_(),jD=Dc(),qD=p_(),BD=m_(),UD=ko(),VD=Lc(),HD=Xp(),zD=Qp(),KD=Nc(),WD=Fc(),GD=Zp(),JD=$_(),YD=k_(),XD=Ao(),QD=zt(),ZD=Co(),eL=B_(),tL=V_(),rL=z_(),nL=G_(),iL=Y_(),sL=Bc(),oL=r0(),aL=i0(),cL=a0(),lL=l0(),dL=m0();b0.exports={parse:AD,valid:PD,clean:CD,inc:MD,diff:RD,major:TD,minor:ID,patch:OD,prerelease:DD,compare:LD,rcompare:ND,compareLoose:FD,compareBuild:jD,sort:qD,rsort:BD,gt:UD,lt:VD,eq:HD,neq:zD,gte:KD,lte:WD,cmp:GD,coerce:JD,truncate:YD,Comparator:XD,Range:QD,satisfies:ZD,toComparators:eL,maxSatisfying:tL,minSatisfying:rL,minVersion:nL,validRange:iL,outside:sL,gtr:oL,ltr:aL,intersects:cL,simplifyRange:lL,subset:dL,SemVer:kD,re:uh.re,src:uh.src,tokens:uh.t,SEMVER_SPEC_VERSION:y0.SEMVER_SPEC_VERSION,RELEASE_TYPES:y0.RELEASE_TYPES,compareIdentifiers:g0.compareIdentifiers,rcompareIdentifiers:g0.rcompareIdentifiers}});var mj={};ly(mj,{default:()=>Dd});module.exports=sE(mj);var Lt=require("obsidian"),Nd="https://mdbase.dev/contracts/catalog.json",Ns="mdbase.lock.yaml",Fr=".mdbase/obsidian-pack-install.json";function br(r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("Invalid contract catalog or type pack.");return r}function Yt(r){if(typeof r!="string"||!r)throw new Error("Missing catalog field.");return r}function fy(r){let e=Yt(r);if(!/^sha256:[a-f0-9]{64}$/.test(e))throw new Error("Invalid pack digest.");return e}function Ra(r){let e=Yt(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 Fd(r){return Array.isArray(r)?`[${r.map(Fd).join(",")}]`:r&&typeof r=="object"?`{${Object.entries(r).sort(([e],[t])=>et?1:0).map(([e,t])=>`${JSON.stringify(e)}:${Fd(t)}`).join(",")}}`:JSON.stringify(r)}function oE(r){let e=new URL(Yt(r),Nd);if(e.origin!==new URL(Nd).origin||!e.pathname.startsWith("/contracts/"))throw new Error("Pack artifacts must come from the first-party contract catalog.");return e.href}async function aE(){let r=await(0,Lt.requestUrl)({url:Nd,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=br(r.json);if(e.catalog_version!==2||!Array.isArray(e.packs))throw new Error("Unsupported contract catalog.");return e.packs.map(t=>{let n=br(t),i=br(n.display),s=br(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:Yt(n.id),version:Yt(n.version),digest:fy(n.digest),provision:oE(n.provision),resource_count:Number(n.resource_count),display:{name:Yt(i.name),summary:Yt(i.summary)},installation:{visibility:Yt(s.visibility),recommendation:Yt(s.recommendation),primary_type:s.primary_type==null?null:Yt(s.primary_type),...typeof s.caution=="string"?{caution:s.caution}:{}}}})}async function Gn(r,e){let t=r.vault.getAbstractFileByPath(e);if(t&&!(t instanceof Lt.TFile))throw new Error(`A folder occupies ${e}.`);return t instanceof Lt.TFile?r.vault.read(t):null}async function uy(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 cE(r,e){let t=await(0,Lt.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 lE(r,e,JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(t.arrayBuffer)))}async function lE(r,e,t){let n=br(t),i=br(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=br(m),g=Ra(y.source);if(s.has(g))throw new Error("Duplicate pack source.");let b=Yt(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 Gn(r,Ns),u=l?(0,Lt.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(Fd(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=br(m),g=Ra(y.source),b=Ra(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),_=fy(y.digest);if(!S||await Pi(S)!==_)throw new Error(`Resource digest mismatch: ${g}`);if(u.packs.some(R=>R.id!==e.id&&R.resources.some($=>$.mode==="managed"&&$.target===b)))throw new Error(`${b} belongs to another installed pack.`);let E=await Gn(r,b),A=d?.resources.find(R=>R.target===b);if(y.mode==="managed"&&E!==null&&await Pi(E)!==_)throw new Error(`${b} already exists with different contents. Nothing was overwritten.`);let x=E===null&&!(y.mode==="seed"&&A)?"create":y.mode==="seed"?"preserve":"unchanged";a.push({path:b,before:E,after:S,action:x}),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 jd(r){if(!await r.vault.adapter.exists(Fr))return;let e=br(JSON.parse(await r.vault.adapter.read(Fr)));if(!Array.isArray(e.created))throw new Error("Invalid pack recovery journal.");if(await Gn(r,Ns)===e.lockAfter){await r.vault.adapter.remove(Fr);return}for(let t of[...e.created].reverse()){let n=br(t),i=Ra(n.path),s=r.vault.getAbstractFileByPath(i);if(s instanceof Lt.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(Fr)}var Ld=new WeakSet;async function dE(r,e,t,n){if(Ld.has(r))throw new Error("Another contract pack is installing. Wait for it to finish.");Ld.add(r);try{await uE(r,e,t,n)}finally{Ld.delete(r)}}async function uE(r,e,t,n){if(t(),await r.vault.adapter.exists(Fr))throw new Error("Recover the previous pack installation before trying again.");if(await Gn(r,Ns)!==e.lockBefore)throw new Error("Pack lock changed. Review again.");for(let s of e.files)if(await Gn(r,s.path)!==s.before)throw new Error(`${s.path} changed. Review again.`);await uy(r,Fr);let i={lockAfter:e.lockAfter,created:[]};await r.vault.adapter.write(Fr,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 uy(r,c.path),await Gn(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(Fr,JSON.stringify(i)),await r.vault.create(c.path,c.after),await Gn(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(Ns);o instanceof Lt.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(Ns,e.lockAfter),await r.vault.adapter.remove(Fr)}catch(s){throw await jd(r),s}}var Ta=class extends Lt.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 aE();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,cE(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,dE(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 Ia=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 it=require("obsidian");var bw=require("obsidian");Vt();function YT(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 bw.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=Dp(n,i)}onOpen(){this.titleEl.setText(`New ${this.type.name}`),this.contentEl.addClass("mdbase-create-note");let t=Lp(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)]:xc(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 Np(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=YT(this.pathInput.value);if(bt(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?es(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}};Vt();var ts=require("obsidian");var jp=class extends ts.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 qp(r,e){return new Promise(t=>{new jp(r,e,i=>{if(i.type==="selected"){t(i.typeDef);return}t(null)}).open()})}var Ec=class extends ts.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())}},kc=class extends ts.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 ts.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 move unchanged synced files to trash. 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:"Trash 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 vw(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||QT(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 ZT(r)}),r.addCommand({id:"mdbase-create-note-from-type",name:"Create note from type",callback:()=>void Bp(r)}),r.addCommand({id:"mdbase-validate-current-note",name:"Validate current note",checkCallback:n=>{let i=e.workspace.getActiveFile();return!(i instanceof it.TFile)||i.extension!=="md"?!1:(n||eI(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||XT(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 it.TFile)||!t()||n.addItem(s=>s.setTitle("Sync history").setIcon("history").onClick(()=>r.openNoteSyncHistory(i.path)))}))}async function XT(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 it.Notice(`Review before syncing: ${i.join(", ").toLowerCase()||"changes need attention"}.`),await r.openWorkspace("sync")}else e==="busy"?new it.Notice("A sync is already running."):e==="paused"?new it.Notice("Sync is paused."):e==="failed"?new it.Notice(n?.message??(t||"Sync failed.")):t&&new it.Notice(t)}async function QT(r){r.connectSync.assertLocalAuthorityWritable();let{created:e}=await xo(r.app.vault,{seedNoteType:!1});r.invalidateSchemaCache(),new it.Notice(e.length?`Initialized mdbase collection: ${e.join(", ")}`:"mdbase collection already initialized.")}async function ZT(r){let e=await r.requireConfigAndTypes();if(!e)return;if(e.types.size===0){new it.Notice("No type definitions found.");return}let t=r.app.workspace.getActiveFile(),n=[];if(t instanceof it.TFile&&t.extension==="md"){let o=[...e.types.values()].find(a=>a.filePath===t.path);if(o)n=[o];else{let a=Te(await r.app.vault.cachedRead(t));a.error||(n=Ge(t.path,a.frontmatter,e.config,e.types).flatMap(c=>e.types.get(c)??[]))}}let i=n.length===1?n[0]:await qp(r.app,n.length?n:[...e.types.values()]);if(!i)return;await(await r.openWorkspace("types")).editType(i.filePath)}async function eI(r,e){let t=await r.validateFileAndStore(e,"manual");if(t.length===0){new it.Notice("No issues in current note.");return}new it.Notice(`Found ${t.length} issue${t.length===1?"":"s"} in current note.`),(await r.openWorkspace("issues")).showIssuesForPath(e.path)}async function Bp(r,e){r.connectSync.assertLocalAuthorityWritable();let t=await r.requireConfigAndTypes();if(!t)return;if(t.types.size===0){new it.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 qp(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(()=>(Vt(),gw)),a=await o(r.app.vault,i,s);await r.app.workspace.getLeaf(!0).openFile(a),await r.validateFileAndStore(a,"manual")}).open()}var ww=require("obsidian");Vt();function Up(r,e){let t=Te(r);if(t.error)throw new Error(`Invalid frontmatter: ${t.error}`);return tI(t.frontmatter,e)?{content:`--- ${(0,ww.stringifyYaml)(t.frontmatter).trimEnd()} --- -${t.body}`,changed:!0}:{content:r,changed:!1}}function _w(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 Sw(r){return _w(r)?["unknown_field","schema_additional_properties"].includes(r.code)?"Remove field":"Add placeholder":null}function tI(r,e){let t=_w(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}}}},$o=class extends Error{status;error;constructor(e,t){super(t.message),this.status=e,this.error=t,this.name="ActionHandlerError"}};var xw=Wn(Zf(),1),$w=Wn(lp(),1);var Vp={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 rI=$w.default;function Ew(){return Object.fromEntries(Object.entries(Vp).map(([r,e])=>[r,structuredClone(e)]))}function Hp(){let r=new xw.Ajv2020({allErrors:!0,strict:!1,validateFormats:!0});rI(r);let e=Ew();r.addSchema(e.profile);for(let[t,n]of Object.entries(e))t!=="profile"&&r.addSchema(n);return r}function Vr(r,e){let t=String(Vp[e].$id),n=r.getSchema(t);if(!n)throw new Error(`Canonical interoperability schema is unavailable: ${e}`);return n}function wn(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 kw(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 Pc(r){return ns(kw(r))}async function ns(r){return`sha256:${await nI(zp(r))}`}function Aw(r,e){return{data:rs(r,e.data_schema,`${e.id} data_schema`),...e.source_schema?{source:rs(r,e.source_schema,`${e.id} source_schema`)}:{}}}function Pw(r,e){return{input:rs(r,e.input_schema,`${e.id} input_schema`),...e.output_schema?{output:rs(r,e.output_schema,`${e.id} output_schema`)}:{},...e.error_schema?{error:rs(r,e.error_schema,`${e.id} error_schema`)}:{},...e.provider_schema?{provider:rs(r,e.provider_schema,`${e.id} provider_schema`)}:{}}}function Cc(r,e,t,n){if(!(!r||r(e)))throw new O(t,`${n} failed JSON Schema validation: ${wn(r.errors)}`)}function rs(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 zp(r){return r===null||typeof r!="object"?JSON.stringify(r):Array.isArray(r)?`[${r.map(zp).join(",")}]`:`{${Object.entries(r).filter(([,t])=>t!==void 0).sort(([t],[n])=>tn?1:0).map(([t,n])=>`${JSON.stringify(t)}:${zp(n)}`).join(",")}}`}async function nI(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 zr=Wn(v0(),1);var fh={delivery:["ephemeral"],ordering:["none"],cancellation:!0,deadlines:!0,provider_discovery:!0,request_deduplication:!0,cross_process_identity:!1},uN=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=Hp();contractValidator=Vr(this.ajv,"contract");eventValidator=Vr(this.ajv,"event");actionRequestValidator=Vr(this.ajv,"actionRequest");actionInvocationValidator=Vr(this.ajv,"actionInvocation");actionOutcomeValidator=Vr(this.ajv,"actionOutcome");eventSourceDeclarationValidator=Vr(this.ajv,"eventSourceDeclaration");actionProviderDeclarationValidator=Vr(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={...fh,...structuredClone(e.transport??{}),delivery:[...e.transport?.delivery??fh.delivery],ordering:[...e.transport?.ordering??fh.ordering]}}connect(e){this.assertActive(),fN(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=w0(l.requirement,u.reference);if(_0(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: ${wn(u.sourceValidator.errors)}`);let f=Uc(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 ns(o)};Sn(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=Uc(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}}),ph(t.data,"invalid_event_data",`Event ${o.reference.id} data`),Cc(o.dataValidator,t.data,"invalid_event_data",`Event ${o.reference.id} data`);let a=t.extensions??{};for(let h of Object.keys(a))if(uN.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:pN(n.identity),type:o.reference.id,time:t.time??this.now().toISOString(),...t.subject===void 0?{}:{subject:t.subject},datacontenttype:"application/json",dataschema:$0(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}};Sn(this.eventValidator,c,"invalid_event_data","Event envelope"),hh(this.transport,c),hN(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)),x0(this.recentEvents,this.recentEventLimit);let d=[...this.subscriptions.values()].filter(({subscription:h})=>Vc(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);mh(t.contract),gN(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=w0(d.requirement,f.reference);if(_0(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: ${wn(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 ns(a)};Sn(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);mh(t.contract);let i=t.request_id??this.idFactory("req");this.cleanCompletedActions(),ph(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)};Sn(this.actionRequestValidator,s,"request_rejected","Action request"),hh(this.transport,s);let o=await this.acquireAdmission(i);try{let a=await ns(mN(s)),c=this.activeActions.get(i);if(c){if(S0(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(S0(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.`);Cc(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)};Sn(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}),x0(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.`})}ph(i,"invalid_action_output",`Action ${e.contract.reference.id} output`),Cc(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 Sn(this.actionOutcomeValidator,s,"invalid_action_output","Action outcome"),hh(this.transport,s),s}catch(i){if(i instanceof $o)return e.contract.errorValidator&&!e.contract.errorValidator(i.error.details??{})?this.failureOutcome(t,"failed",{code:"handler_failure",message:`Provider returned invalid declared error details: ${wn(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||bN(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 Sn(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})=>Vc(e,s.reference)&&yN(t,o.provider)),i=(0,zr.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})=>Vc(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 Pc(e)};this.assertNoContractConflict(t);let n=Aw(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 Pc(e)};this.assertNoContractConflict(t);let n=Pw(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(Sn(this.contractValidator,e,"contract_digest_conflict",`Contract ${e.id||""}`),!(0,zr.valid)(e.version))throw new O("unsupported_contract_version",`${e.id} version must be exact SemVer.`)}assertNoContractConflict(e){let t=this.contracts.get(Uc(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=Uc(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 Sn(r,e,t,n){if(!r(e))throw new O(t,`${n} is invalid: ${wn(r.errors)}`)}function fN(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,zr.valid)(r.version))throw new O("request_rejected","Implementation identity version must be exact SemVer.")}function mh(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,zr.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 w0(r,e){let t=r??{id:e.id,version:e.version,digest:e.digest};return mh(t),structuredClone(t)}function _0(r,e){if(!Vc(r,e))throw new O("unsupported_contract_version",`${e.id} ${e.version} does not satisfy its implementation requirement.`)}function Vc(r,e){return r.id===e.id&&(0,zr.satisfies)(e.version,r.version,{includePrerelease:!0})&&(!r.digest||r.digest===e.digest)}function Uc(r){return`${r.id}@${r.version}`}function $0(r){return`urn:mdbase:contract:${r.id}:${r.version}:${r.digest}`}function pN(r){return`urn:mdbase:app:${[r.application,r.implementation,...r.instance_id?[r.instance_id]:[]].map(encodeURIComponent).join(":")}`}function hN(r,e){if(r.type!==e.id||r.mdbasecontractversion!==e.version||r.mdbasecontractdigest!==e.digest||r.dataschema!==$0(e))throw new O("contract_digest_conflict","Event contract evidence is inconsistent.")}function mN(r){let{created_at:e,...t}=r;return t}function S0(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 ph(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 hh(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 yN(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 gN(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 bN(r){return r instanceof Error&&r.name==="AbortError"}var Hc=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()}};Vt();var J=require("obsidian"),s$=Wn(wp(),1);var zc=Symbol.for("yaml.alias"),Kc=Symbol.for("yaml.document"),rr=Symbol.for("yaml.map"),yh=Symbol.for("yaml.pair"),Pt=Symbol.for("yaml.scalar"),Kr=Symbol.for("yaml.seq"),ot=Symbol.for("yaml.node.type"),nr=r=>!!r&&typeof r=="object"&&r[ot]===zc,kr=r=>!!r&&typeof r=="object"&&r[ot]===Kc,ir=r=>!!r&&typeof r=="object"&&r[ot]===rr,te=r=>!!r&&typeof r=="object"&&r[ot]===yh,W=r=>!!r&&typeof r=="object"&&r[ot]===Pt,sr=r=>!!r&&typeof r=="object"&&r[ot]===Kr;function ae(r){if(r&&typeof r=="object")switch(r[ot]){case rr:case Kr:return!0}return!1}function ne(r){if(r&&typeof r=="object")switch(r[ot]){case zc:case rr:case Pt:case Kr:return!0}return!1}var Wc=r=>(W(r)||ae(r))&&!!r.anchor;var vt=Symbol("break visit"),E0=Symbol("skip children"),Ar=Symbol("remove node");function Pr(r,e){let t=k0(e);kr(r)?os(null,r.contents,t,Object.freeze([r]))===Ar&&(r.contents=null):os(null,r,t,Object.freeze([]))}Pr.BREAK=vt;Pr.SKIP=E0;Pr.REMOVE=Ar;function os(r,e,t,n){let i=A0(r,e,t,n);if(ne(i)||te(i))return P0(r,n,i),os(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=>vN[e]),Cr=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+wN(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={};Pr(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(` -`)}};Cr.defaultYaml={explicit:!1,version:"1.2"};Cr.defaultTags={"!!":"tag:yaml.org,2002:"};function Jc(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 gh(r){let e=new Set;return Pr(r,{Value(t,n){n.anchor&&e.add(n.anchor)}}),e}function bh(r,e){for(let t=1;;++t){let n=`${r}${t}`;if(!e.has(n))return n}}function C0(r,e){let t=[],n=new Map,i=null;return{onAnchor:s=>{t.push(s),i??(i=gh(r));let o=bh(e,i);return i.add(o),o},setAnchors:()=>{for(let s of t){let o=n.get(s);if(typeof o=="object"&&o.anchor&&(W(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 xn(r,e,t,n){if(n&&typeof n=="object")if(Array.isArray(n))for(let i=0,s=n.length;iTe(n,String(i),t));if(r&&typeof r.toJSON=="function"){if(!t||!Wc(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 $n=class{constructor(e){Object.defineProperty(this,ot,{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(!kr(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=Te(this,"",o);if(typeof i=="function")for(let{count:c,res:l}of o.anchors.values())i(l,c);return typeof s=="function"?xn(s,{"":a},"",a):a}};var Wr=class extends $n{constructor(e){super(zc),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=[],Pr(e,{Node:(s,o)=>{(nr(o)||Wc(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||(Te(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=Yc(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(Jc(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 Yc(r,e,t){if(nr(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=Yc(r,i,t);s>n&&(n=s)}return n}else if(te(e)){let n=Yc(r,e.key,t),i=Yc(r,e.value,t);return Math.max(n,i)}return 1}var Xc=r=>!r||typeof r!="function"&&typeof r!="object",F=class extends $n{constructor(e){super(Pt),this.value=e}toJSON(e,t){return t?.keep?this.value:Te(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 _N="tag:yaml.org,2002:";function SN(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 Gr(r,e,t){if(kr(r)&&(r=r.contents),ne(r))return r;if(te(r)){let d=t.schema[rr].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 Wr(c.anchor);c={anchor:null,node:null},a.set(r,c)}e?.startsWith("!!")&&(e=_N+e.slice(2));let l=SN(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[rr]:Symbol.iterator in Object(r)?o[Kr]:o[rr]}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 Ro(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 Gr(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 ls=r=>r==null||typeof r=="object"&&!!r[Symbol.iterator]().next().done,cs=class extends $n{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(ls(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,Ro(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&&W(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&&W(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,Ro(this.schema,i,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${i}`)}}};var M0=r=>r.replace(/^(?!$)(?: $)?/gm,"#");function Kt(r,e){return/^\n+$/.test(r)?r.substring(1):e?r.replace(/^(?! *$)/gm,e):r}var Mr=(r,e,t)=>r.endsWith(` +${t.body}`,changed:!0}:{content:r,changed:!1}}function _w(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 Sw(r){return _w(r)?["unknown_field","schema_additional_properties"].includes(r.code)?"Remove field":"Add placeholder":null}function tI(r,e){let t=_w(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 N=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}}}},$o=class extends Error{status;error;constructor(e,t){super(t.message),this.status=e,this.error=t,this.name="ActionHandlerError"}};var xw=Wn(Zf(),1),$w=Wn(lp(),1);var Vp={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 rI=$w.default;function Ew(){return Object.fromEntries(Object.entries(Vp).map(([r,e])=>[r,structuredClone(e)]))}function Hp(){let r=new xw.Ajv2020({allErrors:!0,strict:!1,validateFormats:!0});rI(r);let e=Ew();r.addSchema(e.profile);for(let[t,n]of Object.entries(e))t!=="profile"&&r.addSchema(n);return r}function Vr(r,e){let t=String(Vp[e].$id),n=r.getSchema(t);if(!n)throw new Error(`Canonical interoperability schema is unavailable: ${e}`);return n}function wn(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 kw(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 Pc(r){return ns(kw(r))}async function ns(r){return`sha256:${await nI(zp(r))}`}function Aw(r,e){return{data:rs(r,e.data_schema,`${e.id} data_schema`),...e.source_schema?{source:rs(r,e.source_schema,`${e.id} source_schema`)}:{}}}function Pw(r,e){return{input:rs(r,e.input_schema,`${e.id} input_schema`),...e.output_schema?{output:rs(r,e.output_schema,`${e.id} output_schema`)}:{},...e.error_schema?{error:rs(r,e.error_schema,`${e.id} error_schema`)}:{},...e.provider_schema?{provider:rs(r,e.provider_schema,`${e.id} provider_schema`)}:{}}}function Cc(r,e,t,n){if(!(!r||r(e)))throw new O(t,`${n} failed JSON Schema validation: ${wn(r.errors)}`)}function rs(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 zp(r){return r===null||typeof r!="object"?JSON.stringify(r):Array.isArray(r)?`[${r.map(zp).join(",")}]`:`{${Object.entries(r).filter(([,t])=>t!==void 0).sort(([t],[n])=>tn?1:0).map(([t,n])=>`${JSON.stringify(t)}:${zp(n)}`).join(",")}}`}async function nI(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 zr=Wn(v0(),1);var fh={delivery:["ephemeral"],ordering:["none"],cancellation:!0,deadlines:!0,provider_discovery:!0,request_deduplication:!0,cross_process_identity:!1},uL=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=Hp();contractValidator=Vr(this.ajv,"contract");eventValidator=Vr(this.ajv,"event");actionRequestValidator=Vr(this.ajv,"actionRequest");actionInvocationValidator=Vr(this.ajv,"actionInvocation");actionOutcomeValidator=Vr(this.ajv,"actionOutcome");eventSourceDeclarationValidator=Vr(this.ajv,"eventSourceDeclaration");actionProviderDeclarationValidator=Vr(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={...fh,...structuredClone(e.transport??{}),delivery:[...e.transport?.delivery??fh.delivery],ordering:[...e.transport?.ordering??fh.ordering]}}connect(e){this.assertActive(),fL(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=w0(l.requirement,u.reference);if(_0(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: ${wn(u.sourceValidator.errors)}`);let f=Uc(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 ns(o)};Sn(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=Uc(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}}),ph(t.data,"invalid_event_data",`Event ${o.reference.id} data`),Cc(o.dataValidator,t.data,"invalid_event_data",`Event ${o.reference.id} data`);let a=t.extensions??{};for(let h of Object.keys(a))if(uL.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:pL(n.identity),type:o.reference.id,time:t.time??this.now().toISOString(),...t.subject===void 0?{}:{subject:t.subject},datacontenttype:"application/json",dataschema:$0(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}};Sn(this.eventValidator,c,"invalid_event_data","Event envelope"),hh(this.transport,c),hL(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)),x0(this.recentEvents,this.recentEventLimit);let d=[...this.subscriptions.values()].filter(({subscription:h})=>Vc(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);mh(t.contract),gL(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=w0(d.requirement,f.reference);if(_0(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: ${wn(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 ns(a)};Sn(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);mh(t.contract);let i=t.request_id??this.idFactory("req");this.cleanCompletedActions(),ph(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)};Sn(this.actionRequestValidator,s,"request_rejected","Action request"),hh(this.transport,s);let o=await this.acquireAdmission(i);try{let a=await ns(mL(s)),c=this.activeActions.get(i);if(c){if(S0(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(S0(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.`);Cc(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)};Sn(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}),x0(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.`})}ph(i,"invalid_action_output",`Action ${e.contract.reference.id} output`),Cc(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 Sn(this.actionOutcomeValidator,s,"invalid_action_output","Action outcome"),hh(this.transport,s),s}catch(i){if(i instanceof $o)return e.contract.errorValidator&&!e.contract.errorValidator(i.error.details??{})?this.failureOutcome(t,"failed",{code:"handler_failure",message:`Provider returned invalid declared error details: ${wn(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||bL(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 Sn(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})=>Vc(e,s.reference)&&yL(t,o.provider)),i=(0,zr.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})=>Vc(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 Pc(e)};this.assertNoContractConflict(t);let n=Aw(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 Pc(e)};this.assertNoContractConflict(t);let n=Pw(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(Sn(this.contractValidator,e,"contract_digest_conflict",`Contract ${e.id||""}`),!(0,zr.valid)(e.version))throw new O("unsupported_contract_version",`${e.id} version must be exact SemVer.`)}assertNoContractConflict(e){let t=this.contracts.get(Uc(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=Uc(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 Sn(r,e,t,n){if(!r(e))throw new O(t,`${n} is invalid: ${wn(r.errors)}`)}function fL(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,zr.valid)(r.version))throw new O("request_rejected","Implementation identity version must be exact SemVer.")}function mh(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,zr.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 w0(r,e){let t=r??{id:e.id,version:e.version,digest:e.digest};return mh(t),structuredClone(t)}function _0(r,e){if(!Vc(r,e))throw new O("unsupported_contract_version",`${e.id} ${e.version} does not satisfy its implementation requirement.`)}function Vc(r,e){return r.id===e.id&&(0,zr.satisfies)(e.version,r.version,{includePrerelease:!0})&&(!r.digest||r.digest===e.digest)}function Uc(r){return`${r.id}@${r.version}`}function $0(r){return`urn:mdbase:contract:${r.id}:${r.version}:${r.digest}`}function pL(r){return`urn:mdbase:app:${[r.application,r.implementation,...r.instance_id?[r.instance_id]:[]].map(encodeURIComponent).join(":")}`}function hL(r,e){if(r.type!==e.id||r.mdbasecontractversion!==e.version||r.mdbasecontractdigest!==e.digest||r.dataschema!==$0(e))throw new O("contract_digest_conflict","Event contract evidence is inconsistent.")}function mL(r){let{created_at:e,...t}=r;return t}function S0(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 ph(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 hh(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 yL(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 gL(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 bL(r){return r instanceof Error&&r.name==="AbortError"}var Hc=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()}};Vt();var J=require("obsidian"),s$=Wn(wp(),1);var zc=Symbol.for("yaml.alias"),Kc=Symbol.for("yaml.document"),rr=Symbol.for("yaml.map"),yh=Symbol.for("yaml.pair"),Pt=Symbol.for("yaml.scalar"),Kr=Symbol.for("yaml.seq"),ot=Symbol.for("yaml.node.type"),nr=r=>!!r&&typeof r=="object"&&r[ot]===zc,kr=r=>!!r&&typeof r=="object"&&r[ot]===Kc,ir=r=>!!r&&typeof r=="object"&&r[ot]===rr,te=r=>!!r&&typeof r=="object"&&r[ot]===yh,W=r=>!!r&&typeof r=="object"&&r[ot]===Pt,sr=r=>!!r&&typeof r=="object"&&r[ot]===Kr;function ae(r){if(r&&typeof r=="object")switch(r[ot]){case rr:case Kr:return!0}return!1}function ne(r){if(r&&typeof r=="object")switch(r[ot]){case zc:case rr:case Pt:case Kr:return!0}return!1}var Wc=r=>(W(r)||ae(r))&&!!r.anchor;var vt=Symbol("break visit"),E0=Symbol("skip children"),Ar=Symbol("remove node");function Pr(r,e){let t=k0(e);kr(r)?os(null,r.contents,t,Object.freeze([r]))===Ar&&(r.contents=null):os(null,r,t,Object.freeze([]))}Pr.BREAK=vt;Pr.SKIP=E0;Pr.REMOVE=Ar;function os(r,e,t,n){let i=A0(r,e,t,n);if(ne(i)||te(i))return P0(r,n,i),os(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=>vL[e]),Cr=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+wL(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={};Pr(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(` +`)}};Cr.defaultYaml={explicit:!1,version:"1.2"};Cr.defaultTags={"!!":"tag:yaml.org,2002:"};function Jc(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 gh(r){let e=new Set;return Pr(r,{Value(t,n){n.anchor&&e.add(n.anchor)}}),e}function bh(r,e){for(let t=1;;++t){let n=`${r}${t}`;if(!e.has(n))return n}}function C0(r,e){let t=[],n=new Map,i=null;return{onAnchor:s=>{t.push(s),i??(i=gh(r));let o=bh(e,i);return i.add(o),o},setAnchors:()=>{for(let s of t){let o=n.get(s);if(typeof o=="object"&&o.anchor&&(W(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 xn(r,e,t,n){if(n&&typeof n=="object")if(Array.isArray(n))for(let i=0,s=n.length;iOe(n,String(i),t));if(r&&typeof r.toJSON=="function"){if(!t||!Wc(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 $n=class{constructor(e){Object.defineProperty(this,ot,{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(!kr(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=Oe(this,"",o);if(typeof i=="function")for(let{count:c,res:l}of o.anchors.values())i(l,c);return typeof s=="function"?xn(s,{"":a},"",a):a}};var Wr=class extends $n{constructor(e){super(zc),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=[],Pr(e,{Node:(s,o)=>{(nr(o)||Wc(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||(Oe(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=Yc(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(Jc(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 Yc(r,e,t){if(nr(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=Yc(r,i,t);s>n&&(n=s)}return n}else if(te(e)){let n=Yc(r,e.key,t),i=Yc(r,e.value,t);return Math.max(n,i)}return 1}var Xc=r=>!r||typeof r!="function"&&typeof r!="object",F=class extends $n{constructor(e){super(Pt),this.value=e}toJSON(e,t){return t?.keep?this.value:Oe(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 _L="tag:yaml.org,2002:";function SL(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 Gr(r,e,t){if(kr(r)&&(r=r.contents),ne(r))return r;if(te(r)){let d=t.schema[rr].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 Wr(c.anchor);c={anchor:null,node:null},a.set(r,c)}e?.startsWith("!!")&&(e=_L+e.slice(2));let l=SL(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[rr]:Symbol.iterator in Object(r)?o[Kr]:o[rr]}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 Ro(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 Gr(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 ls=r=>r==null||typeof r=="object"&&!!r[Symbol.iterator]().next().done,cs=class extends $n{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(ls(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,Ro(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&&W(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&&W(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,Ro(this.schema,i,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${i}`)}}};var M0=r=>r.replace(/^(?!$)(?: $)?/gm,"#");function Kt(r,e){return/^\n+$/.test(r)?r.substring(1):e?r.replace(/^(?! *$)/gm,e):r}var Mr=(r,e,t)=>r.endsWith(` `)?Kt(t,e):t.includes(` `)?` `+Kt(t,e):(r.endsWith(" ")?"":" ")+t;var vh="flow",Qc="block",To="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===Qc&&(m=R0(r,m,e.length),m!==-1&&(d=m+c));for(let v;v=r[m+=1];){if(t===To&&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===` @@ -36,7 +36,7 @@ ${t.body}`,changed:!0}:{content:r,changed:!1}}function _w(r){if(!r.field)return `&&S!==" "&&(f=m)}if(m>=d)if(f)l.push(f),d=f+c,f=void 0;else if(t===To){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;v({indentAtStart:e?r.indent.length:r.indentAtStart,lineWidth:r.options.lineWidth,minContentWidth:r.options.minContentWidth}),tl=r=>/^(%|---|\.\.\.)/m.test(r);function xN(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}),tl=r=>/^(%|---|\.\.\.)/m.test(r);function xL(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||(tl(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(` @@ -54,11 +54,11 @@ ${t}`)+"'";return e.implicitKey?n:Io(n,t,vh,el(e,!1))}function ds(r,e){let{singl `)g=y;else break}let b=t.substring(0,g{E=!0});let x=Io(`${b}${_}${p}`,l,Qc,A);if(!E)return`>${S} ${l}${x}`}return t=t.replace(/\n+/g,`$&${l}`),`|${S} -${l}${b}${t}${p}`}function $N(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 $L(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 ds(s,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(s))return a||u||!s.includes(` `)?ds(s,e):Zc(r,e,t,n);if(!a&&!u&&i!==F.PLAIN&&s.includes(` `))return Zc(r,e,t,n);if(tl(s)){if(c==="")return e.forceBlockIndent=!0,Zc(r,e,t,n);if(a&&c===l)return ds(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 ds(s,e)}return a?d:Io(d,c,vh,el(e,!1))}function li(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?ds(o.value,e):Zc(o,e,t,n);case F.QUOTE_DOUBLE:return Oo(o.value,e);case F.QUOTE_SINGLE:return wh(o.value,e);case F.PLAIN:return $N(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 rl(r,e){let t=Object.assign({blockQuote:!0,commentString:M0,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 EN(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(W(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 kN(r,e,{anchors:t,doc:n}){if(!n.directives)return"";let i=[],s=(W(r)||ae(r))&&r.anchor;s&&Jc(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 Jr(r,e,t,n){if(te(r))return r.toString(e,t,n);if(nr(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=EN(e.doc.schema.tags,s));let o=kN(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):W(s)?li(s,e,t,n):s.toString(e,t,n);return o?W(s)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o} +${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 ds(s,e)}return a?d:Io(d,c,vh,el(e,!1))}function li(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?ds(o.value,e):Zc(o,e,t,n);case F.QUOTE_DOUBLE:return Oo(o.value,e);case F.QUOTE_SINGLE:return wh(o.value,e);case F.PLAIN:return $L(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 rl(r,e){let t=Object.assign({blockQuote:!0,commentString:M0,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 EL(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(W(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 kL(r,e,{anchors:t,doc:n}){if(!n.directives)return"";let i=[],s=(W(r)||ae(r))&&r.anchor;s&&Jc(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 Jr(r,e,t,n){if(te(r))return r.toString(e,t,n);if(nr(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=EL(e.doc.schema.tags,s));let o=kL(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):W(s)?li(s,e,t,n):s.toString(e,t,n);return o?W(s)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o} ${e.indent}${a}`:a}function T0({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 A="With simple keys, collection cannot be used as a key value";throw new Error(A)}}let p=!d&&(!r||f&&e==null&&!t.inFlow||ae(r)||(W(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=Jr(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+=Mr(y,t.indent,l(f)):m&&i&&i(),y;h&&(f=null),p?(f&&(y+=Mr(y,t.indent,l(f))),y=`? ${y} ${a}:`):(y=`${y}:`,f&&(y+=Mr(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&&W(e)&&(t.indentAtStart=y.length+1),m=!1,!u&&c.length>=2&&!t.inFlow&&!p&&sr(e)&&!e.flow&&!e.tag&&!e.anchor&&(t.indent=t.indent.substring(2));let S=!1,_=Jr(e,t,()=>S=!0,()=>m=!0),E=" ";if(f||g||b){if(E=g?` `:"",b){let A=l(b);E+=` @@ -69,20 +69,20 @@ ${Kt(A,t.indent)}`}_===""&&!t.inFlow?E===` ${t.indent}`}else if(!p&&ae(e)){let A=_[0],x=_.indexOf(` `),R=x!==-1,$=t.inFlow??e.flow??e.items.length===0;if(R||!$){let q=!1;if(R&&(A==="&"||A==="!")){let M=_.indexOf(" ");A==="&"&&M!==-1&&Mr===il||typeof r=="symbol"&&r.description===il,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new F(Symbol(il)),{addToJSMap:xh}),stringify:()=>il},I0=(r,e)=>(or.identify(e)||W(e)&&(!e.type||e.type===F.PLAIN)&&or.identify(e.value))&&r?.doc.schema.tags.some(t=>t.tag===or.tag&&t.default);function xh(r,e,t){let n=O0(r,t);if(sr(n))for(let i of n.items)Sh(r,e,i);else if(Array.isArray(n))for(let i of n)Sh(r,e,i);else Sh(r,e,n)}function Sh(r,e,t){let n=O0(r,t);if(!ir(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 O0(r,e){return r&&nr(e)?e.resolve(r.doc,r):e}function sl(r,e,{key:t,value:n}){if(ne(t)&&t.addToJSMap)t.addToJSMap(r,e,n);else if(I0(r,t))xh(r,e,n);else{let i=Te(t,"",r);if(e instanceof Map)e.set(i,Te(n,i,r));else if(e instanceof Set)e.add(i);else{let s=AN(t,i,r),o=Te(n,s,r);s in e?Object.defineProperty(e,s,{value:o,writable:!0,enumerable:!0,configurable:!0}):e[s]=o}}return e}function AN(r,e,t){if(e===null)return"";if(typeof e!="object")return String(e);if(ne(r)&&t?.doc){let n=rl(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)+'..."'),nl(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 us(r,e,t){let n=Gr(r,void 0,t),i=Gr(e,void 0,t);return new _e(n,i)}var _e=class r{constructor(e,t=null){Object.defineProperty(this,ot,{value:yh}),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 sl(t,n,this)}toString(e,t,n){return e?.doc?T0(this,e,t,n):JSON.stringify(this)}};function al(r,e,t){return(e.inFlow??r.flow?CN:PN)(r,e,t)}function PN({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+=Mr(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===il||typeof r=="symbol"&&r.description===il,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new F(Symbol(il)),{addToJSMap:xh}),stringify:()=>il},I0=(r,e)=>(or.identify(e)||W(e)&&(!e.type||e.type===F.PLAIN)&&or.identify(e.value))&&r?.doc.schema.tags.some(t=>t.tag===or.tag&&t.default);function xh(r,e,t){let n=O0(r,t);if(sr(n))for(let i of n.items)Sh(r,e,i);else if(Array.isArray(n))for(let i of n)Sh(r,e,i);else Sh(r,e,n)}function Sh(r,e,t){let n=O0(r,t);if(!ir(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 O0(r,e){return r&&nr(e)?e.resolve(r.doc,r):e}function sl(r,e,{key:t,value:n}){if(ne(t)&&t.addToJSMap)t.addToJSMap(r,e,n);else if(I0(r,t))xh(r,e,n);else{let i=Oe(t,"",r);if(e instanceof Map)e.set(i,Oe(n,i,r));else if(e instanceof Set)e.add(i);else{let s=AL(t,i,r),o=Oe(n,s,r);s in e?Object.defineProperty(e,s,{value:o,writable:!0,enumerable:!0,configurable:!0}):e[s]=o}}return e}function AL(r,e,t){if(e===null)return"";if(typeof e!="object")return String(e);if(ne(r)&&t?.doc){let n=rl(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)+'..."'),nl(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 us(r,e,t){let n=Gr(r,void 0,t),i=Gr(e,void 0,t);return new _e(n,i)}var _e=class r{constructor(e,t=null){Object.defineProperty(this,ot,{value:yh}),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 sl(t,n,this)}toString(e,t,n){return e?.doc?T0(this,e,t,n):JSON.stringify(this)}};function al(r,e,t){return(e.inFlow??r.flow?CL:PL)(r,e,t)}function PL({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+=Mr(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;hy=null);l||(l=d.length>u||g.includes(` +`+Kt(l(r),c),a&&a()):d&&o&&o(),p}function CL({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 h=0;hy=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+=Mr(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 ol({indent:r,options:{commentString:e}},t,n,i){if(n&&i&&(n=n.replace(/^\n+/,"")),n){let s=Kt(e(n),r);t.push(s.trimStart())}}function En(r,e){let t=W(e)?e.value:e;for(let n of r)if(te(n)&&(n.key===e||n.key===t||W(n.key)&&n.key.value===t))return n}var Ee=class extends cs{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(rr,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(us(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=En(this.items,n.key),s=this.schema?.sortMapEntries;if(i){if(!t)throw new Error(`Key ${n.key} already set`);W(i.value)&&Xc(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=En(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){let i=En(this.items,e)?.value;return(!t&&W(i)?i.value:i)??void 0}has(e){return!!En(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)sl(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})),al(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:n,onComment:t})}};var ar={collection:"map",default:!0,nodeClass:Ee,tag:"tag:yaml.org,2002:map",resolve(r,e){return ir(r)||e("Expected a mapping for this tag"),r},createNode:(r,e,t)=>Ee.from(r,e,t)};var Je=class extends cs{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(Kr,e),this.items=[]}add(e){this.items.push(e)}delete(e){let t=cl(e);return typeof t!="number"?!1:this.items.splice(t,1).length>0}get(e,t){let n=cl(e);if(typeof n!="number")return;let i=this.items[n];return!t&&W(i)?i.value:i}has(e){let t=cl(e);return typeof t=="number"&&t=0?e:null}var cr={collection:"seq",default:!0,nodeClass:Je,tag:"tag:yaml.org,2002:seq",resolve(r,e){return sr(r)||e("Expected a sequence for this tag"),r},createNode:(r,e,t)=>Je.from(r,e,t)};var kn={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),li(r,e,t,n)}};var di={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"&&di.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 Ye({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 ll={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:Ye},dl={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():Ye(r)}},ul={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:Ye};var fl=r=>typeof r=="bigint"||Number.isInteger(r),$h=(r,e,t,{intAsBigInt:n})=>n?BigInt(r):parseInt(r.substring(e),t);function D0(r,e,t){let{value:n}=r;return fl(n)&&n>=0?t+n.toString(e):Ye(r)}var pl={identify:r=>fl(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=>D0(r,8,"0o")},hl={identify:fl,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(r,e,t)=>$h(r,0,10,t),stringify:Ye},ml={identify:r=>fl(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=>D0(r,16,"0x")};var N0=[ar,cr,kn,di,Do,pl,hl,ml,ll,dl,ul];function L0(r){return typeof r=="bigint"||Number.isInteger(r)}var yl=({value:r})=>JSON.stringify(r),MN=[{identify:r=>typeof r=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:r=>r,stringify:yl},{identify:r=>r==null,createNode:()=>new F(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:yl},{identify:r=>typeof r=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:r=>r==="true",stringify:yl},{identify:L0,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})=>L0(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:yl}],RN={default:!0,tag:"",test:/^/,resolve(r,e){return e(`Unresolved plain scalar ${JSON.stringify(r)}`),r}},F0=[ar,cr].concat(MN,RN);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;i{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(us(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=En(this.items,n.key),s=this.schema?.sortMapEntries;if(i){if(!t)throw new Error(`Key ${n.key} already set`);W(i.value)&&Xc(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=En(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){let i=En(this.items,e)?.value;return(!t&&W(i)?i.value:i)??void 0}has(e){return!!En(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)sl(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})),al(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:n,onComment:t})}};var ar={collection:"map",default:!0,nodeClass:Ee,tag:"tag:yaml.org,2002:map",resolve(r,e){return ir(r)||e("Expected a mapping for this tag"),r},createNode:(r,e,t)=>Ee.from(r,e,t)};var Je=class extends cs{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(Kr,e),this.items=[]}add(e){this.items.push(e)}delete(e){let t=cl(e);return typeof t!="number"?!1:this.items.splice(t,1).length>0}get(e,t){let n=cl(e);if(typeof n!="number")return;let i=this.items[n];return!t&&W(i)?i.value:i}has(e){let t=cl(e);return typeof t=="number"&&t=0?e:null}var cr={collection:"seq",default:!0,nodeClass:Je,tag:"tag:yaml.org,2002:seq",resolve(r,e){return sr(r)||e("Expected a sequence for this tag"),r},createNode:(r,e,t)=>Je.from(r,e,t)};var kn={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),li(r,e,t,n)}};var di={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"&&di.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 Ye({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 ll={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:Ye},dl={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():Ye(r)}},ul={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:Ye};var fl=r=>typeof r=="bigint"||Number.isInteger(r),$h=(r,e,t,{intAsBigInt:n})=>n?BigInt(r):parseInt(r.substring(e),t);function D0(r,e,t){let{value:n}=r;return fl(n)&&n>=0?t+n.toString(e):Ye(r)}var pl={identify:r=>fl(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=>D0(r,8,"0o")},hl={identify:fl,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(r,e,t)=>$h(r,0,10,t),stringify:Ye},ml={identify:r=>fl(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=>D0(r,16,"0x")};var L0=[ar,cr,kn,di,Do,pl,hl,ml,ll,dl,ul];function N0(r){return typeof r=="bigint"||Number.isInteger(r)}var yl=({value:r})=>JSON.stringify(r),ML=[{identify:r=>typeof r=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:r=>r,stringify:yl},{identify:r=>r==null,createNode:()=>new F(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:yl},{identify:r=>typeof r=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:r=>r==="true",stringify:yl},{identify:N0,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})=>N0(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:yl}],RL={default:!0,tag:"",test:/^/,resolve(r,e){return e(`Unresolved plain scalar ${JSON.stringify(r)}`),r}},F0=[ar,cr].concat(ML,RL);var Lo={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 kh(r,e,t){let{replacer:n}=t,i=new Je(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(us(a,c,t))}return i}var Lo={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Eh,createNode:kh};var fs=class r extends Je{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=Te(i.key,"",t),o=Te(i.value,s,t)):s=Te(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=kh(e,t,n),s=new this;return s.items=i.items,s}};fs.tag="tag:yaml.org,2002:omap";var Fo={collection:"seq",identify:r=>r instanceof Map,nodeClass:fs,default:!1,tag:"tag:yaml.org,2002:omap",resolve(r,e){let t=Eh(r,e),n=[];for(let{key:i}of t.items)W(i)&&(n.includes(i.value)?e(`Ordered maps must not include duplicate keys: ${i.value}`):n.push(i.value));return Object.assign(new fs,t)},createNode:(r,e,t)=>fs.from(r,e,t)};function j0({value:r,source:e},t){return e&&(r?Ah:Ph).test.test(e)?e:r?t.options.trueStr:t.options.falseStr}var Ah={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:j0},Ph={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:j0};var q0={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:Ye},B0={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():Ye(r)}},U0={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(r){let e=new 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:Ye};var jo=r=>typeof r=="bigint"||Number.isInteger(r);function gl(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 Ch(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 Ye(r)}var V0={identify:jo,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(r,e,t)=>gl(r,2,2,t),stringify:r=>Ch(r,2,"0b")},H0={identify:jo,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(r,e,t)=>gl(r,1,8,t),stringify:r=>Ch(r,8,"0")},z0={identify:jo,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(r,e,t)=>gl(r,0,10,t),stringify:Ye},K0={identify:jo,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(r,e,t)=>gl(r,2,16,t),stringify:r=>Ch(r,16,"0x")};var ps=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),En(this.items,t.key)||this.items.push(t)}get(e,t){let n=En(this.items,e);return!t&&te(n)?W(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=En(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(us(o,null,n));return s}};ps.tag="tag:yaml.org,2002:set";var qo={collection:"map",identify:r=>r instanceof Set,nodeClass:ps,default:!1,tag:"tag:yaml.org,2002:set",createNode:(r,e,t)=>ps.from(r,e,t),resolve(r,e){if(ir(r)){if(r.hasAllNullValues(!0))return Object.assign(new ps,r);e("Set items must all have null values")}else e("Expected a mapping for this tag");return r}};function Mh(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 W0(r){let{value:e}=r,t=o=>o;if(typeof e=="bigint")t=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return Ye(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 bl={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})=>Mh(r,t),stringify:W0},vl={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=>Mh(r,!1),stringify:W0},hs={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(hs.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=Mh(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 Rh=[ar,cr,kn,di,Ah,Ph,V0,H0,z0,K0,q0,B0,U0,No,or,Fo,Lo,qo,bl,vl,hs];var G0=new Map([["core",N0],["failsafe",[ar,cr,kn]],["json",F0],["yaml11",Rh],["yaml-1.1",Rh]]),J0={binary:No,bool:Do,float:ul,floatExp:dl,floatNaN:ll,floatTime:vl,int:hl,intHex:ml,intOct:pl,intTime:bl,map:ar,merge:or,null:di,omap:Fo,pairs:Lo,seq:cr,set:qo,timestamp:hs},Y0={"tag:yaml.org,2002:binary":No,"tag:yaml.org,2002:merge":or,"tag:yaml.org,2002:omap":Fo,"tag:yaml.org,2002:pairs":Lo,"tag:yaml.org,2002:set":qo,"tag:yaml.org,2002:timestamp":hs};function wl(r,e,t){let n=G0.get(e);if(n&&!r)return t&&!n.includes(or)?n.concat(or):n.slice();let i=n;if(!i)if(Array.isArray(r))i=[];else{let s=Array.from(G0.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${e}"; use one of ${s} or define customTags array`)}if(Array.isArray(r))for(let s of r)i=i.concat(s);else typeof r=="function"&&(i=r(i.slice()));return t&&(i=i.concat(or)),i.reduce((s,o)=>{let a=typeof o=="string"?J0[o]:o;if(!a){let c=JSON.stringify(o),l=Object.keys(J0).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 TN=(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)?wl(e,"compat"):e?wl(null,e):null,this.name=typeof s=="string"&&s||"core",this.knownTags=i?Y0:{},this.tags=wl(t,this.name,n),this.toStringOptions=a??null,Object.defineProperty(this,rr,{value:ar}),Object.defineProperty(this,Pt,{value:kn}),Object.defineProperty(this,Kr,{value:cr}),this.sortMapEntries=typeof o=="function"?o:o===!0?TN:null}clone(){let e=Object.create(r.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};function X0(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=rl(r,e),{commentString:s}=i.options;if(r.commentBefore){t.length!==1&&t.unshift("");let c=s(r.commentBefore);t.unshift(Kt(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(Kt(u,""))}i.forceBlockIndent=!!r.comment,a=r.contents.comment}let c=a?void 0:()=>o=!0,l=Jr(r.contents,i,()=>a=null,c);a&&(l+=Mr(l,"",s(a))),(l[0]==="|"||l[0]===">")&&t[t.length-1]==="---"?t[t.length-1]=`--- ${l}`:t.push(l)}else t.push(Jr(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 kh(r,e,t){let{replacer:n}=t,i=new Je(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(us(a,c,t))}return i}var No={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Eh,createNode:kh};var fs=class r extends Je{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=Oe(i.key,"",t),o=Oe(i.value,s,t)):s=Oe(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=kh(e,t,n),s=new this;return s.items=i.items,s}};fs.tag="tag:yaml.org,2002:omap";var Fo={collection:"seq",identify:r=>r instanceof Map,nodeClass:fs,default:!1,tag:"tag:yaml.org,2002:omap",resolve(r,e){let t=Eh(r,e),n=[];for(let{key:i}of t.items)W(i)&&(n.includes(i.value)?e(`Ordered maps must not include duplicate keys: ${i.value}`):n.push(i.value));return Object.assign(new fs,t)},createNode:(r,e,t)=>fs.from(r,e,t)};function j0({value:r,source:e},t){return e&&(r?Ah:Ph).test.test(e)?e:r?t.options.trueStr:t.options.falseStr}var Ah={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:j0},Ph={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:j0};var q0={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:Ye},B0={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():Ye(r)}},U0={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(r){let e=new 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:Ye};var jo=r=>typeof r=="bigint"||Number.isInteger(r);function gl(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 Ch(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 Ye(r)}var V0={identify:jo,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(r,e,t)=>gl(r,2,2,t),stringify:r=>Ch(r,2,"0b")},H0={identify:jo,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(r,e,t)=>gl(r,1,8,t),stringify:r=>Ch(r,8,"0")},z0={identify:jo,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(r,e,t)=>gl(r,0,10,t),stringify:Ye},K0={identify:jo,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(r,e,t)=>gl(r,2,16,t),stringify:r=>Ch(r,16,"0x")};var ps=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),En(this.items,t.key)||this.items.push(t)}get(e,t){let n=En(this.items,e);return!t&&te(n)?W(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=En(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(us(o,null,n));return s}};ps.tag="tag:yaml.org,2002:set";var qo={collection:"map",identify:r=>r instanceof Set,nodeClass:ps,default:!1,tag:"tag:yaml.org,2002:set",createNode:(r,e,t)=>ps.from(r,e,t),resolve(r,e){if(ir(r)){if(r.hasAllNullValues(!0))return Object.assign(new ps,r);e("Set items must all have null values")}else e("Expected a mapping for this tag");return r}};function Mh(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 W0(r){let{value:e}=r,t=o=>o;if(typeof e=="bigint")t=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return Ye(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 bl={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})=>Mh(r,t),stringify:W0},vl={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=>Mh(r,!1),stringify:W0},hs={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(hs.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=Mh(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 Rh=[ar,cr,kn,di,Ah,Ph,V0,H0,z0,K0,q0,B0,U0,Lo,or,Fo,No,qo,bl,vl,hs];var G0=new Map([["core",L0],["failsafe",[ar,cr,kn]],["json",F0],["yaml11",Rh],["yaml-1.1",Rh]]),J0={binary:Lo,bool:Do,float:ul,floatExp:dl,floatNaN:ll,floatTime:vl,int:hl,intHex:ml,intOct:pl,intTime:bl,map:ar,merge:or,null:di,omap:Fo,pairs:No,seq:cr,set:qo,timestamp:hs},Y0={"tag:yaml.org,2002:binary":Lo,"tag:yaml.org,2002:merge":or,"tag:yaml.org,2002:omap":Fo,"tag:yaml.org,2002:pairs":No,"tag:yaml.org,2002:set":qo,"tag:yaml.org,2002:timestamp":hs};function wl(r,e,t){let n=G0.get(e);if(n&&!r)return t&&!n.includes(or)?n.concat(or):n.slice();let i=n;if(!i)if(Array.isArray(r))i=[];else{let s=Array.from(G0.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${e}"; use one of ${s} or define customTags array`)}if(Array.isArray(r))for(let s of r)i=i.concat(s);else typeof r=="function"&&(i=r(i.slice()));return t&&(i=i.concat(or)),i.reduce((s,o)=>{let a=typeof o=="string"?J0[o]:o;if(!a){let c=JSON.stringify(o),l=Object.keys(J0).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 TL=(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)?wl(e,"compat"):e?wl(null,e):null,this.name=typeof s=="string"&&s||"core",this.knownTags=i?Y0:{},this.tags=wl(t,this.name,n),this.toStringOptions=a??null,Object.defineProperty(this,rr,{value:ar}),Object.defineProperty(this,Pt,{value:kn}),Object.defineProperty(this,Kr,{value:cr}),this.sortMapEntries=typeof o=="function"?o:o===!0?TL:null}clone(){let e=Object.create(r.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};function X0(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=rl(r,e),{commentString:s}=i.options;if(r.commentBefore){t.length!==1&&t.unshift("");let c=s(r.commentBefore);t.unshift(Kt(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(Kt(u,""))}i.forceBlockIndent=!!r.comment,a=r.contents.comment}let c=a?void 0:()=>o=!0,l=Jr(r.contents,i,()=>a=null,c);a&&(l+=Mr(l,"",s(a))),(l[0]==="|"||l[0]===">")&&t[t.length-1]==="---"?t[t.length-1]=`--- ${l}`:t.push(l)}else t.push(Jr(r.contents,i));if(r.directives?.docEnd)if(r.comment){let c=s(r.comment);c.includes(` `)?(t.push("..."),t.push(Kt(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(Kt(s(c),"")))}return t.join(` `)+` -`}var An=class r{constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,ot,{value:Kc});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 Cr({version:o}),this.setSchema(o,n),this.contents=e===void 0?null:this.createNode(e,i,n)}clone(){let e=Object.create(r.prototype,{[ot]:{value:Kc}});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){ms(this.contents)&&this.contents.add(e)}addIn(e,t){ms(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){let n=gh(this);e.anchor=!t||n.has(t)?bh(t||"a",n):t}return new Wr(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}=C0(this,o||"a"),h={aliasDuplicateObjects:s??!0,keepUndefined:c??!1,onAnchor:d,onTagObj:l,replacer:i,schema:this.schema,sourceObjects:p},m=Gr(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 ms(this.contents)?this.contents.delete(e):!1}deleteIn(e){return ls(e)?this.contents==null?!1:(this.contents=null,!0):ms(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 ls(e)?!t&&W(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 ls(e)?this.contents!==void 0:ae(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=Ro(this.schema,[e],t):ms(this.contents)&&this.contents.set(e,t)}setIn(e,t){ls(e)?this.contents=t:this.contents==null?this.contents=Ro(this.schema,Array.from(e),t):ms(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 Cr({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 Cr({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=Te(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"?xn(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 X0(this,e)}};function ms(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}},lr=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)}},Th=(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 An=class r{constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,ot,{value:Kc});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 Cr({version:o}),this.setSchema(o,n),this.contents=e===void 0?null:this.createNode(e,i,n)}clone(){let e=Object.create(r.prototype,{[ot]:{value:Kc}});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){ms(this.contents)&&this.contents.add(e)}addIn(e,t){ms(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){let n=gh(this);e.anchor=!t||n.has(t)?bh(t||"a",n):t}return new Wr(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}=C0(this,o||"a"),h={aliasDuplicateObjects:s??!0,keepUndefined:c??!1,onAnchor:d,onTagObj:l,replacer:i,schema:this.schema,sourceObjects:p},m=Gr(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 ms(this.contents)?this.contents.delete(e):!1}deleteIn(e){return ls(e)?this.contents==null?!1:(this.contents=null,!0):ms(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 ls(e)?!t&&W(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 ls(e)?this.contents!==void 0:ae(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=Ro(this.schema,[e],t):ms(this.contents)&&this.contents.set(e,t)}setIn(e,t){ls(e)?this.contents=t:this.contents==null?this.contents=Ro(this.schema,Array.from(e),t):ms(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 Cr({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 Cr({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=Oe(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"?xn(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 X0(this,e)}};function ms(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}},lr=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)}},Th=(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} @@ -94,7 +94,7 @@ ${l} `+E.comment:l.comment=E.comment),d=E.end;continue}!o&&t.options.strict&&Pn(v)&&i(v,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(y===0)E.comma&&i(E.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`);else if(E.comma||i(E.start,"MISSING_CHAR",`Missing , between ${a} items`),E.comment){let A="";e:for(let x of b)switch(x.type){case"comma":case"space":break;case"comment":A=x.source.substring(1);break e;default:break e}if(A){let x=l.items[l.items.length-1];te(x)&&(x=x.value??x.key),x.comment?x.comment+=` `+A:x.comment=A,E.comment=E.comment.substring(A.length+1)}}if(!o&&!S&&!E.found){let A=_?r(t,_,E,i):e(t,E.end,S,null,E,i);l.items.push(A),d=A.range[2],Oh(_)&&i(A.range,"BLOCK_IN_FLOW",Ih)}else{t.atKey=!0;let A=E.end,x=v?r(t,v,E,i):e(t,A,b,null,E,i);Oh(v)&&i(x.range,"BLOCK_IN_FLOW",Ih),t.atKey=!1;let R=Rr(S??[],{flow:a,indicator:"map-value-ind",next:_,offset:x.range[2],onError:i,parentIndent:n.indent,startOnNewline:!1});if(R.found){if(!o&&!E.found&&t.options.strict){if(S)for(let M of S){if(M===R.found)break;if(M.type==="newline"){i(M,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}E.start0){let y=Tr(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 Dh(r,e,t,n,i,s){let o=t.type==="block-map"?Z0(r,e,t,n,s):t.type==="block-seq"?eS(r,e,t,n,s):tS(r,e,t,n,s),a=o.constructor;return i==="!"||i===a.tagName?(o.tag=a.tagName,o):(i&&(o.tag=i),o)}function rS(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),Dh(r,e,t,i,o)}let l=Dh(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 Nh(r,e,t){let n=e.offset,i=IN(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?ON(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?` +`+y.comment:l.comment=y.comment),l.range=[n.offset,m,y.offset]}else l.range=[n.offset,m,m];return l}function Dh(r,e,t,n,i,s){let o=t.type==="block-map"?Z0(r,e,t,n,s):t.type==="block-seq"?eS(r,e,t,n,s):tS(r,e,t,n,s),a=o.constructor;return i==="!"||i===a.tagName?(o.tag=a.tagName,o):(i&&(o.tag=i),o)}function rS(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),Dh(r,e,t,i,o)}let l=Dh(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 Lh(r,e,t){let n=e.offset,i=IL(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?OL(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;mc||g[0]===" "?(f===" "?f=` @@ -109,31 +109,31 @@ ${l} `+o[m][0].slice(c);d[d.length-1]!==` `&&(d+=` `);break;default:d+=` -`}let h=n+i.length+e.source.length;return{value:d,type:s,comment:i.comment,range:[n,h,h]}}function IN({offset:r,props:e},t,n){if(e[0].type!=="block-scalar-header")return n(e[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:i}=e[0],s=i[0],o=0,a="",c=-1;for(let f=1;ft(n+f,p,h);switch(i){case"scalar":a=F.PLAIN,c=DN(s,l);break;case"single-quoted-scalar":a=F.QUOTE_SINGLE,c=NN(s,l);break;case"double-quoted-scalar":a=F.QUOTE_DOUBLE,c=LN(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=Tr(o,u,e,t);return{value:c,type:a,comment:d.comment,range:[n,u,d.offset]}}function DN(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}`),nS(r)}function NN(r,e){return(r[r.length-1]!=="'"||r.length===1)&&e(r.length,"MISSING_CHAR","Missing closing 'quote"),nS(r.slice(1,-1)).replace(/''/g,"'")}function nS(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,h);switch(i){case"scalar":a=F.PLAIN,c=DL(s,l);break;case"single-quoted-scalar":a=F.QUOTE_SINGLE,c=LL(s,l);break;case"double-quoted-scalar":a=F.QUOTE_DOUBLE,c=NL(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=Tr(o,u,e,t);return{value:c,type:a,comment:d.comment,range:[n,u,d.offset]}}function DL(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}`),nS(r)}function LL(r,e){return(r[r.length-1]!=="'"||r.length===1)&&e(r.length,"MISSING_CHAR","Missing closing 'quote"),nS(r.slice(1,-1)).replace(/''/g,"'")}function nS(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 FN(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 FL(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 jN={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:` -`,r:"\r",t:" ",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function qN(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 Fh(r,e,t,n){let{value:i,type:s,comment:o,range:a}=e.type==="block-scalar"?Nh(r,e,n):Lh(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[Pt]:c?l=BN(r.schema,i,c,t,n):e.type==="scalar"?l=UN(r,i,e,n):l=r.schema[Pt];let u;try{let d=l.resolve(i,f=>n(t??e,"TAG_RESOLVE_FAILED",f),r.options);u=W(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 BN(r,e,t,n,i){if(t==="!")return r[Pt];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[Pt])}function UN({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[Pt];if(t.compat){let a=t.compat.find(c=>c.default&&c.test?.test(n))??t[Pt];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 iS(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 VN={composeNode:jh,composeEmptyNode:Sl};function jh(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=HN(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=Fh(r,e,c,n),a&&(l.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=rS(VN,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=Sl(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&&(!W(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 Sl(r,e,t,n,{spaceBefore:i,comment:s,anchor:o,tag:a,end:c},l){let u={type:"scalar",offset:iS(e,t,n),indent:-1,source:""},d=Fh(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 HN({options:r},{offset:e,source:t,end:n},i){let s=new Wr(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=Tr(n,o,r.strict,i);return s.range=[e,o,a.offset],a.comment&&(s.comment=a.comment),s}function sS(r,e,{offset:t,start:n,value:i,end:s},o){let a=Object.assign({_directives:e},r),c=new An(void 0,a),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=Rr(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?jh(l,i,u,o):Sl(l,u.end,n,null,u,o);let d=c.contents.range[2],f=Tr(s,d,!1,o);return f.comment&&(c.comment=f.comment),c.range=[t,d,f.offset],c}function 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 oS(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[Pt]:c?l=BL(r.schema,i,c,t,n):e.type==="scalar"?l=UL(r,i,e,n):l=r.schema[Pt];let u;try{let d=l.resolve(i,f=>n(t??e,"TAG_RESOLVE_FAILED",f),r.options);u=W(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 BL(r,e,t,n,i){if(t==="!")return r[Pt];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[Pt])}function UL({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[Pt];if(t.compat){let a=t.compat.find(c=>c.default&&c.test?.test(n))??t[Pt];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 iS(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 VL={composeNode:jh,composeEmptyNode:Sl};function jh(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=HL(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=Fh(r,e,c,n),a&&(l.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=rS(VL,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=Sl(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&&(!W(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 Sl(r,e,t,n,{spaceBefore:i,comment:s,anchor:o,tag:a,end:c},l){let u={type:"scalar",offset:iS(e,t,n),indent:-1,source:""},d=Fh(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 HL({options:r},{offset:e,source:t,end:n},i){let s=new Wr(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=Tr(n,o,r.strict,i);return s.range=[e,o,a.offset],a.comment&&(s.comment=a.comment),s}function sS(r,e,{offset:t,start:n,value:i,end:s},o){let a=Object.assign({_directives:e},r),c=new An(void 0,a),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=Rr(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?jh(l,i,u,o):Sl(l,u.end,n,null,u,o);let d=c.contents.range[2],f=Tr(s,d,!1,o);return f.comment&&(c.comment=f.comment),c.range=[t,d,f.offset],c}function 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 oS(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 lr(o,n,i))},this.directives=new Cr({version:e.version||"1.2"}),this.options=e}decorate(e,t){let{comment:n,afterEmptyLine:i}=oS(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=sS(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 lr(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 lr(zo(e),"UNEXPECTED_TOKEN",n));break}this.doc.directives.docEnd=!0;let t=Tr(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),t.comment){let 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 lr(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 An(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 qh=Symbol("break visit"),zN=Symbol("skip children"),aS=Symbol("remove item");function ui(r,e){"type"in r&&r.type==="document"&&(r={start:r.start,value:r.value}),cS(Object.freeze([]),r,e)}ui.BREAK=qh;ui.SKIP=zN;ui.REMOVE=aS;ui.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};ui.parentCollection=(r,e)=>{let t=ui.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 cS(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};ui.parentCollection=(r,e)=>{let t=ui.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 cS(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 dr(r){switch(r){case void 0:case" ":case` -`:case"\r":case" ":return!0;default:return!1}}var dS=new Set("0123456789ABCDEFabcdef"),WN=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),$l=new Set(",[]{}"),GN=new Set(` ,[]{} -\r `),Hh=r=>!r||GN.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 dS=new Set("0123456789ABCDEFabcdef"),WL=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),$l=new Set(",[]{}"),GL=new Set(` ,[]{} +\r `),Hh=r=>!r||GL.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===` @@ -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 xl,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(dr(s)||e&&$l.has(s))break;t=n}else if(dr(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 xl,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(Hh),e+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let t=this.flowLevel>0,n=this.charAt(1);if(dr(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(;!dr(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(WN.has(t))t=this.buffer[++e];else if(t==="%"&&dS.has(this.buffer[e+1])&&dS.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 xl,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(Hh),e+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let t=this.flowLevel>0,n=this.charAt(1);if(dr(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(;!dr(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(WL.has(t))t=this.buffer[++e];else if(t==="%"&&dS.has(this.buffer[e+1])&&dS.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 kl(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"&&fS(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&&uS(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(Cn(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(pS(t.key)&&!Cn(t.sep,"newline")){let o=ys(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(Cn(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{let o=ys(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]}):Cn(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&&!Cn(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)){kl(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||Cn(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=El(n),s=ys(i);fS(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=El(e),n=ys(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=El(e),n=ys(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 JN(r){let e=r.prettyErrors!==!1;return{lineCounter:r.lineCounter||e&&new Go||null,prettyErrors:e}}function hS(r,e={}){let{lineCounter:t,prettyErrors:n}=JN(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 lr(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&t&&(o.errors.forEach(Th(r,t)),o.warnings.forEach(Th(r,t))),o}function fi(r,e,t){let n;typeof e=="function"?n=e:t===void 0&&e&&typeof e=="object"&&(t=e);let i=hS(r,t);if(!i)return null;if(i.warnings.forEach(s=>nl(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 QN=r=>r/2**32|0,ZN=r=>r>>>0;function mS(r,e,t,n){let i=QN(t),s=ZN(t);r.setUint32(e,n?s:i,n),r.setUint32(e+4,n?i:s,n)}function yS(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in r&&r.BYTES_PER_ELEMENT===1}var zh=r=>r?`"${r}" `:"";function eL(r,e=""){if(typeof r!="number")throw new TypeError(zh(e)+"expected number, got "+typeof r);if(!Number.isSafeInteger(r)||r<0)throw new RangeError(zh(e)+"expected integer >= 0, got "+r);return r}function Al(r,e,t=""){if(yS(r)&&(e===void 0||r.length===e))return r;e!==void 0&&eL(e,"length");let n=yS(r),i=e!==void 0?` of length ${e}`:"",s=n?`length=${r.length}`:`type=${typeof r}`,o=zh(t)+"expected Uint8Array"+i+", got "+s;throw n?new RangeError(o):new TypeError(o)}var tL=(r,e)=>{if(r===null||typeof r!="object"||Array.isArray(r))throw new TypeError((e==="object"?"":`"${e}" `)+"expected object, got type="+typeof r)},gS=(r,e)=>{tL(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 Kh(r,e=!0){if(r.destroyed)throw new Error("hash was destroyed");if(e&&r.finished)throw new Error("digest() was already called")}function bS(r,e){Al(r,void 0,"output");let t=e.outputLen;if(!(r.length>=t))throw new RangeError('"output" expected length >= '+t)}function gs(...r){for(let e=0;e>>e}function Cl(r,e){return r<>>32-e>>>0}var rL=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",nL=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function Le(r){if(Al(r),rL)return r.toHex();let e="";for(let t=0;t= '+t)}function gs(...r){for(let e=0;e>>e}function Cl(r,e){return r<>>32-e>>>0}var rN=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",nN=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function Ne(r){if(Al(r),rN)return r.toHex();let e="";for(let t=0;to.command!=="advance_checkpoint");t.kind==="rebuild"&&n.push("Mirror rebuild"),t.kind==="initial"&&i.some(o=>["put_remote","move_remote","delete_remote","delete_local"].includes(o.command))&&n.push("First sync"),t.summary.blocking_issues>0&&!i.length&&n.push("Blocking issues");let s=i.filter(o=>o.command==="delete_remote").length;return s>e.maxDeletions&&n.push(`${s} deletions`),{safe:n.length===0,reasons:n}}var Lx=require("obsidian");var Am=3e4,F2=64*1024;function Pm(r){return Am+Math.ceil(r/F2)*1e3}var Es=class extends w{constructor(e,t){super(e,t),this.name="NetworkError"}},Dn=class extends w{constructor(t,n,i,s){super(t,n);this.status=i;this.retryAfterMs=s;this.name="HttpStatusError"}},km=new Set([408,425,429,500,502,503,504]),j2=new Set(["network_unreachable","network_timeout","authority_unavailable","mirror_enrollment_unreachable","authority_adoption_unreachable"]);function ks(r){if(r instanceof Dn)return km.has(r.status);if(r&&typeof r=="object"){let e=r.status;if(typeof e=="number"&&km.has(e))return!0;let t=r.code;if(typeof t=="string"&&j2.has(t))return!0}return!1}function q2(r){return km.has(r)}var B2={attempts:4,baseDelayMs:500,maxDelayMs:3e4,sleep:z2,random:Math.random};function Cm(r,e,t){let n=Math.min(e.maxDelayMs,e.baseDelayMs*2**r),i=Math.round(n/2+e.random()*n/2);return t===void 0?i:Math.min(Math.max(i,t),6e4)}function Fx(r,e=B2){return async t=>{for(let n=0;;n+=1){K2(t.signal);let i;try{let s=await r(t);if(!q2(s.status)||n+1>=e.attempts)return s;i=aa(s.headers)}catch(s){if(W2(s)&&t.signal?.aborted||!ks(s)||n+1>=e.attempts)throw s}await e.sleep(Cm(n,e,i),t.signal)}}}function jx(r=U2()){return r?e=>V2(e,r.fetch,r.AbortController,r.headers):e=>H2(e)}function U2(){try{if(typeof require!="function")return null;let r=require("electron").remote,e=r?.net?.fetch,t=r?.getGlobal?.("AbortController"),n=r?.getGlobal?.("Object");return!e||!r?.net||typeof t!="function"||!n?null:{fetch:e.bind(r.net),AbortController:t,headers:i=>n.fromEntries(i)}}catch{return null}}async function V2(r,e,t=AbortController,n=i=>Object.fromEntries(i)){let{signal:i,check:s,dispose:o}=qx(r.signal,r.timeoutMs??Am),a=new t,c=()=>a.abort();i.aborted?c():i.addEventListener("abort",c,{once:!0});try{let l={...r.headers??{}};r.contentType&&!Object.keys(l).some(p=>p.toLowerCase()==="content-type")&&(l["content-type"]=r.contentType);let u,d;try{u=await e(r.url,{method:r.method,headers:l,body:r.body,signal:a.signal}),d=await u.arrayBuffer()}catch(p){throw ad(p,r.signal,i)}if(s(),i.aborted)throw ad(i.reason,r.signal,i);let f=new TextDecoder().decode(d);if(r.throw!==!1&&u.status>=400)throw new Dn(`http_${u.status}`,`Request failed with status ${u.status}`,u.status);return{status:u.status,headers:n(u.headers),arrayBuffer:d,json:G2(f),text:f}}finally{i.removeEventListener("abort",c),o()}}async function H2(r,e=t=>(0,Lx.requestUrl)(t)){let{signal:t,timeoutMs:n,...i}=r,{signal:s,check:o,dispose:a}=qx(t,n??Am),c=()=>{};try{return await new Promise((l,u)=>{let d=()=>u(ad(s.reason,t,s));if(s.aborted)return d();s.addEventListener("abort",d,{once:!0}),c=()=>s.removeEventListener("abort",d),e(i).then(f=>{o(),s.aborted?d():l(f)},f=>u(ad(f,t,s)))})}finally{c(),a()}}function aa(r){if(!r)return;let e=Object.entries(r).find(([i])=>i.toLowerCase()==="retry-after")?.[1];if(!e)return;let t=Number(e);if(Number.isFinite(t)&&t>=0)return t*1e3;let n=Date.parse(e);if(Number.isFinite(n))return Math.max(0,n-Date.now())}function z2(r,e){return new Promise((t,n)=>{if(e?.aborted)return n(oa());let i=window.setTimeout(()=>{e?.removeEventListener("abort",s),t()},r),s=()=>{window.clearTimeout(i),n(oa())};e?.addEventListener("abort",s,{once:!0})})}function K2(r){if(r?.aborted)throw oa()}function oa(){return new DOMException("Synchronization stopped.","AbortError")}function W2(r){return r instanceof DOMException&&r.name==="AbortError"}function qx(r,e){let t=new AbortController,n=Date.now()+e,i=()=>t.abort(oa());r?.aborted?i():r?.addEventListener("abort",i,{once:!0});let s=()=>t.abort(new Es("network_timeout","Connect did not respond in time.")),o=window.setTimeout(s,e);return{signal:t.signal,check:()=>{!t.signal.aborted&&Date.now()>=n&&s()},dispose:()=>{window.clearTimeout(o),r?.removeEventListener("abort",i)}}}function ad(r,e,t){if(e?.aborted)return oa();if(t.aborted)return t.reason instanceof Es?t.reason:new Es("network_timeout","Connect did not respond in time.");if(r instanceof w)return r;let n=r&&typeof r=="object"?r.status:void 0;if(typeof n=="number")return new Dn(`http_${n}`,`Request failed with status ${n}`,n);let i=r instanceof Error&&r.message?` (${r.message})`:"";return new Es("network_unreachable",`Connect could not be reached${i}.`)}function G2(r){if(!r.trim())return null;try{return JSON.parse(r)}catch{return null}}var Ux={maxAgeDays:90,maxFiles:5e3,maxRuns:1e3};function dd(r,e,t=new Date().toISOString()){return{id:crypto.randomUUID(),collectionId:r,startedAt:t,finishedAt:t,outcome:"event",files:[],...e}}function Vx(r){return r.summary!==void 0}function Hx(r,e,t){if(r.command==="advance_checkpoint")return null;let n=Em(r),i=r.command==="move_local"||r.command==="move_remote"?r.source.path:void 0;return{path:n.path,...i&&i!==n.path?{fromPath:i}:{},kind:n.kind,direction:n.direction,action:n.action,status:e.status,at:t,...e.failure?.message?{message:e.failure.message}:{}}}var cd=class{constructor(e,t){this.inner=e;this.onReceipt=t;this.seen=new Map}read(){return this.inner.read()}async write(e){await this.inner.write(e);let t=e.batch;if(!t)return;let n=t.plan.fingerprint,i=this.seen.get(n);if(i===void 0){this.seen.set(n,{receipts:t.receipts.length,actions:new Map(t.plan.actions.map(o=>[o.action_id,o]))});return}let s=i.receipts;i.receipts=t.receipts.length;for(let o of t.receipts.slice(s)){let a=i.actions.get(o.action_id);a&&this.onReceipt(a,o)}}};function zx(r){if(r.summary!==void 0)return r.summary;let e=i=>r.files.filter(s=>s.direction===i&&s.status==="completed").length;return[[e("download"),"downloaded"],[e("upload"),"uploaded"],[r.files.filter(i=>i.direction==="attention"||i.status==="conflicted").length,"conflicts"],[r.files.filter(i=>i.status==="rejected").length,"rejected"]].filter(([i])=>i>0).map(([i,s])=>`${i} ${s}`).join(" \xB7 ")||"No file changes"}function Kx(r,e){return r.flatMap(t=>t.summary!==void 0?t.path===e?[{run:t,file:J2(t)}]:[]:t.files.filter(n=>n.path===e||n.fromPath===e).map(n=>({run:t,file:n}))).sort((t,n)=>n.file.at.localeCompare(t.file.at))}function J2(r){return{path:r.path??"",kind:"document",direction:"attention",action:"review",status:"completed",at:r.finishedAt,...r.message?{message:r.message}:{}}}function Wx(r,e){let t=e.trim().toLowerCase();return t?r.flatMap(n=>{if(n.summary!==void 0)return n.path?.toLowerCase().includes(t)?[n]:[];let i=n.files.filter(s=>s.path.toLowerCase().includes(t)||s.fromPath?.toLowerCase().includes(t));return i.length?[{...n,files:i}]:[]}):[...r]}function Bx(r,e=Ux,t=Date.now()){let n=t-e.maxAgeDays*864e5,i=r.filter(a=>Date.parse(a.finishedAt)>=n),s=i.reduce((a,c)=>a+c.files.length,0),o=0;for(;(s>e.maxFiles||i.length-o>e.maxRuns)&&o0&&!r.endsWith(` +`)&&e.slice(1)===r}function um(r,e){if(r===e)return!0;if(Array.isArray(r)||Array.isArray(e))return Array.isArray(r)&&Array.isArray(e)&&r.length===e.length&&r.every((i,s)=>um(i,e[s]));if(!r||!e||typeof r!="object"||typeof e!="object")return!1;let t=Object.entries(r),n=e;return t.length===Object.keys(n).length&&t.every(([i,s])=>Object.prototype.hasOwnProperty.call(n,i)&&um(s,n[i]))}var $s=class{fileSystem;runtime;mode;blobStore;constructor(e,t,n,i){this.fileSystem=e,this.runtime=t,this.mode=n,this.blobStore=i}async recordPathPolicy(e){return lx(Object.keys(e.resources??{}),()=>this.fileSystem.read("mdbase.yaml"))}async put(e,t,n={}){let{managedState:i=e,acceptedHash:s,materialized:o,inspectionPreflighted:a}=n;a||In(t.path,await this.recordPathPolicy(e)),o===void 0&&!a&&fx(t.path,t.record_id,Object.keys(e.resources??{}),Object.entries(e.records),Object.entries(e.files??{}));let c=o?.document??Il(t),l=a===1?await this.fileSystem.readText(t.path):await this.fileSystem.read(t.path),u=typeof l=="string"||l===null?l:void 0,d=i?.records[t.record_id],f=u==null?null:this.runtime.digest(u);if(a!==1&&f!==null&&u!==c&&!(d!==void 0&&d.path===t.path&&f===d.hash)&&(!s||f!==s))throw new $t(t.record_id,t.path);d&&d.path!==t.path&&await this.remove(i,t.record_id,d.path);let p=u===c?f:this.runtime.digest(c);u!==c&&await this.fileSystem.write(t.path,c,u),e.records[t.record_id]={path:t.path,revision:t.revision,hash:o?.hash??p,...this.mode==="read_write"?{record:t}:{}}}async putFile(e,t,n=e,i){if(xt(t),!this.blobStore)throw new w("file_storage_unavailable","Selected collection files require a content-addressed blob store adapter.");px(t.path,t.file_id,e),e.files??={};let s=n.files?.[t.file_id],o=await this.fileSystem.inspectBinary(t.path),a=Rt(t.path),c=Object.values(n.files??{}).find(h=>Rt(h.file.path)===a),l=[...Object.values(n.resources??{}),...Object.values(n.records)].find(h=>Rt(h.path)===a),u=l?await this.fileSystem.read(t.path):null,d=s?.file.path===t.path&&tn(o,s.file),f=c!==void 0&&tn(o,c.file),p=l!==void 0&&u!==null&&this.runtime.digest(u)===l.hash;if(o!==null&&!tn(o,t)&&!d&&!f&&!p&&!(i!==void 0&&o?.size===i.size&&o.content_digest===i.content_digest))throw new $t(t.file_id,t.path);if(s&&s.file.path!==t.path){let h=await this.fileSystem.inspectBinary(s.file.path);if(h!==null&&!tn(h,s.file))throw new $t(t.file_id,s.file.path)}tn(o,t)||await this.fileSystem.writeBinary(t.path,Bl(this.blobStore.read(t.content_digest),t),o),s&&s.file.path!==t.path&&await this.fileSystem.remove(s.file.path,s.file),e.files[t.file_id]={file:t}}async removeFile(e,t){let n=e.files?.[t];if(!n)return;let i=await this.fileSystem.inspectBinary(n.file.path);if(i!==null&&!tn(i,n.file))throw new $t(t,n.file.path);i!==null&&await this.fileSystem.remove(n.file.path,i),delete e.files[t]}async remove(e,t,n,i={}){let s=e.records[t],o=s?.path??n;i.inspectionPreflighted||In(o,await this.recordPathPolicy(e));let a=await this.fileSystem.read(o);if(a!==null&&s&&this.runtime.digest(a)!==s.hash)throw new $t(t,s.path);a!==null&&await this.fileSystem.remove(o,a),delete e.records[t]}async putResource(e,t,n){let i=await this.fileSystem.read(t.path),s=n?.resources?.[t.path];if(i!==null&&i!==t.document&&(!s||this.runtime.digest(i)!==s.hash))throw new $t(`resource:${t.path}`,t.path);await this.fileSystem.write(t.path,t.document,i),e.resources??={},e.resources[t.path]={path:t.path,revision:t.revision,hash:this.runtime.digest(t.document)}}async removeResource(e,t,n){let i=await this.fileSystem.read(t);if(i!==null&&this.runtime.digest(i)!==n.hash)throw new $t(`resource:${t}`,t);i!==null&&await this.fileSystem.remove(t,i),e.resources&&delete e.resources[t]}};async function mx(r,e,t,n){for(let i in r.records){if(!Object.hasOwn(r.records,i))continue;let s=r.records[i];In(s.path,e);let o=await t.read(s.path);if(o===null||n(o)!==s.hash)throw new $t(i,s.path)}for(let[i,s]of Object.entries(r.resources??{})){let o=await t.read(s.path);if(o===null||n(o)!==s.hash)throw new $t(`resource:${i}`,s.path)}for(let[i,s]of Object.entries(r.files??{})){let o=await t.inspectBinary(s.file.path);if(!tn(o,s.file))throw new $t(i,s.file.path)}}async function yx(r){let{state:e,selectiveSync:t,fileSystem:n,pathPolicy:i,digest:s}=r;if(t.excluded_folders.length>0||t.file_classes.length!==5)throw new w("promotion_incomplete_file_projection","Moving the source of truth requires every collection file class with no excluded folders.");if(Object.keys(e.planned_conflicts??{}).length>0||e.batch!==void 0)throw new w("promotion_not_converged","Upload or resolve every local change before moving the source of truth.");await mx(e,i,n,s);let o=new Set(Object.keys(e.resources??{})),a=new Set(Object.values(e.records).map(d=>d.path)),c=(await n.listMarkdown(o)).filter(d=>!a.has(d));if(c.length>0)throw new w("promotion_unmanaged_files",`Synchronize unmanaged Markdown before promotion: ${c.join(", ")}.`);if(!n.listBinary)throw new w("promotion_file_scan_unavailable","Moving the source of truth requires binary file enumeration.");let l=new Set(Object.values(e.files??{}).map(d=>d.file.path)),u=(await n.listBinary(new Set([...o,...a]))).filter(d=>!l.has(d));if(u.length>0)throw new w("promotion_unmanaged_files",`Synchronize unmanaged files before moving the source of truth: ${u.join(", ")}.`);return{cursor:e.cursor,digest:Dl([...Object.entries(e.resources??{}).map(([d,f])=>({kind:"resource",path:d,identity:"",document_hash:Yh(f.hash)})),...Object.entries(e.records).map(([d,f])=>({kind:"record",path:f.path,identity:d,document_hash:Yh(f.hash)})),...Object.values(e.files??{}).map(({file:d})=>({kind:"file",path:d.path,identity:d.file_id,document_hash:Ll(d)}))])}}function Ir(r,e,t,n,i){return{status:r,plan_fingerprint:e.fingerprint,applied:n,pending:t.pending,checkpoint_cursor:t.cursor,conflicts:t.conflicts.length,issues:e.issues,...i?{failure:i}:{}}}function gx(r,e){if(["planned","applying","cancelled","stale","blocked","failed"].includes(r.state))return r;let t=[...r.local_issues];for(let n of e.issues)n.path&&(n.code==="invalid_frontmatter"||n.code==="file_read_failed")&&!t.some(({path:i,code:s,message:o})=>i===n.path&&s===n.code&&o===n.message)&&t.push({path:n.path,code:n.code,message:n.message});return r.conflicts.length>0||t.length>0||e.summary.blocking_issues>0||e.summary.conflicts>0?{...r,state:"attention",local_issues:t}:{...r,state:e.actions.some(n=>n.command!=="advance_checkpoint")?"changes_waiting":"up_to_date"}}function Wt(r,e){if(!r)return{state:"not_initialized",mode:e,pending:0,pending_files:0,conflicts:[],local_issues:[],cursor:null,last_synced_at:null};let t=[];for(let[o,a]of Object.entries(r.planned_conflicts??{})){let c=t.findIndex(({entity:u,object_id:d})=>u===a.entity&&d===o);c!==-1&&t.splice(c,1);let l=a.local.state==="exact"?a.local.object.path:a.remote.state==="exact"?a.remote.object.path:null;t.push({entity:a.entity,object_id:o,decision_id:a.decision_id??"",path:l,kind:a.conflict_kind==="rejected"?"rejected":"conflicted",message:a.conflict_kind==="rejected"?"The authority rejected this local change.":"Local and authority changes need a decision."})}let n=[],i=r.batch?r.batch.plan.actions.slice(r.batch.next_action).filter(o=>o.command!=="advance_checkpoint").length:0;return{state:(r.batch?r.batch.phase==="prepared"?"planned":r.batch.phase==="applying"||r.batch.phase==="effects_complete"?"applying":r.batch.phase==="cancelled"?"cancelled":r.batch.failure?.code==="sync_plan_stale"?"stale":"blocked":null)??(t.length?"attention":"up_to_date"),mode:e,pending:i,pending_files:r.batch?r.batch.plan.actions.slice(r.batch.next_action).filter(o=>o.command!=="advance_checkpoint"&&("target"in o&&o.target.entity==="file"||"source"in o&&o.source.entity==="file"||"entity"in o&&o.entity==="file")).length:0,conflicts:t,local_issues:n,cursor:r.batch?.checkpoint_before.cursor??r.cursor,last_synced_at:r.last_synced_at??null,generation:r.generation??0,pending_checkpoint:r.batch?.checkpoint_after.cursor??null,...r.batch?{plan_fingerprint:r.batch.plan.fingerprint}:{},...r.last_completed_plan?{last_completed_plan:r.last_completed_plan}:{},recovery_required:r.batch!==void 0,...r.batch?.failure?{failure:r.batch.failure}:{}}}async function l2(r,e,t){let n=await e.openSession();if(n.protocol_version!==1||n.protocol_profile!=="exact_document_v1"||n.replica_id!==r||n.mode!==t)throw new w("sync_protocol_incompatible",`Filesystem mirror requires exact-document v1 and its own ${t.replace("_","-")} replica.`);return n}async function Jl(r,e,t,n,i){let s=await l2(r,e,t),o=s.resources.documents??[],a=Wl(o),c=new Gl(a,o,i.digest),l=[];await hx(e,s,async f=>{for(let p of f){let h=c.validate(p);bi(n,h.record.path)&&l.push(h)}});let u=[],d=new Set;return await HS(e,s,async f=>{for(let p of f)if(Ul(n,p)){if(d.has(p.file_id))throw new w("invalid_snapshot",`Hosted snapshot repeats file identity ${p.file_id}.`);d.add(p.file_id),u.push(p)}}),ea([...o.map(f=>f.path),...l.map(({record:f})=>f.path),...u.map(f=>f.path)]),{session:s,resources:o,records:l,files:u}}var Yl="exact_document_plan_only_v1",Xl="three_way_exact_document_v1",Ql="portable_mirror_projection_v1";function Zl(r){return JSON.stringify(fm(r))}function _i(r,e){return`sha256:${e(Zl(r))}`}function fm(r){if(r===null||typeof r=="string"||typeof r=="boolean")return r;if(typeof r=="number"){if(!Number.isSafeInteger(r))throw new w("invalid_sync_plan","Sync plans contain only safe integer numeric values.");return r}if(Array.isArray(r))return r.map(fm);if(typeof r=="object"){let e={};for(let t of Object.keys(r).sort()){let n=r[t];if(n===void 0)throw new w("invalid_sync_plan",`Sync plan field ${t} is undefined rather than an explicit state.`);e[t]=fm(n)}return e}throw new w("invalid_sync_plan","Sync plans contain only canonical I-JSON values.")}function Sx(r,e,t){let n=new Map(r.base.map(u=>[u.identity,u])),i=new Map(r.remote.map(u=>[u.identity,u])),s=new Map,o=new Map(r.local.map(u=>[u.object.path,u]));for(let u of r.local)!u.stable_identity||u.object.identity===""||(s.set(u.object.identity,u.object),o.delete(u.object.path));for(let[u,d]of n){let f=o.get(d.path);f&&(s.set(u,{...f.object,identity:u}),o.delete(d.path))}for(let[u,d]of i){if(s.has(u))continue;let f=o.get(d.path);f&&f.object.entity===d.entity&&(s.set(u,{...f.object,identity:u}),o.delete(d.path))}for(let[u,d]of n){if(s.has(u))continue;let f=[...o.values()].filter(h=>h.object.entity===d.entity&&h.object.payload_revision===d.payload_revision);if(f.length!==1)continue;let p=f[0];s.set(u,{...p.object,identity:u,revision:p.object.payload_revision===d.payload_revision?d.revision:p.object.revision}),o.delete(p.object.path)}for(let u of o.values()){let d=u.stable_identity?u.object.identity:v2(e,u.object,t);s.set(d,{...u.object,identity:d})}let a=new Set([...n.keys(),...s.keys(),...i.keys()]),c=new Map([...s.values()].map(u=>[u.path,u])),l=new Map([...i.values()].map(u=>[u.path,u]));return[...a].sort().map(u=>{let d=n.get(u),f=s.get(u),p=i.get(u),h=p?.path??f?.path??d.path,m=f?.path??p?.path??d.path;return{entity:(f??p??d).entity,identity:u,base:ta(d),local:ta(f),remote:ta(p),local_target_owner:ta(c.get(h)),remote_target_owner:ta(l.get(m))}})}function gm(r,e){let t=r.issues.some(A=>A.blocking),n=[],i=r.issues.filter(A=>A.blocking),s=[...r.objects].sort(_2),o=new Set(s.filter(A=>{if(r.mode!=="read_only"||A.local.state!=="exact"||A.remote.state!=="exact"||A.local.object.path!==A.remote.object.path)return!1;let x=i.filter(R=>R.path===A.local.object.path);return x.length>0&&x.every(R=>R.code==="invalid_frontmatter")})),a=new Set(i.map(A=>A.path).filter(A=>A!==void 0&&![...o].some(x=>x.local.object.path===A))),c=new Set,l=A=>[A.base,A.local,A.remote].filter(x=>x.state==="exact").map(x=>x.object.path),u=new Map,d=new Map,f=A=>A.split("/").map((x,R,$)=>$.slice(0,R+1).join("/")),p=(A,x,R)=>{A.has(x)||A.set(x,new Set),A.get(x).add(R)};if(a.size)for(let A of s)for(let x of l(A)){p(u,x,A);for(let R of f(x))p(d,R,A)}let h=[...a],m=new Set;for(let A=0;A!A.path)){for(let A of s)c.has(A)||y2(r,A,n,o.has(A));n=f2(n,r.objects,e),n=d2(n,r.objects)}if(n.length>0||!t&&(r.kind!=="incremental"||r.boundary.checkpoint.cursor!==r.boundary.authority_cursor)){let A=n.map(x=>x.key);n.push({key:"checkpoint",depends_on_keys:A,command:"advance_checkpoint",reason:r.kind==="incremental"?"remote_change":r.kind,expected:r.boundary.checkpoint,next:t?r.boundary.checkpoint:{generation:r.boundary.checkpoint.generation+1,cursor:r.boundary.authority_cursor}})}let g=new Map;for(let A of n){let{key:x,depends_on_keys:R,...$}=A;g.set(x,_i({action_scope:{replica_id:r.boundary.replica_id,scope_epoch:r.boundary.scope_epoch,generation:r.boundary.checkpoint.generation},key:x,...$},e))}let b=n.map(A=>{let{key:x,depends_on_keys:R,...$}=A,q={...$,action_id:g.get(x),depends_on:R.map(M=>g.get(M))};if((q.command==="put_remote"||q.command==="move_remote"||q.command==="delete_remote")&&(q.idempotency_key=q.action_id),q.command==="move_remote"){let M=R.find(V=>V===`${q.source.identity}:put-remote`);M&&(q.revision_from_dependency=g.get(M))}return q}),v=[...c].filter(A=>!i.some(x=>l(A).includes(x.path))).map(A=>({code:"local_collision",blocking:!0,path:l(A)[0],message:"Deferred because a related path transition is blocked. Independent files can still sync."})),S=[...r.issues,...v].sort(S2),_={uploads:b.filter($2).length,downloads:b.filter(E2).length,conflicts:b.filter(A=>A.command==="record_conflict").length,blocking_issues:S.filter(A=>A.blocking).length},E={plan_version:1,engine_profile:Yl,protocol_profile:"exact_document_v1",planner_policy:Xl,projection_policy:Ql,replica_id:r.boundary.replica_id,mode:r.mode,kind:r.kind,base_cursor:r.boundary.checkpoint.cursor,authority_cursor:r.boundary.authority_cursor,scope_epoch:r.boundary.scope_epoch,checkpoint_generation:r.boundary.checkpoint.generation,selective_sync:r.selective_sync,actions:b,issues:S,summary:_};return{...E,fingerprint:_i(E,e)}}function d2(r,e){if(!r.some(c=>c.command==="move_remote"))return r;let t=[...r],n=new Set;for(let c of u2(t))for(let l of c){let u=t.find(d=>d.key===l);u?.command==="move_remote"&&n.add(u.source.identity)}let i=mm(t),s=new Map(t.map(c=>[c.key,c])),o=!0;for(;o;){o=!1;for(let c of t){if(c.command!=="move_remote")continue;let l=c.expected_target_owner;if(l.state!=="exact"||l.object.identity===c.source.identity)continue;let u=s.get(i.get(Or(l.object))??""),d=u&&bx(u);(!u||d&&n.has(d))&&!n.has(c.source.identity)&&(n.add(c.source.identity),o=!0)}}if(n.size>0){t=t.filter(l=>{let u=bx(l);return!u||!n.has(u)||l.command!=="put_remote"&&l.command!=="move_remote"});let c=new Map(e.map(l=>[l.identity,l]));for(let l of[...n].sort()){let u=c.get(l);!u||u.entity==="resource"||t.push({key:`${l}:conflict`,depends_on_keys:[],command:"record_conflict",reason:"local_change",identity:l,entity:u.entity,local:u.local,remote:u.remote,conflict_kind:"path_occupied"})}}let a=mm(t);for(let c of t){if(c.command!=="move_remote")continue;let l=c.expected_target_owner;if(l.state!=="exact"||l.object.identity===c.source.identity)continue;let u=a.get(Or(l.object));!u||u===c.key||(c.depends_on_keys.includes(u)||c.depends_on_keys.push(u),c.expected_target_owner={state:"absent"})}return xx(t)}function u2(r){let e=r.filter(s=>s.command==="move_remote"),t=new Map(e.map(s=>[s.key,s])),n=mm(r),i=new Map;for(let s of e){let o=[],a=new Map,c=s;for(;c;){let l=a.get(c.key);if(l!==void 0){let d=o.slice(l);i.set([...d].sort().join("\0"),d);break}a.set(c.key,o.length),o.push(c.key);let u=c.expected_target_owner;c=u.state==="exact"?t.get(n.get(Or(u.object))??""):void 0}}return[...i.values()]}function mm(r){let e=new Map;for(let t of r)t.command==="move_remote"?e.set(Or(t.source),t.key):t.command==="delete_remote"&&e.set(Or(t.target),t.key);return e}function bx(r){if(r.command==="move_remote")return r.source.identity;if(r.command==="put_remote"||r.command==="delete_remote")return r.target.identity}function f2(r,e,t){if(!r.some(d=>d.command==="move_local"||d.command==="write_local"))return r;let n=[...r],i=new Set;for(let d of e)d.base.state==="exact"&&i.add(d.base.object.path),d.local.state==="exact"&&i.add(d.local.object.path),d.remote.state==="exact"&&i.add(d.remote.object.path);for(;;){let d=p2(n);if(!d)break;let f=[...d].sort()[0],p=n.findIndex(b=>b.key===f),h=n[p];if(!h||h.command!=="move_local")throw new Error("Planner invariant: local path cycle contains a non-move action.");let m=m2(h.source,h.target_path,i,t);i.add(m);let y={...h.source,path:m},g={key:`${h.source.identity}:stage-local`,depends_on_keys:[...h.depends_on_keys],command:"move_local",reason:h.reason,source:h.source,target_path:m,expected_source_owner:h.expected_source_owner,expected_target_owner:{state:"absent"}};h.source=y,h.expected_source_owner={state:"exact",object:y},h.depends_on_keys=[g.key],n.splice(p,0,g)}let s=ym(n),o=new Map(e.map(d=>[d.identity,d])),a=new Set,c=new Map(n.map(d=>[d.key,d])),l=!0;for(;l;){l=!1;for(let d of n){let f=vx(d),p=ed(d);if(f?.state!=="exact"||f.object.identity===p)continue;let h=c.get(s.get(Or(f.object))??""),m=h&&ed(h);(!h||m&&a.has(m))&&!a.has(p)&&(a.add(p),l=!0)}}if(a.size>0){n=n.filter(d=>!a.has(ed(d))||d.command!=="move_local"&&d.command!=="write_local");for(let d of[...a].sort()){let f=o.get(d);!f||f.entity==="resource"||n.push({key:`${d}:conflict`,depends_on_keys:[],command:"record_conflict",reason:"remote_change",identity:d,entity:f.entity,local:f.local,remote:f.remote,conflict_kind:"path_occupied"})}}let u=ym(n);for(let d of n){let f=vx(d),p=ed(d);if(f?.state!=="exact"||f.object.identity===p)continue;let h=u.get(Or(f.object));!h||h===d.key||(d.depends_on_keys.includes(h)||d.depends_on_keys.push(h),h2(d,{state:"absent"}))}return xx(n)}function p2(r){let e=r.filter(i=>i.command==="move_local"),t=new Map(e.map(i=>[i.key,i])),n=ym(r);for(let i of e){let s=[],o=new Map,a=i;for(;a;){let c=o.get(a.key);if(c!==void 0)return s.slice(c);o.set(a.key,s.length),s.push(a.key);let l=a.expected_target_owner;a=l.state==="exact"?t.get(n.get(Or(l.object))??""):void 0}}}function ym(r){let e=new Map;for(let t of r)t.command==="move_local"?e.set(Or(t.source),t.key):t.command==="delete_local"&&e.set(Or(t.target),t.key);return e}function vx(r){if(r.command==="move_local")return r.expected_target_owner;if(r.command==="write_local")return r.expected_path_owner}function h2(r,e){r.command==="move_local"?r.expected_target_owner=e:r.command==="write_local"&&(r.expected_path_owner=e)}function ed(r){return r.command==="move_local"?r.source.identity:r.command==="write_local"||r.command==="delete_local"?r.target.identity:""}function Or(r){return`${r.entity}\0${r.identity}\0${r.path}`}function m2(r,e,t,n){let i=r.path.lastIndexOf("/"),s=i<0?"":r.path.slice(0,i+1),o=i<0?r.path:r.path.slice(i+1),a=o.lastIndexOf("."),c=a>0?o.slice(a):"";for(let l=0;;l+=1){let u=n(`${r.entity}\0${r.identity}\0${r.path}\0${e}\0${l}`),d=`${s}.mdbase-sync-stage-${u.slice(0,16)}${c}`;if(!t.has(d))return d}}function xx(r){let e=[...r],t=new Set,n=[];for(;e.length>0;){let i=e.findIndex(o=>o.depends_on_keys.every(a=>t.has(a)));if(i<0)throw new Error("Planner invariant: action dependency graph contains a cycle.");let[s]=e.splice(i,1);n.push(s),t.add(s.key)}return n}function y2(r,e,t,n){if(e.frozen_conflict){t.push(w2(e.frozen_conflict.local,e.frozen_conflict.remote)?{key:`${e.identity}:clear-conflict`,depends_on_keys:[],command:"clear_conflict",reason:"pending",identity:e.identity,entity:e.entity,expected_local:e.frozen_conflict.local,expected_remote:e.frozen_conflict.remote}:{key:`${e.identity}:conflict`,depends_on_keys:[],command:"record_conflict",reason:"pending",identity:e.identity,entity:e.entity,...e.frozen_conflict});return}let i=!hm(e.local,e.base),s=!hm(e.remote,e.base);if(!(!i&&!s)){if(e.entity==="resource"){if(i)return;pm(e,t);return}if(r.mode==="read_only"){(!i||n)&&pm(e,t);return}if(i&&s){if(hm(e.local,e.remote))return;t.push(b2(e));return}i?g2(e,t):pm(e,t)}}function pm(r,e){if(r.remote.state==="absent"){r.local.state==="exact"&&e.push({key:`${r.identity}:delete-local`,depends_on_keys:[],command:"delete_local",reason:"remote_change",target:r.local.object,expected_local:r.local,expected_path_owner:r.local_target_owner});return}let t=r.remote.object;if(r.local.state==="absent"){e.push(wx(r,t,[]));return}let n=r.local.object,i;if(n.path!==t.path){let s=`${r.identity}:move-local`;e.push({key:s,depends_on_keys:[],command:"move_local",reason:"remote_change",source:n,target_path:t.path,expected_source_owner:r.local,expected_target_owner:r.local_target_owner}),i=s}n.revision!==t.revision&&e.push(wx(r,t,i?[i]:[]))}function wx(r,e,t){return{key:`${r.identity}:write-local`,depends_on_keys:t,command:"write_local",reason:"remote_change",target:e,payload_revision:e.payload_revision,expected_local:t.length>0?{state:"exact",object:{...e,revision:nn(r.local).revision,payload_revision:nn(r.local).payload_revision,...nn(r.local).size===void 0?{}:{size:nn(r.local).size}}}:r.local,expected_path_owner:t.length>0?{state:"exact",object:{...e,revision:nn(r.local).revision,payload_revision:nn(r.local).payload_revision,...nn(r.local).size===void 0?{}:{size:nn(r.local).size}}}:r.local_target_owner}}function g2(r,e){if(r.local.state==="absent"){r.remote.state==="exact"&&e.push({key:`${r.identity}:delete-remote`,depends_on_keys:[],command:"delete_remote",reason:"local_change",target:r.remote.object,expected_remote:r.remote,expected_local:r.local,idempotency_key:""});return}let t=r.local.object;if(r.remote.state==="absent"){e.push(_x(r,t,[]));return}let n=r.remote.object,i;if(t.revision!==n.revision){let s=_x(r,{...t,path:n.path},[]);e.push(s),i=s.key}t.path!==n.path&&e.push({key:`${r.identity}:move-remote`,depends_on_keys:i?[i]:[],command:"move_remote",reason:"local_change",source:i?{...n,revision:t.revision}:n,target_path:t.path,expected_source_owner:i?{state:"exact",object:{...n,revision:t.revision}}:r.remote,expected_target_owner:r.remote_target_owner,expected_local:r.local,idempotency_key:""})}function _x(r,e,t){return{key:`${r.identity}:put-remote`,depends_on_keys:t,command:"put_remote",reason:"local_change",target:e,payload_revision:nn(r.local).payload_revision,expected_remote:r.remote,expected_local:r.local,idempotency_key:""}}function b2(r){return{key:`${r.identity}:conflict`,depends_on_keys:[],command:"record_conflict",reason:"remote_change",identity:r.identity,entity:r.entity,local:r.local,remote:r.remote,conflict_kind:r.local.state==="absent"||r.remote.state==="absent"?"delete_vs_change":"both_changed"}}function nn(r){if(r.state!=="exact")throw new Error("Planner invariant: expected exact object state.");return r.object}function ta(r){return r?{state:"exact",object:r}:{state:"absent"}}function v2(r,e,t){let n=t(`${r}\0${e.entity}\0${e.path}\0${e.revision}`);return`${n.slice(0,8)}-${n.slice(8,12)}-5${n.slice(13,16)}-8${n.slice(17,20)}-${n.slice(20,32)}`}function hm(r,e){return Zl(r)===Zl(e)}function w2(r,e){return r.state==="absent"||e.state==="absent"?r.state===e.state:r.object.entity===e.object.entity&&r.object.identity===e.object.identity&&r.object.path===e.object.path&&r.object.payload_revision===e.object.payload_revision&&r.object.size===e.object.size}function _2(r,e){return`${r.entity}\0${r.identity}`.localeCompare(`${e.entity}\0${e.identity}`)}function S2(r,e){return x2(`${r.path??""}\0${r.code}\0${r.message}`,`${e.path??""}\0${e.code}\0${e.message}`)}function x2(r,e){let t=new TextEncoder,n=t.encode(r),i=t.encode(e),s=Math.min(n.length,i.length);for(let o=0;o[c.record_id,c])),a=new Map(n.files.map(c=>[c.file_id,c]));return this.finish({kind:e,prior:t,authorityCursor:n.session.head,scopeEpoch:n.session.scope_epoch,local:s,remoteRecords:o,remoteResources:n.resources,remoteFiles:a,snapshot:n})}async inspectIncremental(e){let t=new Map;for(let[l,u]of Object.entries(e.records))u.record&&t.set(l,u.record);let n=new Map(Object.entries(e.files??{}).map(([l,u])=>[l,u.file])),i=new Map(Ex(e).map(l=>[A2(l),l])),s=e.cursor,o=e.cursor;for(;;){let l=s,u=await this.transport.changes(l,200);if(u.scope_epoch!==e.scope_epoch||u.cursoru.head||u.has_more&&u.cursor===l)throw new w("invalid_change_page","Authority returned an invalid change boundary.");if(u.reset_required)return this.inspectSnapshot("rebuild",e);for(let d of u.events){if(d.sequence<=o||d.sequence>u.cursor)throw new w("invalid_change_page","Authority change events are not strictly ordered.");o=d.sequence,this.applyRemoteObservation(i,t,n,d)}if(s=u.cursor,!u.has_more)break}let a=Object.values(e.resources??{}).map(l=>({path:l.path,kind:C2(l.path),revision:l.revision,document:""})),c=await this.inspectLocal(e,a,await this.currentRecordPathPolicy(e));return this.mode==="read_only"&&c.issues.some(l=>l.code==="invalid_frontmatter"&&l.blocking)?this.inspectSnapshot("rebuild",e):this.finish({kind:"incremental",prior:e,authorityCursor:s,scopeEpoch:e.scope_epoch,local:c,remoteRecords:t,remoteResources:[],remoteFiles:n,remoteRefs:[...i.values()]})}applyRemoteObservation(e,t,n,i){if(i.type==="put"){AS(i);let s=i.record.record_id;bi(this.selectiveSync,i.record.path)?(e.set(`record:${s}`,kx(i.record)),t.set(s,i.record)):(e.delete(`record:${s}`),t.delete(s));return}if(i.type==="remove"){e.delete(`record:${i.record_id}`),t.delete(i.record_id);return}if(i.type==="file_put"){xt(i.file);let s=i.file.file_id;Ul(this.selectiveSync,i.file)?(e.set(`file:${s}`,vm(i.file)),n.set(s,i.file)):(e.delete(`file:${s}`),n.delete(s));return}e.delete(`file:${i.file_id}`),n.delete(i.file_id)}async inspectLocal(e,t,n){let i=[],s=new Map,o=new Map,a=[],c=new Map(Object.entries(e?.records??{}).map(([h,m])=>[m.path,[h,m]])),l=new Map(Object.entries(e?.planned_conflicts??{}).filter(([,h])=>h.entity==="record"&&h.local.state==="exact").map(([h,m])=>[m.local.state==="exact"?m.local.object.path:"",h])),u=new Map(Object.entries(e?.local_bindings??{}).filter(([,h])=>h.entity==="record").map(([h,m])=>[m.path,h])),d=new Set([...Object.keys(e?.resources??{}),...t.map(h=>h.path)]);for(let h of d){let m=e?.resources?.[h],y;try{y=await this.fileSystem.read(h)}catch{a.push(Px(h)),m&&i.push({stable_identity:!0,object:On("resource",h,h,m.revision)});continue}if(y===null)continue;let g=y,b=_t(g,this.runtime);i.push({stable_identity:!0,object:On("resource",h,h,b)}),s.set(h,g);let v=t.find(S=>S.path===h);!m&&v&&v.revision!==b?a.push({code:"local_collision",message:`${h} differs locally from the exact authority document.`,path:h,blocking:!0}):m&&m.revision!==b&&a.push({code:"mirror_diverged",message:`Authority-owned resource ${h} changed locally.`,path:h,blocking:!0})}let f=new Set(Object.values(e?.records??{}).map(h=>h.path)),p=dx(await this.fileSystem.listMarkdown(d),n).filter(h=>bi(this.selectiveSync,h)||f.has(h));for(let h of p){let m=l.get(h),y=u.get(h),g=c.get(h),b=g?.[0],v=m??y??b??"",S;try{S=await this.fileSystem.readText(h)}catch{S=null}if(typeof S!="string"){a.push(S===null?Px(h):{code:"invalid_frontmatter",message:`Invalid frontmatter (${S.code}).`,path:h,blocking:!0});let x=S?.revision??g?.[1].revision;x&&i.push({stable_identity:v!=="",object:On("record",v,h,x)});continue}let _=S,E=_t(_,this.runtime);i.push({stable_identity:v!=="",object:On("record",v,h,E)}),s.set(h,_);let A=xS(_);A.outcome!=="parsed"&&a.push({code:"invalid_frontmatter",message:`Invalid frontmatter (${A.outcome}).`,path:h,blocking:!1})}if(this.selectiveSync.file_classes.length>0){if(!this.fileSystem.listBinary)throw new w("file_storage_unavailable","Selected files require binary enumeration.");let h=new Set(Object.values(e?.files??{}).map(v=>v.file.path)),m=new Map(Object.entries(e?.files??{}).map(([v,S])=>[S.file.path,[v,S]])),y=new Map(Object.entries(e?.planned_conflicts??{}).filter(([,v])=>v.entity==="file"&&v.local.state==="exact").map(([v,S])=>[S.local.state==="exact"?S.local.object.path:"",v])),g=new Map(Object.entries(e?.local_bindings??{}).filter(([,v])=>v.entity==="file").map(([v,S])=>[S.path,v])),b=(await this.fileSystem.listBinary(d)).filter(v=>US(this.selectiveSync,v)||h.has(v));for(let v of b){let S=await this.fileSystem.inspectBinary(v);if(!S)continue;let _=y.get(v),E=g.get(v),A=m.get(v),x=_??E??A?.[0]??"";i.push({stable_identity:x!=="",object:{entity:"file",identity:x,path:v,revision:A&&A[1].file.content_digest===S.content_digest?A[1].file.revision:S.content_digest,payload_revision:S.content_digest,size:S.size}}),o.set(v,S)}}try{ea([...d,...p,...o.keys()])}catch(h){let m=pi(h);a.push({code:hi(h,"sync_inspection_failed"),message:m.message,blocking:!0})}return{observations:i,documents:s,binary:o,issues:a}}async finish(e){let{prior:t,local:n}=e,i=e.remoteRefs??[...e.remoteResources.map(k2),...[...e.remoteRecords.values()].map(kx),...[...e.remoteFiles.values()].map(vm)],s=Sx({base:t?Ex(t):[],local:n.observations,remote:i},`${this.replicaId}\0${e.scopeEpoch}\0${t?.generation??0}`,this.runtime.digest);for(let d of s){let f=t?.planned_conflicts?.[d.identity];!f||f.entity!==d.entity||(d.frozen_conflict={local:d.local,remote:d.remote,conflict_kind:f.conflict_kind})}let o=[...n.issues];for(let d of s)(e.kind==="initial"||e.kind==="rebuild")&&d.base.state==="absent"&&d.local.state==="exact"&&d.remote.state==="exact"&&!Ax(d.local,d.remote)&&o.push({code:"local_collision",message:`${d.remote.object.path} differs locally from the exact authority object.`,path:d.remote.object.path,blocking:this.mode!=="read_write"||d.entity==="resource"}),d.remote.state==="exact"&&d.local_target_owner.state==="exact"&&d.remote.object.identity!==d.local_target_owner.object.identity&&o.push({code:"local_collision",message:`${d.remote.object.path} is owned by different local bytes.`,path:d.remote.object.path,blocking:!0});try{ea([...i.map(d=>d.path),...n.observations.map(({object:d})=>d.path)])}catch(d){let f=pi(d);o.push({code:hi(d,"sync_inspection_failed"),message:f.message,blocking:!0})}if(this.mode==="read_only"){for(let d of s)if(d.entity!=="resource"&&!Ax(d.local,d.base)){let f=P2(d.local,d.base);if(o.some(p=>p.blocking&&p.path===f))continue;o.push({code:"mirror_diverged",message:`${f} changed in a receive-only mirror.`,path:f,blocking:!0})}}let a=_i(gi(this.selectiveSync),this.runtime.digest),c={boundary:{engine_profile:Yl,protocol_profile:"exact_document_v1",planner_policy:Xl,projection_policy:Ql,replica_id:this.replicaId,scope_epoch:e.scopeEpoch,authority_cursor:e.authorityCursor,checkpoint:{generation:t?.generation??0,cursor:t?.cursor??null},selective_sync_fingerprint:a},mode:this.mode,kind:e.kind,selective_sync:gi(this.selectiveSync),objects:s,issues:$x(o)},l=gm(c,this.runtime.digest);if(this.fileSystem.pathKind){let d=new Map,f=p=>(d.has(p)||d.set(p,this.fileSystem.pathKind(p)),d.get(p));for(let p of l.actions){let h=p.command==="write_local"?p.target.path:p.command==="move_local"?p.target_path:null;if(h===null)continue;let m=await f(h)==="folder"?h:null,y=h.split("/");for(let g=1;m===null&&g[c.path,c]));for(let c of e.actions)if(c.command==="put_remote"){let l=c.expected_local.state==="exact"?c.expected_local.object.path:c.target.path;if(c.target.entity==="file"){let u=t.binary.get(l);if(!u)throw Si(c.action_id);await this.stageLocalBinary(l,u),o.local_files[c.action_id]={path:l,...u}}else{let u=t.documents.get(l);if(u===void 0||_t(u,this.runtime)!==c.payload_revision)throw Si(c.action_id);o.documents[c.action_id]=u}c.target.entity==="record"&&(o.mutations[c.action_id]={operation:"put",mutation_id:bm(c.action_id),replica_id:this.replicaId,scope_epoch:e.scope_epoch,record_id:c.target.identity,...c.expected_remote.state==="exact"?{base_revision:c.expected_remote.object.revision}:{},path:c.target.path,document:o.documents[c.action_id],created_at:this.runtime.now()})}else if(c.command==="write_local")if(c.target.entity==="record"){let l=n.get(c.target.identity);if(!l||l.revision!==c.target.revision)throw Si(c.action_id);o.records[c.action_id]=l}else if(c.target.entity==="resource"){let l=a.get(c.target.path);if(!l||l.revision!==c.target.revision)throw Si(c.action_id);o.resources[c.action_id]=l}else{let l=s.get(c.target.identity);if(!l||l.revision!==c.target.revision||!this.blobStore)throw Si(c.action_id);o.files[c.action_id]=l}else if(c.command==="record_conflict"&&c.remote.state==="exact")if(c.entity==="record"){let l=n.get(c.identity);if(!l||l.revision!==c.remote.object.revision)throw Si(c.action_id);o.records[c.action_id]=l}else{let l=s.get(c.identity);if(!l||l.revision!==c.remote.object.revision)throw Si(c.action_id);o.files[c.action_id]=l}else c.command==="move_remote"&&c.source.entity==="record"?o.mutations[c.action_id]={operation:"move",mutation_id:bm(c.action_id),replica_id:this.replicaId,scope_epoch:e.scope_epoch,record_id:c.source.identity,base_revision:c.expected_source_owner.state==="exact"?c.expected_source_owner.object.revision:c.source.revision,path:c.target_path,created_at:this.runtime.now()}:c.command==="delete_remote"&&c.target.entity==="record"&&(o.mutations[c.action_id]={operation:"delete",mutation_id:bm(c.action_id),replica_id:this.replicaId,scope_epoch:e.scope_epoch,record_id:c.target.identity,base_revision:c.expected_remote.state==="exact"?c.expected_remote.object.revision:c.target.revision,created_at:this.runtime.now()});return o}async stageLocalBinary(e,t){if(!this.blobStore||!this.fileSystem.readBinary)throw new w("writable_file_storage_unavailable","Writable files require streaming filesystem and blob-store adapters.");if(await this.blobStore.has(t.content_digest))return;let n=await this.fileSystem.readBinary(e);if(!n)throw new w("sync_plan_stale",`${e} disappeared during inspection.`);await this.blobStore.write(t.content_digest,zS(n,t,e))}};function $x(r){let e=new Map;for(let t of r)e.set(`${t.code}\0${t.path??""}\0${t.message}\0${t.blocking}`,t);return[...e.values()]}function Ex(r){return[...Object.entries(r.resources??{}).map(([e,t])=>On("resource",e,t.path,t.revision)),...Object.entries(r.records).map(([e,t])=>On("record",e,t.path,t.revision)),...Object.entries(r.files??{}).map(([e,t])=>vm({...t.file,file_id:e}))]}function kx(r){return On("record",r.record_id,r.path,r.revision)}function k2(r){return On("resource",r.path,r.path,r.revision)}function On(r,e,t,n){return{entity:r,identity:e,path:t,revision:n,payload_revision:n}}function vm(r){return{entity:"file",identity:r.file_id,path:r.path,revision:r.revision,payload_revision:r.content_digest,size:r.size}}function A2(r){return`${r.entity}:${r.identity}`}function Ax(r,e){return JSON.stringify(r)===JSON.stringify(e)}function P2(r,e){return r.state==="exact"?r.object.path:e.state==="exact"?e.object.path:"mirror"}function Si(r){return new w("sync_payload_incomplete",`Inspected action ${r} has no revision-bound payload.`)}function Px(r){return{code:"file_read_failed",message:"Could not read local file.",path:r,blocking:!0}}function C2(r){return r==="mdbase.yaml"?"configuration":r.endsWith("lock.yaml")?"lock":r.startsWith("_types/")?"type":r.startsWith("_contracts/")?"contract":r.startsWith("_views/")?"view":"schema"}function bm(r){let e=r.replace(/^sha256:/u,"");return`${e.slice(0,8)}-${e.slice(8,12)}-4${e.slice(13,16)}-8${e.slice(17,20)}-${e.slice(20,32)}`}var ra=class{fileSystem;runtime;constructor(e,t){this.fileSystem=e,this.runtime=t}async validate(e,t){if((t?.generation??0)!==e.checkpoint_generation||(t?.cursor??null)!==e.base_cursor||(t?.scope_epoch??e.scope_epoch)!==e.scope_epoch)throw hr("The durable checkpoint changed after inspection.");for(let n of e.actions)n.depends_on.length===0&&await this.validateAction(n)}async validateAction(e){switch(e.command){case"write_local":await this.validateExpected(e.expected_local),await this.validateExpectedAt(e.target.path,e.expected_path_owner);return;case"delete_local":await this.validateExpected(e.expected_local),await this.validateExpectedAt(e.target.path,e.expected_path_owner);return;case"move_local":await this.validateExpectedAt(e.source.path,e.expected_source_owner),await this.validateExpectedAt(e.target_path,e.expected_target_owner);return;case"put_remote":case"move_remote":await this.validateExpected(e.expected_local);return;case"delete_remote":await this.validateExpectedAt(e.target.path,e.expected_local);return;case"record_conflict":await this.validateExpected(e.local);return;case"clear_conflict":await this.validateExpected(e.expected_local);return;case"advance_checkpoint":return}}async validateExpectedAt(e,t){if(t.state==="absent"){if(await this.fileSystem.exists(e))throw hr(`${e} is no longer vacant.`);return}if(t.object.path!==e||!await rd(this.fileSystem,this.runtime,t.object,!0))throw hr(`${e} no longer has the inspected owner and bytes.`)}async validateExpected(e){if(e.state!=="absent"&&!await rd(this.fileSystem,this.runtime,e.object,!0))throw hr(`${e.object.path} no longer matches the inspected bytes.`)}};async function rd(r,e,t,n){if(t.entity==="file"){let s=await r.inspectBinary(t.path);return!!s&&s.content_digest===t.payload_revision&&(t.size===void 0||s.size===t.size)}let i;try{i=await r.readText(t.path)}catch(s){throw s instanceof w&&s.code==="file_read_failed"&&n?hr(s.message):s}return(typeof i=="string"?_t(i,e):i?.revision)===t.payload_revision}function hr(r){return new w("sync_plan_stale",r)}async function Cx(r,e,t,n){if(r?.batch){if(r.batch.plan.fingerprint!==e.fingerprint)throw new w("mirror_recovery_required","A different prepared sync batch must recover before this plan can apply.");return r}let i=r?structuredClone(r):R2(e.replica_id,e.scope_epoch,e.mode,e.selective_sync);i.scope_epoch=e.scope_epoch,i.selective_sync=e.selective_sync;let s=e.actions.at(-1);if(s?.command!=="advance_checkpoint")throw new w("invalid_sync_plan","Prepared plan has no checkpoint action.");return i.batch={phase:"prepared",plan:e,next_action:0,receipts:[],payloads:t,checkpoint_before:{generation:e.checkpoint_generation,cursor:e.base_cursor},checkpoint_after:s.next},await n.write(i),i}async function Mx(r,e){let t=lt(r);t.phase!=="effects_complete"&&(t.phase="applying",delete t.failure,await id(r,{type:"phase",plan_fingerprint:t.plan.fingerprint,phase:"applying"},e))}async function Rx(r,e,t){let n=lt(r),i=n.plan.actions[n.next_action];if(!i||i.action_id!==e.action_id)throw De("The durable sync receipt does not match the next prepared action.");let s={type:"receipt",plan_fingerprint:n.plan.fingerprint,receipt:structuredClone(e),delta:M2(r,i)};n.receipts.push(structuredClone(e)),n.next_action+=1,await id(r,s,t)}async function Tx(r,e){let t=lt(r),n=t.plan.actions[t.next_action];if(!n||n.command!=="advance_checkpoint")throw De("Sync effects cannot complete before the checkpoint action is next.");t.phase="effects_complete",await id(r,{type:"effects_complete",plan_fingerprint:t.plan.fingerprint},e)}async function nd(r,e,t,n){let i=lt(r);i.phase=e,i.failure=t,await id(r,{type:"phase",plan_fingerprint:i.plan.fingerprint,phase:e,failure:t},n)}async function id(r,e,t){t.appendJournal?await t.appendJournal(e):await t.write(r)}function M2(r,e){let t="identity"in e?e.identity:"target"in e?e.target.identity:"source"in e?e.source.identity:null;if(t===null)return{};let n="entity"in e?e.entity:"target"in e?e.target.entity:"source"in e?e.source.entity:null;if(n===null)return{};let i={planned_conflicts:{[t]:na(r.planned_conflicts?.[t])},local_bindings:{[t]:na(r.local_bindings?.[t])}};return n==="record"?i.records={[t]:na(r.records[t])}:n==="resource"?i.resources={[t]:na(r.resources?.[t])}:i.files={[t]:na(r.files?.[t])},i}function na(r){return r===void 0?null:structuredClone(r)}function lt(r){if(!r.batch)throw De("The mirror has no prepared sync batch.");return r.batch}async function wm(r,e){let t=lt(r);if(t.phase!=="blocked"||t.failure?.code!=="sync_plan_stale")throw new w("mirror_recovery_required","Only a stale batch at a durable action boundary can be abandoned.");delete r.batch,await e.write(r)}function R2(r,e,t,n){return{protocol_version:1,engine_version:3,generation:0,replica_id:r,scope_epoch:e,cursor:0,records:{},resources:{},files:{},selective_sync:n,mode:t,planned_conflicts:{}}}var od=class{ports;materializer;ownersByPath=new Map;pathsByOwner=new Map;constructor(e){this.ports=e,this.materializer=new $s(e.fileSystem,e.runtime,e.mode,e.blobStore)}async execute(e,t){let n=lt(e);this.indexPathOwners(e);let i=new Set(n.receipts.map(s=>s.action_id));for(await Mx(e,this.ports.store);n.next_action!i.has(a));if(o){let a={code:"invalid_mirror_state",message:`Action ${s.action_id} is missing dependency ${o}.`,action_id:s.action_id};return await nd(e,"blocked",a,this.ports.store),{status:"blocked",completed:n.next_action,failure:a}}try{let a=await this.dispatch(e,s);await Rx(e,a,this.ports.store),i.add(a.action_id),this.ports.onProgress?.(n.next_action,n.plan.actions.length-1)}catch(a){let c=t?.aborted===!0,l=c?{code:"sync_cancelled",message:"Sync paused during transfer.",action_id:s.action_id}:O2(a,s.action_id);return await nd(e,c?"cancelled":"blocked",l,this.ports.store),{status:c?"cancelled":l.code==="sync_plan_stale"?"stale":"blocked",completed:n.next_action,failure:l}}}throw De("Prepared plan has no checkpoint action.")}async dispatch(e,t){switch(t.command){case"write_local":return this.writeLocal(e,t);case"move_local":return this.moveLocal(e,t);case"delete_local":return this.deleteLocal(e,t);case"put_remote":return this.putRemote(e,t);case"move_remote":return this.moveRemote(e,t);case"delete_remote":return this.deleteRemote(e,t);case"record_conflict":{e.planned_conflicts??={};let n=t.identity in e.planned_conflicts?e.planned_conflicts[t.identity].ancestor_document:t.entity==="record"?e.records[t.identity]?.record?.document:void 0;return e.planned_conflicts[t.identity]={decision_id:Ix(t.entity,t.identity,t.local,t.remote,t.conflict_kind,this.ports.runtime.digest),entity:t.entity,local:t.local,remote:t.remote,conflict_kind:t.conflict_kind,...n===void 0?{}:{ancestor_document:n}},e.local_bindings??={},t.local.state==="exact"?e.local_bindings[t.identity]={entity:t.entity,path:t.local.object.path}:delete e.local_bindings[t.identity],this.rebaseConflict(e,t),{action_id:t.action_id,status:"conflicted"}}case"clear_conflict":return delete e.planned_conflicts?.[t.identity],delete e.local_bindings?.[t.identity],{action_id:t.action_id,status:"completed"};case"advance_checkpoint":throw De("The executor cannot dispatch checkpoint actions.")}}rebaseConflict(e,t){let n=lt(e).payloads;if(t.entity==="record"){if(t.remote.state==="absent"){delete e.records[t.identity];return}let s=n.records[t.action_id];if(!s||s.revision!==t.remote.object.revision)throw mr(t);sd(s,this.ports.runtime,s.revision),e.records[t.identity]={path:s.path,revision:s.revision,hash:t.local.state==="exact"?t.local.object.payload_revision.replace(/^sha256:/u,""):this.ports.runtime.digest(s.document),...this.ports.mode==="read_write"?{record:s}:{}};return}if(e.files??={},t.remote.state==="absent"){delete e.files[t.identity];return}let i=n.files[t.action_id];if(!i||i.revision!==t.remote.object.revision)throw mr(t);xt(i),e.files[t.identity]={file:i}}async writeLocal(e,t){let n=lt(e),i=await this.ports.fileSystem.exists(t.target.path);(!i||!await this.matchesRef(t.target))&&(await this.assertLocal(t.expected_local),await this.assertPathOwner(t.target.path,t.expected_path_owner,i));let s=n.payloads;if(t.target.entity==="record"){let a=s.records[t.action_id];if(!a||a.revision!==t.payload_revision)throw mr(t);return sd(a,this.ports.runtime,t.payload_revision),await this.materializer.put(e,a,{inspectionPreflighted:this.ports.mode==="read_only"&&n.plan.issues.some(c=>c.blocking&&c.code==="invalid_frontmatter"&&c.path===t.target.path)?1:!0}),this.installPathOwner(t.target),{action_id:t.action_id,status:"completed"}}if(t.target.entity==="resource"){let a=s.resources[t.action_id];if(!a||a.revision!==t.payload_revision||_t(a.document,this.ports.runtime)!==a.revision)throw mr(t);return await this.materializer.putResource(e,a,e),this.installPathOwner(t.target),{action_id:t.action_id,status:"completed"}}let o=s.files[t.action_id];if(!o||o.content_digest!==t.payload_revision||!this.ports.blobStore)throw mr(t);return await Vl(this.ports.transport,this.ports.blobStore,o),await this.materializer.putFile(e,o,e),this.installPathOwner(t.target),{action_id:t.action_id,status:"completed"}}async moveLocal(e,t){return await this.matchesRef({...t.source,path:t.target_path})||(await this.assertLocal(t.expected_source_owner),await this.assertPathOwner(t.target_path,t.expected_target_owner),await this.ports.fileSystem.move(t.source.path,t.target_path)),T2(e,t.source,t.target_path),this.installPathOwner({...t.source,path:t.target_path}),{action_id:t.action_id,status:"completed"}}async deleteLocal(e,t){if(await this.matchesRef(t.target))if(await this.assertLocal(t.expected_local),t.target.entity==="record")await this.materializer.remove(e,t.target.identity,t.target.path,{inspectionPreflighted:!0});else if(t.target.entity==="resource"){let i=e.resources?.[t.target.identity];if(i)await this.materializer.removeResource(e,t.target.path,i);else{let s=await this.ports.fileSystem.read(t.target.path);if(s!==null){if(_t(s,this.ports.runtime)!==t.target.payload_revision)throw hr(`${t.target.path} changed before removal.`);await this.ports.fileSystem.remove(t.target.path,s)}}}else await this.materializer.removeFile(e,t.target.identity);else I2(e,t.target);return this.removePathOwner(t.target),{action_id:t.action_id,status:"completed"}}async putRemote(e,t){let n=lt(e).payloads;if(t.target.entity==="record"){let a=n.mutations[t.action_id],c=n.documents[t.action_id];if(!a||a.operation!=="put"||c===void 0)throw mr(t);if(_t(c,this.ports.runtime)!==t.payload_revision)throw hr("Prepared local document payload no longer matches its revision.");let l=await this.ports.transport.mutate(a);return this.acceptRecordReceipt(e,t,l,c),_m(t.action_id,l)}if(t.target.entity==="resource")throw new w("invalid_sync_plan","Authority resources are not writable mirror objects.");let i=n.local_files[t.action_id];if(!i||!this.ports.blobStore||!this.ports.transport.uploadFile)throw mr(t);let s={protocol_version:1,type:"open_file_upload",transfer_id:xm(t.action_id),path:t.target.path,size:i.size,content_digest:i.content_digest,...i.media_type?{media_type:i.media_type}:{},...t.expected_remote.state==="exact"?{if_revision:t.expected_remote.object.revision}:{}},o=await this.ports.transport.uploadFile(s,this.ports.blobStore.read(i.content_digest));if(xt(o.file),o.transfer_id!==s.transfer_id||o.file.path!==t.target.path||o.file.content_digest!==i.content_digest||o.file.size!==i.size)throw Sm(t);return e.files??={},e.files[o.file.file_id]={file:o.file},delete e.local_bindings?.[t.target.identity],{action_id:t.action_id,status:"completed",file:o.file}}async moveRemote(e,t){if(t.source.entity==="record"){let s=lt(e).payloads.mutations[t.action_id];if(!s||s.operation!=="move")throw mr(t);let o=await this.ports.transport.mutate(s);return this.acceptRecordReceipt(e,t,o),_m(t.action_id,o)}if(t.source.entity==="resource"||!this.ports.transport.moveFile)throw new w("invalid_sync_plan","This remote move command is unsupported.");let n={protocol_version:1,type:"move_file",mutation_id:xm(t.action_id),file_id:t.source.identity,if_revision:this.dependencyFileRevision(e,t)??(t.expected_source_owner.state==="exact"?t.expected_source_owner.object.revision:t.source.revision),from_path:t.source.path,path:t.target_path,update_references:!1},i=await this.ports.transport.moveFile(n);if(xt(i.file),i.mutation_id!==n.mutation_id||i.file.file_id!==t.source.identity||i.file.path!==t.target_path)throw Sm(t);return e.files??={},e.files[t.source.identity]={file:i.file},delete e.local_bindings?.[t.source.identity],{action_id:t.action_id,status:"completed",file:i.file}}dependencyFileRevision(e,t){if(!t.revision_from_dependency)return;let n=lt(e).receipts.find(({action_id:i})=>i===t.revision_from_dependency);if(!n?.file||n.file.file_id!==t.source.identity)throw De(`Move ${t.action_id} is missing its dependency file receipt.`);return n.file.revision}async deleteRemote(e,t){if(t.target.entity==="record"){let s=lt(e).payloads.mutations[t.action_id];if(!s||s.operation!=="delete")throw mr(t);let o=await this.ports.transport.mutate(s);return this.acceptRecordReceipt(e,t,o),_m(t.action_id,o)}if(t.target.entity==="resource"||!this.ports.transport.deleteFile)throw new w("invalid_sync_plan","This remote delete command is unsupported.");let n={protocol_version:1,type:"delete_file",mutation_id:xm(t.action_id),file_id:t.target.identity,if_revision:t.expected_remote.state==="exact"?t.expected_remote.object.revision:t.target.revision,path:t.target.path},i=await this.ports.transport.deleteFile(n);if(i.mutation_id!==n.mutation_id||i.file_id!==t.target.identity||i.previous_path!==t.target.path)throw Sm(t);return delete e.files?.[t.target.identity],delete e.local_bindings?.[t.target.identity],{action_id:t.action_id,status:"completed"}}acceptRecordReceipt(e,t,n,i){let o=("target"in t?t.target:t.source).identity;if(n.status==="applied"||n.status==="previously_applied"){if(n.record){sd(n.record,this.ports.runtime,n.record.revision);let d=e.records[o];e.records[o]={path:n.record.path,revision:n.record.revision,hash:i===void 0?d?.hash??this.ports.runtime.digest(n.record.document):this.ports.runtime.digest(i),...this.ports.mode==="read_write"?{record:n.record}:{}}}else delete e.records[o];delete e.local_bindings?.[o];return}let a=n.status==="conflicted"?n.conflict.current:void 0;a&&sd(a,this.ports.runtime,a.revision);let c=a?{state:"exact",object:{entity:"record",identity:o,path:a.path,revision:a.revision,payload_revision:a.revision}}:t.command==="move_remote"?t.expected_source_owner:t.expected_remote;e.planned_conflicts??={};let l=n.status==="rejected"?"rejected":"both_changed",u=o in e.planned_conflicts?e.planned_conflicts[o].ancestor_document:e.records[o]?.record?.document;e.planned_conflicts[o]={decision_id:Ix("record",o,t.expected_local,c,l,this.ports.runtime.digest),entity:"record",local:t.expected_local,remote:c,conflict_kind:l,...u===void 0?{}:{ancestor_document:u}},e.local_bindings??={},t.expected_local.state==="exact"&&(e.local_bindings[o]={entity:"record",path:t.expected_local.object.path}),a&&(e.records[o]={path:a.path,revision:a.revision,hash:t.expected_local.state==="exact"?t.expected_local.object.payload_revision.replace(/^sha256:/u,""):this.ports.runtime.digest(a.document),...this.ports.mode==="read_write"?{record:a}:{}})}async assertLocal(e){if(e.state!=="absent"&&!await this.matchesRef(e.object))throw hr(`${e.object.path} no longer matches the inspected revision.`)}async assertPathOwner(e,t,n){let i=this.ownersByPath.get(e);if(t.state==="absent"){if(i||(n??await this.ports.fileSystem.exists(e)))throw hr(`${e} is no longer vacant.`);return}if(!i||i.entity!==t.object.entity||i.identity!==t.object.identity)throw hr(`${e} has a different path owner.`)}matchesRef(e){return rd(this.ports.fileSystem,this.ports.runtime,e,!1)}indexPathOwners(e){this.ownersByPath.clear(),this.pathsByOwner.clear();for(let[t,n]of Object.entries(e.records))this.installPathOwner({entity:"record",identity:t,path:n.path,revision:n.revision,payload_revision:`sha256:${n.hash}`});for(let[t,n]of Object.entries(e.resources??{}))this.installPathOwner({entity:"resource",identity:t,path:n.path,revision:n.revision,payload_revision:`sha256:${n.hash}`});for(let[t,n]of Object.entries(e.files??{}))this.installPathOwner({entity:"file",identity:t,path:n.file.path,revision:n.file.revision,payload_revision:n.file.content_digest,size:n.file.size})}installPathOwner(e){let t=`${e.entity}:${e.identity}`,n=this.pathsByOwner.get(t);n!==void 0&&this.ownersByPath.delete(n),this.ownersByPath.set(e.path,e),this.pathsByOwner.set(t,e.path)}removePathOwner(e){let t=`${e.entity}:${e.identity}`,n=this.pathsByOwner.get(t)??e.path;this.ownersByPath.delete(n),this.pathsByOwner.delete(t)}};function Ix(r,e,t,n,i,s){return _i({entity:r,identity:e,local:t,remote:n,conflict_kind:i},s)}function T2(r,e,t){if(e.entity==="record"){let n=r.records[e.identity];n&&(n.path=t,n.record&&(n.record.path=t))}else if(e.entity==="resource"){let n=r.resources?.[e.identity];n&&(n.path=t)}else{let n=r.files?.[e.identity];n&&(n.file.path=t)}}function I2(r,e){e.entity==="record"?delete r.records[e.identity]:e.entity==="resource"?delete r.resources?.[e.identity]:delete r.files?.[e.identity]}function sd(r,e,t){let n=Il(r);if(r.revision!==t||_t(n,e)!==t)throw new w("invalid_sync_response","Record receipt does not match its exact document revision.")}function _m(r,e){return e.status==="applied"||e.status==="previously_applied"?{action_id:r,status:"completed",...e.record?{record:e.record}:{}}:{action_id:r,status:e.status}}function mr(r){return new w("sync_payload_incomplete",`Prepared action ${r.action_id} has no exact payload capability.`)}function Sm(r){return new w("invalid_sync_response",`Authority receipt does not match prepared action ${r.action_id}.`)}function O2(r,e){let t=pi(r);return{code:hi(r,"sync_action_failed"),message:t.message,action_id:e}}function xm(r){let e=r.replace(/^sha256:/u,"");return`${e.slice(0,8)}-${e.slice(8,12)}-4${e.slice(13,16)}-8${e.slice(17,20)}-${e.slice(20,32)}`}async function Ox(r,e,t){let n=lt(r);if(n.phase!=="effects_complete")throw De("A checkpoint cannot advance before every prepared effect is durable.");let i=n.plan.actions[n.next_action];if(!i||i.command!=="advance_checkpoint")throw De("Prepared checkpoint action is missing.");if(i.expected.generation!==n.checkpoint_before.generation||i.expected.cursor!==n.checkpoint_before.cursor||i.next.generation!==n.checkpoint_after.generation||i.next.cursor!==n.checkpoint_after.cursor)throw De("Prepared checkpoint boundary is inconsistent.");let s=n.plan.fingerprint;return r.generation=i.next.generation,r.cursor=i.next.cursor??0,r.last_completed_plan=s,r.last_synced_at=e.now(),delete r.batch,await t.write(r),s}async function Dx(r,e,t,n){let[i]=e.actions;if(e.actions.length!==1||!i||i.command!=="advance_checkpoint"||i.expected.generation!==(r.generation??0)||i.expected.cursor!==r.cursor||i.next.generation!==(r.generation??0)+1||i.next.cursor!==e.authority_cursor||r.batch!==void 0)throw De("Empty checkpoint plan is inconsistent.");return r.generation=i.next.generation,r.cursor=i.next.cursor??0,r.last_completed_plan=e.fingerprint,r.last_synced_at=t.now(),await n.write(r),e.fingerprint}var xi=class{replicaId;transport;mode;stateStore;fileSystem;blobStore;selectiveSync;lease;runtime;materializer;onProgress;constructor(e,t,n,i="read_only"){this.replicaId=e,this.transport=t,this.mode=i,this.stateStore=n.stateStore,this.fileSystem=n.fileSystem,this.blobStore=n.blobStore,this.selectiveSync=gi(n.selectiveSync),this.lease=n.lease??new Qo,this.runtime=n.runtime??Zo,this.materializer=new $s(this.fileSystem,this.runtime,this.mode,this.blobStore),this.onProgress=n.onProgress}async sync(e={}){return this.lease.runExclusive(async()=>{let t=await this.readState();if(t?.batch?.phase==="blocked"&&t.batch.failure?.code==="sync_plan_stale"&&(await wm(t,this.journalStore()),t=await this.readState()),t?.batch)return this.executePrepared(t,e.signal);let n=await this.inspectDetailed(t);return this.applyInspection(n,e.signal)})}async inspect(){return this.lease.runExclusive(async()=>{let e=await this.readState();return e?.batch?.plan??(await this.inspectDetailed(e)).plan})}async apply(e,t={}){return this.lease.runExclusive(async()=>{let n=await this.readState();if(n?.batch){if(n.batch.plan.fingerprint!==e.fingerprint)throw new w("mirror_recovery_required","A different prepared plan must recover before this plan can apply.");return this.executePrepared(n,t.signal)}if(n?.last_completed_plan===e.fingerprint){let s=Wt(n,this.mode);return Ir(s.state==="attention"||e.summary.blocking_issues>0?"attention":"applied",e.summary.blocking_issues>0?e:{...e,issues:[]},s,0)}let i=await this.inspectDetailed(n);return i.plan.fingerprint!==e.fingerprint?Ir("stale",e,Wt(i.prior,this.mode),0,{code:"sync_plan_stale",message:"The local folder or authority changed. Inspect the sync plan again."}):this.applyInspection(i,t.signal)})}async applyInspection(e,t){let n=e.plan;if(n.issues.some(s=>s.blocking)&&n.actions.length===0)return Ir("attention",n,Wt(e.prior,this.mode),0);if(t?.aborted)return Ir("cancelled",n,Wt(e.prior,this.mode),0,{code:"sync_cancelled",message:"Sync cancelled before preparation."});try{await new ra(this.fileSystem,this.runtime).validate(n,e.prior)}catch(s){let o=pi(s),a=hi(s,"sync_revalidation_failed");return Ir(a==="sync_plan_stale"?"stale":"failed",n,Wt(e.prior,this.mode),0,{code:a,message:o.message})}if(n.actions.length===0)return Ir("applied",n,Wt(e.prior,this.mode),0);if(e.prior&&n.actions.length===1&&n.actions[0]?.command==="advance_checkpoint")return await Dx(e.prior,n,this.runtime,this.journalStore()),Ir("applied",n,Wt(e.prior,this.mode),0);let i=await Cx(e.prior??this.initialUnchangedState(e),n,e.durable_payloads,this.journalStore());return this.executePrepared(i,t)}async executePrepared(e,t){let n=e.batch,i=await new od({transport:this.transport,fileSystem:this.fileSystem,blobStore:this.blobStore,runtime:this.runtime,mode:this.mode,store:this.journalStore(),onProgress:(c,l)=>this.onProgress?.({phase:"applying",completed:c,total:l,done:c===l})}).execute(e,t);if(i.status!=="effects_complete"){i.status==="stale"&&await wm(e,this.journalStore());let c=Wt(e,this.mode);return Ir(i.status==="blocked"?"failed":i.status,n.plan,c,i.completed,i.failure)}let s=n.plan;await Ox(e,this.runtime,this.journalStore()),await this.pruneFileBlobs();let o=Wt(e,this.mode),a=o.conflicts.length>0||o.local_issues.length>0||s.summary.conflicts>0||s.summary.blocking_issues>0;return Ir(a?"attention":"applied",s,o,i.completed)}inspectDetailed(e){return new td(this.replicaId,this.transport,this.mode,this.fileSystem,this.blobStore,this.selectiveSync,this.runtime,()=>this.readState(),t=>this.currentRecordPathPolicy(t)).inspect(e)}initialUnchangedState(e){if(e.plan.kind!=="initial"||!e.snapshot)return null;let t=new Set(e.summary.objects.filter(o=>o.local.state==="exact"&&o.remote.state==="exact"&&JSON.stringify(o.local)===JSON.stringify(o.remote)).map(o=>`${o.entity}:${o.identity}`)),n={};for(let{record:o,hash:a}of e.snapshot.records)t.has(`record:${o.record_id}`)&&(n[o.record_id]={path:o.path,revision:o.revision,hash:a,...this.mode==="read_write"?{record:o}:{}});let i={};for(let o of e.snapshot.resources)t.has(`resource:${o.path}`)&&(i[o.path]={path:o.path,revision:o.revision,hash:this.runtime.digest(o.document)});let s={};for(let o of e.snapshot.files)t.has(`file:${o.file_id}`)&&(s[o.file_id]={file:o});return{protocol_version:1,engine_version:3,generation:0,replica_id:e.plan.replica_id,scope_epoch:e.plan.scope_epoch,cursor:0,records:n,resources:i,files:s,selective_sync:e.plan.selective_sync,mode:e.plan.mode,planned_conflicts:{}}}async review(){return this.lease.runExclusive(async()=>{let e=await this.readState(),t=Wt(e,this.mode),n=e?.batch?.plan??(await this.inspectDetailed(e)).plan,i=t.state==="not_initialized"&&!n.issues.some(s=>s.code==="invalid_frontmatter"||s.code==="file_read_failed")?t:gx(t,n);return{plan:n,status:i}})}async status(){return(await this.review()).status}async checkpointStatus(){return this.lease.runExclusive(()=>this.checkpointStatusUnlocked())}async checkpointStatusUnlocked(){return Wt(await this.readState(),this.mode)}async authorityPromotionManifest(){return this.lease.runExclusive(async()=>{if(this.mode!=="read_write")throw new w("promotion_requires_writable_mirror","Only a read-write mirror can prove an authority promotion source.");let e=await this.readState();if(!e)throw new w("mirror_not_initialized","Synchronize this mirror first.");if(e.batch||Object.keys(e.planned_conflicts??{}).length>0)throw new w("promotion_mirror_not_clean","Finish the prepared batch and resolve conflicts before promotion.");let t=await yx({state:e,selectiveSync:this.selectiveSync,fileSystem:this.fileSystem,pathPolicy:await this.currentRecordPathPolicy(e),digest:this.runtime.digest});if((await this.inspectDetailed(e)).plan.actions.some(i=>i.command!=="advance_checkpoint"))throw new w("promotion_mirror_not_clean","Synchronize this mirror immediately before promotion.");return t})}async previewInitialization(){let e=await this.inspect(),t=e.actions.filter(i=>i.command==="put_remote"||i.command==="move_remote"||i.command==="delete_remote"),n=e.actions.filter(i=>i.command==="write_local"||i.command==="move_local"||i.command==="delete_local");return{already_initialized:e.kind==="incremental",download_documents:n.filter(i=>"target"in i&&i.target.entity!=="file"||"source"in i&&i.source.entity!=="file").length,upload_documents:t.filter(i=>"target"in i&&i.target.entity==="record"||"source"in i&&i.source.entity==="record").length,unchanged_documents:0,download_files:n.filter(i=>"target"in i&&i.target.entity==="file"||"source"in i&&i.source.entity==="file").length,upload_files:t.filter(i=>"target"in i&&i.target.entity==="file"||"source"in i&&i.source.entity==="file").length,unchanged_files:0,collisions:e.issues.filter(i=>i.code==="local_collision"&&i.path).map(i=>i.path),local_issues:e.issues.filter(i=>i.code==="invalid_frontmatter"&&i.path!==void 0).map(i=>({code:"invalid_frontmatter",message:i.message,path:i.path}))}}async resolveConflict(e,t,n,i){await this.lease.runExclusive(()=>this.resolveConflictUnlocked(e,t,n,i))}async resolveConflictUnlocked(e,t,n,i){if(this.mode!=="read_write")throw new w("mirror_read_only","Receive-only mirrors have no writable conflicts.");let s=await this.readState();if(!s||s.batch)throw new w("mirror_recovery_required","Finish sync recovery before resolving conflicts.");let o=s.planned_conflicts?.[e];if(!o)throw new w("mirror_conflict_not_found","Writable mirror conflict was not found.");if((o.decision_id??"")!==t)throw ia();if(i!==void 0&&(n!=="local"||o.entity!=="record"||o.local.state!=="exact"))throw new w("invalid_conflict_resolution","A merged document requires an exact local record conflict.");let a=await Jl(this.replicaId,this.transport,this.mode,this.selectiveSync,this.runtime),c=o.entity==="record"?a.records.find(({record:f})=>f.record_id===e)?.record:void 0,l=o.entity==="file"?a.files.find(f=>f.file_id===e):void 0;if(!(o.entity==="record"?D2(o.remote,c):L2(o.remote,l)))throw ia();let d=new ra(this.fileSystem,this.runtime);if(o.local.state==="exact"?await d.validateExpected(o.local):o.remote.state==="exact"&&await d.validateExpectedAt(o.remote.object.path,o.local),n==="remote"&&(o.entity==="record"?await this.installRemoteRecord(s,e,c):await this.installRemoteFile(s,e,l)),i!==void 0){let f=o.local.object.path,p=await this.fileSystem.read(f);if(p===null||_t(p,this.runtime)!==o.local.object.payload_revision)throw ia();await this.fileSystem.write(f,i,p)}delete s.planned_conflicts?.[e],n==="remote"&&delete s.local_bindings?.[e],await this.writeState(s)}async installRemoteRecord(e,t,n){if(n){let o=e.planned_conflicts?.[t]?.local;await this.materializer.put(e,n,{...o?.state==="exact"&&o.object.path===n.path?{acceptedHash:o.object.payload_revision.replace(/^sha256:/u,"")}:{}});return}let i=e.planned_conflicts?.[t],s=i?.local.state==="exact"?i.local.object.path:e.records[t]?.path;if(s){let o=await this.fileSystem.read(s);if(o!==null){if(i?.local.state!=="exact"||_t(o,this.runtime)!==i.local.object.payload_revision)throw ia();await this.fileSystem.remove(s,o)}}delete e.records[t]}async installRemoteFile(e,t,n){if(n){if(!this.blobStore)throw new w("file_storage_unavailable","File resolution needs a blob store.");await Vl(this.transport,this.blobStore,n);let o=e.planned_conflicts?.[t],a=o?.local.state==="exact"?{content_digest:o.local.object.payload_revision,size:o.local.object.size??0}:void 0,c=e.local_bindings?.[t]?.path;await this.materializer.putFile(e,n,e,a),c&&c!==n.path&&await this.fileSystem.remove(c,a??null);return}let i=e.planned_conflicts?.[t],s=i?.local.state==="exact"?i.local.object.path:e.files?.[t]?.file.path;if(s){let o=await this.fileSystem.inspectBinary(s);if(o!==null){if(i?.local.state!=="exact"||o.content_digest!==i.local.object.payload_revision||i.local.object.size!==void 0&&o.size!==i.local.object.size)throw ia();await this.fileSystem.remove(s,o)}}delete e.files?.[t]}async readState(){let e=await this.stateStore.read();if(e===null)return null;try{return sx(e,this.replicaId,this.mode)}catch(t){throw t instanceof w?t:De("Mirror metadata is corrupt or belongs to another replica.")}}writeState(e){return this.stateStore.write(e)}journalStore(){let e=this.stateStore;return{write:t=>this.writeState(t),...e.appendJournal?{appendJournal:t=>e.appendJournal(t)}:{}}}async pruneFileBlobs(){if(!this.blobStore)return;let e=await this.readState();if(!e)return;let t=new Set;for(let n of Object.values(e.files??{}))t.add(n.file.content_digest);for(let n of Object.values(e.batch?.payloads.files??{}))t.add(n.content_digest);for(let n of Object.values(e.batch?.payloads.local_files??{}))t.add(n.content_digest);await this.blobStore.prune(t)}currentRecordPathPolicy(e){return this.materializer.recordPathPolicy(e)}};function D2(r,e){return r.state==="absent"?e===void 0:e!==void 0&&r.object.entity==="record"&&r.object.identity===e.record_id&&r.object.path===e.path&&r.object.revision===e.revision&&r.object.payload_revision===e.revision&&r.object.size===void 0}function L2(r,e){return r.state==="absent"?e===void 0:e!==void 0&&r.object.entity==="file"&&r.object.identity===e.file_id&&r.object.path===e.path&&r.object.revision===e.revision&&r.object.payload_revision===e.content_digest&&r.object.size===e.size}function ia(){return new w("mirror_conflict_stale","Local or hosted content changed after this conflict was recorded. Synchronize again before choosing a version.")}var sa=class extends xi{constructor(e,t,n){super(e,t,n,"read_write")}};Vt();function $m(r){let e=[...r.actions.flatMap(t=>t.command==="advance_checkpoint"?[]:[Em(t)]),...r.issues.map(t=>({kind:"document",path:t.path??"Sync engine",direction:"attention",action:t.blocking?"fix":"review",detail:t.message}))];return{plan:r,phase:r.kind,entries:e,cursor:r.base_cursor,remoteHead:r.authority_cursor,already_initialized:r.kind==="incremental",download_documents:r.actions.filter(t=>["write_local","move_local","delete_local"].includes(t.command)&&("target"in t?t.target.entity!=="file":"source"in t&&t.source.entity!=="file")).length,upload_documents:r.actions.filter(t=>["put_remote","move_remote","delete_remote"].includes(t.command)&&("target"in t?t.target.entity==="record":"source"in t&&t.source.entity==="record")).length,unchanged_documents:0,download_files:r.actions.filter(t=>["write_local","move_local","delete_local"].includes(t.command)&&("target"in t?t.target.entity==="file":"source"in t&&t.source.entity==="file")).length,upload_files:r.actions.filter(t=>["put_remote","move_remote","delete_remote"].includes(t.command)&&("target"in t?t.target.entity==="file":"source"in t&&t.source.entity==="file")).length,unchanged_files:0,collisions:r.issues.filter(t=>t.blocking&&t.code==="local_collision"&&t.path!==void 0).map(t=>t.path),local_issues:r.issues.filter(t=>["invalid_frontmatter","file_read_failed"].includes(t.code)&&t.path!==void 0).map(t=>({code:t.code,message:t.message,path:t.path}))}}function Em(r){if(r.command==="advance_checkpoint")throw new Error("Checkpoint actions are not preview entries.");if(r.command==="record_conflict"){let a=r.local.state==="exact"?r.local.object:r.remote.state==="exact"?r.remote.object:void 0;return{kind:r.entity==="file"?"file":"document",path:a?.path??r.identity,direction:"attention",action:"fix",detail:`Local and hosted ${r.entity} changes conflict (${r.conflict_kind.replace(/_/g," ")}).`,...a?.entity==="file"&&a.size!==void 0?{estimatedBytes:a.size}:{},...r.entity==="record"?{recordId:r.identity}:{fileId:r.identity}}}if(r.command==="clear_conflict"){let a=r.expected_local.state==="exact"?r.expected_local.object:r.expected_remote.state==="exact"?r.expected_remote.object:void 0;return{kind:r.entity==="file"?"file":"document",path:a?.path??r.identity,direction:"attention",action:"fix",detail:`Local and hosted ${r.entity} content now matches; clear the resolved conflict.`,...a?.entity==="file"&&a.size!==void 0?{estimatedBytes:a.size}:{},...r.entity==="record"?{recordId:r.identity}:{fileId:r.identity}}}let e=r.command.endsWith("_local"),t="target"in r?r.target:r.source,n=r.command==="move_local"||r.command==="move_remote"?r.target_path:t.path,i=r.command==="write_local"&&r.expected_local.state==="absent"||r.command==="put_remote"&&r.expected_remote.state==="absent",s=r.command.startsWith("move_")?"rename":r.command.startsWith("delete_")?"delete":i?"create":"update",o=s==="delete"?e?"Move this device's copy to trash.":"Delete from Connect.":s==="rename"?`Rename ${e?"on this device":"in Connect"} from ${t.path}.`:e?"Download from Connect.":"Upload to Connect.";return{kind:t.entity==="file"?"file":"document",path:n,direction:e?"download":"upload",action:s,detail:o,...t.entity==="file"&&t.size!==void 0?{estimatedBytes:t.size}:{},...t.entity==="record"?{recordId:t.identity}:{},...t.entity==="file"?{fileId:t.identity}:{}}}var N2={maxDeletions:20};function Lx(r,e=N2){let{plan:t}=r,n=[],i=t.actions.filter(o=>o.command!=="advance_checkpoint");t.kind==="rebuild"&&n.push("Mirror rebuild"),t.kind==="initial"&&i.some(o=>["put_remote","move_remote","delete_remote","delete_local"].includes(o.command))&&n.push("First sync"),t.summary.blocking_issues>0&&!i.length&&n.push("Blocking issues");let s=i.filter(o=>o.command==="delete_remote").length;return s>e.maxDeletions&&n.push(`${s} deletions`),{safe:n.length===0,reasons:n}}var Nx=require("obsidian");var Am=3e4,F2=64*1024;function Pm(r){return Am+Math.ceil(r/F2)*1e3}var Es=class extends w{constructor(e,t){super(e,t),this.name="NetworkError"}},Dn=class extends w{constructor(t,n,i,s){super(t,n);this.status=i;this.retryAfterMs=s;this.name="HttpStatusError"}},km=new Set([408,425,429,500,502,503,504]),j2=new Set(["network_unreachable","network_timeout","authority_unavailable","mirror_enrollment_unreachable","authority_adoption_unreachable"]);function ks(r){if(r instanceof Dn)return km.has(r.status);if(r&&typeof r=="object"){let e=r.status;if(typeof e=="number"&&km.has(e))return!0;let t=r.code;if(typeof t=="string"&&j2.has(t))return!0}return!1}function q2(r){return km.has(r)}var B2={attempts:4,baseDelayMs:500,maxDelayMs:3e4,sleep:z2,random:Math.random};function Cm(r,e,t){let n=Math.min(e.maxDelayMs,e.baseDelayMs*2**r),i=Math.round(n/2+e.random()*n/2);return t===void 0?i:Math.min(Math.max(i,t),6e4)}function Fx(r,e=B2){return async t=>{for(let n=0;;n+=1){K2(t.signal);let i;try{let s=await r(t);if(!q2(s.status)||n+1>=e.attempts)return s;i=aa(s.headers)}catch(s){if(W2(s)&&t.signal?.aborted||!ks(s)||n+1>=e.attempts)throw s}await e.sleep(Cm(n,e,i),t.signal)}}}function jx(r=U2()){return r?e=>V2(e,r.fetch,r.AbortController,r.headers):e=>H2(e)}function U2(){try{if(typeof require!="function")return null;let r=require("electron").remote,e=r?.net?.fetch,t=r?.getGlobal?.("AbortController"),n=r?.getGlobal?.("Object");return!e||!r?.net||typeof t!="function"||!n?null:{fetch:e.bind(r.net),AbortController:t,headers:i=>n.fromEntries(i)}}catch{return null}}async function V2(r,e,t=AbortController,n=i=>Object.fromEntries(i)){let{signal:i,check:s,dispose:o}=qx(r.signal,r.timeoutMs??Am),a=new t,c=()=>a.abort();i.aborted?c():i.addEventListener("abort",c,{once:!0});try{let l={...r.headers??{}};r.contentType&&!Object.keys(l).some(p=>p.toLowerCase()==="content-type")&&(l["content-type"]=r.contentType);let u,d;try{u=await e(r.url,{method:r.method,headers:l,body:r.body,signal:a.signal}),d=await u.arrayBuffer()}catch(p){throw ad(p,r.signal,i)}if(s(),i.aborted)throw ad(i.reason,r.signal,i);let f=new TextDecoder().decode(d);if(r.throw!==!1&&u.status>=400)throw new Dn(`http_${u.status}`,`Request failed with status ${u.status}`,u.status);return{status:u.status,headers:n(u.headers),arrayBuffer:d,json:G2(f),text:f}}finally{i.removeEventListener("abort",c),o()}}async function H2(r,e=t=>(0,Nx.requestUrl)(t)){let{signal:t,timeoutMs:n,...i}=r,{signal:s,check:o,dispose:a}=qx(t,n??Am),c=()=>{};try{return await new Promise((l,u)=>{let d=()=>u(ad(s.reason,t,s));if(s.aborted)return d();s.addEventListener("abort",d,{once:!0}),c=()=>s.removeEventListener("abort",d),e(i).then(f=>{o(),s.aborted?d():l(f)},f=>u(ad(f,t,s)))})}finally{c(),a()}}function aa(r){if(!r)return;let e=Object.entries(r).find(([i])=>i.toLowerCase()==="retry-after")?.[1];if(!e)return;let t=Number(e);if(Number.isFinite(t)&&t>=0)return t*1e3;let n=Date.parse(e);if(Number.isFinite(n))return Math.max(0,n-Date.now())}function z2(r,e){return new Promise((t,n)=>{if(e?.aborted)return n(oa());let i=window.setTimeout(()=>{e?.removeEventListener("abort",s),t()},r),s=()=>{window.clearTimeout(i),n(oa())};e?.addEventListener("abort",s,{once:!0})})}function K2(r){if(r?.aborted)throw oa()}function oa(){return new DOMException("Synchronization stopped.","AbortError")}function W2(r){return r instanceof DOMException&&r.name==="AbortError"}function qx(r,e){let t=new AbortController,n=Date.now()+e,i=()=>t.abort(oa());r?.aborted?i():r?.addEventListener("abort",i,{once:!0});let s=()=>t.abort(new Es("network_timeout","Connect did not respond in time.")),o=window.setTimeout(s,e);return{signal:t.signal,check:()=>{!t.signal.aborted&&Date.now()>=n&&s()},dispose:()=>{window.clearTimeout(o),r?.removeEventListener("abort",i)}}}function ad(r,e,t){if(e?.aborted)return oa();if(t.aborted)return t.reason instanceof Es?t.reason:new Es("network_timeout","Connect did not respond in time.");if(r instanceof w)return r;let n=r&&typeof r=="object"?r.status:void 0;if(typeof n=="number")return new Dn(`http_${n}`,`Request failed with status ${n}`,n);let i=r instanceof Error&&r.message?` (${r.message})`:"";return new Es("network_unreachable",`Connect could not be reached${i}.`)}function G2(r){if(!r.trim())return null;try{return JSON.parse(r)}catch{return null}}var Ux={maxAgeDays:90,maxFiles:5e3,maxRuns:1e3};function dd(r,e,t=new Date().toISOString()){return{id:crypto.randomUUID(),collectionId:r,startedAt:t,finishedAt:t,outcome:"event",files:[],...e}}function Vx(r){return r.summary!==void 0}function Hx(r,e,t){if(r.command==="advance_checkpoint")return null;let n=Em(r),i=r.command==="move_local"||r.command==="move_remote"?r.source.path:void 0;return{path:n.path,...i&&i!==n.path?{fromPath:i}:{},kind:n.kind,direction:n.direction,action:n.action,status:e.status,at:t,...e.failure?.message?{message:e.failure.message}:{}}}var cd=class{constructor(e,t){this.inner=e;this.onReceipt=t;this.seen=new Map}read(){return this.inner.read()}async write(e){await this.inner.write(e);let t=e.batch;if(!t)return;let n=t.plan.fingerprint,i=this.seen.get(n);if(i===void 0){this.seen.set(n,{receipts:t.receipts.length,actions:new Map(t.plan.actions.map(o=>[o.action_id,o]))});return}let s=i.receipts;i.receipts=t.receipts.length;for(let o of t.receipts.slice(s)){let a=i.actions.get(o.action_id);a&&this.onReceipt(a,o)}}};function zx(r){if(r.summary!==void 0)return r.summary;let e=i=>r.files.filter(s=>s.direction===i&&s.status==="completed").length;return[[e("download"),"downloaded"],[e("upload"),"uploaded"],[r.files.filter(i=>i.direction==="attention"||i.status==="conflicted").length,"conflicts"],[r.files.filter(i=>i.status==="rejected").length,"rejected"]].filter(([i])=>i>0).map(([i,s])=>`${i} ${s}`).join(" \xB7 ")||"No file changes"}function Kx(r,e){return r.flatMap(t=>t.summary!==void 0?t.path===e?[{run:t,file:J2(t)}]:[]:t.files.filter(n=>n.path===e||n.fromPath===e).map(n=>({run:t,file:n}))).sort((t,n)=>n.file.at.localeCompare(t.file.at))}function J2(r){return{path:r.path??"",kind:"document",direction:"attention",action:"review",status:"completed",at:r.finishedAt,...r.message?{message:r.message}:{}}}function Wx(r,e){let t=e.trim().toLowerCase();return t?r.flatMap(n=>{if(n.summary!==void 0)return n.path?.toLowerCase().includes(t)?[n]:[];let i=n.files.filter(s=>s.path.toLowerCase().includes(t)||s.fromPath?.toLowerCase().includes(t));return i.length?[{...n,files:i}]:[]}):[...r]}function Bx(r,e=Ux,t=Date.now()){let n=t-e.maxAgeDays*864e5,i=r.filter(a=>Date.parse(a.finishedAt)>=n),s=i.reduce((a,c)=>a+c.files.length,0),o=0;for(;(s>e.maxFiles||i.length-o>e.maxRuns)&&o0&&!r.endsWith(` `);for(let n of r.split(` `))if(n.trim())try{let i=JSON.parse(n);X2(i)?e.push(i):t=!0}catch{t=!0}return{runs:e.sort((n,i)=>n.finishedAt.localeCompare(i.finishedAt)),needsRepair:t}}function X2(r){if(!r||typeof r!="object"||Array.isArray(r))return!1;let e=r;return typeof e.id=="string"&&typeof e.collectionId=="string"&&typeof e.startedAt=="string"&&typeof e.finishedAt=="string"&&typeof e.outcome=="string"&&Array.isArray(e.files)&&e.files.every(t=>!!t&&typeof t.path=="string"&&typeof t.at=="string")}var ld=class{constructor(e,t,n=Ux){this.adapter=e;this.path=t;this.limits=n;this.runs=[];this.writes=Promise.resolve()}async load(){await this.enqueue(async()=>{let e=await this.adapter.exists(this.path)?await this.adapter.read(this.path):"",t=Y2(e),n=Bx(t.runs,this.limits);(t.needsRepair||n.length!==t.runs.length)&&await this.rewrite(n),this.runs=n})}list(e){return this.runs.filter(t=>e===void 0||t.collectionId===e)}append(e){return this.enqueue(async()=>{let t=Bx([...this.runs,e],this.limits);t.length!==this.runs.length+1||!await this.adapter.exists(this.path)?await this.rewrite(t):await this.adapter.append(this.path,`${JSON.stringify(e)} `),this.runs=t})}acknowledge(e){return this.enqueue(async()=>{let t=this.runs.map(n=>n.id===e?{...n,needsAcknowledgement:!1}:n);await this.rewrite(t),this.runs=t})}clear(){return this.enqueue(async()=>{let e=this.runs.filter(t=>t.needsAcknowledgement);await this.rewrite(e),this.runs=e})}rewrite(e){return this.adapter.write(this.path,Q2(e))}enqueue(e){return this.writes=this.writes.then(e,e),this.writes}};function Q2(r){return r.map(e=>`${JSON.stringify(e)} @@ -188,11 +188,11 @@ ${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.pus `),t.join(` `))?.split(` `)??null;let a=new Map;for(let l of new Set([...i.order,...s.order,...n.order])){let u=Qx(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 Qx(r,e,t){return e===t?e:e===r?t:t===r?e:null}function Oe(r){return[...r.normalize("NFC")].map(e=>e.toLowerCase()).join("").normalize("NFC")}function Om(r){let e=new Map;for(let t of r){let n=Oe(t),i=e.get(n)??[];i.push(t),e.set(n,i)}return[...e.values()].filter(t=>t.length>1)}function Zx(r,e,t){let n=new Set([...e].map(Oe)),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,h;do h=`${f} (${p++})${d}`;while(n.has(Oe(h)));n.add(Oe(h)),i.push({from:c,to:h})}}return{renames:i,manual:s}}function o$(r){if(!Ze(r))return null;let e=r;if(!(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.deviceId===void 0||typeof e.deviceId=="string")))return null;let t;try{t=Nr(e.selectiveSync)}catch{t=Nr()}return{...e,selectiveSync:t}}function nF(r){try{let e=(0,J.parseYaml)(r);return e===null||typeof e=="object"&&!Array.isArray(e)}catch{return!1}}var Nn=".mdbase/connect-role.json",ca=".mdbase/authority-adoption.json",la=".mdbase/authority-adoption-snapshot.json",iF="mdbase-obsidian-connect",Dr="mirrors",sF="mdbase-obsidian-connect-blobs",Ln="manifests",Fn="chunks",ud=1024*1024,oF=32*1024*1024,e$=2e3;function $i(r){if(!Number.isSafeInteger(r)||r<0||r>oF)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 aF="mdbase-connect-access-",cF="mdbase-connect-refresh-",lF="mdbase-connect-adoption-",dF=300*1e3,uF=[".git",".trash",".mdbase"],fF=new Set([".git",".mdbase",".trash","node_modules","_contracts","_schemas","_types","_views"]),Dm=["image","audio","video","pdf","other"],fa=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Ze(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function Nr(r){let e=r?.file_classes??[];if(e.some(s=>!Dm.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)=>Dm.indexOf(s)-Dm.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=>bn(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 a$(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 t$(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 pF(r,e,t=a$(e)){if(!r.file_classes.includes(t))return!1;let n=(0,J.normalizePath)(e);return!r.excluded_folders.some(i=>n===i||n.startsWith(`${i}/`))}var hF=/\.(?:md|base)$/,c$=/\.(?:md|base)$/i;function da(r,e=!1){let t=bn(r),n=t.split("/");if(t.length>1024||!e&&c$.test(t)||n.some(i=>i.startsWith(".")||fF.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 pa(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 Lm(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,$i(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 r$(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 mF(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=Fx(jx());function yF(){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 gF(){return async r=>{if(r.signal?.aborted)throw new DOMException("Collection adoption cancelled.","AbortError");let e=await mF(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 Fm=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){$i(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=n$(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){$i(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 jm(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 Dn(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=n$(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=Ze(n)&&Ze(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 Dn(s,typeof i.message=="string"?i.message:`Sync request failed (${e.status}).`,e.status,aa(e.headers))}},jm=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 n$(r,e){return Object.entries(r).find(([n])=>n.toLowerCase()===e.toLowerCase())?.[1]}function l$(r){return[r.configDir||".obsidian",...uF].map(t=>(0,J.normalizePath)(t).replace(/\/+$/,""))}function Tt(r,e){let t=bn(e),n=Oe(t);if(l$(r).some(i=>n===Oe(i)||n.startsWith(`${Oe(i)}/`)))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 Ue(r,e){return r??new Error(`IndexedDB ${e} failed without an error detail.`)}function _F(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,J.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 J.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 qm=class{constructor(e,t=s=>e.delete(s,!0),n=()=>{},i=()=>{}){this.vault=e;this.trashFile=t;this.assertActive=n;this.observeWrite=i}async cachedEntry(e){let t=this.vault.getAbstractFileByPath(e);if(t||!await this.vault.adapter.exists(e))return t;let n=e.lastIndexOf("/"),i=await this.vault.adapter.list(n<0?"":e.slice(0,n)),s=Oe(e),o=[...i.files,...i.folders].filter(l=>Oe(l)===s);if(o.length!==1)throw new w("mirror_path_collision",`More than one physical spelling blocks ${e}.`);let a=this.vault.getAbstractFileByPath(o[0]);if(a)return a;let c=this.vault.getAllLoadedFiles().filter(l=>Oe(l.path)===s);if(c.length>1)throw new w("mirror_path_collision",`More than one cached spelling blocks ${e}.`);return c[0]??null}async exists(e){let t=Tt(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=Tt(this.vault,e);if(this.vault.getAbstractFileByPath(t)instanceof J.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 pa(i)).content_digest}}}async pathKind(e){let t=Tt(this.vault,e);return(await this.vault.adapter.stat(t))?.type??null}async write(e,t,n){let i=Tt(this.vault,e),s=()=>new w("sync_plan_stale",`${i} changed before it could be written. Review sync again.`),o=n;if(o===void 0){let l=await this.readText(i);if(typeof l=="string"||l===null)o=l;else{let u=await this.vault.adapter.readBinary(i);if((await pa(u)).content_digest!==l.revision)throw s();o=new TextDecoder("utf-8",{ignoreBOM:!0}).decode(u)}}let a=i.lastIndexOf("/");a>=0&&await Ps(this.vault,i.slice(0,a));let c=await this.cachedEntry(i);if(c instanceof J.TFolder)throw new w("mirror_path_collision",`A folder blocks the mirror file ${i}.`);if(this.assertActive(),c instanceof J.TFile){let l=c.path;await this.vault.process(c,u=>{if(this.assertActive(),c.path!==l||this.vault.getAbstractFileByPath(l)!==c||u!==o&&u!==t)throw s();return this.observeWrite(i),this.observeWrite(l),t})}else{if(o!==null)throw s();this.observeWrite(i),await this.vault.create(i,t)}}async move(e,t){let n=Tt(this.vault,e),i=Tt(this.vault,t),s=await this.cachedEntry(n);if(!(s instanceof J.TFile))throw new w("mirror_path_collision",`Expected a file at ${n}.`);let o=await this.cachedEntry(i);if(!(o===s&&Oe(n)===Oe(i))&&(o!==null||await this.vault.adapter.exists(i)))throw new w("mirror_path_collision",`A file or folder blocks the mirror path ${i}.`);let c=i.lastIndexOf("/");c>=0&&await Ps(this.vault,i.slice(0,c)),this.assertActive(),this.observeWrite(n),this.observeWrite(s.path),this.observeWrite(i),await this.vault.rename(s,i)}async remove(e,t){let n=Tt(this.vault,e);if(t!==void 0){let s;if(t===null)s=!await this.exists(n);else if(typeof t=="string")s=await this.read(n)===t;else{let o=await this.inspectBinary(n);s=o?.content_digest===t.content_digest&&o?.size===t.size}if(!s)throw new w("sync_plan_stale",`${n} changed before it could be removed. Review sync again.`)}let i=await this.cachedEntry(n);if(i!=null){if(!(i instanceof J.TFile))throw new w("mirror_path_collision",`Expected a file at ${n}.`);this.assertActive(),this.observeWrite(n),this.observeWrite(i.path),await this.trashFile(i)}}async listMarkdown(e){return hd(this.vault).map(t=>(0,J.normalizePath)(t.path)).filter(t=>hF.test(t)&&!e.has(t)).filter(t=>!l$(this.vault).some(n=>Oe(t)===Oe(n)||Oe(t).startsWith(`${Oe(n)}/`))).sort()}async inspectBinary(e){let t=da(Tt(this.vault,e)),n=await this.cachedEntry(t);if(n==null)return null;if(!(n instanceof J.TFile))throw new w("mirror_path_collision",`Expected a file at ${t}.`);$i(n.stat.size);let i=await this.vault.readBinary(n);return $i(i.byteLength),pa(i)}async writeBinary(e,t,n){let i=da(Tt(this.vault,e)),s=n===void 0?await this.inspectBinary(i):n,o=await Lm(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=await this.cachedEntry(i);if(l instanceof J.TFolder)throw new w("mirror_path_collision",`A folder blocks the mirror file ${i}.`);this.assertActive(),this.observeWrite(i),l instanceof J.TFile?(this.observeWrite(l.path),await this.vault.modifyBinary(l,o)):await this.vault.createBinary(i,o)}async listBinary(e){return hd(this.vault).map(t=>(0,J.normalizePath)(t.path)).filter(t=>!c$.test(t)&&!e.has(t)).filter(t=>{try{return da(Tt(this.vault,t)),!0}catch{return!1}}).sort()}async readBinary(e){let t=da(Tt(this.vault,e)),n=await this.cachedEntry(t);if(n==null)return null;if(!(n instanceof J.TFile))throw new w("mirror_path_collision",`Expected a file at ${t}.`);$i(n.stat.size);let i=new Uint8Array(await this.vault.readBinary(n));return $i(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(Ln,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(Ln,"readonly").objectStore(Ln).openCursor();l.onsuccess=()=>{let u=l.result;if(!u)return o(c);c.push([u.key,u.value]),u.continue()},l.onerror=()=>a(Ue(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(Ln,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(Fn,"readonly").objectStore(Fn).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(Ue(l.error,"chunk cursor"))});for(let o of s)await this.delete(Fn,o)}manifest(e){return this.get(Ln,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(Ue(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(Ue(a.error,`write to ${e}`)),a.onabort=()=>o(Ue(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(Ue(o.error,`delete from ${e}`)),o.onabort=()=>s(Ue(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.");if(this.database)return this.database;let e=new Promise((t,n)=>{let i=indexedDB.open(sF,1);i.onupgradeneeded=()=>{i.result.objectStoreNames.contains(Ln)||i.result.createObjectStore(Ln),i.result.objectStoreNames.contains(Fn)||i.result.createObjectStore(Fn)},i.onerror=()=>n(Ue(i.error,"binary store open")),i.onsuccess=()=>{let s=i.result,o=()=>{this.database===e&&(this.database=null)};s.onclose=o,s.onversionchange=()=>{s.close(),o()},t(s)}});return this.database=e,e.catch(()=>{this.database===e&&(this.database=null)}),e}};function ua(r){return r?{cursor:r.cursor,scope_epoch:r.scope_epoch,recovery_required:!!r.batch}:null}var Um=class{constructor(e){this.key=e;this.database=null;this.checkpointReady=!1}get checkpointKey(){return[this.key,"checkpoint"]}async read(){let e=await this.open(),t=!this.checkpointReady;return new Promise((n,i)=>{let s=e.transaction(Dr,t?"readwrite":"readonly"),o=s.objectStore(Dr),a=o.get(this.key),c=null;a.onsuccess=()=>{c=a.result??null,t&&(c?o.put(ua(c),this.checkpointKey):o.delete(this.checkpointKey))},s.oncomplete=()=>{t&&(this.checkpointReady=!0),n(c)},s.onerror=()=>i(Ue(s.error,"mirror state read")),s.onabort=()=>i(Ue(s.error,"mirror state read"))})}async readCheckpoint(){if(!this.checkpointReady)return ua(await this.read());let e=await this.open(),t=await new Promise((n,i)=>{let s=e.transaction(Dr,"readonly"),o=s.objectStore(Dr),a=o.get(this.checkpointKey),c=o.getKey(this.key);s.oncomplete=()=>n({exists:c.result!==void 0,checkpoint:a.result??null}),s.onerror=()=>i(Ue(s.error,"mirror checkpoint read")),s.onabort=()=>i(Ue(s.error,"mirror checkpoint read"))});return t.exists?t.checkpoint?t.checkpoint:(this.checkpointReady=!1,ua(await this.read())):null}async write(e){let t=await this.open();await new Promise((n,i)=>{let s=t.transaction(Dr,"readwrite"),o=s.objectStore(Dr);o.put(e,this.key),o.put(ua(e),this.checkpointKey),s.oncomplete=()=>n(),s.onerror=()=>i(Ue(s.error,"mirror state write")),s.onabort=()=>i(Ue(s.error,"mirror state write"))}),this.checkpointReady=!0}async clear(){let e=await this.open();await new Promise((t,n)=>{let i=e.transaction(Dr,"readwrite"),s=i.objectStore(Dr);s.delete(this.key),s.delete(this.checkpointKey),i.oncomplete=()=>t(),i.onerror=()=>n(Ue(i.error,"mirror state clear")),i.onabort=()=>n(Ue(i.error,"mirror state clear"))}),this.checkpointReady=!0}close(){this.database?.then(e=>e.close(),()=>{}),this.database=null,this.checkpointReady=!1}open(){if(typeof indexedDB>"u")throw new w("storage_unavailable","IndexedDB is required for persistent mirror state.");if(this.database)return this.database;let e=new Promise((t,n)=>{let i=indexedDB.open(iF,1);i.onupgradeneeded=()=>{i.result.objectStoreNames.contains(Dr)||i.result.createObjectStore(Dr)},i.onerror=()=>n(Ue(i.error,"mirror state store open")),i.onsuccess=()=>{let s=i.result,o=()=>{this.database===e&&(this.database=null)};s.onclose=o,s.onversionchange=()=>{s.close(),o()},t(s)}});return this.database=e,e.catch(()=>{this.database===e&&(this.database=null)}),e}},Vm=class r{constructor(e){this.key=e}static{this.active=new Set}async runExclusive(e){let t=typeof navigator>"u"?null:navigator.locks;if(t)return t.request(`mdbase-mirror:${this.key}`,{ifAvailable:!0},async n=>{if(!n)throw new w("mirror_busy","Another window is synchronizing this vault.");return 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 qm(e.vault,i=>e.fileManager.trashFile(i),()=>this.assertActive(),i=>this.noteEngineWrite(i)),this.enrollmentClient=n.enrollmentClient??new jl({request:yF()}),this.adoptionClient=n.adoptionClient??new Kl({request:gF()})}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(Nn)||!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 Nr(this.settingsHost.getMirrorProfile()?.selectiveSync??this.adoptionMarker?.selective_sync)}async configureSelectiveSync(e){let t=this.requireProfile();await this.settingsHost.saveMirrorProfile({...t,selectiveSync:Nr(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"}),t$(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:Nm(i),selective_sync:Nr(e.selectiveSync),manifest_digest:null,source_revision:null,source_head:null}),await t.onVerification(Nm(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?.(Nm(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(Nn)}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=this.stateStoreFor(e),n=t.readCheckpoint?await t.readCheckpoint():ua(await t.read());if(!n||n.recovery_required)return!0;let s=await(await this.transportFor(e)).changes(n.cursor,1);return s.reset_required||s.scope_epoch!==n.scope_epoch||s.head>n.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=i$(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 J.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(Tt(this.app.vault,t));if(l instanceof J.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(){return this.withMirrorOperation(()=>this.autoResolveConflictsActive())}async autoResolveConflictsActive(){if(!this.settingsHost.getMirrorProfile())return[];let e=await this.createMirror(),t=await e.status();if(!t?.conflicts.length||t.recovery_required)return[];let n=this.requireProfile(),i=await this.stateStoreFor(n).read();if(!i||i.batch)return[];let s=t.conflicts.filter(c=>c.entity==="record"&&i.planned_conflicts?.[c.object_id]?.conflict_kind==="both_changed").map(c=>c.object_id),o=s.length?await this.remoteRecords(new Set(s)):new Map,a=[];for(let c of t.conflicts){let l=i.planned_conflicts?.[c.object_id];if(l)try{a.push(await this.autoResolve(e,c,l,o.get(c.object_id)))}catch(u){if(u instanceof w&&["conflict_decision_stale","sync_plan_stale"].includes(u.code))continue;a.push({path:c.path??c.object_id,outcome:"unresolved",reason:u instanceof Error?u.message:String(u)})}}return a}async autoResolve(e,t,n,i){let{object_id:s,decision_id:o}=t,a=n.local.state==="exact"?n.local.object.path:null,c=n.remote.state==="exact"?n.remote.object.path:null,l=t.path??a??c??s;if(n.conflict_kind==="rejected")return{path:l,outcome:"unresolved",reason:t.message};if(a===null)return await e.resolveConflict(s,o,"remote"),{path:l,outcome:c?"restored":"took_hosted"};if(c===null)return await e.resolveConflict(s,o,"local"),{path:l,outcome:"kept_local"};if(t.entity==="record"&&n.conflict_kind==="both_changed"&&i&&i.path===a&&n.remote.state==="exact"&&i.revision===n.remote.object.revision){let d=n.ancestor_document,f=await this.fileSystem.read(a);if(d!==void 0&&f!==null){let p=Xx(d,f,i.document,nF);if(p.clean)return await e.resolveConflict(s,o,"local",p.text),{path:l,outcome:"merged"}}}let u=await this.preserveConflictCopy(a);return await e.resolveConflict(s,o,"remote"),{path:l,outcome:"kept_both",copyPath:u}}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 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,h)=>p===l[h]))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=Tt(this.app.vault,e);if(!(this.app.vault.getAbstractFileByPath(t)instanceof J.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(async()=>{let t=this.requireProfile();return this.leaseFor(t).runExclusive(()=>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(Nn);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>e$&&this.engineWrites.delete(n);this.engineWrites.set((0,J.normalizePath)(e),t)}consumeEngineWrite(e){let t=(0,J.normalizePath)(e),n=this.engineWrites.get(t);this.engineWrites.delete(t);let i=n===void 0?-1:Date.now()-n;return i>=0&&i<=e$}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"):SF(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 Qr("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(Nn),i}return await this.clearAdoptionCheckpoint(e.adoptionId),this.requireProfile()}async adoptionSources(e,t){fe(t);let n=await ci(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,J.parseYaml)(i),o=`${(0,J.normalizePath)(n.settings.types_folder)}/`,a=this.app.vault.getMarkdownFiles().filter(h=>(0,J.normalizePath)(h.path).startsWith(o)).sort((h,m)=>h.path.localeCompare(m.path)),c=xF(s).map(h=>(0,s$.default)(h,{dot:!0})),l=hd(this.app.vault).filter(h=>h.extension==="base"&&c.some(m=>m((0,J.normalizePath)(h.path)))).sort((h,m)=>h.path.localeCompare(m.path)),u=this.app.vault.getMarkdownFiles().filter(h=>!bt((0,J.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=>pF(e,h)&&!bt(h,n)):[];fe(t);let p={records:u.length,resources:d.length,files:f.length,conflicts:Om([...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(Nr(e)),i=this.renameNamespace().map(c=>c.path).sort(),s=Zx(t.conflicts,i,new Set(n)),o=s.renames.map(({from:c})=>{let l=this.app.vault.getAbstractFileByPath(c);return[c,l instanceof J.TFile?l.stat:null]}),a=(await pa(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(Nn))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 J.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=>Oe(d.path)===Oe(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(Nr(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);t$(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,J.normalizePath)(m.path),kind:p,document:await this.app.vault.cachedRead(m)});let d=[];for(let p of a){fe(t);let h=(0,J.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 Lm(m);fe(t);let g=await pa(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:zl(e,`file:${h}`),path:h,revision:g.content_digest,...g,...r$(h)?{media_type:r$(h)}:{},media_class:a$(h),modified_at:new Date(b instanceof J.TFile&&b.stat?.mtime?b.stat.mtime:Date.now()).toISOString()})}}return fe(t),sm({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=>Lm(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,J.parseYaml)(e)}catch{throw new w("invalid_collection_configuration","mdbase.yaml must contain valid YAML.")}if(!Ze(t))throw new w("invalid_collection_configuration","mdbase.yaml must contain a YAML mapping.");let n=Ze(t["x-mdbase-connect"])?t["x-mdbase-connect"].collection_id:void 0,i;if(n===void 0){i=crypto.randomUUID();let o=Ze(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,J.stringifyYaml)(t))}else if(typeof n=="string"&&fa.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 Um(t),this.stateStores.set(t,n)),n}cachedBlobStore(e){this.assertActive();let t=this.blobStores.get(e);return t||(t=new Bm(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 Fm(e.syncUrl,this.transportCredentials(e),md,n,t);return _F(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 cd(a,i):a,fileSystem:this.fileSystem,blobStore:this.blobStoreFor(s),selectiveSync:Nr(s.selectiveSync),lease:this.leaseFor(s),onProgress:e};return s.mode==="read_write"?new sa(s.replicaId,o,c):new xi(s.replicaId,o,c)}leaseFor(e){return this.options.leaseFactory?.(e)??new Vm(`${e.collectionId}:${e.replicaId}`)}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"?aF:cF;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`${lF}${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(i$(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 kF(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()>dF?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,J.parseYaml)(await this.app.vault.adapter.read("mdbase.yaml"))}catch{throw new w("invalid_collection_configuration","mdbase.yaml must contain valid YAML.")}if(!Ze(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(!Ze(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"||!fa.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(Nn,`${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(Nn))return null;let e;try{e=JSON.parse(await this.app.vault.adapter.read(Nn))}catch{throw new w("invalid_mirror_marker","The mirror role marker is corrupt.")}if(!Ze(e)||e.version!==1||e.role!=="mirror"||typeof e.collection_id!="string"||!fa.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(!$F(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 Nm(r){let{credential:e,...t}=r;return t}function SF(r){return r instanceof G&&["authority_adoption_expired","authority_adoption_cancelled"].includes(r.code)}function xF(r){if(!Ze(r))return[];let e=r["x-obsidian"];return!Ze(e)||!Ze(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 J.TFile?t.push(s):s instanceof J.TFolder&&n(s)};return n(r.getRoot()),t}function $F(r){if(!Ze(r)||r.version!==1||!["waiting_for_approval","uploading","fenced","activating","adopted"].includes(String(r.phase))||!Ze(r.session))return!1;let e=r.session;return typeof e.controlUrl=="string"&&typeof e.adoptionId=="string"&&fa.test(e.adoptionId)&&typeof e.verificationUri=="string"&&typeof e.expiresAt=="string"&&Ze(e.requested)&&typeof e.requested.collectionId=="string"&&fa.test(e.requested.collectionId)&&typeof e.requested.displayName=="string"&&typeof e.requested.sourceName=="string"&&e.requested.retainMirror===!0&&(r.selective_sync===void 0||EF(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 EF(r){if(!Ze(r)||!Array.isArray(r.file_classes)||!Array.isArray(r.excluded_folders))return!1;try{let e=Nr(r);return e.file_classes.length===r.file_classes.length&&e.excluded_folders.length===r.excluded_folders.length}catch{return!1}}function i$(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:Nr(e),...t?{deviceId:t}:{}}}async function kF(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 et=require("obsidian");Vt();var ga="0.3.0",AF=new Set(["name","description","display_name_key","strict","path_pattern","filename_pattern","match","fields","extends"]),PF=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 ke(r){return r===void 0?r:JSON.parse(JSON.stringify(r))}function sn(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 Hm(r){if(Array.isArray(r))return r.map(Hm);if(!pe(r))return r;let e={};for(let[t,n]of Object.entries(r)){let i=Hm(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 CF(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 zm(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)?ke(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=zm(`${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=zm(`${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=ke(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");(!PF.has(c)||(c==="tn_role"||c==="tn_completed_values")&&!u)&&(s[`${r}.${c}`]=ke(l))}return{schema:a,links:i,legacy:s,unsupported:o}}function ha(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 MF(r,e,t){if(t==="now")ha(r,"on_create",e,{now:!0});else if(t==="now_on_write")ha(r,"on_update",e,{now:!0});else if(t==="uuid")ha(r,"on_create",e,{uuid:!0});else if(t==="ulid")ha(r,"on_create",e,{ulid:!0});else if(pe(t)&&t.transform==="slugify"&&typeof t.from=="string")ha(r,"on_create",e,{slugify:t.from});else return!1;return!0}function RF(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 TF(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=CF(t),i=t.name.trim().toLowerCase(),s={type:{const:i}},o=[],a={},c={},l=[],u={},d={},f=[],p=[],h={},m={},y={};for(let[E,A]of Object.entries(t.fields)){let x=pe(A)?A:{},R=zm(E,x,n);s[E]=R.schema,Object.assign(c,R.links),Object.assign(d,R.legacy),f.push(...R.unsupported),x.required===!0&&o.push(E),x.default!==void 0&&(a[E]=ke(x.default)),x.unique===!0&&l.push({field:E,scope:"collection"}),x.generated!==void 0&&(MF(u,E,x.generated)?p.push(E):(d[`${E}.generated`]=ke(x.generated),f.push(`${E}.generated`))),typeof x.tn_role=="string"&&(h[x.tn_role]=E),Array.isArray(x.tn_completed_values)&&(m.completed_values=ke(x.tn_completed_values))}a.status!==void 0&&(m.default=ke(a.status)),a.priority!==void 0&&(y.default=ke(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?RF(t.path_pattern):{pattern:t.path_pattern});let v={};for(let[E,A]of Object.entries(t))AF.has(E)||(v[E]=ke(A));Object.keys(d).length&&(v.fields=d);let S=Hm({kind:"mdbase.type",name:i,version:1,description:typeof t.description=="string"?t.description:void 0,match:pe(t.match)?ke(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 IF=["default_strict","write_nulls","write_empty_lists","write_defaults","rename_update_refs","cache_folder","migrations_folder","extensions"];function OF(r,e){let t=ke(r);t.spec_version=ga;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,et.normalizePath)(n.types_folder):"_types",s=(Array.isArray(n.exclude)?n.exclude:[]).map(String).flatMap(a=>DF(a,i)??[]);for(let a of s)NF(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 IF)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 DF(r,e){return/[/*?[]/.test(r)?r.includes("/")?r:`**/${r}`:r.startsWith(".")||r==="node_modules"||r===e?null:`${r}/**`}function NF(r){return r!==""&&!r.startsWith("/")&&!/[{}\\]/.test(r)&&r.split("/").every(e=>e==="**"||!e.includes("**"))}function d$(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 LF(r,e){let t={};for(let[n,i]of Object.entries(pe(e.fields)?e.fields:{}))pe(i)&&(t[n]=ke(i));return{name:typeof e.name=="string"?e.name:r.split("/").pop()?.replace(/\.md$/,"")??"type",fields:t,match:pe(e.match)?ke(e.match):void 0,filePath:r,specProfile:"v0.2"}}function FF(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:vn(n),match:pe(e.match)?ke(e.match):void 0,collection:pe(e.collection)?ke(e.collection):void 0,schema:ke(n),filePath:r,specProfile:"v0.3"}}function jF(r,e,t){let n=ke(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]=ke(a.default))}return n}function qF(r,e,t){let n=ke(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]=ke(a))}return n}async function BF(r,e){let t=(0,et.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 et.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,et.normalizePath)(e),i=n.lastIndexOf("/");if(i>=0&&await BF(r,n.slice(0,i)),n.startsWith(".mdbase/")){await r.adapter.write(n,t);return}let s=r.getAbstractFileByPath(n);if(s instanceof et.TFolder)throw new Error(`A folder blocks file ${n}.`);s instanceof et.TFile?await r.modify(s,t):await r.create(n,t)}async function ya(r,e){let t=(0,et.normalizePath)(e),n=r.getAbstractFileByPath(t);if(n instanceof et.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 u$(r){let e=await ya(r,"mdbase.yaml"),t=(0,et.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===ga?"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,et.normalizePath)(i.types_folder):"_types",o=`${s}/`,a=[],c=[],l=[],u=OF(t,l),d=`${(0,et.stringifyYaml)(u).trimEnd()} -`;a.push({path:"mdbase.yaml",sourceDigest:sn(e),targetDigest:sn(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 A=TF(S.path,n,E.frontmatter),x=LF(S.path,E.frontmatter),R=FF(S.path,A.target);f.set(x.name,x),p.set(R.name,R);let $=`${gt(A.target,E.body)} -`;a.push({path:S.path,sourceDigest:sn(_),targetDigest:sn($),source:_,target:$}),c.push(A.summary),l.push(...A.diagnostics)}if(!c.length)throw new Error(`No v0.2 type files were found in ${s}.`);let h=0,m=0,y=d$(t,n),g=d$(u,ga),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 A=Ge(_.path,E.frontmatter,y,f),x=Ge(_.path,E.frontmatter,g,p),R=jF(E.frontmatter,A,f),$=qF(E.frontmatter,x,p);(Ei(A.slice().sort())!==Ei(x.slice().sort())||Ei(R)!==Ei($))&&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=sn(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:ga,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 ma(r,e,t){await yd(r,e,`${JSON.stringify(t,null,2)} +`))}function Qx(r,e,t){return e===t?e:e===r?t:t===r?e:null}function ke(r){return[...r.normalize("NFC")].map(e=>e.toLowerCase()).join("").normalize("NFC")}function Om(r){let e=new Map;for(let t of r){let n=ke(t),i=e.get(n)??[];i.push(t),e.set(n,i)}return[...e.values()].filter(t=>t.length>1)}function Zx(r,e,t){let n=new Set([...e].map(ke)),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,h;do h=`${f} (${p++})${d}`;while(n.has(ke(h)));n.add(ke(h)),i.push({from:c,to:h})}}return{renames:i,manual:s}}function o$(r){if(!Ze(r))return null;let e=r;if(!(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.deviceId===void 0||typeof e.deviceId=="string")))return null;let t;try{t=Lr(e.selectiveSync)}catch{t=Lr()}return{...e,selectiveSync:t}}function nF(r){try{let e=(0,J.parseYaml)(r);return e===null||typeof e=="object"&&!Array.isArray(e)}catch{return!1}}var Ln=".mdbase/connect-role.json",ca=".mdbase/authority-adoption.json",la=".mdbase/authority-adoption-snapshot.json",iF="mdbase-obsidian-connect",Dr="mirrors",sF="mdbase-obsidian-connect-blobs",Nn="manifests",Fn="chunks",ud=1024*1024,oF=32*1024*1024,e$=2e3;function $i(r){if(!Number.isSafeInteger(r)||r<0||r>oF)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 aF="mdbase-connect-access-",cF="mdbase-connect-refresh-",lF="mdbase-connect-adoption-",dF=300*1e3,uF=[".git",".trash",".mdbase"],fF=new Set([".git",".mdbase",".trash","node_modules","_contracts","_schemas","_types","_views"]),Dm=["image","audio","video","pdf","other"],fa=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Ze(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function Lr(r){let e=r?.file_classes??[];if(e.some(s=>!Dm.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)=>Dm.indexOf(s)-Dm.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=>bn(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 a$(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 t$(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 pF(r,e,t=a$(e)){if(!r.file_classes.includes(t))return!1;let n=(0,J.normalizePath)(e);return!r.excluded_folders.some(i=>n===i||n.startsWith(`${i}/`))}var hF=/\.(?:md|base)$/,c$=/\.(?:md|base)$/i;function da(r,e=!1){let t=bn(r),n=t.split("/");if(t.length>1024||!e&&c$.test(t)||n.some(i=>i.startsWith(".")||fF.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 pa(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 Nm(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,$i(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 r$(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 mF(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){try{let t=r.json;if(t!=null)return t}catch{}let e=r.text;if(!e.trim())return{};try{return JSON.parse(e)}catch{return{}}}var md=Fx(jx());function yF(){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),retryAfterMs:aa(e.headers)}}}function gF(){return async r=>{if(r.signal?.aborted)throw new DOMException("Collection adoption cancelled.","AbortError");let e=await mF(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),retryAfterMs:aa(t.headers),headers:t.headers}}}var Fm=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){$i(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=n$(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){$i(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 jm(t);try{return await this.uploadParts(e,n,i,s)}finally{await s.close().catch(()=>{})}}async uploadParts(e,t,n,i){let s=Math.max(1,Math.ceil(e.size/n));if(t.received.some(u=>!Number.isSafeInteger(u)||u<0||u>=s)||new Set(t.received).size!==t.received.length)throw new w("invalid_sync_response","Authority returned invalid upload progress.");let o=t.uploaded_parts??[];if(o.some((u,d)=>!Number.isSafeInteger(u.part_number)||u.part_number<1||u.part_number>s||!u.etag||u.etag.length>255||d>0&&o[d-1].part_number>=u.part_number)||(t.strategy.kind==="object_multipart"?o.length!==t.received.length||o.some((u,d)=>u.part_number-1!==t.received[d]):o.length!==0))throw new w("invalid_sync_response","Authority returned invalid uploaded part receipts.");let a=t.received.reduce((u,d)=>{let f=d*n;return u+Math.min(n,Math.max(0,e.size-f))},0);if(this.onFileProgress?.({direction:"upload",path:e.path,transferredBytes:a,totalBytes:e.size}),t.received.length===s)return this.commitUpload(e.transfer_id,o);let c=new Set(t.received),l=Array.from({length:s},()=>{});for(let u of o)l[u.part_number-1]=u;for(let u=0;u=300)throw new Dn(m.status===429||m.status>=500?"authority_unavailable":"file_upload_failed",`Object storage returned HTTP ${m.status}.`,m.status);if(a+=f,this.onFileProgress?.({direction:"upload",path:e.path,transferredBytes:a,totalBytes:e.size}),t.strategy.kind==="object_multipart"){let y=n$(m.headers,"etag");if(!y)throw new w("invalid_sync_response","Object storage omitted a multipart ETag.");l[u]={part_number:u+1,etag:y}}}return await i.expectEnd(),this.commitUpload(e.transfer_id,l.filter(u=>u!==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);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),i=Ze(n)&&Ze(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 Dn(s,typeof i.message=="string"?i.message:`Sync request failed (${e.status}).`,e.status,aa(e.headers))}},jm=class{constructor(e){this.remainder=new Uint8Array;this.iterator=e[Symbol.asyncIterator]()}async read(e){let t=new Uint8Array(new ArrayBuffer(e));return await this.consume(e,t),t}async skip(e){await this.consume(e)}async consume(e,t){let n=0;for(;n!["authorization","cookie","host","proxy-authorization","content-length"].includes(e.toLowerCase())))}function n$(r,e){return Object.entries(r).find(([n])=>n.toLowerCase()===e.toLowerCase())?.[1]}function l$(r){return[r.configDir||".obsidian",...uF].map(t=>(0,J.normalizePath)(t).replace(/\/+$/,""))}function Tt(r,e){let t=bn(e),n=ke(t);if(l$(r).some(i=>n===ke(i)||n.startsWith(`${ke(i)}/`)))throw new w("unsafe_mirror_path",`The collection authority attempted to write a reserved path: ${t}`);return t}function ue(r){if(r?.aborted)throw new DOMException("Synchronization cancelled.","AbortError")}function Ue(r,e){return r??new Error(`IndexedDB ${e} failed without an error detail.`)}function _F(r,e){let t=async a=>{ue(e);let c=await a();return ue(e),c},n=async function*(a){ue(e);for await(let c of a)ue(e),yield c,ue(e);ue(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,J.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 J.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 qm=class{constructor(e,t=s=>e.delete(s,!0),n=()=>{},i=()=>{}){this.vault=e;this.trashFile=t;this.assertActive=n;this.observeWrite=i}async cachedEntry(e){let t=this.vault.getAbstractFileByPath(e);if(t||!await this.vault.adapter.exists(e))return t;let n=e.lastIndexOf("/"),i=await this.vault.adapter.list(n<0?"":e.slice(0,n)),s=ke(e),o=[...i.files,...i.folders].filter(l=>ke(l)===s);if(o.length!==1)throw new w("mirror_path_collision",`More than one physical spelling blocks ${e}.`);let a=this.vault.getAbstractFileByPath(o[0]);if(a)return a;let c=this.vault.getAllLoadedFiles().filter(l=>ke(l.path)===s);if(c.length>1)throw new w("mirror_path_collision",`More than one cached spelling blocks ${e}.`);return c[0]??null}assertEntry(e,t){if(ke(t.path)!==ke(e)||this.vault.getAbstractFileByPath(t.path)!==t)throw new w("sync_plan_stale",`${e} moved before it could be changed. Review sync again.`)}async exists(e){let t=Tt(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=Tt(this.vault,e);if(this.vault.getAbstractFileByPath(t)instanceof J.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 pa(i)).content_digest}}}async pathKind(e){let t=Tt(this.vault,e);return(await this.vault.adapter.stat(t))?.type??null}async write(e,t,n){let i=Tt(this.vault,e),s=()=>new w("sync_plan_stale",`${i} changed before it could be written. Review sync again.`),o=n;if(o===void 0){let l=await this.readText(i);if(typeof l=="string"||l===null)o=l;else{let u=await this.vault.adapter.readBinary(i);if((await pa(u)).content_digest!==l.revision)throw s();o=new TextDecoder("utf-8",{ignoreBOM:!0}).decode(u)}}let a=i.lastIndexOf("/");a>=0&&await Ps(this.vault,i.slice(0,a));let c=await this.cachedEntry(i);if(c instanceof J.TFolder)throw new w("mirror_path_collision",`A folder blocks the mirror file ${i}.`);if(this.assertActive(),c instanceof J.TFile){this.assertEntry(i,c);let l=c.path;await this.vault.process(c,u=>{if(this.assertActive(),c.path!==l||this.vault.getAbstractFileByPath(l)!==c||u!==o&&u!==t)throw s();return this.observeWrite(i),this.observeWrite(l),t})}else{if(o!==null)throw s();this.observeWrite(i),await this.vault.create(i,t)}}async move(e,t){let n=Tt(this.vault,e),i=Tt(this.vault,t),s=await this.cachedEntry(n);if(!(s instanceof J.TFile))throw new w("mirror_path_collision",`Expected a file at ${n}.`);this.assertEntry(n,s);let o=s.path,a=await this.cachedEntry(i);if(!(a===s&&ke(n)===ke(i))&&(a!==null||await this.vault.adapter.exists(i)))throw new w("mirror_path_collision",`A file or folder blocks the mirror path ${i}.`);let l=i.lastIndexOf("/");if(l>=0&&await Ps(this.vault,i.slice(0,l)),this.assertActive(),this.assertEntry(n,s),s.path!==o)throw new w("sync_plan_stale",`${n} moved before it could be renamed. Review sync again.`);this.observeWrite(n),this.observeWrite(s.path),this.observeWrite(i),await this.vault.rename(s,i)}async remove(e,t){let n=Tt(this.vault,e);if(t!==void 0){let s;if(t===null)s=!await this.exists(n);else if(typeof t=="string")s=await this.read(n)===t;else{let o=await this.inspectBinary(n);s=o?.content_digest===t.content_digest&&o?.size===t.size}if(!s)throw new w("sync_plan_stale",`${n} changed before it could be removed. Review sync again.`)}let i=await this.cachedEntry(n);if(i!=null){if(!(i instanceof J.TFile))throw new w("mirror_path_collision",`Expected a file at ${n}.`);this.assertActive(),this.assertEntry(n,i),this.observeWrite(n),this.observeWrite(i.path),await this.trashFile(i)}}async listMarkdown(e){return hd(this.vault).map(t=>(0,J.normalizePath)(t.path)).filter(t=>hF.test(t)&&!e.has(t)).filter(t=>!l$(this.vault).some(n=>ke(t)===ke(n)||ke(t).startsWith(`${ke(n)}/`))).sort()}async inspectBinary(e){let t=da(Tt(this.vault,e)),n=await this.cachedEntry(t);if(n==null)return null;if(!(n instanceof J.TFile))throw new w("mirror_path_collision",`Expected a file at ${t}.`);this.assertEntry(t,n),$i(n.stat.size);let i=await this.vault.readBinary(n);return $i(i.byteLength),pa(i)}async writeBinary(e,t,n){let i=da(Tt(this.vault,e)),s=n===void 0?await this.inspectBinary(i):n,o=await Nm(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=await this.cachedEntry(i);if(l instanceof J.TFolder)throw new w("mirror_path_collision",`A folder blocks the mirror file ${i}.`);this.assertActive(),this.observeWrite(i),l instanceof J.TFile?(this.assertEntry(i,l),this.observeWrite(l.path),await this.vault.modifyBinary(l,o)):await this.vault.createBinary(i,o)}async listBinary(e){return hd(this.vault).map(t=>(0,J.normalizePath)(t.path)).filter(t=>!c$.test(t)&&!e.has(t)).filter(t=>{try{return da(Tt(this.vault,t)),!0}catch{return!1}}).sort()}async readBinary(e){let t=da(Tt(this.vault,e)),n=await this.cachedEntry(t);if(n==null)return null;if(!(n instanceof J.TFile))throw new w("mirror_path_collision",`Expected a file at ${t}.`);this.assertEntry(t,n),$i(n.stat.size);let i=new Uint8Array(await this.vault.readBinary(n));return $i(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(Ue(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(Fn,"readonly").objectStore(Fn).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(Ue(l.error,"chunk cursor"))});for(let o of s)await this.delete(Fn,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(Ue(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(Ue(a.error,`write to ${e}`)),a.onabort=()=>o(Ue(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(Ue(o.error,`delete from ${e}`)),o.onabort=()=>s(Ue(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.");if(this.database)return this.database;let e=new Promise((t,n)=>{let i=indexedDB.open(sF,1);i.onupgradeneeded=()=>{i.result.objectStoreNames.contains(Nn)||i.result.createObjectStore(Nn),i.result.objectStoreNames.contains(Fn)||i.result.createObjectStore(Fn)},i.onerror=()=>n(Ue(i.error,"binary store open")),i.onsuccess=()=>{let s=i.result,o=()=>{this.database===e&&(this.database=null)};s.onclose=o,s.onversionchange=()=>{s.close(),o()},t(s)}});return this.database=e,e.catch(()=>{this.database===e&&(this.database=null)}),e}};function ua(r){return r?{cursor:r.cursor,scope_epoch:r.scope_epoch,recovery_required:!!r.batch}:null}var Um=class{constructor(e){this.key=e;this.database=null;this.checkpointReady=!1}get checkpointKey(){return[this.key,"checkpoint"]}async read(){let e=await this.open(),t=!this.checkpointReady;return new Promise((n,i)=>{let s=e.transaction(Dr,t?"readwrite":"readonly"),o=s.objectStore(Dr),a=o.get(this.key),c=null;a.onsuccess=()=>{c=a.result??null,t&&(c?o.put(ua(c),this.checkpointKey):o.delete(this.checkpointKey))},s.oncomplete=()=>{t&&(this.checkpointReady=!0),n(c)},s.onerror=()=>i(Ue(s.error,"mirror state read")),s.onabort=()=>i(Ue(s.error,"mirror state read"))})}async readCheckpoint(){if(!this.checkpointReady)return ua(await this.read());let e=await this.open(),t=await new Promise((n,i)=>{let s=e.transaction(Dr,"readonly"),o=s.objectStore(Dr),a=o.get(this.checkpointKey),c=o.getKey(this.key);s.oncomplete=()=>n({exists:c.result!==void 0,checkpoint:a.result??null}),s.onerror=()=>i(Ue(s.error,"mirror checkpoint read")),s.onabort=()=>i(Ue(s.error,"mirror checkpoint read"))});return t.exists?t.checkpoint?t.checkpoint:(this.checkpointReady=!1,ua(await this.read())):null}async write(e){let t=await this.open();await new Promise((n,i)=>{let s=t.transaction(Dr,"readwrite"),o=s.objectStore(Dr);o.put(e,this.key),o.put(ua(e),this.checkpointKey),s.oncomplete=()=>n(),s.onerror=()=>i(Ue(s.error,"mirror state write")),s.onabort=()=>i(Ue(s.error,"mirror state write"))}),this.checkpointReady=!0}async clear(){let e=await this.open();await new Promise((t,n)=>{let i=e.transaction(Dr,"readwrite"),s=i.objectStore(Dr);s.delete(this.key),s.delete(this.checkpointKey),i.oncomplete=()=>t(),i.onerror=()=>n(Ue(i.error,"mirror state clear")),i.onabort=()=>n(Ue(i.error,"mirror state clear"))}),this.checkpointReady=!0}close(){this.database?.then(e=>e.close(),()=>{}),this.database=null,this.checkpointReady=!1}open(){if(typeof indexedDB>"u")throw new w("storage_unavailable","IndexedDB is required for persistent mirror state.");if(this.database)return this.database;let e=new Promise((t,n)=>{let i=indexedDB.open(iF,1);i.onupgradeneeded=()=>{i.result.objectStoreNames.contains(Dr)||i.result.createObjectStore(Dr)},i.onerror=()=>n(Ue(i.error,"mirror state store open")),i.onsuccess=()=>{let s=i.result,o=()=>{this.database===e&&(this.database=null)};s.onclose=o,s.onversionchange=()=>{s.close(),o()},t(s)}});return this.database=e,e.catch(()=>{this.database===e&&(this.database=null)}),e}},Vm=class r{constructor(e){this.key=e}static{this.active=new Set}async runExclusive(e){let t=typeof navigator>"u"?null:navigator.locks;if(t)return t.request(`mdbase-mirror:${this.key}`,{ifAvailable:!0},async n=>{if(!n)throw new w("mirror_busy","Another window is synchronizing this vault.");return 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.engineLeaseHeld=!1;this.adoptionMarker=null;this.adoptionBusy=!1;this.engineWrites=new Map;this.renewal=null;this.fileSystem=n.fileSystem??new qm(e.vault,i=>e.fileManager.trashFile(i),()=>this.assertActive(),i=>this.noteEngineWrite(i)),this.enrollmentClient=n.enrollmentClient??new jl({request:yF()}),this.adoptionClient=n.adoptionClient??new Kl({request:gF()})}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 ue(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(Ln)||!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 ue(t),await this.updateAdoptionPhase("adopted"),this.persistAdoptedMirror(n.session,i)})}getSelectiveSync(){return Lr(this.settingsHost.getMirrorProfile()?.selectiveSync??this.adoptionMarker?.selective_sync)}async configureSelectiveSync(e){let t=this.requireProfile();await this.settingsHost.saveMirrorProfile({...t,selectiveSync:Lr(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"}),t$(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:Lm(i),selective_sync:Lr(e.selectiveSync),manifest_digest:null,source_revision:null,source_head:null}),await t.onVerification(Lm(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?.(Lm(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(Ln)}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=this.stateStoreFor(e),n=t.readCheckpoint?await t.readCheckpoint():ua(await t.read());if(!n||n.recovery_required)return!0;let s=await(await this.transportFor(e)).changes(n.cursor,1);return s.reset_required||s.scope_epoch!==n.scope_epoch||s.head>n.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()=>(await this.leaseFor(t).runExclusive(async()=>{ue(e.signal);let c=this.requireProfile();if(c.collectionId!==t.collectionId||c.replicaId!==t.replicaId||c.enrollmentId!==t.enrollmentId)throw new w("mirror_identity_conflict","The connection changed during approval. The current mirror was not changed.");let l=n?null:await i.read();if(l?.batch)throw new w("mirror_recovery_required","Resume the durable synchronization checkpoint before approving this vault again.");let u=i$(o,c.selectiveSync);l&&o.replicaId!==t.replicaId&&await this.stateStoreFor(u).write({...l,replica_id:o.replicaId}),await this.persistEnrollment(o,c.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 J.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(Tt(this.app.vault,t));if(l instanceof J.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(){return this.withMirrorOperation(()=>this.autoResolveConflictsActive())}async autoResolveConflictsActive(){if(!this.settingsHost.getMirrorProfile())return[];let e=await this.createMirror(),t=await e.status();if(!t?.conflicts.length||t.recovery_required)return[];let n=this.requireProfile(),i=await this.stateStoreFor(n).read();if(!i||i.batch)return[];let s=t.conflicts.filter(c=>c.entity==="record"&&i.planned_conflicts?.[c.object_id]?.conflict_kind==="both_changed").map(c=>c.object_id),o=s.length?await this.remoteRecords(new Set(s)):new Map,a=[];for(let c of t.conflicts){let l=i.planned_conflicts?.[c.object_id];if(l)try{a.push(await this.autoResolve(e,c,l,o.get(c.object_id)))}catch(u){if(u instanceof w&&["conflict_decision_stale","sync_plan_stale"].includes(u.code))continue;a.push({path:c.path??c.object_id,outcome:"unresolved",reason:u instanceof Error?u.message:String(u)})}}return a}async autoResolve(e,t,n,i){let{object_id:s,decision_id:o}=t,a=n.local.state==="exact"?n.local.object.path:null,c=n.remote.state==="exact"?n.remote.object.path:null,l=t.path??a??c??s;if(n.conflict_kind==="rejected")return{path:l,outcome:"unresolved",reason:t.message};if(a===null)return await e.resolveConflict(s,o,"remote"),{path:l,outcome:c?"restored":"took_hosted"};if(c===null)return await e.resolveConflict(s,o,"local"),{path:l,outcome:"kept_local"};if(t.entity==="record"&&n.conflict_kind==="both_changed"&&i&&i.path===a&&n.remote.state==="exact"&&i.revision===n.remote.object.revision){let d=n.ancestor_document,f=await this.fileSystem.read(a);if(d!==void 0&&f!==null){let p=Xx(d,f,i.document,nF);if(p.clean)return await e.resolveConflict(s,o,"local",p.text),{path:l,outcome:"merged"}}}let u=await this.preserveConflictCopy(a);return await e.resolveConflict(s,o,"remote"),{path:l,outcome:"kept_both",copyPath:u}}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 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(?: [a-zA-Z0-9%_-]+)?(?: \d+)?\))+$/,""),l=this.settingsHost.getMirrorProfile()?.replicaId,u=l?` ${encodeURIComponent(l)}`:"",d=new Uint8Array(t),f=c.slice(0,c.lastIndexOf("/")+1),p=new TextEncoder,h=1;for(;;){let m=` (${n}${u}${h===1?"":` ${h}`})${o}`,y=Math.min(255,1024-f.length)-p.encode(m).byteLength;if(y<1)throw new w("mirror_path_collision","This filename leaves no room for a recovery copy. Shorten it before settling the conflict.");let g=[...c.slice(f.length)];for(;p.encode(g.join("")).byteLength>y;)g.pop();let b=`${f}${g.join("")}${m}`;if(b===e){h+=1;continue}if(this.app.vault.getAbstractFileByPath(b)||await this.app.vault.adapter.exists(b)){try{let v=new Uint8Array(await this.app.vault.adapter.readBinary(b));if(v.length===d.length&&v.every((S,_)=>S===d[_]))return b}catch{}h+=1;continue}try{return await this.app.vault.createBinary(b,t),b}catch(v){if(!await this.app.vault.adapter.exists(b))throw v}}}async preserveConflictCopy(e){let t=Tt(this.app.vault,e);if(!(this.app.vault.getAbstractFileByPath(t)instanceof J.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(async()=>{let t=this.requireProfile();return this.leaseFor(t).runExclusive(()=>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(Ln);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=>{ue(s.signal),this.progress=c,t?.({...c})},s.signal,c=>{ue(s.signal),this.fileProgress=c,n?.({...c})},i)).apply(e.plan,{signal:s.signal});return ue(s.signal),a})}finally{this.progress=null,this.fileProgress=null,this.syncAbort=null}}cancelSync(){this.syncAbort?.abort()}noteEngineWrite(e){let t=performance.now();for(let[i,s]of this.engineWrites){if(t-s<=e$)break;this.engineWrites.delete(i)}let n=(0,J.normalizePath)(e);this.engineWrites.delete(n),this.engineWrites.set(n,t)}consumeEngineWrite(e){let t=(0,J.normalizePath)(e),n=this.engineWrites.get(t);this.engineWrites.delete(t);let i=n===void 0?-1:performance.now()-n;return i>=0&&i<=e$}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"):SF(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 Qr("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(Ln),i}return await this.clearAdoptionCheckpoint(e.adoptionId),this.requireProfile()}async adoptionSources(e,t){ue(t);let n=await ci(this.app.vault);if(ue(t),!n)throw new w("invalid_collection_configuration","A valid mdbase.yaml is required.");let i=await this.app.vault.adapter.read("mdbase.yaml");ue(t);let s=(0,J.parseYaml)(i),o=`${(0,J.normalizePath)(n.settings.types_folder)}/`,a=this.app.vault.getMarkdownFiles().filter(h=>(0,J.normalizePath)(h.path).startsWith(o)).sort((h,m)=>h.path.localeCompare(m.path)),c=xF(s).map(h=>(0,s$.default)(h,{dot:!0})),l=hd(this.app.vault).filter(h=>h.extension==="base"&&c.some(m=>m((0,J.normalizePath)(h.path)))).sort((h,m)=>h.path.localeCompare(m.path)),u=this.app.vault.getMarkdownFiles().filter(h=>!bt((0,J.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=>pF(e,h)&&!bt(h,n)):[];ue(t);let p={records:u.length,resources:d.length,files:f.length,conflicts:Om([...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(Lr(e)),i=this.renameNamespace().map(c=>c.path).sort(),s=Zx(t.conflicts,i,new Set(n)),o=s.renames.map(({from:c})=>{let l=this.app.vault.getAbstractFileByPath(c);return[c,l instanceof J.TFile?l.stat:null]}),a=(await pa(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(Ln))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(ue(i),this.assertLocalAuthorityWritable(),!(u instanceof J.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=>ke(d.path)===ke(l.to))||await this.app.vault.adapter.exists(l.to))throw new Error("The destination is now occupied. Review again.");ue(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(Lr(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);t$(l);let u=[{path:"mdbase.yaml",kind:"configuration",document:i}];for(let[p,h]of[["type",s],["view",o]])for(let m of h)ue(t),u.push({path:(0,J.normalizePath)(m.path),kind:p,document:await this.app.vault.cachedRead(m)});let d=[];for(let p of a){ue(t);let h=(0,J.normalizePath)(p.path),m=await this.app.vault.cachedRead(p);ue(t),d.push({path:h,document:m})}let f=[];if(c.length){let p=this.adoptionBlobStore(e);for(let h of c){ue(t);let m=await this.fileSystem.readBinary?.(h);if(ue(t),!m)continue;let y=await Nm(m);ue(t);let g=await pa(y);ue(t),await p.write(g.content_digest,(async function*(){yield new Uint8Array(y)})()),ue(t);let b=this.app.vault.getAbstractFileByPath(h);f.push({file_id:zl(e,`file:${h}`),path:h,revision:g.content_digest,...g,...r$(h)?{media_type:r$(h)}:{},media_class:a$(h),modified_at:new Date(b instanceof J.TFile&&b.stat?.mtime?b.stat.mtime:Date.now()).toISOString()})}}return ue(t),sm({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=>Nm(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,J.parseYaml)(e)}catch{throw new w("invalid_collection_configuration","mdbase.yaml must contain valid YAML.")}if(!Ze(t))throw new w("invalid_collection_configuration","mdbase.yaml must contain a YAML mapping.");let n=Ze(t["x-mdbase-connect"])?t["x-mdbase-connect"].collection_id:void 0,i;if(n===void 0){i=crypto.randomUUID();let o=Ze(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,J.stringifyYaml)(t))}else if(typeof n=="string"&&fa.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 Um(t),this.stateStores.set(t,n)),n}cachedBlobStore(e){this.assertActive();let t=this.blobStores.get(e);return t||(t=new Bm(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 Fm(e.syncUrl,this.transportCredentials(e),md,n,t);return _F(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 cd(a,i):a,fileSystem:this.fileSystem,blobStore:this.blobStoreFor(s),selectiveSync:Lr(s.selectiveSync),lease:{runExclusive:l=>this.leaseFor(s).runExclusive(async()=>{this.engineLeaseHeld=!0;try{return await l()}finally{this.engineLeaseHeld=!1}})},onProgress:e};return s.mode==="read_write"?new sa(s.replicaId,o,c):new xi(s.replicaId,o,c)}leaseFor(e){let t=this.currentDeviceId()??e.deviceId??e.replicaId;return this.options.leaseFactory?.(e)??new Vm(`${e.collectionId}:${t}`)}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"?aF:cF;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`${lF}${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(i$(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 kF(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()>dF?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=async()=>{await this.assertMirror(e.collectionId);let s=this.requireProfile(),o=this.app.secretStorage.getSecret(this.secretIds("refresh",e).current);if(s.collectionId!==e.collectionId||s.replicaId!==e.replicaId||s.enrollmentId!==e.enrollmentId||o!==t)throw new w("mirror_identity_conflict","The connection changed while credentials were renewing. Retry with the current connection.");await this.persistEnrollment(n,s.selectiveSync)};return this.engineLeaseHeld?await i():await this.leaseFor(e).runExclusive(i),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,J.parseYaml)(await this.app.vault.adapter.read("mdbase.yaml"))}catch{throw new w("invalid_collection_configuration","mdbase.yaml must contain valid YAML.")}if(!Ze(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(!Ze(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"||!fa.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(Ln,`${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(Ln))return null;let e;try{e=JSON.parse(await this.app.vault.adapter.read(Ln))}catch{throw new w("invalid_mirror_marker","The mirror role marker is corrupt.")}if(!Ze(e)||e.version!==1||e.role!=="mirror"||typeof e.collection_id!="string"||!fa.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(!$F(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 Lm(r){let{credential:e,...t}=r;return t}function SF(r){return r instanceof G&&["authority_adoption_expired","authority_adoption_cancelled"].includes(r.code)}function xF(r){if(!Ze(r))return[];let e=r["x-obsidian"];return!Ze(e)||!Ze(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 J.TFile?t.push(s):s instanceof J.TFolder&&n(s)};return n(r.getRoot()),t}function $F(r){if(!Ze(r)||r.version!==1||!["waiting_for_approval","uploading","fenced","activating","adopted"].includes(String(r.phase))||!Ze(r.session))return!1;let e=r.session;return typeof e.controlUrl=="string"&&typeof e.adoptionId=="string"&&fa.test(e.adoptionId)&&typeof e.verificationUri=="string"&&typeof e.expiresAt=="string"&&Ze(e.requested)&&typeof e.requested.collectionId=="string"&&fa.test(e.requested.collectionId)&&typeof e.requested.displayName=="string"&&typeof e.requested.sourceName=="string"&&e.requested.retainMirror===!0&&(r.selective_sync===void 0||EF(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 EF(r){if(!Ze(r)||!Array.isArray(r.file_classes)||!Array.isArray(r.excluded_folders))return!1;try{let e=Lr(r);return e.file_classes.length===r.file_classes.length&&e.excluded_folders.length===r.excluded_folders.length}catch{return!1}}function i$(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:Lr(e),...t?{deviceId:t}:{}}}async function kF(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 et=require("obsidian");Vt();var ga="0.3.0",AF=new Set(["name","description","display_name_key","strict","path_pattern","filename_pattern","match","fields","extends"]),PF=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 sn(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 Hm(r){if(Array.isArray(r))return r.map(Hm);if(!pe(r))return r;let e={};for(let[t,n]of Object.entries(r)){let i=Hm(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 CF(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 zm(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=zm(`${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=zm(`${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");(!PF.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 ha(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 MF(r,e,t){if(t==="now")ha(r,"on_create",e,{now:!0});else if(t==="now_on_write")ha(r,"on_update",e,{now:!0});else if(t==="uuid")ha(r,"on_create",e,{uuid:!0});else if(t==="ulid")ha(r,"on_create",e,{ulid:!0});else if(pe(t)&&t.transform==="slugify"&&typeof t.from=="string")ha(r,"on_create",e,{slugify:t.from});else return!1;return!0}function RF(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 TF(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=CF(t),i=t.name.trim().toLowerCase(),s={type:{const:i}},o=[],a={},c={},l=[],u={},d={},f=[],p=[],h={},m={},y={};for(let[E,A]of Object.entries(t.fields)){let x=pe(A)?A:{},R=zm(E,x,n);s[E]=R.schema,Object.assign(c,R.links),Object.assign(d,R.legacy),f.push(...R.unsupported),x.required===!0&&o.push(E),x.default!==void 0&&(a[E]=Ae(x.default)),x.unique===!0&&l.push({field:E,scope:"collection"}),x.generated!==void 0&&(MF(u,E,x.generated)?p.push(E):(d[`${E}.generated`]=Ae(x.generated),f.push(`${E}.generated`))),typeof x.tn_role=="string"&&(h[x.tn_role]=E),Array.isArray(x.tn_completed_values)&&(m.completed_values=Ae(x.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?RF(t.path_pattern):{pattern:t.path_pattern});let v={};for(let[E,A]of Object.entries(t))AF.has(E)||(v[E]=Ae(A));Object.keys(d).length&&(v.fields=d);let S=Hm({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 IF=["default_strict","write_nulls","write_empty_lists","write_defaults","rename_update_refs","cache_folder","migrations_folder","extensions"];function OF(r,e){let t=Ae(r);t.spec_version=ga;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,et.normalizePath)(n.types_folder):"_types",s=(Array.isArray(n.exclude)?n.exclude:[]).map(String).flatMap(a=>DF(a,i)??[]);for(let a of s)LF(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 IF)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 DF(r,e){return/[/*?[]/.test(r)?r.includes("/")?r:`**/${r}`:r.startsWith(".")||r==="node_modules"||r===e?null:`${r}/**`}function LF(r){return r!==""&&!r.startsWith("/")&&!/[{}\\]/.test(r)&&r.split("/").every(e=>e==="**"||!e.includes("**"))}function d$(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 NF(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 FF(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:vn(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 jF(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 qF(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 BF(r,e){let t=(0,et.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 et.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,et.normalizePath)(e),i=n.lastIndexOf("/");if(i>=0&&await BF(r,n.slice(0,i)),n.startsWith(".mdbase/")){await r.adapter.write(n,t);return}let s=r.getAbstractFileByPath(n);if(s instanceof et.TFolder)throw new Error(`A folder blocks file ${n}.`);s instanceof et.TFile?await r.modify(s,t):await r.create(n,t)}async function ya(r,e){let t=(0,et.normalizePath)(e),n=r.getAbstractFileByPath(t);if(n instanceof et.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 u$(r){let e=await ya(r,"mdbase.yaml"),t=(0,et.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===ga?"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,et.normalizePath)(i.types_folder):"_types",o=`${s}/`,a=[],c=[],l=[],u=OF(t,l),d=`${(0,et.stringifyYaml)(u).trimEnd()} +`;a.push({path:"mdbase.yaml",sourceDigest:sn(e),targetDigest:sn(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=Te(_);if(!E.hasFrontmatter||E.error)throw new Error(`Cannot migrate ${S.path}: ${E.error??"frontmatter is missing"}.`);let A=TF(S.path,n,E.frontmatter),x=NF(S.path,E.frontmatter),R=FF(S.path,A.target);f.set(x.name,x),p.set(R.name,R);let $=`${gt(A.target,E.body)} +`;a.push({path:S.path,sourceDigest:sn(_),targetDigest:sn($),source:_,target:$}),c.push(A.summary),l.push(...A.diagnostics)}if(!c.length)throw new Error(`No v0.2 type files were found in ${s}.`);let h=0,m=0,y=d$(t,n),g=d$(u,ga),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=Te(await r.cachedRead(_));if(E.error){m+=1;continue}let A=Ge(_.path,E.frontmatter,y,f),x=Ge(_.path,E.frontmatter,g,p),R=jF(E.frontmatter,A,f),$=qF(E.frontmatter,x,p);(Ei(A.slice().sort())!==Ei(x.slice().sort())||Ei(R)!==Ei($))&&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=sn(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:ga,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 ma(r,e,t){await yd(r,e,`${JSON.stringify(t,null,2)} `)}async function f$(r,e,t={}){if(e.planVersion!==1||e.targetVersion!==ga)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 ya(r,s.path);if(sn(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 ma(r,n,i),i.status="applying",await ma(r,n,i);try{for(let s of e.operations){let o=await ya(r,s.path);if(sn(o)!==s.sourceDigest)throw new Error(`${s.path} changed during migration.`);i.written.push(s.path),await ma(r,n,i),await yd(r,s.path,s.target);let a=await ya(r,s.path);if(sn(a)!==s.targetDigest)throw new Error(`${s.path} did not verify after write.`)}return i.status="applied",i.completed_at=new Date().toISOString(),await ma(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),sn(await ya(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 ma(r,n,i)}catch{}return{applied:!1,restored:o.length===0,manifestPath:n,written:[...i.written],error:i.error}}}var gd=require("obsidian");Vt();function we(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function It(r){return JSON.parse(JSON.stringify(r))}var UF=new Set(["file","formula","this"]);function VF(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(UF.has(e.toLowerCase()))throw new Error(`Type name '${e}' is reserved.`);return e}function Km(){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 HF(r){return we(r)?Object.entries(r).filter(e=>we(e[1])).map(([e,t])=>({name:e,definition:It(t)})):[]}function zF(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)?It(e.binding):void 0;return[{contract:e.contract,version:e.version,fields:t,...n?{binding:n}:{}}]}):[]}function KF(r){return Object.fromEntries(r.map(e=>[e.name,e.definition]))}function WF(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=HF(n?vn(s):r.fields);n&&GF(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]=It(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:It(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:Km().fields,implementations:zF(r.implements),body:e.trim()||`# ${t} @@ -210,17 +210,17 @@ Type definition for ${t}.`,extraFrontmatter:h,...o?{readOnlyReason:`This type us -`;var P$=require("obsidian");var YF={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 XF(r){return YF[r]??r.replace(/^schema_/,"").replace(/_/g," ")}function QF(r){return[r.type??"",r.field??"",r.code].join("\0")}function Qm(r){return[r.type,r.field,XF(r.code)].filter(Boolean).join(" \xB7 ")}function x$(r){let e=new Map;for(let t of r){let n=QF(t),i=e.get(n);i||(i={key:n,label:Qm(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))}Vt();function $$(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function E$(r,e,t){let n=new Map;for(let i of r){let s=Ge(i.path,i.frontmatter,e,t);s.length&&n.set(i.path,s)}return n}function k$(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 Zm(i,r))n(s).issues+=1;return t}function Zm(r,e){return r.type?[r.type]:e.get(r.path)??[]}function ZF(r,e){let t=jn(r),n=$$(t.schema)?t.schema:{},i=$$(n.value)?n.value:{};return _c(t,e??`${r.name||"new"}.md`,i)}function ej(){return new Promise(r=>window.setTimeout(r,0))}async function A$(r){let e;try{e=ZF(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 ej(),r.isCurrent&&!r.isCurrent()))return null;let a=t!==null&&Ge(o.path,o.frontmatter,r.config,r.types).includes(t.name),c=Ge(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?es(o.path,o.frontmatter,t).length:0,u=c?es(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,P$.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:Qm(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=Zm(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 kc(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 Ts=require("obsidian"),_d="https://connect.mdbase.dev",C$=["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 Bn(r){return JSON.parse(JSON.stringify(r))}function M$(r){let e=Ts.Platform.isIosApp?"iOS":Ts.Platform.isAndroidApp?"Android":Ts.Platform.isMacOS?"Mac":Ts.Platform.isWin?"Windows":Ts.Platform.isLinux?"Linux":"Obsidian";return`${r} \xB7 ${e}`}function ey(r){return r==="any"?"Any value":r==="datetime"?"Date and time":r&&r[0].toUpperCase()+r.slice(1)}function Ea(r){return typeof r.type=="string"?r.type:"any"}function R$(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 Ot(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 Gt(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 ty(r){if(r<1e3)return String(r);let e=r<1e4?1:0;return`${(r/1e3).toFixed(e)}k`}var ka=10,T$={cancelled:"Paused",stale:"Stopped: changes detected",attention:"Needs attention",blocked:"Stopped",failed:"Failed"};function ry(r){return r.charAt(0).toUpperCase()+r.slice(1)}function I$(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 O$(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 xd(r){return r instanceof Error&&r.name==="AbortError"}var D$=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 Ed(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 D$.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 N$(r,e){let t=r.split(` +`;var P$=require("obsidian");var YF={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 XF(r){return YF[r]??r.replace(/^schema_/,"").replace(/_/g," ")}function QF(r){return[r.type??"",r.field??"",r.code].join("\0")}function Qm(r){return[r.type,r.field,XF(r.code)].filter(Boolean).join(" \xB7 ")}function x$(r){let e=new Map;for(let t of r){let n=QF(t),i=e.get(n);i||(i={key:n,label:Qm(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))}Vt();function $$(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function E$(r,e,t){let n=new Map;for(let i of r){let s=Ge(i.path,i.frontmatter,e,t);s.length&&n.set(i.path,s)}return n}function k$(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 Zm(i,r))n(s).issues+=1;return t}function Zm(r,e){return r.type?[r.type]:e.get(r.path)??[]}function ZF(r,e){let t=jn(r),n=$$(t.schema)?t.schema:{},i=$$(n.value)?n.value:{};return _c(t,e??`${r.name||"new"}.md`,i)}function ej(){return new Promise(r=>window.setTimeout(r,0))}async function A$(r){let e;try{e=ZF(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 ej(),r.isCurrent&&!r.isCurrent()))return null;let a=t!==null&&Ge(o.path,o.frontmatter,r.config,r.types).includes(t.name),c=Ge(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?es(o.path,o.frontmatter,t).length:0,u=c?es(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,P$.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:Qm(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=Zm(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 kc(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 Ts=require("obsidian"),_d="https://connect.mdbase.dev",C$=["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 Bn(r){return JSON.parse(JSON.stringify(r))}function M$(r){let e=Ts.Platform.isIosApp?"iOS":Ts.Platform.isAndroidApp?"Android":Ts.Platform.isMacOS?"Mac":Ts.Platform.isWin?"Windows":Ts.Platform.isLinux?"Linux":"Obsidian";return`${r} \xB7 ${e}`}function ey(r){return r==="any"?"Any value":r==="datetime"?"Date and time":r&&r[0].toUpperCase()+r.slice(1)}function Ea(r){return typeof r.type=="string"?r.type:"any"}function R$(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 Ot(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 Gt(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 ty(r){if(r<1e3)return String(r);let e=r<1e4?1:0;return`${(r/1e3).toFixed(e)}k`}var ka=10,T$={cancelled:"Paused",stale:"Stopped: changes detected",attention:"Needs attention",blocked:"Stopped",failed:"Failed"};function ry(r){return r.charAt(0).toUpperCase()+r.slice(1)}function I$(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 O$(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 xd(r){return r instanceof Error&&r.name==="AbortError"}var D$=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 Ed(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 D$.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 L$(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 yr(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 L$(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 ${yr(i.transferredBytes)} of ${yr(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(r.paused&&!s)return{state:"paused",label:"mdbase: Paused",detail:"Changes wait until you resume sync",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 rj=new Set(["mirror_credentials_missing","invalid_mirror_enrollment","mirror_enrollment_expired","mirror_pairing_not_found","invalid_mirror_pairing","mirror_access_rejected","replica_revoked"]);function Dt(r){let e=ij(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"}:rj.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","mirror_conflict_copy_missing"].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"}:ks(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:`${sj(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 F$(r){return Dt(Object.assign(new Error(r.message),{code:r.code}))}function j$(r){return Array.isArray(r)?r.filter(nj).slice(-tj):[]}function nj(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 ij(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 sj(r,e){return r instanceof Error&&r.message?r.message:e}var kd=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=ka;this.previewComparisons=new Map;this.comparedPreview=null;this.loadingPreviewComparisons=new Set;this.enrollmentVerification="";this.enrollmentAbort=null;this.enrollmentControlUrl=_d;this.enrollmentMirrorName=M$(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=!!this.enrollmentAbort,l=i.preview,u=this.session.safety(),d=!!(l?.plan.actions.length||l?.entries.length),f=c?"Waiting for approval":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":d&&u&&!u.safe?"Review needed":l?.plan.actions.length?"Changes waiting":O$(i.status),p=t.createEl("section",{cls:"mdbase-sync-status"});p.setAttr("data-state",i.status?.state??"checking");let h=p.createDiv({cls:"mdbase-sync-heading"});h.createEl("h2",{text:n.name}),h.createDiv({cls:"mdbase-muted",text:`${f} \xB7 ${I$(i.status?.last_synced_at)}`});let m=h.createDiv({cls:"mdbase-muted mdbase-sync-scope"});m.createSpan({text:this.syncScopeText(n.mode)});let y=m.createEl("button",{cls:"mdbase-link-button",text:"Settings"});if(y.setAttr("aria-label","Open sync settings"),y.onclick=()=>this.ctx.host.openSettings(),i.message&&!i.problem){let v=p.createDiv({cls:"mdbase-inline-message mdbase-notice"});v.createSpan({text:i.message}).setAttr("role","status");let S=this.ctx.iconButton(v,"x","Dismiss sync message");S.onclick=()=>this.session.clearMessage()}if(s){let v=p.createDiv({cls:"mdbase-sync-progress",attr:{"aria-live":"polite"}}),S=i.fileProgress?.totalBytes??i.progress?.total??null,_=i.fileProgress?.transferredBytes??i.progress?.completed??0,E=v.createEl("progress");E.setAttr("aria-label","Sync progress"),E.max=S??1,E.value=S==null?0:_,S==null&&E.removeAttribute("value"),v.createDiv({cls:"mdbase-progress-label",text:i.fileProgress?`${i.fileProgress.direction==="upload"?"Uploading":"Downloading"} ${i.fileProgress.path} \xB7 ${yr(_)} of ${yr(S??0)}`:`${i.progress?.phase==="uploading"?"Uploading local changes":i.progress?.phase==="downloading"?"Downloading collection files":"Applying changes"} \xB7 ${_}${S==null?"":` of ${S}`}`});let A=v.createEl("button",{text:"Stop"});A.setAttr("data-focus-key","sync-stop"),A.onclick=()=>this.session.cancel()}let g=this.ctx.host.otherSyncServices();g.length&&p.createDiv({cls:"mdbase-inline-message mdbase-sync-coexistence",text:`${g.join(" and ")} also ${g.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.`}),c?this.renderApproval(p,!1):a&&this.renderRecoveryCard(p,a);let b=this.ctx.busy||i.busy||s;if(l!==this.comparedPreview&&(this.previewComparisons.clear(),this.comparedPreview=l,this.transferPages.clear()),d&&u&&!u.safe&&l?.plan.actions.length&&p.createDiv({cls:"mdbase-muted mdbase-review-reasons",text:`${u.reasons.join(", ")}.`}),!s&&!a&&!c){let v=p.createDiv({cls:"mdbase-sync-actions"});if(d&&l){let S=ny(l.plan,l.entries.length,b);if(l.plan.actions.length&&!S.actionDisabled){let E=v.createEl("button",{text:S.actionLabel,cls:"mod-cta"});E.setAttr("data-focus-key","sync-apply"),E.disabled=S.actionDisabled,E.onclick=()=>void this.session.apply()}let _=this.ctx.iconButton(v,"refresh-cw","Refresh review");_.disabled=b,_.onclick=()=>void this.session.review()}else{let S=v.createEl("button",{text:i.busy?"Checking\u2026":"Sync now",cls:"mod-cta"});S.setAttr("data-focus-key","sync-now"),S.disabled=b,S.onclick=()=>void this.session.syncNow()}}l&&d&&this.renderMirrorPreview(t,l),i.status?.conflicts.length&&this.renderConflicts(t,i.status),i.status?.local_issues.length&&!d&&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.setAttr("data-focus-key","sync-recovery"),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.setAttr("data-focus-key","sync-diagnostics"),c.disabled=this.ctx.busy,c.onclick=()=>void this.ctx.perform(async()=>{try{await this.ctx.host.copySyncDiagnostics()}finally{this.ctx.pendingFocusKey="sync-diagnostics"}})}}renderApproval(e,t=!0){let n=e.createDiv({cls:"mdbase-approval-link"});if(t&&n.createSpan({text:this.enrollmentVerification?"Waiting for approval \xB7 ":"Connecting\u2026 "}).setAttr("role","status"),this.enrollmentVerification){let s=n.createEl("a",{text:"Open Connect",href:this.enrollmentVerification});s.setAttr("target","_blank"),s.setAttr("rel","noopener noreferrer"),s.setAttr("data-focus-key","approval-link")}let i=n.createEl("button",{text:"Stop waiting"});i.setAttr("data-focus-key","stop-approval"),i.onclick=()=>{this.enrollmentAbort?.abort(),this.enrollmentVerification="",this.ctx.render()}}async reauthorizeCollection(){this.enrollmentAbort?.abort();let e=new AbortController;this.enrollmentAbort=e,this.ctx.pendingFocusKey="stop-approval",this.ctx.render();try{await this.session.reauthorize({signal:e.signal,onVerification:t=>{this.enrollmentVerification=t.verificationUri,this.ctx.message="",window.open(t.verificationUri,"_blank","noopener,noreferrer"),this.ctx.render()},onStatus:t=>{this.ctx.message=t.state==="waiting_for_approval"?"":`Connect is retrying approval (attempt ${t.attempt}).`,this.ctx.render()}}),this.ctx.message=""}catch(t){if(!xd(t))throw t;this.ctx.message="Cancelled. Your files and connection are unchanged.",this.ctx.pendingFocusKey="sync-recovery"}finally{this.enrollmentAbort===e&&(this.enrollmentAbort=null,this.enrollmentVerification="")}}renderHistory(e){let t=this.session.historyRuns();if(!t.length)return;let n=t.filter(d=>d.needsAcknowledgement),i=this.ctx.disclosure(e,"sync-activity","History",n.length>0);i.addClass("mdbase-activity"),i.id="mdbase-sync-activity";let s=i.parentElement;if(this.renderHistoryOnToggle(s),!s.open)return;for(let d of[...n].reverse())this.renderEventRow(i,d);let o=t.filter(d=>!d.needsAcknowledgement);if(!o.length)return;let a=i.createDiv({cls:"mdbase-section-header mdbase-history-controls"}),c=a.createEl("input",{type:"search"});if(c.setAttr("aria-label","Filter history by path"),c.setAttr("data-focus-key","history-search"),c.placeholder="Filter by path",c.value=this.historyQuery,c.oninput=()=>{this.historyQuery=c.value,this.historyLimit=ka,this.ctx.render()},t.length>n.length){let d=a.createEl("button",{text:"Clear history"});d.setAttr("data-focus-key","history-clear"),d.disabled=this.ctx.busy,d.onclick=()=>void this.ctx.perform(async()=>{await this.session.clearHistory(),this.ctx.pendingFocusKey=this.session.historyRuns().length?"disclosure-sync-activity":"destination-sync"})}let l=this.historyQuery.trim().toLowerCase(),u=Wx(o,l).sort((d,f)=>f.finishedAt.localeCompare(d.finishedAt));if(!u.length){i.createDiv({cls:"mdbase-muted",text:l?"No synced files match.":"No completed syncs."});return}for(let d of u.slice(0,this.historyLimit))Vx(d)?this.renderEventRow(i,d):this.renderHistoryRun(i,d,l!=="");if(u.length>this.historyLimit){let d=i.createEl("button",{cls:"mdbase-link-button",text:`Show ${Math.min(ka,u.length-this.historyLimit)} more`});d.setAttr("data-focus-key","history-more"),d.onclick=()=>{this.historyLimit+=ka,this.ctx.render()}}}renderHistoryOnToggle(e){let t=e.open;e.addEventListener("toggle",()=>{this.ctx.containerEl.contains(e)&&e.open!==t&&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:zx(t)});let l=T$[t.outcome];if(c.createSpan({cls:"mdbase-muted",text:l?`${As(t.finishedAt)} \xB7 ${l}`:As(t.finishedAt)}),t.message&&t.outcome!=="applied"&&c.createDiv({text:t.message}),(0,Is.setIcon)(o.createSpan({cls:"mdbase-history-chevron"}),"chevron-right"),this.renderHistoryOnToggle(i),!i.open)return;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.setAttr("data-focus-key",`history-open-${t.id}-${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?`${ry(d.status)}: ${d.message}`:ry(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"),c=`history-event-${t.id}`;a.dataset.disclosure=c,a.open=this.ctx.disclosures.get(c)??!!t.needsAcknowledgement,a.createEl("summary",{text:o}).setAttr("data-focus-key",`disclosure-${c}`),a.createDiv({text:t.message})}else s.createEl("strong",{text:o});if(s.createSpan({cls:"mdbase-muted",text:As(t.finishedAt)}),t.path&&this.ctx.app.vault.getAbstractFileByPath(t.path)){let a=t.path,c=s.createEl("button",{cls:"mdbase-link-button mdbase-transfer-open",text:a});c.setAttr("title",`Open ${a}`),c.setAttr("data-focus-key",`event-open-${t.id}`),c.onclick=()=>void this.ctx.host.openFileByPath(a)}if(t.needsAcknowledgement){let a=i.createEl("button",{text:"Dismiss"});a.setAttr("data-focus-key",`event-dismiss-${t.id}`),a.disabled=this.ctx.busy,a.onclick=()=>void this.ctx.perform(async()=>{await this.session.dismissEvent(t.id),this.ctx.pendingFocusKey=t.message&&t.message!==o?`disclosure-history-event-${t.id}`:"disclosure-sync-activity"})}}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"}),Ed(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.enrollmentAbort){this.renderApproval(t);return}Ot(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.setAttr("data-focus-key","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");Ot(u,"Connect URL",this.enrollmentControlUrl,p=>{this.enrollmentControlUrl=p},{placeholder:_d}),Ot(u,"Collection ID",this.enrollmentCollectionId,p=>{this.enrollmentCollectionId=p},{placeholder:"Choose during approval"}),this.renderFilePolicyControls(u);let f=t.createDiv({cls:"mdbase-actions mdbase-enrollment-actions"}).createEl("button",{text:"Connect"});f.setAttr("title","Opens Connect in your browser to choose a collection"),f.setAttr("data-focus-key","enrollment-connect"),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,this.ctx.pendingFocusKey="stop-approval",this.ctx.render();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:y=>{this.enrollmentVerification=y.verificationUri,this.ctx.message="",window.open(y.verificationUri,"_blank","noopener,noreferrer"),this.ctx.render()},onStatus:y=>{this.ctx.message=y.state==="waiting_for_approval"?"":`Connect is retrying enrollment (attempt ${y.attempt}).`,this.ctx.render()}}),this.enrollmentVerification="",this.enrollmentAbort===p&&(this.enrollmentAbort=null);let h=await this.session.syncNow(),m=this.session.state.preview;if(h==="needs_review"&&m){let y=m.entries.reduce((b,v)=>b+(v.estimatedBytes??0),0),g=m.entries.length;this.ctx.message=`Connected. Review ${g} ${g===1?"item":"items"}${y?` \xB7 ${yr(y)}`:""} before syncing.`,this.ctx.pendingFocusKey="sync-apply"}else this.ctx.message="",this.ctx.pendingFocusKey=this.session.state.problem?"sync-recovery":h==="busy"?"sync-stop":"sync-now"}catch(h){if(this.ctx.pendingFocusKey="enrollment-connect",!xd(h))throw h;this.enrollmentVerification="",this.ctx.message="Cancelled. No files synced."}finally{this.enrollmentAbort===p&&(this.enrollmentAbort=null,this.enrollmentVerification="")}})}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");Gt(u,"Collection",t.session.requested.collectionId),Gt(u,"Phase",t.phase.replace(/_/g," ")),Gt(u,"Connect",t.session.controlUrl);let d=this.ctx.host.connectSync.getSelectiveSync();Gt(u,"Files",d.file_classes.length?d.file_classes.join(", "):"Markdown only")}else{Ot(o,"Device name",this.enrollmentMirrorName,d=>{this.enrollmentMirrorName=d});let u=this.ctx.disclosure(o,"adoption-options","Advanced");Ot(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 ${yr(g)} of ${yr(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=""),!xd(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 ${yr(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"),l.setAttr("data-focus-key","transfer-filter");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 x=E.createDiv({cls:"mdbase-transfer-body"}),R=x.createDiv({cls:"mdbase-transfer-path"}),$=this.ctx.app.vault.getAbstractFileByPath(_.path)?_.path:null;if($){let M=R.createEl("button",{cls:"mdbase-link-button mdbase-transfer-open"});M.createEl("code",{text:_.path}),M.setAttr("title",`Open ${_.path}`),M.setAttr("data-focus-key",`preview-open-${_.path}`),M.onclick=()=>void this.ctx.host.openFileByPath($)}else R.createEl("code",{text:_.path});_.estimatedBytes!==void 0&&R.createSpan({cls:"mdbase-transfer-size",text:yr(_.estimatedBytes)}),_.direction==="attention"||["rename","replace","delete"].includes(_.action)?x.createDiv({text:_.detail}):E.setAttr("title",_.detail);let q=_.recordId;if(q&&_.kind==="document"&&_.action==="update"&&$){let M=`${q}:${_.path}`,V=this.previewComparisons.get(M),P=E.createEl("button",{text:V?"Hide":this.loadingPreviewComparisons.has(M)?"Loading\u2026":"Compare"});P.setAttr("data-focus-key",`preview-compare-${M}`),P.disabled=this.loadingPreviewComparisons.has(M),P.onclick=()=>{V?(this.previewComparisons.delete(M),this.ctx.render()):this.loadPreviewComparison(M,q,_.path)},V&&this.renderConflictComparison(x,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 A=_.createEl("button",{text:`Next ${p.title.toLowerCase()}`});A.disabled=S+250>=h.length,A.setAttr("data-focus-key",`transfer-next-${p.direction}`),A.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?ny(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=l[d].state==="absent",p=a.createEl("button",{text:d==="local"?f?"Delete from Connect":"Keep local":f?"Move local file to trash":"Use hosted",cls:f?"mod-warning":""});p.setAttr("data-focus-key",`resolve-${c}-${d}`),p.disabled=this.ctx.busy,p.onclick=()=>void this.resolveMirrorConflict(i,d,!1)}if(i.path&&l.local.state==="exact"){let d=a.createEl("button",{text:l.remote.state==="absent"?"Keep a local copy":"Keep both"});d.setAttr("data-focus-key",`resolve-${c}-both`),d.disabled=this.ctx.busy,d.onclick=()=>void this.resolveMirrorConflict(i,"remote",!0)}this.renderConflictComparison(s,l,!!i.path)}}}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=Dt(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,n=!1){let i=e.createDiv({cls:"mdbase-conflict-comparison"});if(t.local.state==="absent"&&i.createDiv({cls:"mdbase-muted",text:"No local version."}),t.remote.state==="absent"&&i.createDiv({cls:"mdbase-muted",text:n&&t.local.state==="exact"?"No hosted version. Keeping a local copy saves this device's version before moving the original to trash.":"No hosted version."}),t.entity==="record"){let o=N$(t.local.document??"",t.remote.document??""),a=i.createDiv({cls:"mdbase-conflict-legend"});a.createSpan({text:"\u2212 Local only",cls:"is-local"}),a.createSpan({text:"+ Hosted only",cls:"is-remote"});let c=i.createEl("pre",{cls:"mdbase-conflict-diff"});for(let l of o.lines){let u=c.createEl("div",{cls:`is-${l.kind}`});u.createSpan({text:l.kind==="local"?"\u2212":l.kind==="remote"?"+":" "}),u.createSpan({text:l.value||" "})}o.truncated&&i.createDiv({cls:"mdbase-muted",text:"Diff shortened for a responsive review. Open the local note to inspect it in full."});return}let s=i.createDiv({cls:"mdbase-conflict-sides"});this.renderConflictSide(s,"Local",t.local),this.renderConflictSide(s,"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: ${yr(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({cls:"mdbase-conflict-summary"});o.createEl("strong",{text:i.path}),o.createDiv({text:i.message});let c=s.createDiv({cls:"mdbase-actions"}).createEl("button",{text:"Open file"});c.setAttr("data-focus-key",`issue-open-${i.path}`),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=Dt(e).message}return}await this.session.refreshStatus()}}};var tt=require("obsidian");Vt();function q$(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function Os(r){return typeof r=="number"&&Number.isFinite(r)?r:null}function iy(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 an(r){return typeof r=="string"?r:typeof r=="number"||typeof r=="boolean"||typeof r=="bigint"?String(r):JSON.stringify(r)??""}function sy(r){let e=an(r);return e.length>24?`${e.slice(0,23)}\u2026`:e}function B$(r){let e=typeof r.type=="string"?r.type:"any",t=[];if(e==="enum"&&Array.isArray(r.values)){let n=r.values.map(sy);t.push(n.length>3?`${n.slice(0,3).join(", ")}, +${n.length-3}`:n.join(", ")||"no values")}if(e==="integer"||e==="number"){let n=iy(Os(r.min),Os(r.max));n&&t.push(n)}if(e==="list"){let n=iy(Os(r.min_length),Os(r.max_length),"items");n&&t.push(n),q$(r.items)&&typeof r.items.type=="string"&&t.push(`of ${r.items.type}`)}else{let n=iy(Os(r.min_length),Os(r.max_length),"chars");n&&t.push(n)}if(typeof r.pattern=="string"&&r.pattern&&t.push(`/${sy(r.pattern)}/`),e==="link"&&typeof r.target=="string"&&r.target&&t.push(`\u2192 ${r.target}`),e==="object"&&q$(r.fields)){let n=Object.keys(r.fields).length;t.push(`${n} ${n===1?"field":"fields"}`)}return r.default!==void 0&&t.push(`default ${sy(r.default)}`),r.unique===!0&&t.push("unique"),r.deprecated===!0&&t.push("deprecated"),t}function U$(r,e,t){if(e!==void 0&&an(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 V$(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 Vn=require("@codemirror/commands"),Hn=require("@codemirror/language"),Jt=require("@codemirror/state"),Et=require("@codemirror/view"),Un=require("@lezer/highlight"),oj=Hn.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"))}}),aj=Hn.HighlightStyle.define([{tag:Un.tags.propertyName,color:"var(--text-accent)"},{tag:Un.tags.string,color:"var(--text-normal)"},{tag:Un.tags.number,color:"var(--color-orange)"},{tag:Un.tags.atom,color:"var(--color-purple)"},{tag:Un.tags.comment,color:"var(--text-faint)",fontStyle:"italic"},{tag:Un.tags.meta,color:"var(--text-faint)"},{tag:Un.tags.punctuation,color:"var(--text-muted)"}]),H$=Jt.StateEffect.define(),cj=Jt.StateField.define({create:()=>Et.Decoration.none,update(r,e){let t=r.map(e.changes);for(let n of e.effects){if(!n.is(H$))continue;let i=new Jt.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,Et.Decoration.line({class:`mdbase-yaml-problem-line is-${c}`}))}t=i.finish()}return t},provide:r=>Et.EditorView.decorations.from(r)}),Ad=class{constructor(e){this.editable=new Jt.Compartment;this.applyingExternalChange=!1;this.view=new Et.EditorView({state:Jt.EditorState.create({doc:e.doc,extensions:[(0,Et.lineNumbers)(),(0,Vn.history)(),Hn.indentUnit.of(" "),Jt.EditorState.tabSize.of(2),Et.keymap.of([...Vn.defaultKeymap,...Vn.historyKeymap,Vn.indentWithTab]),oj,(0,Hn.syntaxHighlighting)(aj),cj,Et.EditorView.lineWrapping,this.editable.of(this.editability(e.readOnly)),Et.EditorView.contentAttributes.of({"aria-labelledby":e.labelledBy,"data-focus-key":"yaml-editor",spellcheck:"false"}),Et.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:H$.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[Jt.EditorState.readOnly.of(e),Et.EditorView.editable.of(!e)]}};function z$(r,e=2){let t=r.match(/line (\d+)/i)??r.match(/\((\d+):\d+\)/);return t?Number(t[1])+e-1:null}function oy(r,e){if(!e)return null;let t=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),n=new RegExp(`^\\s*(?:-\\s+)?["']?${t}["']?\\s*:`),s=r.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 yr(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 N$(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 ${yr(i.transferredBytes)} of ${yr(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(r.busy)return r.paused?{state:"syncing",label:"mdbase: Stopping\u2026",detail:"Stopping synchronization",destination:"sync"}:{state:"syncing",label:"mdbase: Checking\u2026",detail:"Checking sync",destination:"sync"};if(r.paused&&!s)return{state:"paused",label:"mdbase: Paused",detail:"Changes wait until you resume sync",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 rj=new Set(["mirror_credentials_missing","invalid_mirror_enrollment","mirror_enrollment_expired","mirror_pairing_not_found","invalid_mirror_pairing","mirror_access_rejected","replica_revoked"]);function Dt(r){let e=ij(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"}:rj.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","mirror_conflict_copy_missing"].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"}:ks(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:`${sj(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 F$(r){return Dt(Object.assign(new Error(r.message),{code:r.code}))}function j$(r){return Array.isArray(r)?r.filter(nj).slice(-tj):[]}function nj(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 ij(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 sj(r,e){return r instanceof Error&&r.message?r.message:e}var kd=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=ka;this.previewComparisons=new Map;this.comparedPreview=null;this.loadingPreviewComparisons=new Set;this.enrollmentVerification="";this.enrollmentAbort=null;this.enrollmentControlUrl=_d;this.enrollmentMirrorName=M$(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=!!this.enrollmentAbort,l=i.preview,u=this.session.safety(),d=!!(l?.plan.actions.length||l?.entries.length),f=c?"Waiting for approval":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":d&&u&&!u.safe?"Review needed":l?.plan.actions.length?"Changes waiting":O$(i.status),p=t.createEl("section",{cls:"mdbase-sync-status"});p.setAttr("data-state",i.status?.state??"checking");let h=p.createDiv({cls:"mdbase-sync-heading"});h.createEl("h2",{text:n.name}),h.createDiv({cls:"mdbase-muted",text:`${f} \xB7 ${I$(i.status?.last_synced_at)}`});let m=h.createDiv({cls:"mdbase-muted mdbase-sync-scope"});m.createSpan({text:this.syncScopeText(n.mode)});let y=m.createEl("button",{cls:"mdbase-link-button",text:"Settings"});if(y.setAttr("aria-label","Open sync settings"),y.onclick=()=>this.ctx.host.openSettings(),i.message&&!i.problem){let v=p.createDiv({cls:"mdbase-inline-message mdbase-notice"});v.createSpan({text:i.message}).setAttr("role","status");let S=this.ctx.iconButton(v,"x","Dismiss sync message");S.onclick=()=>this.session.clearMessage()}if(s){let v=p.createDiv({cls:"mdbase-sync-progress",attr:{"aria-live":"polite"}}),S=i.fileProgress?.totalBytes??i.progress?.total??null,_=i.fileProgress?.transferredBytes??i.progress?.completed??0,E=v.createEl("progress");E.setAttr("aria-label","Sync progress"),E.max=S??1,E.value=S==null?0:_,S==null&&E.removeAttribute("value"),v.createDiv({cls:"mdbase-progress-label",text:i.fileProgress?`${i.fileProgress.direction==="upload"?"Uploading":"Downloading"} ${i.fileProgress.path} \xB7 ${yr(_)} of ${yr(S??0)}`:`${i.progress?.phase==="uploading"?"Uploading local changes":i.progress?.phase==="downloading"?"Downloading collection files":"Applying changes"} \xB7 ${_}${S==null?"":` of ${S}`}`});let A=v.createEl("button",{text:"Stop"});A.setAttr("data-focus-key","sync-stop"),A.onclick=()=>this.session.cancel()}let g=this.ctx.host.otherSyncServices();g.length&&p.createDiv({cls:"mdbase-inline-message mdbase-sync-coexistence",text:`${g.join(" and ")} also ${g.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.`}),c?this.renderApproval(p,!1):a&&this.renderRecoveryCard(p,a);let b=this.ctx.busy||i.busy||s;if(l!==this.comparedPreview&&(this.previewComparisons.clear(),this.loadingPreviewComparisons.clear(),this.comparedPreview=l,this.transferPages.clear()),d&&u&&!u.safe&&l?.plan.actions.length&&p.createDiv({cls:"mdbase-muted mdbase-review-reasons",text:`${u.reasons.join(", ")}.`}),!s&&!a&&!c){let v=p.createDiv({cls:"mdbase-sync-actions"});if(d&&l){let S=ny(l.plan,l.entries.length,b);if(l.plan.actions.length&&!S.actionDisabled){let E=v.createEl("button",{text:S.actionLabel,cls:"mod-cta"});E.setAttr("data-focus-key","sync-apply"),E.disabled=S.actionDisabled,E.onclick=()=>void this.session.apply()}let _=this.ctx.iconButton(v,"refresh-cw","Refresh review");_.disabled=b,_.onclick=()=>void this.session.review()}else{let S=v.createEl("button",{text:i.busy?"Checking\u2026":"Sync now",cls:"mod-cta"});S.setAttr("data-focus-key","sync-now"),S.disabled=b,S.onclick=()=>void this.session.syncNow()}}l&&d&&this.renderMirrorPreview(t,l),i.status?.conflicts.length&&this.renderConflicts(t,i.status),i.status?.local_issues.length&&!d&&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.setAttr("data-focus-key","sync-recovery"),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.setAttr("data-focus-key","sync-diagnostics"),c.disabled=this.ctx.busy,c.onclick=()=>void this.ctx.perform(async()=>{try{await this.ctx.host.copySyncDiagnostics()}finally{this.ctx.pendingFocusKey="sync-diagnostics"}})}}renderApproval(e,t=!0){let n=e.createDiv({cls:"mdbase-approval-link"});if(t&&n.createSpan({text:this.enrollmentVerification?"Waiting for approval \xB7 ":"Connecting\u2026 "}).setAttr("role","status"),this.enrollmentVerification){let s=n.createEl("a",{text:"Open Connect",href:this.enrollmentVerification});s.setAttr("target","_blank"),s.setAttr("rel","noopener noreferrer"),s.setAttr("data-focus-key","approval-link")}let i=n.createEl("button",{text:"Stop waiting"});i.setAttr("data-focus-key","stop-approval"),i.onclick=()=>{this.enrollmentAbort?.abort(),this.enrollmentVerification="",this.ctx.render()}}async reauthorizeCollection(){this.enrollmentAbort?.abort();let e=new AbortController;this.enrollmentAbort=e,this.ctx.pendingFocusKey="stop-approval",this.ctx.render();try{await this.session.reauthorize({signal:e.signal,onVerification:t=>{this.enrollmentVerification=t.verificationUri,this.ctx.message="",window.open(t.verificationUri,"_blank","noopener,noreferrer"),this.ctx.render()},onStatus:t=>{this.ctx.message=t.state==="waiting_for_approval"?"":`Connect is retrying approval (attempt ${t.attempt}).`,this.ctx.render()}}),this.ctx.message=""}catch(t){if(!xd(t))throw t;this.ctx.message="Cancelled. Your files and connection are unchanged.",this.ctx.pendingFocusKey="sync-recovery"}finally{this.enrollmentAbort===e&&(this.enrollmentAbort=null,this.enrollmentVerification="")}}renderHistory(e){let t=this.session.historyRuns();if(!t.length)return;let n=t.filter(d=>d.needsAcknowledgement),i=this.ctx.disclosure(e,"sync-activity","History",n.length>0);i.addClass("mdbase-activity"),i.id="mdbase-sync-activity";let s=i.parentElement;if(this.renderHistoryOnToggle(s),!s.open)return;for(let d of[...n].reverse())this.renderEventRow(i,d);let o=t.filter(d=>!d.needsAcknowledgement);if(!o.length)return;let a=i.createDiv({cls:"mdbase-section-header mdbase-history-controls"}),c=a.createEl("input",{type:"search"});if(c.setAttr("aria-label","Filter history by path"),c.setAttr("data-focus-key","history-search"),c.placeholder="Filter by path",c.value=this.historyQuery,c.oninput=()=>{this.historyQuery=c.value,this.historyLimit=ka,this.ctx.render()},t.length>n.length){let d=a.createEl("button",{text:"Clear history"});d.setAttr("data-focus-key","history-clear"),d.disabled=this.ctx.busy,d.onclick=()=>void this.ctx.perform(async()=>{await this.session.clearHistory(),this.ctx.pendingFocusKey=this.session.historyRuns().length?"disclosure-sync-activity":"destination-sync"})}let l=this.historyQuery.trim().toLowerCase(),u=Wx(o,l).sort((d,f)=>f.finishedAt.localeCompare(d.finishedAt));if(!u.length){i.createDiv({cls:"mdbase-muted",text:l?"No synced files match.":"No completed syncs."});return}for(let d of u.slice(0,this.historyLimit))Vx(d)?this.renderEventRow(i,d):this.renderHistoryRun(i,d,l!=="");if(u.length>this.historyLimit){let d=i.createEl("button",{cls:"mdbase-link-button",text:`Show ${Math.min(ka,u.length-this.historyLimit)} more`});d.setAttr("data-focus-key","history-more"),d.onclick=()=>{this.historyLimit+=ka,this.ctx.render()}}}renderHistoryOnToggle(e){let t=e.open;e.addEventListener("toggle",()=>{this.ctx.containerEl.contains(e)&&e.open!==t&&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:zx(t)});let l=T$[t.outcome];if(c.createSpan({cls:"mdbase-muted",text:l?`${As(t.finishedAt)} \xB7 ${l}`:As(t.finishedAt)}),t.message&&t.outcome!=="applied"&&c.createDiv({text:t.message}),(0,Is.setIcon)(o.createSpan({cls:"mdbase-history-chevron"}),"chevron-right"),this.renderHistoryOnToggle(i),!i.open)return;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.setAttr("data-focus-key",`history-open-${t.id}-${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?`${ry(d.status)}: ${d.message}`:ry(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"),c=`history-event-${t.id}`;a.dataset.disclosure=c,a.open=this.ctx.disclosures.get(c)??!!t.needsAcknowledgement,a.createEl("summary",{text:o}).setAttr("data-focus-key",`disclosure-${c}`),a.createDiv({text:t.message})}else s.createEl("strong",{text:o});if(s.createSpan({cls:"mdbase-muted",text:As(t.finishedAt)}),t.path&&this.ctx.app.vault.getAbstractFileByPath(t.path)){let a=t.path,c=s.createEl("button",{cls:"mdbase-link-button mdbase-transfer-open",text:a});c.setAttr("title",`Open ${a}`),c.setAttr("data-focus-key",`event-open-${t.id}`),c.onclick=()=>void this.ctx.host.openFileByPath(a)}if(t.needsAcknowledgement){let a=i.createEl("button",{text:"Dismiss"});a.setAttr("data-focus-key",`event-dismiss-${t.id}`),a.disabled=this.ctx.busy,a.onclick=()=>void this.ctx.perform(async()=>{await this.session.dismissEvent(t.id),this.ctx.pendingFocusKey=t.message&&t.message!==o?`disclosure-history-event-${t.id}`:"disclosure-sync-activity"})}}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"}),Ed(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.enrollmentAbort){this.renderApproval(t);return}Ot(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.setAttr("data-focus-key","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");Ot(u,"Connect URL",this.enrollmentControlUrl,p=>{this.enrollmentControlUrl=p},{placeholder:_d}),Ot(u,"Collection ID",this.enrollmentCollectionId,p=>{this.enrollmentCollectionId=p},{placeholder:"Choose during approval"}),this.renderFilePolicyControls(u);let f=t.createDiv({cls:"mdbase-actions mdbase-enrollment-actions"}).createEl("button",{text:"Connect"});f.setAttr("title","Opens Connect in your browser to choose a collection"),f.setAttr("data-focus-key","enrollment-connect"),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,this.ctx.pendingFocusKey="stop-approval",this.ctx.render();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:y=>{this.enrollmentVerification=y.verificationUri,this.ctx.message="",window.open(y.verificationUri,"_blank","noopener,noreferrer"),this.ctx.render()},onStatus:y=>{this.ctx.message=y.state==="waiting_for_approval"?"":`Connect is retrying enrollment (attempt ${y.attempt}).`,this.ctx.render()}}),this.enrollmentVerification="",this.enrollmentAbort===p&&(this.enrollmentAbort=null);let h=await this.session.syncNow(),m=this.session.state.preview;if(h==="needs_review"&&m){let y=m.entries.reduce((b,v)=>b+(v.estimatedBytes??0),0),g=m.entries.length;this.ctx.message=`Connected. Review ${g} ${g===1?"item":"items"}${y?` \xB7 ${yr(y)}`:""} before syncing.`,this.ctx.pendingFocusKey="sync-apply"}else this.ctx.message="",this.ctx.pendingFocusKey=this.session.state.problem?"sync-recovery":h==="busy"?"sync-stop":"sync-now"}catch(h){if(this.ctx.pendingFocusKey="enrollment-connect",!xd(h))throw h;this.enrollmentVerification="",this.ctx.message="Cancelled. No files synced."}finally{this.enrollmentAbort===p&&(this.enrollmentAbort=null,this.enrollmentVerification="")}})}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");Gt(u,"Collection",t.session.requested.collectionId),Gt(u,"Phase",t.phase.replace(/_/g," ")),Gt(u,"Connect",t.session.controlUrl);let d=this.ctx.host.connectSync.getSelectiveSync();Gt(u,"Files",d.file_classes.length?d.file_classes.join(", "):"Markdown only")}else{Ot(o,"Device name",this.enrollmentMirrorName,d=>{this.enrollmentMirrorName=d});let u=this.ctx.disclosure(o,"adoption-options","Advanced");Ot(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 ${yr(g)} of ${yr(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=""),!xd(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 ${yr(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"),l.setAttr("data-focus-key","transfer-filter");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 x=E.createDiv({cls:"mdbase-transfer-body"}),R=x.createDiv({cls:"mdbase-transfer-path"}),$=this.ctx.app.vault.getAbstractFileByPath(_.path)?_.path:null;if($){let M=R.createEl("button",{cls:"mdbase-link-button mdbase-transfer-open"});M.createEl("code",{text:_.path}),M.setAttr("title",`Open ${_.path}`),M.setAttr("data-focus-key",`preview-open-${_.path}`),M.onclick=()=>void this.ctx.host.openFileByPath($)}else R.createEl("code",{text:_.path});_.estimatedBytes!==void 0&&R.createSpan({cls:"mdbase-transfer-size",text:yr(_.estimatedBytes)}),_.direction==="attention"||["rename","replace","delete"].includes(_.action)?x.createDiv({text:_.detail}):E.setAttr("title",_.detail);let q=_.recordId;if(q&&_.kind==="document"&&_.action==="update"&&$){let M=`${q}:${_.path}`,V=this.previewComparisons.get(M),P=E.createEl("button",{text:V?"Hide":this.loadingPreviewComparisons.has(M)?"Loading\u2026":"Compare"});P.setAttr("data-focus-key",`preview-compare-${M}`),P.disabled=this.loadingPreviewComparisons.has(M),P.onclick=()=>{V?(this.previewComparisons.delete(M),this.ctx.render()):this.loadPreviewComparison(M,q,_.path,t)},V&&this.renderConflictComparison(x,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 A=_.createEl("button",{text:`Next ${p.title.toLowerCase()}`});A.disabled=S+250>=h.length,A.setAttr("data-focus-key",`transfer-next-${p.direction}`),A.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?ny(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){let d=this.ctx.busy||this.session.state.busy||this.session.isSyncing();for(let f of["local","remote"]){let p=l[f].state==="absent",h=a.createEl("button",{text:f==="local"?p?"Delete from Connect":"Keep local":p?"Move local file to trash":"Use hosted",cls:p?"mod-warning":""});h.setAttr("data-focus-key",`resolve-${c}-${f}`),h.disabled=d,h.onclick=()=>void this.resolveMirrorConflict(i,f,!1)}if(i.path&&l.local.state==="exact"){let f=a.createEl("button",{text:l.remote.state==="absent"?"Keep a local copy":"Keep both"});f.setAttr("data-focus-key",`resolve-${c}-both`),f.disabled=d,f.onclick=()=>void this.resolveMirrorConflict(i,"remote",!0)}this.renderConflictComparison(s,l,!!i.path)}}}async loadPreviewComparison(e,t,n,i){if(this.session.state.preview===i){this.loadingPreviewComparisons.add(e),this.ctx.render();try{let s=await this.ctx.host.connectSync.recordComparison(t,n);this.session.state.preview===i&&this.previewComparisons.set(e,s)}catch(s){this.session.state.preview===i&&(this.ctx.message=Dt(s).message)}finally{this.session.state.preview===i&&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,n=!1){let i=e.createDiv({cls:"mdbase-conflict-comparison"});if(t.local.state==="absent"&&i.createDiv({cls:"mdbase-muted",text:"No local version."}),t.remote.state==="absent"&&i.createDiv({cls:"mdbase-muted",text:n&&t.local.state==="exact"?"No hosted version. Keeping a local copy saves this device's version before moving the original to trash.":"No hosted version."}),t.entity==="record"){let o=L$(t.local.document??"",t.remote.document??""),a=i.createDiv({cls:"mdbase-conflict-legend"});a.createSpan({text:"\u2212 Local only",cls:"is-local"}),a.createSpan({text:"+ Hosted only",cls:"is-remote"});let c=i.createEl("pre",{cls:"mdbase-conflict-diff"});for(let l of o.lines){let u=c.createEl("div",{cls:`is-${l.kind}`});u.createSpan({text:l.kind==="local"?"\u2212":l.kind==="remote"?"+":" "}),u.createSpan({text:l.value||" "})}o.truncated&&i.createDiv({cls:"mdbase-muted",text:"Diff shortened for a responsive review. Open the local note to inspect it in full."});return}let s=i.createDiv({cls:"mdbase-conflict-sides"});this.renderConflictSide(s,"Local",t.local),this.renderConflictSide(s,"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: ${yr(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({cls:"mdbase-conflict-summary"});o.createEl("strong",{text:i.path}),o.createDiv({text:i.message});let c=s.createDiv({cls:"mdbase-actions"}).createEl("button",{text:"Open file"});c.setAttr("data-focus-key",`issue-open-${i.path}`),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=Dt(e).message}return}await this.session.refreshStatus()}}};var tt=require("obsidian");Vt();function q$(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function Os(r){return typeof r=="number"&&Number.isFinite(r)?r:null}function iy(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 an(r){return typeof r=="string"?r:typeof r=="number"||typeof r=="boolean"||typeof r=="bigint"?String(r):JSON.stringify(r)??""}function sy(r){let e=an(r);return e.length>24?`${e.slice(0,23)}\u2026`:e}function B$(r){let e=typeof r.type=="string"?r.type:"any",t=[];if(e==="enum"&&Array.isArray(r.values)){let n=r.values.map(sy);t.push(n.length>3?`${n.slice(0,3).join(", ")}, +${n.length-3}`:n.join(", ")||"no values")}if(e==="integer"||e==="number"){let n=iy(Os(r.min),Os(r.max));n&&t.push(n)}if(e==="list"){let n=iy(Os(r.min_length),Os(r.max_length),"items");n&&t.push(n),q$(r.items)&&typeof r.items.type=="string"&&t.push(`of ${r.items.type}`)}else{let n=iy(Os(r.min_length),Os(r.max_length),"chars");n&&t.push(n)}if(typeof r.pattern=="string"&&r.pattern&&t.push(`/${sy(r.pattern)}/`),e==="link"&&typeof r.target=="string"&&r.target&&t.push(`\u2192 ${r.target}`),e==="object"&&q$(r.fields)){let n=Object.keys(r.fields).length;t.push(`${n} ${n===1?"field":"fields"}`)}return r.default!==void 0&&t.push(`default ${sy(r.default)}`),r.unique===!0&&t.push("unique"),r.deprecated===!0&&t.push("deprecated"),t}function U$(r,e,t){if(e!==void 0&&an(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 V$(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 Vn=require("@codemirror/commands"),Hn=require("@codemirror/language"),Jt=require("@codemirror/state"),Et=require("@codemirror/view"),Un=require("@lezer/highlight"),oj=Hn.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"))}}),aj=Hn.HighlightStyle.define([{tag:Un.tags.propertyName,color:"var(--text-accent)"},{tag:Un.tags.string,color:"var(--text-normal)"},{tag:Un.tags.number,color:"var(--color-orange)"},{tag:Un.tags.atom,color:"var(--color-purple)"},{tag:Un.tags.comment,color:"var(--text-faint)",fontStyle:"italic"},{tag:Un.tags.meta,color:"var(--text-faint)"},{tag:Un.tags.punctuation,color:"var(--text-muted)"}]),H$=Jt.StateEffect.define(),cj=Jt.StateField.define({create:()=>Et.Decoration.none,update(r,e){let t=r.map(e.changes);for(let n of e.effects){if(!n.is(H$))continue;let i=new Jt.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,Et.Decoration.line({class:`mdbase-yaml-problem-line is-${c}`}))}t=i.finish()}return t},provide:r=>Et.EditorView.decorations.from(r)}),Ad=class{constructor(e){this.editable=new Jt.Compartment;this.applyingExternalChange=!1;this.view=new Et.EditorView({state:Jt.EditorState.create({doc:e.doc,extensions:[(0,Et.lineNumbers)(),(0,Vn.history)(),Hn.indentUnit.of(" "),Jt.EditorState.tabSize.of(2),Et.keymap.of([...Vn.defaultKeymap,...Vn.historyKeymap,Vn.indentWithTab]),oj,(0,Hn.syntaxHighlighting)(aj),cj,Et.EditorView.lineWrapping,this.editable.of(this.editability(e.readOnly)),Et.EditorView.contentAttributes.of({"aria-labelledby":e.labelledBy,"data-focus-key":"yaml-editor",spellcheck:"false"}),Et.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:H$.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[Jt.EditorState.readOnly.of(e),Et.EditorView.editable.of(!e)]}};function z$(r,e=2){let t=r.match(/line (\d+)/i)??r.match(/\((\d+):\d+\)/);return t?Number(t[1])+e-1:null}function oy(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 Pd=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&&!tt.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?E$(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:k$(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 A$({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"});Gt(s,"Files replaced",String(t.operations.length)),Gt(s,"Type definitions",String(t.typeSummaries.length)),Gt(s,"Record reads verified",String(t.recordsVerified)),t.recordsSkipped&&Gt(s,"Records skipped",String(t.recordsSkipped)),Gt(s,"Record files rewritten","0"),Gt(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 tt.Modal(this.ctx.app);u.titleEl.setText("Current source and recovered draft");let d=s.yamlDraft;if(d===void 0)try{d=gt(Aa(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?gt(Aa(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 tt.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=xa(this.originalModel,t),s=Sa(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=Sa(t,{knownTypes:this.typeEntries().map(M=>M.name),contracts:this.ctx.schema?.contracts.values()}),s=e.createEl("section",{cls:"mdbase-editor-section"});s.id="mdbase-section-identity";let o=Ot(s,"Name",t.name,M=>{t.name=M,this.markDirty()});o.disabled=n;let a=Ot(s,"Description",t.description,M=>{t.description=M,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 M of t.fields)d.createEl("option",{value:M.name,text:M.name||"Unnamed field"});t.displayNameKey&&!t.fields.some(M=>M.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=Ot(h,"Path glob",t.matchPathGlob,M=>{t.matchPathGlob=M,this.markDirty()},{placeholder:"Projects/**/*.md"});m.disabled=n;let y=Ot(h,"Fields present",t.matchFieldsPresent,M=>{t.matchFieldsPresent=M,this.markDirty()},{description:"Comma-separated frontmatter keys."});y.disabled=n;let g=Ot(h,"Where",t.matchWhere,M=>{t.matchWhere=M,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 M=this.ctx.iconButton(S,"fold-vertical","Collapse all fields");M.onclick=()=>{this.expandedFields.clear(),this.ctx.render()}}let _=this.ctx.iconButton(S,"plus","Add field");if(_.disabled=n,_.onclick=()=>{let M={type:"string"};t.fields.push({name:"",definition:M}),this.expandedFields.add(this.fieldId(M)),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"}),A=this.fieldQuery.trim().toLowerCase(),x=t.fields.filter(M=>!A||this.fieldMatches(M.name,M.definition,A));for(let M of x){let V=t.fields.indexOf(M);this.renderFieldRow(E,M,V,n)}x.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 $=Ot(c,"Path pattern",t.pathPattern,M=>{t.pathPattern=M,this.markDirty()},{placeholder:"Notes/{title}.md"});if($.disabled=n,this.renderContractEditor(e,t,n),!this.dirty&&!i.length)return;let q=this.ctx.disclosure(e,"type-review","Changes",i.some(M=>M.severity==="error"));if(q.id="mdbase-section-review",this.dirty&&this.fillImpact(q.createDiv({cls:"mdbase-impact"})),i.length){let M=q.createDiv({cls:"mdbase-diagnostic-summary"}),V=i.filter(C=>C.severity==="error").length,P=i.length-V;M.createEl("strong",{text:`${V} ${V===1?"error":"errors"} \xB7 ${P} ${P===1?"warning":"warnings"}`});for(let C of i.slice(0,12)){let Ve=M.createDiv({cls:"mdbase-diagnostic-item"});Ve.setAttr("data-severity",C.severity),Ve.createEl("code",{text:C.path}),Ve.createSpan({text:C.message})}}if(this.dirty){let M=q.createEl("ul");for(let V of xa(this.originalModel,t))M.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{m$(t,f),this.markDirty(!0)}catch(p){new tt.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=()=>{y$(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=ba(i),d=va(t),f=u.filter(b=>Rs(n,b)),p=u.filter(b=>b.required),h=p.filter(b=>Rs(n,b)).length,m=o.createEl("details");m.open=h$.reference===v),_=wa(b,S),E=g.createDiv({cls:`mdbase-contract-mapping-row ${_.level}`}),A=E.createDiv({cls:"mdbase-contract-field-definition"});A.createEl("code",{text:b.reference}),A.createSpan({cls:b.required?"mdbase-contract-required":"mdbase-contract-optional",text:b.required?"Required":"Optional"}),A.createEl("small",{text:b.description||b$(b.schema)});let x=E.createEl("select");x.setAttr("aria-label",`${n.contract} ${b.reference} source field`),x.setAttr("aria-invalid",_.level==="error"?"true":"false"),x.disabled=s,x.createEl("option",{value:"",text:b.required?"Choose a source field":"Not exposed"});for(let $ of d){let q=wa(b,$),M=x.createEl("option",{value:$.reference,text:`${$.reference} \xB7 ${$.type}${q.level==="warning"?" \xB7 review":""}`});M.disabled=q.level==="error"}x.value=v,x.onchange=()=>{g$(n,b.reference,x.value||void 0),this.markDirty(!0)};let R=E.createDiv({cls:"mdbase-contract-mapping-status"});R.createEl("strong",{text:_.label}),R.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(_)&&(Wm(n,_),this.markDirty())},"Settings",s);else{let _=S.createEl("button",{text:"Configure settings"});_.disabled=s,_.onclick=()=>{let E=_a(i.binding_schema);Se(E)&&(Wm(n,E),this.markDirty(!0))}}}}renderContractSchemaValue(e,t,n,i,s,o){if(qn(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]:_a(b)})}}return}this.renderContractSchemaControl(e,t,n,i,s,o)}renderContractSchemaControl(e,t,n,i,s,o){let a=qn(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,_a(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,tt.setIcon)(l,"chevron-right"),c.createSpan({cls:"mdbase-field-summary-name",text:a}),c.createSpan({cls:"mdbase-field-summary-type",text:ey(Ea(t))});let u=c.createSpan({cls:"mdbase-field-summary-rules"}),d=()=>{u.textContent=B$(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 C$)p.createEl("option",{value:y,text:ey(y)});p.value=Ea(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 tt.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=Ea(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:an(_)});let v=b.findIndex(S=>JSON.stringify(S)===JSON.stringify(t.default));t.default!==void 0&&v===-1?(g.createEl("option",{value:"missing",text:`${an(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?"":an(t.default),m.disabled=i.readOnly;let y=f.createDiv({cls:"mdbase-constraint-error"});m.oninput=()=>{let g=V$(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} ${Ea(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=an(p),m.disabled=n.readOnly,m.oninput=()=>{c[f]=U$(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}: ${an(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 ${an(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=R$(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 tt.Notice("Nested field name is required."),h.value=f;return}if(m!==f&&Object.prototype.hasOwnProperty.call(s,m)){new tt.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?Bn(s.model):i;this.selectedPath=e,this.model=a,this.originalModel=Bn(i),this.yamlDraft=o&&s.yamlDraft!==void 0?s.yamlDraft:`${gt(Aa(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?Bn(e.model):Km();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=`${gt(Aa(this.model),this.model.body)} -`}catch(t){new tt.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(` +`}catch(t){new tt.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=Te(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:z$(e.error)};if(e.frontmatter.kind!=="mdbase.type")return{error:"Canonical v0.3 type YAML requires kind: mdbase.type.",line:oy(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"}]:Sa(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:oy(this.yamlDraft,n),message:t.message,severity:t.severity==="error"?"error":"warning"}})}readYamlDraftIntoModel(){let e=this.modelFromYamlDraft();return"error"in e?(new tt.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=Sa(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 tt.Notice(t[0].message);return}let n=xa(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:xa(this.originalModel,this.model).filter(l=>l.risk!=="safe");if(!await new Ec(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=Bn(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:Bn(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=Bn(n),this.yamlDraft=`${gt(Aa(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 Aa(r){return r.specProfile==="v0.3"&&!r.readOnlyReason?jn(r):Bn(r.originalFrontmatter??{name:r.name,fields:Object.fromEntries(r.fields.map(e=>[e.name,e.definition]))})}var Lr="mdbase-workspace-view",Cd=class r 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 Pd(this);this.sync=new kd(this);this.issues=new wd(this);this.navigationId=`mdbase-workspace-${++r.nextNavigationId}`;this.refreshVersion=0;this.unsubscribeSync=null;this.syncRenderTimer=null}static{this.nextNavigationId=0}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 Lr}getDisplayText(){return"mdbase"}getIcon(){return $a}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()})}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())return;if(this.schema=s,this.destination==="types"){if(await this.types.onSchemaLoaded(t,i),!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)}else this.destination==="sync"&&await this.sync.refresh();if(!i())return;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==="types"?this.refresh():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"),s.id=`${this.navigationId}-${this.destination}-panel`,s.setAttr("role","tabpanel"),s.setAttr("aria-labelledby",`${this.navigationId}-${this.destination}-tab`),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&&(this.focusTarget(t,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}syncTabStatus(){if(this.destination==="sync"||!this.host.getMirrorProfile())return null;let{problem:t,paused:n,status:i,progress:s,fileProgress:o}=this.host.sync.state;if(s||o)return null;let a=t?.kind??(n?"paused":i?.recovery_required?"recovery":null);return!a||a==="busy"?null:{kind:a,label:{offline:"Offline",auth:"Sign in",device:"Set up",internal:"Error",decision:"Review",recovery:"Review",paused:"Paused"}[a],detail:t?.title??(n?"Sync is paused":"Synchronization needs recovery")}}renderTopbarOnly(){let t=this.containerEl.querySelector(".mdbase-topbar");if(!t)return;let n=this.captureRenderSnapshot(t),i=this.containerEl.ownerDocument.createElement("div");this.renderTopbar(i);let s=i.firstElementChild;s&&(t.replaceWith(s),this.restoreRenderSnapshot(s,n))}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=this.focusTarget(t,n.focusKey);i?.focus({preventScroll:!0}),(i instanceof HTMLInputElement||i instanceof HTMLTextAreaElement)&&n.selectionStart!==null&&n.selectionEnd!==null&&i.setSelectionRange(n.selectionStart,n.selectionEnd)}focusTarget(t,n){return Array.from(t.querySelectorAll("[data-focus-key]")).find(i=>i.getAttr("data-focus-key")===n)}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"),i.setAttr("aria-label","mdbase destinations");let s=[["types","Types"],["sync","Sync"],["issues","Issues"]];for(let[o,[a,c]]of s.entries()){let l=i.createEl("button",{text:c,cls:"clickable-icon"});if(l.addClass("mdbase-nav-button"),l.setAttr("role","tab"),l.id=`${this.navigationId}-${a}-tab`,this.destination===a&&l.setAttr("aria-controls",`${this.navigationId}-${a}-panel`),l.tabIndex=this.destination===a?0:-1,l.setAttr("data-focus-key",`destination-${a}`),l.setAttr("aria-selected",String(this.destination===a)),this.destination===a&&l.addClass("is-active"),a==="issues"&&this.host.getIssues().length){let f=this.host.getIssues().length;l.createSpan({cls:"mdbase-count",text:ty(f)}).setAttr("title",`${f} issues`),l.setAttr("aria-label",`Issues \xB7 ${f} validation ${f===1?"issue":"issues"}`)}let u=a==="sync"?this.syncTabStatus():null,d=a==="sync"?this.syncAttention():null;if(u){let f=l.createSpan({cls:"mdbase-count mdbase-nav-status",text:u.label});f.setAttr("data-kind",u.kind),f.setAttr("title",u.detail),l.setAttr("aria-label",`Sync \xB7 ${u.detail}`)}else d&&(l.createSpan({cls:"mdbase-count",text:ty(d.count)}).setAttr("title",d.label),l.setAttr("aria-label",`Sync \xB7 ${d.label}`));l.onclick=()=>this.showDestination(a),l.onkeydown=f=>{let p=f.key==="ArrowRight"?(o+1)%s.length:f.key==="ArrowLeft"?(o+s.length-1)%s.length:f.key==="Home"?0:f.key==="End"?s.length-1:null;p!==null&&(f.preventDefault(),this.pendingFocusKey=`destination-${s[p][0]}`,this.showDestination(s[p][0]))}}}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 Pa=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 K$=require("obsidian");var Md=class extends K$.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=Kx(this.runs,this.path).map(({run:i,file:s})=>({at:s.at,label:i.summary??Gx(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:As(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 De=require("obsidian");var lj=[["image","Images"],["audio","Audio"],["video","Video"],["pdf","PDFs"],["other","Other files"]],Rd=class extends De.PluginSettingTab{constructor(t,n){super(t,n);this.plugin=n}display(){let{containerEl:t,plugin:n}=this;t.empty(),new De.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 De.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 De.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 De.Setting(t).setName("Sync").setHeading(),!i){new De.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 De.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);try{await n.openWorkspace("sync").then(u=>u.reconnectCollection())}catch(u){new De.Notice(u instanceof Error?u.message:String(u))}finally{l.setDisabled(!1)}})),new De.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{return await n.sync.configureSelectiveSync(l),!0}catch(u){return new De.Notice(u instanceof Error?u.message:String(u)),this.display(),!1}};for(let[l,u]of lj)new De.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 De.Setting(t).setName("Excluded folders").setDesc($d);Ed(this.app,c.controlEl,a,l=>{a=l}),c.addButton(l=>l.setButtonText("Apply").onClick(async()=>{l.setDisabled(!0);try{await o({...n.connectSync.getSelectiveSync(),excluded_folders:a})&&new De.Notice("Excluded folders updated. The next sync applies them.")}finally{l.setDisabled(!1)}})),new De.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 De.Notice(n.sync.state.message)}catch(d){new De.Notice(d instanceof Error?d.message:String(d))}this.display()}}))}};async function W$(r,e,t,n){let i=await r.resolveConflict(e,t,n),s=await r.preview();return{status:i,preview:s}}var dj=4,G$={status:null,preview:null,progress:null,fileProgress:null,problem:null,message:"",localChangeObserved:!1,busy:!1,paused:!1,retryAt:null},Id=class{constructor(e,t,n,i=()=>{}){this.controller=e;this.getProfile=t;this.history=n;this.notify=i;this.current={...G$};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({...G$})}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(dd(t,e))}catch(n){console.error("mdbase: could not save sync history",n)}this.update({})}}async dismissEvent(e){await this.history?.acknowledge(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 Td(e,this.getProfile())?(this.update({status:t,problem:null}),t):null}catch(t){return Td(e,this.getProfile())&&this.update({problem:Dt(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?Nx(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=Dt(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 W$(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=Dt(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=Dt(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(){let e=this.getProfile();if(!e)return null;try{let{preview:t,status:n}=await this.controller.inspect();return Td(e,this.getProfile())?(this.update({preview:t,status:n,problem:null}),t):null}catch(t){if(!Td(e,this.getProfile()))return null;let n=Dt(t);return this.update({problem:n,message:n.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=Hx(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"?Dt(new DOMException("Synchronization stopped.","AbortError")):a.status==="failed"||a.status==="blocked"?F$(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=Dt(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 Td(r,e){return r?.collectionId===e?.collectionId&&r?.replicaId===e?.replicaId&&r?.enrollmentId===e?.enrollmentId}function uj(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 fj={localQuietMs:3e3,localMaxWaitMs:2e4,probeVisibleMs:3e4,probeHiddenMs:5*6e4,safetyNetMs:15*6e4,retryBaseMs:5e3,retryMaxMs:5*6e4,unexpectedRetryMaxMs:30*6e4},ay=new Set(["auth","device","paused"]),Od=class{constructor(e,t=pj,n=fj){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===null||e0&&(this.changed=!0),this.failures=0,this.host.setRetryAt(null),this.schedule(this.clock.now())}requestSoon(){this.changed=!0,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()}catch(t){this.host.reportProblem(t);let n=this.host.problemKind();e=n&&ay.has(n)?this.settled():this.failed(ks(t))}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&&ay.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.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"||s==="pending")return this.changed||=n||s==="pending",2e3;if(s==="failed"){this.changed||=n;let o=this.host.problemKind();return o&&ay.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),ks(e)?null:!0}}failed(e){let t=Cm(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())))}},pj={now:()=>Date.now(),setTimeout:(r,e)=>window.setTimeout(r,e),clearTimeout:r=>window.clearTimeout(r),random:()=>Math.random()};function Y$(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: ${J$(e.controlUrl)} \xB7 sync ${J$(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(` +`,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 Aa(r){return r.specProfile==="v0.3"&&!r.readOnlyReason?jn(r):Bn(r.originalFrontmatter??{name:r.name,fields:Object.fromEntries(r.fields.map(e=>[e.name,e.definition]))})}var Nr="mdbase-workspace-view",Cd=class r 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 Pd(this);this.sync=new kd(this);this.issues=new wd(this);this.navigationId=`mdbase-workspace-${++r.nextNavigationId}`;this.refreshVersion=0;this.unsubscribeSync=null;this.syncRenderTimer=null}static{this.nextNavigationId=0}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 Nr}getDisplayText(){return"mdbase"}getIcon(){return $a}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()})}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())return;if(this.schema=s,this.destination==="types"){if(await this.types.onSchemaLoaded(t,i),!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)}else this.destination==="sync"&&await this.sync.refresh();if(!i())return;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==="types"?this.refresh():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"),s.id=`${this.navigationId}-${this.destination}-panel`,s.setAttr("role","tabpanel"),s.setAttr("aria-labelledby",`${this.navigationId}-${this.destination}-tab`),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&&(this.focusTarget(t,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}syncTabStatus(){if(this.destination==="sync"||!this.host.getMirrorProfile())return null;let{problem:t,paused:n,status:i,progress:s,fileProgress:o}=this.host.sync.state;if(s||o)return null;let a=t?.kind??(n?"paused":i?.recovery_required?"recovery":null);return!a||a==="busy"?null:{kind:a,label:{offline:"Offline",auth:"Sign in",device:"Set up",internal:"Error",decision:"Review",recovery:"Review",paused:"Paused"}[a],detail:t?.title??(n?"Sync is paused":"Synchronization needs recovery")}}renderTopbarOnly(){let t=this.containerEl.querySelector(".mdbase-topbar");if(!t)return;let n=this.captureRenderSnapshot(t),i=this.containerEl.ownerDocument.createElement("div");this.renderTopbar(i);let s=i.firstElementChild;s&&(t.replaceWith(s),this.restoreRenderSnapshot(s,n))}captureRenderSnapshot(t){for(let c of Array.from(t.querySelectorAll("details[data-disclosure]"))){let l=c.dataset.disclosure;l&&this.disclosures.set(l,c.open)}let n=t.ownerDocument,i=t.contains(n.activeElement)?n.activeElement:null,s=n.defaultView,o=s&&(i instanceof s.HTMLInputElement||i instanceof s.HTMLTextAreaElement)?i:null,a=new Map;for(let c of Array.from(t.querySelectorAll("[data-scroll-key]"))){let l=c.getAttr("data-scroll-key");l&&a.set(l,{top:c.scrollTop,left:c.scrollLeft})}return{focusKey:i?.getAttr("data-focus-key")??null,selectionStart:o?.selectionStart??null,selectionEnd:o?.selectionEnd??null,scroll:a}}restoreRenderSnapshot(t,n){for(let[o,a]of n.scroll){let c=t.querySelector(`[data-scroll-key="${o}"]`);c&&(c.scrollTop=a.top,c.scrollLeft=a.left)}if(!n.focusKey)return;let i=this.focusTarget(t,n.focusKey);i?.focus({preventScroll:!0});let s=t.ownerDocument.defaultView;s&&(i instanceof s.HTMLInputElement||i instanceof s.HTMLTextAreaElement)&&n.selectionStart!==null&&n.selectionEnd!==null&&i.setSelectionRange(n.selectionStart,n.selectionEnd)}focusTarget(t,n){return Array.from(t.querySelectorAll("[data-focus-key]")).find(i=>i.getAttr("data-focus-key")===n)}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"),i.setAttr("aria-label","mdbase destinations");let s=[["types","Types"],["sync","Sync"],["issues","Issues"]];for(let[o,[a,c]]of s.entries()){let l=i.createEl("button",{text:c,cls:"clickable-icon"});if(l.addClass("mdbase-nav-button"),l.setAttr("role","tab"),l.id=`${this.navigationId}-${a}-tab`,this.destination===a&&l.setAttr("aria-controls",`${this.navigationId}-${a}-panel`),l.tabIndex=this.destination===a?0:-1,l.setAttr("data-focus-key",`destination-${a}`),l.setAttr("aria-selected",String(this.destination===a)),this.destination===a&&l.addClass("is-active"),a==="issues"&&this.host.getIssues().length){let f=this.host.getIssues().length;l.createSpan({cls:"mdbase-count",text:ty(f)}).setAttr("title",`${f} issues`),l.setAttr("aria-label",`Issues \xB7 ${f} validation ${f===1?"issue":"issues"}`)}let u=a==="sync"?this.syncTabStatus():null,d=a==="sync"?this.syncAttention():null;if(u){let f=l.createSpan({cls:"mdbase-count mdbase-nav-status",text:u.label});f.setAttr("data-kind",u.kind),f.setAttr("title",u.detail),l.setAttr("aria-label",`Sync \xB7 ${u.detail}`)}else d&&(l.createSpan({cls:"mdbase-count",text:ty(d.count)}).setAttr("title",d.label),l.setAttr("aria-label",`Sync \xB7 ${d.label}`));l.onclick=()=>this.showDestination(a),l.onkeydown=f=>{let p=f.key==="ArrowRight"?(o+1)%s.length:f.key==="ArrowLeft"?(o+s.length-1)%s.length:f.key==="Home"?0:f.key==="End"?s.length-1:null;p!==null&&(f.preventDefault(),this.pendingFocusKey=`destination-${s[p][0]}`,this.showDestination(s[p][0]))}}}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 Pa=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 K$=require("obsidian");var Md=class extends K$.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=Kx(this.runs,this.path).map(({run:i,file:s})=>({at:s.at,label:i.summary??Gx(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:As(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 Pe=require("obsidian");var lj=[["image","Images"],["audio","Audio"],["video","Video"],["pdf","PDFs"],["other","Other files"]],Rd=class extends Pe.PluginSettingTab{constructor(t,n){super(t,n);this.plugin=n}display(){let{containerEl:t,plugin:n}=this;t.empty(),new Pe.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 Pe.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 Pe.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)}openSync(){return this.app.setting?.close(),this.plugin.openWorkspace("sync")}displaySync(t){let{plugin:n}=this,i=n.getMirrorProfile();if(new Pe.Setting(t).setName("Sync").setHeading(),!i){new Pe.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(async()=>{try{await this.openSync()}catch(u){new Pe.Notice(u instanceof Error?u.message:String(u))}}));return}new Pe.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);try{await this.openSync().then(u=>u.reconnectCollection())}catch(u){new Pe.Notice(u instanceof Error?u.message:String(u))}finally{l.setDisabled(!1)}})),new Pe.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{return await n.sync.configureSelectiveSync(l),!0}catch(u){return new Pe.Notice(u instanceof Error?u.message:String(u)),this.display(),!1}};for(let[l,u]of lj)new Pe.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 Pe.Setting(t).setName("Excluded folders").setDesc($d);Ed(this.app,c.controlEl,a,l=>{a=l}),c.addButton(l=>l.setButtonText("Apply").onClick(async()=>{l.setDisabled(!0);try{await o({...n.connectSync.getSelectiveSync(),excluded_folders:a})&&new Pe.Notice("Excluded folders updated. The next sync applies them.")}finally{l.setDisabled(!1)}})),new Pe.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()=>{l.setDisabled(!0);try{let u=await new Ac(this.app).choose(i.name);if(!u)return;l.setButtonText("Disconnecting\u2026"),await n.sync.disconnect(i,u==="remove"),new Pe.Notice(n.sync.state.message)}catch(u){new Pe.Notice(u instanceof Error?u.message:String(u))}finally{l.setDisabled(!1)}this.display()}))}};async function W$(r,e,t,n){let i=await r.resolveConflict(e,t,n),s=await r.preview();return{status:i,preview:s}}var dj=4,G$={status:null,preview:null,progress:null,fileProgress:null,problem:null,message:"",localChangeObserved:!1,busy:!1,paused:!1,retryAt:null},Id=class{constructor(e,t,n,i=()=>{}){this.controller=e;this.getProfile=t;this.history=n;this.notify=i;this.current={...G$};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({...G$})}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(dd(t,e))}catch(n){console.error("mdbase: could not save sync history",n)}this.update({})}}async dismissEvent(e){await this.history?.acknowledge(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 Td(e,this.getProfile())?(this.update({status:t,problem:null}),t):null}catch(t){return Td(e,this.getProfile())&&this.update({problem:Dt(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?Lx(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=Dt(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 W$(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=Dt(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=Dt(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(){let e=this.getProfile();if(!e)return null;try{let{preview:t,status:n}=await this.controller.inspect();return Td(e,this.getProfile())?(this.update({preview:t,status:n,problem:null}),t):null}catch(t){if(!Td(e,this.getProfile()))return null;let n=Dt(t);return this.update({problem:n,message:n.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=Hx(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"?Dt(new DOMException("Synchronization stopped.","AbortError")):a.status==="failed"||a.status==="blocked"?F$(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=Dt(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 Td(r,e){return r?.collectionId===e?.collectionId&&r?.replicaId===e?.replicaId&&r?.enrollmentId===e?.enrollmentId}function uj(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 fj={localQuietMs:3e3,localMaxWaitMs:2e4,probeVisibleMs:3e4,probeHiddenMs:5*6e4,safetyNetMs:15*6e4,retryBaseMs:5e3,retryMaxMs:5*6e4,unexpectedRetryMaxMs:30*6e4},ay=new Set(["auth","device","paused"]),Od=class{constructor(e,t=pj,n=fj){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===null||e0&&(this.changed=!0),this.failures=0,this.host.setRetryAt(null),this.schedule(this.clock.now())}requestSoon(){this.changed=!0,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()}catch(t){this.host.reportProblem(t);let n=this.host.problemKind();e=n&&ay.has(n)?this.settled():this.failed(ks(t))}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&&ay.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.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"||s==="pending")return this.changed||=n||s==="pending",2e3;if(s==="failed"){this.changed||=n;let o=this.host.problemKind();return o&&ay.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),ks(e)?null:!0}}failed(e){let t=Cm(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())))}},pj={now:()=>Date.now(),setTimeout:(r,e)=>window.setTimeout(r,e),clearTimeout:r=>window.clearTimeout(r),random:()=>Math.random()};function Y$(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: ${J$(e.controlUrl)} \xB7 sync ${J$(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 J$(r){try{return new URL(r).host}catch{return"invalid URL"}}var X$={validateOnSave:!0,validateOnOpen:!0,showNoticeOnSave:!1,interopEnabled:!1,mirrorProfile:null,typeDrafts:{},archivedTypeDrafts:[],autoSync:!0,syncSettingsVersion:2},Q$="mdbase-sync-device-id";function hj(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var Dd=class extends L.Plugin{constructor(t,n){super(t,n);this.issueMap=new Map;this.validation=new Ia;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 Pa(this.saveValidationDebounceMs,async(t,n)=>{try{await this.validateFileAndStore(t,"save",n)}catch(i){console.error("mdbase: background validation failed",i)}});this.schemaRefreshes=new Pa(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 Hc(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)($a,S$),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(Lr,n=>new Cd(n,this)),this.addSettingTab(new Rd(this.app,this)),this.ribbonEl=this.addRibbonIcon($a,"Open mdbase",()=>void this.onRibbonClick()),this.ribbonEl.addClass("mdbase-ribbon"),this.updateStatusBar(),vw(this),this.registerVaultEvents(),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 jd(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 Od({connected:()=>this.getMirrorProfile()!==null,automatic:()=>this.settings.autoSync,problemKind:()=>this.sync.state.paused?"paused":this.sync.state.problem?.kind??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(Q$);if(typeof t=="string"&&t)return t;let n=crypto.randomUUID();return this.app.saveLocalStorage(Q$,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(Lr).forEach(t=>t.detach()),this.saveValidations.clear(),this.schemaRefreshes.clear()}async loadSettings(){let t=await this.loadData();this.settings=Object.assign({},X$,t);let n=typeof t?.syncSettingsVersion=="number"&&Number.isSafeInteger(t.syncSettingsVersion)&&t.syncSettingsVersion>=1?t.syncSettingsVersion:1;this.settings.syncSettingsVersion=Math.max(2,n),this.settings.autoSync=n<2||typeof t?.autoSync!="boolean"?X$.autoSync:t.autoSync,this.settings.mirrorProfile=o$(this.settings.mirrorProfile),(!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=Y$({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 Md(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 ld(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 Id(this.connectSync,()=>this.getMirrorProfile(),n,i=>{new L.Notice(`mdbase: ${i}`,1e4)}),this.register(this.sync.subscribe(()=>this.updateStatusBar()))}async migrateSyncActivity(t){let n=j$(this.settings.syncActivity),i=this.settings.mirrorProfile?.collectionId;if(i)for(let s of n)await t.append(dd(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=Xm(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 ci(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||!bt(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 Ta(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 Bp(this,t)}async initializeCollection(){this.connectSync.assertLocalAuthorityWritable();let{created:t}=await xo(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 u$(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 f$(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 Sw(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=Up(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=Up(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=Fp(n),l=new RegExp(`^\\s*${hj(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]=Ge(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 Pp(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"||bt(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 L$({connected:this.getMirrorProfile()!==null,status:n.status,progress:n.progress,fileProgress:n.fileProgress,problem:n.problem,validationIssues:t,localChangeObserved:n.localChangeObserved,paused:n.paused,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(Lr)[0];if(n){await this.app.workspace.revealLeaf(n);let s=n.view;return s.showDestination(t),await s.refresh(),s}let i=this.app.workspace.getLeaf(!0);return await i.setViewState({type:Lr,active:!0,state:{destination:t}}),await this.app.workspace.revealLeaf(i),i.view}refreshWorkspaceViews(t=!1){for(let n of this.app.workspace.getLeavesOfType(Lr)){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 ci(this.app.vault);if(!n)return null;let i=await Cp(this.app.vault,n),s=await Mp(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)}registerVaultEvents(){this.registerEvent(this.app.vault.on("modify",t=>{t instanceof L.TFile&&this.onVaultModify(t)})),this.registerEvent(this.app.vault.on("rename",(t,n)=>{t instanceof L.TFile?this.onVaultRename(t,n):t instanceof L.TFolder&&this.onVaultFolderChange(n,t.path)})),this.registerEvent(this.app.vault.on("delete",t=>{t instanceof L.TFile?this.onVaultDelete(t):t instanceof L.TFolder&&this.onVaultFolderChange(t.path)})),this.registerEvent(this.app.vault.on("create",t=>{t instanceof L.TFile&&this.onVaultCreate(t)}))}onVaultFolderChange(...t){for(let n of t)this.observeLocalMirrorChange(n);this.recordCache=null,this.recordList=null,this.dirtyRecordPaths.clear(),this.refreshSchemaNow()}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.consumeEngineWrite(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 Sc(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 Ip(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(Lr))l.view.refreshValidationControls();else if(c.completed%25===0||c.phase==="uniqueness")for(let l of this.app.workspace.getLeavesOfType(Lr))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(Lr))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=jn(n),c=n.body.trim()||`# ${o} +`}function J$(r){try{return new URL(r).host}catch{return"invalid URL"}}var X$={validateOnSave:!0,validateOnOpen:!0,showNoticeOnSave:!1,interopEnabled:!1,mirrorProfile:null,typeDrafts:{},archivedTypeDrafts:[],autoSync:!0,syncSettingsVersion:2},Q$="mdbase-sync-device-id";function hj(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var Dd=class extends N.Plugin{constructor(t,n){super(t,n);this.issueMap=new Map;this.validation=new Ia;this.validationAbort=null;this.sortedIssuesCache=null;this.noteStatusVersion=0;this.syncScheduler=null;this.recordCache=null;this.recordCacheSettings="";this.recordCacheEpoch=0;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 Pa(this.saveValidationDebounceMs,async(t,n)=>{try{await this.validateFileAndStore(t,"save",n)}catch(i){console.error("mdbase: background validation failed",i)}});this.schemaRefreshes=new Pa(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 Hc(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,N.addIcon)($a,S$),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(Nr,n=>new Cd(n,this)),this.addSettingTab(new Rd(this.app,this)),this.ribbonEl=this.addRibbonIcon($a,"Open mdbase",()=>void this.onRibbonClick()),this.ribbonEl.addClass("mdbase-ribbon"),this.updateStatusBar(),vw(this),this.registerVaultEvents(),this.registerEvent(this.app.workspace.on("file-open",n=>{this.settings.validateOnOpen&&(!(n instanceof N.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 N.TFile&&(this.saveValidations.has(s.path)&&this.scheduleSaveValidation(s),this.schemaRefreshes.has("schema")&&this.isSchemaRelevantPath(s.path)&&this.scheduleSchemaRefresh())}));try{await jd(this.app)}catch(n){new N.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 Od({connected:()=>this.getMirrorProfile()!==null,automatic:()=>this.settings.autoSync,problemKind:()=>this.sync.state.paused?"paused":this.sync.state.problem?.kind??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(Q$);if(typeof t=="string"&&t)return t;let n=crypto.randomUUID();return this.app.saveLocalStorage(Q$,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(Nr).forEach(t=>t.detach()),this.saveValidations.clear(),this.schemaRefreshes.clear()}async loadSettings(){let t=await this.loadData();this.settings=Object.assign({},X$,t);let n=typeof t?.syncSettingsVersion=="number"&&Number.isSafeInteger(t.syncSettingsVersion)&&t.syncSettingsVersion>=1?t.syncSettingsVersion:1;this.settings.syncSettingsVersion=Math.max(2,n),this.settings.autoSync=n<2||typeof t?.autoSync!="boolean"?X$.autoSync:t.autoSync,this.settings.mirrorProfile=o$(this.settings.mirrorProfile),(!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 N.FileSystemAdapter=="function"&&o instanceof N.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=Y$({generatedAt:new Date().toISOString(),pluginVersion:this.manifest.version,obsidianVersion:N.apiVersion,platform:N.Platform.isIosApp?"iOS":N.Platform.isAndroidApp?"Android":N.Platform.isMacOS?"macOS":N.Platform.isWin?"Windows":N.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 N.Notice("Copied sync diagnostics. They name the collection and recent files but contain no note text or credentials.")}openNoteSyncHistory(t){new Md(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 ld(this.app.vault.adapter,(0,N.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 Id(this.connectSync,()=>this.getMirrorProfile(),n,i=>{new N.Notice(`mdbase: ${i}`,1e4)}),this.register(this.sync.subscribe(()=>this.updateStatusBar()))}async migrateSyncActivity(t){let n=j$(this.settings.syncActivity),i=this.settings.mirrorProfile?.collectionId;if(i)for(let s of n)await t.append(dd(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,N.normalizePath)(t));if(!(n instanceof N.TFile))throw new Error(`Type file not found: ${t}`);let i=await this.app.vault.cachedRead(n),s=Te(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=Xm(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 ci(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,N.normalizePath)(n)):null;if(o!=null&&!(o instanceof N.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||!bt(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 Ta(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 N.Notice("Installed contract pack. Edit its type or create a note to try it.")}).open()}async createNoteFromType(t){await Bp(this,t)}async initializeCollection(){this.connectSync.assertLocalAuthorityWritable();let{created:t}=await xo(this.app.vault,{seedNoteType:!1});this.invalidateSchemaCache(),new N.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 u$(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 f$(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 N.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 Sw(t)}async applyQuickFix(t){this.connectSync.assertLocalAuthorityWritable();let n=this.app.vault.getAbstractFileByPath(t.path);if(!(n instanceof N.TFile)){new N.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=Up(s,t);return i=o.changed,o.content}),new N.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 N.TFile)){i+=1;continue}let c=!1;await this.app.vault.process(a,l=>{this.connectSync.assertLocalAuthorityWritable();let u=Up(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 N.TFile)){new N.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 N.MarkdownView))return;let s=i.view;if(!(s.file instanceof N.TFile)||s.file.path!==t.path)return;let o=s.editor,a=o.lineCount();if(a<3)return;let c=Fp(n),l=new RegExp(`^\\s*${hj(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 N.TFile)||!i)return;let[s]=Ge(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.recordLoadPromise)&&(this.dirtyRecordPaths.add((0,N.normalizePath)(t)),this.recordList=null)}loadCollectionRecords(){return this.recordLoadPromise??=this.readRecords().finally(()=>{this.recordLoadPromise=null}),this.recordLoadPromise}async readRecords(){let t=this.recordCacheEpoch,n=await this.getConfigAndTypes();if(!n)return[];let i=JSON.stringify(n.config.settings);if(!this.recordCache||i!==this.recordCacheSettings){this.dirtyRecordPaths.clear();let o=await Pp(this.app.vault,n.config);if(t!==this.recordCacheEpoch)return this.readRecords();this.recordCache=new Map(o.map(a=>[a.path,a])),this.recordCacheSettings=i,this.recordList=null}let s=this.recordCache;if(this.dirtyRecordPaths.size){let o=[...this.dirtyRecordPaths];this.dirtyRecordPaths.clear();for(let a of o){s.delete(a);let c=this.app.vault.getAbstractFileByPath(a);if(!(c instanceof N.TFile)||c.extension!=="md"||bt(a,n.config))continue;let l=Te(await this.app.vault.cachedRead(c));l.error||s.set(a,{path:a,frontmatter:l.frontmatter})}this.recordList=null}return t!==this.recordCacheEpoch?this.readRecords():(this.recordList??=[...s.values()].sort((o,a)=>o.path.localeCompare(a.path)),this.recordList)}syncIndicator(t){let n=this.sync.state,i=this.sync.safety();return N$({connected:this.getMirrorProfile()!==null,status:n.status,progress:n.progress,fileProgress:n.fileProgress,problem:n.problem,validationIssues:t,localChangeObserved:n.localChangeObserved,paused:n.paused,busy:n.busy,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(Nr)[0];if(n){await this.app.workspace.revealLeaf(n);let s=n.view;return s.showDestination(t),await s.refresh(),s}let i=this.app.workspace.getLeaf(!0);return await i.setViewState({type:Nr,active:!0,state:{destination:t}}),await this.app.workspace.revealLeaf(i),i.view}refreshWorkspaceViews(t=!1){for(let n of this.app.workspace.getLeavesOfType(Nr)){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,N.normalizePath)(t);if(n==="mdbase.yaml")return!0;let i=new Set(["_types","_contracts"]);this.schemaCache&&(i.add((0,N.normalizePath)(this.schemaCache.config.settings.types_folder)),i.add((0,N.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;let n=Promise.resolve().then(async()=>{try{let i=await ci(this.app.vault),s=i?{config:i,types:await Cp(this.app.vault,i),contracts:await Mp(this.app.vault,i)}:null;return this.schemaLoadPromise!==n?this.getConfigAndTypes():(s&&(this.schemaCache=s),s)}catch(i){if(this.schemaLoadPromise!==n)return this.getConfigAndTypes();throw i}});this.schemaLoadPromise=n;try{return await n}finally{this.schemaLoadPromise===n&&(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 N.Notice(`No types found in ${i.config.settings.types_folder}`),i):(n||new N.Notice("No mdbase.yaml found. Run 'mdbase: Initialize collection' first."),null)}registerVaultEvents(){this.registerEvent(this.app.vault.on("modify",t=>{t instanceof N.TFile&&this.onVaultModify(t)})),this.registerEvent(this.app.vault.on("rename",(t,n)=>{t instanceof N.TFile?this.onVaultRename(t,n):t instanceof N.TFolder&&this.onVaultFolderChange(n,t.path)})),this.registerEvent(this.app.vault.on("delete",t=>{t instanceof N.TFile?this.onVaultDelete(t):t instanceof N.TFolder&&this.onVaultFolderChange(t.path)})),this.registerEvent(this.app.vault.on("create",t=>{t instanceof N.TFile&&this.onVaultCreate(t)}))}onVaultFolderChange(...t){for(let n of t)this.observeLocalMirrorChange(n);this.recordCacheEpoch++,this.recordCache=null,this.recordList=null,this.dirtyRecordPaths.clear(),this.refreshSchemaNow()}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.consumeEngineWrite(t))return;let n=(0,N.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 Sc(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 N.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 Ip(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(Nr))l.view.refreshValidationControls();else if(c.completed%25===0||c.phase==="uniqueness")for(let l of this.app.workspace.getLeavesOfType(Nr))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 N.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 N.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 N.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(Nr))a.view.refreshValidationControls();this.refreshIssueViews()}}async ensureFolderExists(t){let n=(0,N.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=jn(n),c=n.body.trim()||`# ${o} Type definition for ${o}.`,l=`${gt(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&&Xm(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,N.normalizePath)(t.settings.types_folder),d=(0,N.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&&Xm(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,N.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 N.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 N.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/main.ts b/main.ts index d5f4429..1b8658b 100644 --- a/main.ts +++ b/main.ts @@ -129,6 +129,7 @@ export default class MdbasePlugin extends Plugin { private syncScheduler: SyncScheduler | null = null; private recordCache: Map | null = null; private recordCacheSettings = ""; + private recordCacheEpoch = 0; private recordList: CollectionRecord[] | null = null; private recordLoadPromise: Promise | null = null; private readonly dirtyRecordPaths = new Set(); @@ -770,7 +771,9 @@ export default class MdbasePlugin extends Plugin { private markRecordChanged(path: string): void { this.validation.changed(path); - if (!this.recordCache) return; + // A yielded initial scan can already have read this path. Keep its change + // even before the completed cache is installed, then reconcile it below. + if (!this.recordCache && !this.recordLoadPromise) return; this.dirtyRecordPaths.add(normalizePath(path)); this.recordList = null; } @@ -787,28 +790,33 @@ export default class MdbasePlugin extends Plugin { } private async readRecords(): Promise { + const epoch = this.recordCacheEpoch; const loaded = await this.getConfigAndTypes(); if (!loaded) return []; const settingsKey = JSON.stringify(loaded.config.settings); if (!this.recordCache || settingsKey !== this.recordCacheSettings) { this.dirtyRecordPaths.clear(); const records = await readCollectionRecords(this.app.vault, loaded.config); + if (epoch !== this.recordCacheEpoch) return this.readRecords(); this.recordCache = new Map(records.map((record) => [record.path, record])); this.recordCacheSettings = settingsKey; this.recordList = null; - } else if (this.dirtyRecordPaths.size) { + } + const cache = this.recordCache; + if (this.dirtyRecordPaths.size) { const paths = [...this.dirtyRecordPaths]; this.dirtyRecordPaths.clear(); for (const path of paths) { - this.recordCache.delete(path); + cache.delete(path); const file = this.app.vault.getAbstractFileByPath(path); if (!(file instanceof TFile) || file.extension !== "md" || isExcluded(path, loaded.config)) continue; const parsed = parseFrontmatter(await this.app.vault.cachedRead(file)); - if (!parsed.error) this.recordCache.set(path, { path, frontmatter: parsed.frontmatter }); + if (!parsed.error) cache.set(path, { path, frontmatter: parsed.frontmatter }); } this.recordList = null; } - this.recordList ??= [...this.recordCache.values()].sort((a, b) => a.path.localeCompare(b.path)); + if (epoch !== this.recordCacheEpoch) return this.readRecords(); + this.recordList ??= [...cache.values()].sort((a, b) => a.path.localeCompare(b.path)); return this.recordList; } @@ -824,6 +832,7 @@ export default class MdbasePlugin extends Plugin { validationIssues, localChangeObserved: state.localChangeObserved, paused: state.paused, + busy: state.busy, reviewChanges: safety && !safety.safe ? state.preview?.plan.actions.length ?? 0 : 0, }); } @@ -947,20 +956,30 @@ export default class MdbasePlugin extends Plugin { if (this.schemaCache) return this.schemaCache; if (this.schemaLoadPromise) return this.schemaLoadPromise; - this.schemaLoadPromise = (async () => { - const config = await loadMdbaseConfig(this.app.vault); - if (!config) return null; - const types = await loadTypeDefinitions(this.app.vault, config); - const contracts = await loadContractDefinitions(this.app.vault, config); - return { config, types, contracts }; - })(); + // Store the fenced promise itself: all coalesced callers must reject a + // result invalidated while its asynchronous config/type reads were running. + const loading: Promise = Promise.resolve().then(async () => { + try { + const config = await loadMdbaseConfig(this.app.vault); + const loaded = config ? { + config, + types: await loadTypeDefinitions(this.app.vault, config), + contracts: await loadContractDefinitions(this.app.vault, config), + } : null; + if (this.schemaLoadPromise !== loading) return this.getConfigAndTypes(); + if (loaded) this.schemaCache = loaded; + return loaded; + } catch (error) { + if (this.schemaLoadPromise !== loading) return this.getConfigAndTypes(); + throw error; + } + }); + this.schemaLoadPromise = loading; try { - const loaded = await this.schemaLoadPromise; - if (loaded) this.schemaCache = loaded; - return loaded; + return await loading; } finally { - this.schemaLoadPromise = null; + if (this.schemaLoadPromise === loading) this.schemaLoadPromise = null; } } @@ -1002,6 +1021,8 @@ export default class MdbasePlugin extends Plugin { for (const path of paths) this.observeLocalMirrorChange(path); // A folder event need not be accompanied by child-file events. The old // descendant paths are no longer a valid incremental record/schema cache. + // An older in-flight read must not reinstall those invalidated paths. + this.recordCacheEpoch++; this.recordCache = null; this.recordList = null; this.dirtyRecordPaths.clear(); diff --git a/scripts/test-sync-layout.cjs b/scripts/test-sync-layout.cjs index ba21318..982597f 100644 --- a/scripts/test-sync-layout.cjs +++ b/scripts/test-sync-layout.cjs @@ -25,7 +25,7 @@ fs.mkdirSync(shots, {recursive:true}); app.workspace.leftSplit.collapse();app.workspace.rightSplit.collapse(); window.open=()=>null; }); - const states=['healthy','scope','local-issue','offline','auth','copied','paused','internal','progress','first-sync','deletions','rebuild','conflict','conflict-local-absent','conflict-hosted-absent','history','enrollment','upload','away-offline','away-auth','away-copied','away-paused','away-internal']; + const states=['healthy','scope','local-issue','offline','auth','copied','paused','internal','progress','first-sync','deletions','rebuild','conflict','conflict-busy','conflict-local-absent','conflict-hosted-absent','history','enrollment','upload','away-offline','away-auth','away-copied','away-paused','away-internal']; const results=[]; for(const state of states) { await page.evaluate(state=>{ @@ -63,6 +63,7 @@ fs.mkdirSync(shots, {recursive:true}); p.sync.update({status:{state:'attention',conflicts:[{entity:'record',object_id:'record',decision_id:'decision',path:longPath,message:'Both versions changed. Choose which version to sync.'}],local_issues:[]}}); view.sync.conflictComparisons.set('record:decision',{entity:'record',objectId:'record',decisionId:'decision',local:state==='conflict-local-absent'?{state:'absent'}:{state:'exact',document:'Line from this device'},remote:state==='conflict-hosted-absent'?{state:'absent'}:{state:'exact',document:'Line from another device'}}); } + if(state==='conflict-busy')p.sync.update({busy:true}); if(state==='history') { const at=new Date().toISOString(); window.fixtureRuns=[{id:'fixture-conflict',collectionId:'ux-fixture',startedAt:at,finishedAt:at,outcome:'event',files:[],summary:'Kept both versions of '+longPath.split('/').pop(),message:"This device's version was saved as "+longPath.replace('.md',' (local conflict copy).md'),path:longPath,tone:'attention',needsAcknowledgement:true}]; @@ -80,8 +81,9 @@ fs.mkdirSync(shots, {recursive:true}); const checks=await page.locator('.mdbase-sync-document, .mdbase-issues-document').evaluate(el=>{ const content=el.closest('.mdbase-workspace-content'); const buttons=[...el.querySelectorAll('.mod-cta, .mod-warning, .mdbase-conflict-row button, .mdbase-activity-row > button')].map(b=>({text:b.textContent,height:b.getBoundingClientRect().height})); + const choices=[...el.querySelectorAll('button[data-focus-key^="resolve-"]')].map(b=>({text:b.textContent,disabled:b.disabled})); const topbar=el.closest('.mdbase-workspace').querySelector('.mdbase-topbar'); - return {topbarOverflow:topbar.scrollWidth>topbar.clientWidth+1,tabStatus:topbar.querySelector('.mdbase-nav-status')?.textContent,paneWidth:content.clientWidth,headingWidth:el.querySelector('.mdbase-sync-heading')?.getBoundingClientRect().width,scrollWidth:content.scrollWidth,overflow:content.scrollWidth>content.clientWidth+1,buttons}; + return {topbarOverflow:topbar.scrollWidth>topbar.clientWidth+1,tabStatus:topbar.querySelector('.mdbase-nav-status')?.textContent,paneWidth:content.clientWidth,headingWidth:el.querySelector('.mdbase-sync-heading')?.getBoundingClientRect().width,scrollWidth:content.scrollWidth,overflow:content.scrollWidth>content.clientWidth+1,buttons,choices}; }); const box=await page.locator('.mdbase-workspace').boundingBox(); const cdp=await page.context().newCDPSession(page); @@ -91,6 +93,7 @@ fs.mkdirSync(shots, {recursive:true}); if(checks.overflow)failures.push('Horizontal overflow'); if(checks.topbarOverflow)failures.push('Destination bar overflow'); if(state.startsWith('away-')&&!checks.tabStatus)failures.push('Problem hidden outside Sync'); + if(state==='conflict-busy'&&(checks.choices.length!==3||checks.choices.some(b=>!b.disabled)))failures.push('Conflict decisions enabled during sync'); if(width===390&&checks.headingWidth!=null&&checks.headingWidthb.height<43.5))failures.push('Primary/dismiss target below 44px'); results.push({state,width,theme,...checks,failures}); diff --git a/src/connectSync.ts b/src/connectSync.ts index 7240900..b7840f8 100644 --- a/src/connectSync.ts +++ b/src/connectSync.ts @@ -388,8 +388,17 @@ async function adoptionRequestBody(value: unknown, raw: boolean | undefined): Pr throw new SyncError("invalid_file_upload", "The adoption upload body was not binary data."); } -function parseJsonResponse(text: string, parsed: unknown): unknown { - if (parsed !== undefined && parsed !== null) return parsed; +function parseJsonResponse(response: { text: string; json: unknown }): unknown { + // Mobile requestUrl exposes JSON as a lazy getter. Proxy/plain-text errors + // (and empty 204 replies) can make that getter throw before HTTP status is + // classified. Keep parsing best-effort so retries/auth retain their meaning. + try { + const parsed = response.json; + if (parsed !== undefined && parsed !== null) return parsed; + } catch { + // Parse text below if it is JSON; otherwise retain the HTTP error fallback. + } + const text = response.text; if (!text.trim()) return {}; try { return JSON.parse(text); @@ -416,7 +425,7 @@ export function createObsidianEnrollmentRequester(): MirrorEnrollmentRequester { if (request.signal?.aborted) throw new DOMException("Enrollment cancelled.", "AbortError"); return { status: response.status, - body: parseJsonResponse(response.text, response.json), + body: parseJsonResponse(response), retryAfterMs: retryAfterMilliseconds(response.headers), }; }; @@ -438,7 +447,7 @@ export function createObsidianAdoptionRequester(): AuthorityAdoptionRequester { if (request.signal?.aborted) throw new DOMException("Collection adoption cancelled.", "AbortError"); return { status: response.status, - body: parseJsonResponse(response.text, response.json), + body: parseJsonResponse(response), retryAfterMs: retryAfterMilliseconds(response.headers), headers: response.headers, }; @@ -587,6 +596,21 @@ implements SyncTransport { throw new SyncError("invalid_sync_response", "Authority returned an invalid upload part size."); } const reader = new BinaryPartReader(source); + try { + return await this.uploadParts(request, session, partSize, reader); + } finally { + // Cancellation abandons native requests but must still release the staged + // source. Cleanup must not hide a transfer failure or a committed receipt. + await reader.close().catch(() => undefined); + } + } + + private async uploadParts( + request: OpenFileUploadRequest, + session: FileTransferSession, + partSize: number, + reader: BinaryPartReader, + ): Promise { const count = Math.max(1, Math.ceil(request.size / partSize)); if ( session.received.some((index) => !Number.isSafeInteger(index) || index < 0 || index >= count) @@ -617,8 +641,11 @@ implements SyncTransport { for (let index = 0; index < count; index += 1) { const offset = index * partSize; const length = Math.min(partSize, Math.max(0, request.size - offset)); + if (received.has(index)) { + await reader.skip(length); + continue; + } const bytes = await reader.read(length); - if (received.has(index)) continue; const prepared = await this.fileRequest( "POST", `uploads/${encodeURIComponent(request.transfer_id)}/parts`, @@ -718,7 +745,7 @@ implements SyncTransport { contentType: body === undefined ? undefined : "application/json", throw: false, }); - const value = parseJsonResponse(response.text, response.json); + const value = parseJsonResponse(response); if (response.status < 200 || response.status >= 300) { throw this.responseError(response, "sync_failed"); } @@ -744,7 +771,7 @@ implements SyncTransport { response: { status: number; text: string; json: unknown; headers?: Record }, fallbackCode: string, ): SyncError { - const value = parseJsonResponse(response.text, response.json); + const value = parseJsonResponse(response); const error = isRecord(value) && isRecord(value.error) ? value.error : {}; const code = typeof error.code === "string" ? error.code @@ -772,6 +799,15 @@ class BinaryPartReader { async read(length: number): Promise> { const output = new Uint8Array(new ArrayBuffer(length)); + await this.consume(length, output); + return output; + } + + async skip(length: number): Promise { + await this.consume(length); + } + + private async consume(length: number, output?: Uint8Array): Promise { let offset = 0; while (offset < length) { if (!this.remainder.byteLength) { @@ -783,14 +819,18 @@ class BinaryPartReader { if (!this.remainder.byteLength) continue; } const count = Math.min(length - offset, this.remainder.byteLength); - output.set(this.remainder.subarray(0, count), offset); + output?.set(this.remainder.subarray(0, count), offset); offset += count; // The source chunk was copied on receipt, so a view of its unread tail is // safe. Copying each tail makes small multipart uploads quadratic. Drop // the exhausted view to release its backing buffer during the last PUT. this.remainder = count === this.remainder.byteLength ? new Uint8Array() : this.remainder.subarray(count); } - return output; + } + + async close(): Promise { + this.remainder = new Uint8Array(); + await this.iterator.return?.(); } async expectEnd(): Promise { @@ -950,6 +990,14 @@ export class ObsidianMirrorFileSystem implements MirrorFileSystem { return cached[0] ?? null; } + private assertEntry(path: string, entry: TAbstractFile): void { + // TFile.path is mutable. An awaited alias lookup must not return a file + // that the user has since renamed elsewhere or replaced in the cache. + if (portablePathKey(entry.path) !== portablePathKey(path) || this.vault.getAbstractFileByPath(entry.path) !== entry) { + throw new SyncError("sync_plan_stale", `${path} moved before it could be changed. Review sync again.`); + } + } + async exists(input: string): Promise { const path = safeMirrorPath(this.vault, input); return this.vault.getAbstractFileByPath(path) !== null || await this.vault.adapter.exists(path); @@ -1024,6 +1072,7 @@ export class ObsidianMirrorFileSystem implements MirrorFileSystem { } this.assertActive(); if (existing instanceof TFile) { + this.assertEntry(path, existing); const spelling = existing.path; await this.vault.process(existing, (current) => { this.assertActive(); @@ -1049,6 +1098,8 @@ export class ObsidianMirrorFileSystem implements MirrorFileSystem { if (!(file instanceof TFile)) { throw new SyncError("mirror_path_collision", `Expected a file at ${source}.`); } + this.assertEntry(source, file); + const spelling = file.path; const destination = await this.cachedEntry(target); const sameFile = destination === file && portablePathKey(source) === portablePathKey(target); if (!sameFile && (destination !== null || await this.vault.adapter.exists(target))) { @@ -1057,6 +1108,8 @@ export class ObsidianMirrorFileSystem implements MirrorFileSystem { const slash = target.lastIndexOf("/"); if (slash >= 0) await ensureFolder(this.vault, target.slice(0, slash)); this.assertActive(); + this.assertEntry(source, file); + if (file.path !== spelling) throw new SyncError("sync_plan_stale", `${source} moved before it could be renamed. Review sync again.`); this.observeWrite(source); this.observeWrite(file.path); this.observeWrite(target); @@ -1081,6 +1134,7 @@ export class ObsidianMirrorFileSystem implements MirrorFileSystem { throw new SyncError("mirror_path_collision", `Expected a file at ${path}.`); } this.assertActive(); + this.assertEntry(path, existing); this.observeWrite(path); this.observeWrite(existing.path); await this.trashFile(existing); @@ -1100,6 +1154,7 @@ export class ObsidianMirrorFileSystem implements MirrorFileSystem { const file = await this.cachedEntry(path); if (file == null) return null; if (!(file instanceof TFile)) throw new SyncError("mirror_path_collision", `Expected a file at ${path}.`); + this.assertEntry(path, file); assertBinarySize(file.stat.size); const bytes = await this.vault.readBinary(file); assertBinarySize(bytes.byteLength); @@ -1123,6 +1178,7 @@ export class ObsidianMirrorFileSystem implements MirrorFileSystem { this.assertActive(); this.observeWrite(path); if (existing instanceof TFile) { + this.assertEntry(path, existing); this.observeWrite(existing.path); await this.vault.modifyBinary(existing, bytes); } @@ -1149,6 +1205,7 @@ export class ObsidianMirrorFileSystem implements MirrorFileSystem { const file = await this.cachedEntry(path); if (file == null) return null; if (!(file instanceof TFile)) throw new SyncError("mirror_path_collision", `Expected a file at ${path}.`); + this.assertEntry(path, file); assertBinarySize(file.stat.size); const bytes = new Uint8Array(await this.vault.readBinary(file)); assertBinarySize(bytes.byteLength); @@ -1566,6 +1623,8 @@ export class ConnectSyncController { private syncAbort: AbortController | null = null; private statusRequest: Promise | null = null; private mirrorOperationTail: Promise = Promise.resolve(); + /** A transport renewing during an SDK call already owns the directory lease. */ + private engineLeaseHeld = false; private readonly fileSystem: MirrorFileSystem; private readonly enrollmentClient: MirrorEnrollmentClient; private readonly adoptionClient: AuthorityAdoptionClient; @@ -1954,30 +2013,33 @@ export class ConnectSyncController { throw new SyncError("mirror_identity_conflict", "Connect approved a different collection. The existing mirror was not changed."); } 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(); - } + // Browser approval can stay open while any window advances the mirror. + // Commit the latest checkpoint under the same directory lease as sync. + await this.leaseFor(profile).runExclusive(async () => { + abortIfNeeded(callbacks.signal); + 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(); + } + }); + // status() takes its own lease, so read it after releasing the commit lease. const mirror = await this.createMirror(); return mirror.status(); }); @@ -2223,11 +2285,24 @@ export class ConnectSyncController { 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 base = stem.replace(/(?: \((?:local|hosted) conflict copy(?: [a-zA-Z0-9%_-]+)?(?: \d+)?\))+$/, ""); + // Two devices can preserve different bytes before either sees the other's + // copy. Numbering within one vault cannot reserve a hosted path: partition + // connected copies by the existing replica identity, not by device names. + // Standalone copies (without an enrollment) retain ordinary local numbering. + const replica = this.settingsHost.getMirrorProfile()?.replicaId; + const namespace = replica ? ` ${encodeURIComponent(replica)}` : ""; const bytes = new Uint8Array(document); + const parent = base.slice(0, base.lastIndexOf("/") + 1); + const encoder = new TextEncoder(); let suffix = 1; while (true) { - const target = `${base} (${label}${suffix === 1 ? "" : ` ${suffix}`})${extension}`; + const tail = ` (${label}${namespace}${suffix === 1 ? "" : ` ${suffix}`})${extension}`; + const budget = Math.min(255, 1024 - parent.length) - encoder.encode(tail).byteLength; + if (budget < 1) throw new SyncError("mirror_path_collision", "This filename leaves no room for a recovery copy. Shorten it before settling the conflict."); + const leaf = [...base.slice(parent.length)]; + while (encoder.encode(leaf.join("")).byteLength > budget) leaf.pop(); + const target = `${parent}${leaf.join("")}${tail}`; if (target === path) { suffix += 1; continue; @@ -2344,11 +2419,16 @@ export class ConnectSyncController { private readonly engineWrites = new Map(); private noteEngineWrite(path: string): void { - const now = Date.now(); + const now = performance.now(); + // Refreshing keys at the tail keeps monotonic timestamps in insertion + // order. Each expired entry is visited once, not once per bulk write. for (const [known, at] of this.engineWrites) { - if (now - at > ENGINE_WRITE_ECHO_MS) this.engineWrites.delete(known); + if (now - at <= ENGINE_WRITE_ECHO_MS) break; + this.engineWrites.delete(known); } - this.engineWrites.set(normalizePath(path), now); + const key = normalizePath(path); + this.engineWrites.delete(key); + this.engineWrites.set(key, now); } /** Suppress one echo, not every user edit arriving soon after that write. */ @@ -2356,7 +2436,7 @@ export class ConnectSyncController { const key = normalizePath(path); const at = this.engineWrites.get(key); this.engineWrites.delete(key); - const elapsed = at === undefined ? -1 : Date.now() - at; + const elapsed = at === undefined ? -1 : performance.now() - at; return elapsed >= 0 && elapsed <= ENGINE_WRITE_ECHO_MS; } @@ -2832,7 +2912,12 @@ export class ConnectSyncController { fileSystem: this.fileSystem, blobStore: this.blobStoreFor(profile), selectiveSync: normalizeSelectiveSync(profile.selectiveSync), - lease: this.leaseFor(profile), + lease: { + runExclusive: (operation: () => Promise) => this.leaseFor(profile).runExclusive(async () => { + this.engineLeaseHeld = true; + try { return await operation(); } finally { this.engineLeaseHeld = false; } + }), + }, onProgress, }; return profile.mode === "read_write" @@ -2841,7 +2926,9 @@ export class ConnectSyncController { } private leaseFor(profile: MirrorProfile): MirrorLease { - return this.options.leaseFactory?.(profile) ?? new DeviceMirrorLease(`${profile.collectionId}:${profile.replicaId}`); + // Reapproval changes replica IDs, not the physical vault being protected. + const directory = this.currentDeviceId() ?? profile.deviceId ?? profile.replicaId; + return this.options.leaseFactory?.(profile) ?? new DeviceMirrorLease(`${profile.collectionId}:${directory}`); } private requireProfile(): MirrorProfile { @@ -3032,15 +3119,22 @@ export class ConnectSyncController { refreshCredential, accessTokenExpiresAt: profile.accessTokenExpiresAt, }, { 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); + const commit = async () => { + // Another window may have retired this enrollment while the request ran. + // Its cached profile is not proof that the shared connection still exists. + await this.assertMirror(profile.collectionId); + const current = this.requireProfile(); + const storedRefresh = this.app.secretStorage.getSecret(this.secretIds("refresh", profile).current); + if (current.collectionId !== profile.collectionId || current.replicaId !== profile.replicaId + || current.enrollmentId !== profile.enrollmentId || storedRefresh !== refreshCredential) { + throw new SyncError("mirror_identity_conflict", "The connection changed while credentials were renewing. Retry with the current connection."); + } + await this.persistEnrollment(renewed, current.selectiveSync); + }; + // A 401 callback inside the engine is already fenced. Standalone renewal + // commits must acquire the same lease as disconnect and reauthorization. + if (this.engineLeaseHeld) await commit(); + else await this.leaseFor(profile).runExclusive(commit); return renewed.accessToken; } diff --git a/src/modals.ts b/src/modals.ts index 6d0fc22..91c15de 100644 --- a/src/modals.ts +++ b/src/modals.ts @@ -272,13 +272,13 @@ export class DisconnectMirrorModal extends Modal { this.contentEl.createEl("p", { text: `This stops synchronization with ${collectionName}. 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." }); + this.contentEl.createEl("p", { text: "Keep all local files, or move unchanged synced files to trash. Local edits are kept either way." }); const actions = this.contentEl.createDiv({ cls: "modal-button-container" }); const cancel = actions.createEl("button", { text: "Cancel" }); cancel.onclick = () => this.finish(null); const keep = actions.createEl("button", { text: "Keep files", cls: "mod-cta" }); keep.onclick = () => this.finish("keep"); - const remove = actions.createEl("button", { text: "Remove unchanged files" }); + const remove = actions.createEl("button", { text: "Trash unchanged files" }); remove.addClass("mod-warning"); remove.onclick = () => this.finish("remove"); this.open(); diff --git a/src/settingsTab.ts b/src/settingsTab.ts index 98a7d78..cf859e2 100644 --- a/src/settingsTab.ts +++ b/src/settingsTab.ts @@ -63,6 +63,12 @@ export class MdbaseSettingTab extends PluginSettingTab { this.displaySync(containerEl); } + /** Settings can be a native popout; finish that surface before approval opens. */ + private openSync(): ReturnType { + (this.app as unknown as { setting?: { close(): void } }).setting?.close(); + return this.plugin.openWorkspace("sync"); + } + private displaySync(containerEl: HTMLElement): void { const { plugin } = this; const profile = plugin.getMirrorProfile(); @@ -71,8 +77,12 @@ export class MdbaseSettingTab extends PluginSettingTab { new Setting(containerEl) .setName("Not connected") .setDesc("Connect this vault to mdbase Connect from the sync tab of the mdbase workspace.") - .addButton((button) => button.setButtonText("Open sync").onClick(() => { - void plugin.openWorkspace("sync"); + .addButton((button) => button.setButtonText("Open sync").onClick(async () => { + try { + await this.openSync(); + } catch (error) { + new Notice(error instanceof Error ? error.message : String(error)); + } })); return; } @@ -83,7 +93,7 @@ export class MdbaseSettingTab extends PluginSettingTab { .addButton((button) => button.setButtonText("Reconnect").onClick(async () => { button.setDisabled(true); try { - await plugin.openWorkspace("sync").then((view) => view.reconnectCollection()); + await this.openSync().then((view) => view.reconnectCollection()); } catch (error) { new Notice(error instanceof Error ? error.message : String(error)); } finally { @@ -152,13 +162,17 @@ export class MdbaseSettingTab extends PluginSettingTab { .setWarning() .setDisabled(plugin.sync.isSyncing()) .onClick(async () => { - const choice = await new DisconnectMirrorModal(this.app).choose(profile.name); - if (!choice) return; + button.setDisabled(true); try { + const choice = await new DisconnectMirrorModal(this.app).choose(profile.name); + if (!choice) return; + button.setButtonText("Disconnecting…"); await plugin.sync.disconnect(profile, choice === "remove"); new Notice(plugin.sync.state.message); } catch (error) { new Notice(error instanceof Error ? error.message : String(error)); + } finally { + button.setDisabled(false); } this.display(); })); diff --git a/src/syncUx.ts b/src/syncUx.ts index 64be6c7..8410558 100644 --- a/src/syncUx.ts +++ b/src/syncUx.ts @@ -109,6 +109,8 @@ export function syncIndicator(input: { localChangeObserved: boolean; /** Automatic sync stays off after the person stops it, even with a healthy checkpoint. */ paused?: boolean; + /** The session is checking or restoring sync before transfer progress is available. */ + busy?: boolean; /** Changes in a plan that stopped for review instead of applying automatically. */ reviewChanges?: number; }): SyncIndicator { @@ -143,6 +145,11 @@ export function syncIndicator(input: { destination: "sync", }; } + if (input.busy) { + return input.paused + ? { state: "syncing", label: "mdbase: Stopping…", detail: "Stopping synchronization", destination: "sync" } + : { state: "syncing", label: "mdbase: Checking…", detail: "Checking sync", destination: "sync" }; + } if (input.paused && !problem) { return { state: "paused", label: "mdbase: Paused", detail: "Changes wait until you resume sync", destination: "sync" }; } diff --git a/src/workspace/syncPane.ts b/src/workspace/syncPane.ts index dc38e49..672422e 100644 --- a/src/workspace/syncPane.ts +++ b/src/workspace/syncPane.ts @@ -193,6 +193,7 @@ export class SyncPane { // Comparisons belong to the plan they were opened from. if (preview !== this.comparedPreview) { this.previewComparisons.clear(); + this.loadingPreviewComparisons.clear(); this.comparedPreview = preview; this.transferPages.clear(); } @@ -962,7 +963,7 @@ export class SyncPane { if (comparison) { this.previewComparisons.delete(key); this.ctx.render(); - } else void this.loadPreviewComparison(key, recordId, entry.path); + } else void this.loadPreviewComparison(key, recordId, entry.path, preview); }; if (comparison) this.renderConflictComparison(body, comparison); } @@ -1022,6 +1023,7 @@ export class SyncPane { void this.loadConflictComparison(conflict, comparisonKey); }; if (comparison) { + const resolutionBusy = this.ctx.busy || this.session.state.busy || this.session.isSyncing(); for (const resolution of ["local", "remote"] as const) { const destructive = comparison[resolution].state === "absent"; const button = actions.createEl("button", { @@ -1031,13 +1033,13 @@ export class SyncPane { cls: destructive ? "mod-warning" : "", }); button.setAttr("data-focus-key", `resolve-${comparisonKey}-${resolution}`); - button.disabled = this.ctx.busy; + button.disabled = resolutionBusy; button.onclick = () => void this.resolveMirrorConflict(conflict, resolution, false); } if (conflict.path && comparison.local.state === "exact") { const keepBoth = actions.createEl("button", { text: comparison.remote.state === "absent" ? "Keep a local copy" : "Keep both" }); keepBoth.setAttr("data-focus-key", `resolve-${comparisonKey}-both`); - keepBoth.disabled = this.ctx.busy; + keepBoth.disabled = resolutionBusy; keepBoth.onclick = () => void this.resolveMirrorConflict(conflict, "remote", true); } this.renderConflictComparison(row, comparison, Boolean(conflict.path)); @@ -1045,15 +1047,18 @@ export class SyncPane { } } - private async loadPreviewComparison(key: string, recordId: string, path: string): Promise { + private async loadPreviewComparison(key: string, recordId: string, path: string, preview: MdbaseSyncPreview): Promise { + if (this.session.state.preview !== preview) return; this.loadingPreviewComparisons.add(key); this.ctx.render(); try { - this.previewComparisons.set(key, await this.ctx.host.connectSync.recordComparison(recordId, path)); + const comparison = await this.ctx.host.connectSync.recordComparison(recordId, path); + if (this.session.state.preview === preview) this.previewComparisons.set(key, comparison); } catch (error) { - this.ctx.message = syncProblem(error).message; + if (this.session.state.preview === preview) this.ctx.message = syncProblem(error).message; } finally { - this.loadingPreviewComparisons.delete(key); + // An old request must not clear a newer plan's loading indicator for this path. + if (this.session.state.preview === preview) this.loadingPreviewComparisons.delete(key); this.ctx.render(); } } diff --git a/src/workspaceView.ts b/src/workspaceView.ts index f1f9f80..ab948f6 100644 --- a/src/workspaceView.ts +++ b/src/workspaceView.ts @@ -257,7 +257,8 @@ export class MdbaseWorkspaceView extends ItemView implements WorkspaceContext { } const activeDocument = root.ownerDocument; const active = root.contains(activeDocument.activeElement) ? activeDocument.activeElement as HTMLElement : null; - const editable = active instanceof HTMLInputElement || active instanceof HTMLTextAreaElement ? active : null; + const ownerWindow = activeDocument.defaultView; + const editable = ownerWindow && (active instanceof ownerWindow.HTMLInputElement || active instanceof ownerWindow.HTMLTextAreaElement) ? active : null; const scroll = new Map(); for (const element of Array.from(root.querySelectorAll("[data-scroll-key]"))) { const key = element.getAttr("data-scroll-key"); @@ -281,8 +282,9 @@ export class MdbaseWorkspaceView extends ItemView implements WorkspaceContext { if (!snapshot.focusKey) return; const active = this.focusTarget(root, snapshot.focusKey); active?.focus({ preventScroll: true }); + const ownerWindow = root.ownerDocument.defaultView; if ( - (active instanceof HTMLInputElement || active instanceof HTMLTextAreaElement) + ownerWindow && (active instanceof ownerWindow.HTMLInputElement || active instanceof ownerWindow.HTMLTextAreaElement) && snapshot.selectionStart !== null && snapshot.selectionEnd !== null ) active.setSelectionRange(snapshot.selectionStart, snapshot.selectionEnd); diff --git a/test/collectionRecordCache.test.ts b/test/collectionRecordCache.test.ts new file mode 100644 index 0000000..7ef1e4e --- /dev/null +++ b/test/collectionRecordCache.test.ts @@ -0,0 +1,100 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import MdbasePlugin from "../main"; +import { MemoryVault } from "./memoryVault"; +import type { CollectionRecord } from "../src/mdbaseCore"; + +const config = { + spec_version: "0.3.0", + settings: { types_folder: "_types", explicit_type_keys: ["type"], exclude: [] }, +}; + +function fixture(vault: MemoryVault) { + const plugin = new MdbasePlugin({ vault } as never, {} as never); + const cache = plugin as unknown as { + getConfigAndTypes(): Promise; + markRecordChanged(path: string): void; + onVaultFolderChange(...paths: string[]): void; + observeLocalMirrorChange(path: string): void; + refreshSchemaNow(): void; + loadCollectionRecords(): Promise; + }; + cache.getConfigAndTypes = async () => ({ config, types: new Map(), contracts: new Map() }); + cache.observeLocalMirrorChange = () => undefined; + cache.refreshSchemaNow = () => undefined; + return cache; +} + +test("initial record-cache loading reconciles edits and creations that arrive while reads yield", async () => { + const vault = new MemoryVault(); + await vault.create("a.md", "---\ntype: old\n---\n"); + await vault.create("b.md", "---\ntype: deleted\n---\n"); + await vault.create("c.md", "---\ntype: moved\n---\n"); + await vault.create("z.md", "---\ntype: unchanged\n---\n"); + const cache = fixture(vault); + const read = vault.cachedRead.bind(vault); + let changed = false; + vault.cachedRead = async (file) => { + if (file.path === "z.md" && !changed) { + changed = true; + await vault.modify(vault.getAbstractFileByPath("a.md") as never, "---\ntype: new\n---\n"); + cache.markRecordChanged("a.md"); + await vault.delete(vault.getAbstractFileByPath("b.md") as never); + cache.markRecordChanged("b.md"); + await vault.rename(vault.getAbstractFileByPath("c.md") as never, "renamed.md"); + cache.markRecordChanged("c.md"); + cache.markRecordChanged("renamed.md"); + await vault.create("new.md", "---\ntype: added\n---\n"); + cache.markRecordChanged("new.md"); + } + return read(file); + }; + const records = await cache.loadCollectionRecords(); + assert.deepEqual(records.map(({ path, frontmatter }) => [path, frontmatter.type]), [ + ["a.md", "new"], ["new.md", "added"], ["renamed.md", "moved"], ["z.md", "unchanged"], + ]); + assert.deepEqual(await cache.loadCollectionRecords(), records, "cached lists must remain reconciled"); +}); + +test("a folder-only invalidation cannot be undone by an in-flight initial record scan", async () => { + const vault = new MemoryVault(); + await vault.create("Old/a.md", "---\ntype: moved\n---\n"); + await vault.create("z.md", "---\ntype: unchanged\n---\n"); + const cache = fixture(vault); + const read = vault.cachedRead.bind(vault); + let moved = false; + vault.cachedRead = async (file) => { + if (file.path === "z.md" && !moved) { + moved = true; + await vault.rename(vault.getAbstractFileByPath("Old/a.md") as never, "New/a.md"); + cache.onVaultFolderChange("Old", "New"); + } + return read(file); + }; + const records = await cache.loadCollectionRecords(); + assert.deepEqual(records.map(({ path }) => path), ["New/a.md", "z.md"]); + assert.deepEqual(await cache.loadCollectionRecords(), records); +}); + +test("a folder-only invalidation during incremental reads does not crash or restore stale paths", async () => { + const vault = new MemoryVault(); + await vault.create("Old/a.md", "---\ntype: moved\n---\n"); + await vault.create("b.md", "---\ntype: unchanged\n---\n"); + const cache = fixture(vault); + await cache.loadCollectionRecords(); + cache.markRecordChanged("Old/a.md"); + cache.markRecordChanged("b.md"); + const read = vault.cachedRead.bind(vault); + let moved = false; + vault.cachedRead = async (file) => { + const document = await read(file); + if (file.path === "Old/a.md" && !moved) { + moved = true; + await vault.rename(file, "New/a.md"); + cache.onVaultFolderChange("Old", "New"); + } + return document; + }; + const records = await cache.loadCollectionRecords(); + assert.deepEqual(records.map(({ path }) => path), ["b.md", "New/a.md"]); +}); diff --git a/test/connectSync.portability.test.ts b/test/connectSync.portability.test.ts index d80a34c..e7cde8d 100644 --- a/test/connectSync.portability.test.ts +++ b/test/connectSync.portability.test.ts @@ -90,6 +90,51 @@ test("a hosted spelling can conditionally update and remove an aliased cached TF assert.equal(vault.getFiles().length, 0); }); +test("a user rename during destination checks is not silently replaced by a hosted rename", async () => { + const vault = new AliasingVault(); + const file = await vault.create("note.md", "exact user bytes\n"); + const exists = vault.adapter.exists.bind(vault.adapter); + let raced = false; + vault.adapter.exists = async (path) => { + if (path === "hosted.md" && !raced) { + raced = true; + // Obsidian mutates a TFile's path in place when it is renamed. + const entry = vault.files.get("note.md")!; + vault.files.delete("note.md"); + file.path = "saved-by-user.md"; + vault.files.set(file.path, entry); + } + return exists(path); + }; + const fs = new ObsidianMirrorFileSystem(vault as never); + await assert.rejects(fs.move("note.md", "hosted.md"), (error: unknown) => (error as { code?: string }).code === "sync_plan_stale"); + assert.equal(vault.read("saved-by-user.md"), "exact user bytes\n"); + assert.equal(vault.read("hosted.md"), null); +}); + +test("a TFile renamed before an async cache lookup completes is not deleted at its new path", async () => { + const vault = new AliasingVault(); + const file = await vault.create("note.md", "keep this rename\n"); + const lookup = vault.getAbstractFileByPath.bind(vault); + let raced = false; + vault.getAbstractFileByPath = (path) => { + const result = lookup(path); + if (path === "note.md" && !raced) { + raced = true; + queueMicrotask(() => { + const entry = vault.files.get("note.md")!; + vault.files.delete("note.md"); + file.path = "saved-by-user.md"; + vault.files.set(file.path, entry); + }); + } + return result; + }; + const fs = new ObsidianMirrorFileSystem(vault as never); + await assert.rejects(fs.remove("note.md"), (error: unknown) => (error as { code?: string }).code === "sync_plan_stale"); + assert.equal(vault.read("saved-by-user.md"), "keep this rename\n"); +}); + test("binary inspection and writes use the aliased TFile rather than declaring it absent", async () => { const vault = new AliasingVault(); await vault.createBinary("cafe\u0301.png", new Uint8Array([0, 255, 128]).buffer); diff --git a/test/connectSync.settlement.test.ts b/test/connectSync.settlement.test.ts index 7308480..295c82f 100644 --- a/test/connectSync.settlement.test.ts +++ b/test/connectSync.settlement.test.ts @@ -9,9 +9,9 @@ import { MemoryMirrorBlobStore, MemoryMirrorStateStore, WritableDirectoryMirror, import { ConnectSyncController, ObsidianMirrorFileSystem, type MirrorProfile } from "../src/connectSync"; import { MemoryVault } from "./memoryVault"; -async function pair(document = "base line\n", extraRecords: { record_id: string; path: string; document: string }[] = []) { - const hosted = new MemoryAuthority(); - hosted.seed([{ record_id: "plan", path: "plan.md", frontmatter: {}, body: document, document, types: [] }, +async function pair(document = "base line\n", extraRecords: { record_id: string; path: string; document: string }[] = [], authority?: MemoryAuthority) { + const hosted = authority ?? new MemoryAuthority(); + if (!authority) hosted.seed([{ record_id: "plan", path: "plan.md", frontmatter: {}, body: document, document, types: [] }, ...extraRecords.map((record) => ({ ...record, frontmatter: {}, body: record.document, types: [] }))]); const replicaId = hosted.registerReplica({ name: "Here", mode: "read_write" }); const vault = new MemoryVault(); @@ -51,7 +51,7 @@ async function pair(document = "base line\n", extraRecords: { record_id: string; 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, + return { hosted, vault, state, controller, remoteVault, remoteMirror, sync, conflict, replicaId, wrap: (wrapper: typeof wrapTransport) => { wrapTransport = wrapper; } }; } @@ -271,14 +271,49 @@ test("an old conflict without ancestor capture keeps both and settles only once" assert.equal(copies(here.vault).length, 1); }); +test("two devices preserving different versions choose distinct sibling names before either uploads", async () => { + const left = await pair(); + const right = await pair("base line\n", [], left.hosted); + await left.vault.modify(left.vault.getAbstractFileByPath("plan.md") as TFile, "left recovery bytes\n"); + await right.vault.modify(right.vault.getAbstractFileByPath("plan.md") as TFile, "right recovery bytes\n"); + const [leftCopy, rightCopy] = await Promise.all([ + left.controller.preserveConflictCopy("plan.md"), + right.controller.preserveConflictCopy("plan.md"), + ]); + assert.notEqual(leftCopy, rightCopy, "local-only numbering races for one hosted path and strands a rejected recovery copy"); + await left.sync(); + await right.sync(); + await left.remoteMirror.sync(); + assert.equal(left.remoteVault.read(leftCopy), "left recovery bytes\n"); + assert.equal(left.remoteVault.read(rightCopy), "right recovery bytes\n"); +}); + +test("namespaced recovery copies fit a filesystem component without splitting Unicode", async () => { + const here = await pair(); + const original = `notes/${"📚".repeat(50)}.md`; + await here.vault.createFolder("notes"); + await here.vault.create(original, "long-name recovery bytes\n"); + const create = here.vault.createBinary.bind(here.vault); + here.vault.createBinary = async (path, bytes) => { + assert.ok(new TextEncoder().encode(path.split("/").at(-1)!).byteLength <= 255, "the OS refuses an oversized leaf name"); + return create(path, bytes); + }; + const copy = await here.controller.preserveConflictCopy(original); + assert.ok(copy.endsWith(`(local conflict copy ${here.replicaId}).md`)); + assert.ok(!copy.includes("�"), "truncate complete code points, not UTF-16 halves or UTF-8 bytes"); + assert.equal(here.vault.read(copy), "long-name recovery bytes\n"); + assert.equal(here.vault.read(original), "long-name recovery bytes\n"); +}); + 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 first = `plan (local conflict copy ${here.replicaId}).md`; + await here.vault.create(first, "older copy\n"); + await here.vault.createFolder(`plan (local conflict copy ${here.replicaId} 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(result?.copyPath, `plan (local conflict copy ${here.replicaId} 3).md`); + assert.equal(here.vault.read(first), "older copy\n"); assert.equal(here.vault.read(result!.copyPath!), "local line\n"); }); @@ -286,18 +321,19 @@ test("a collision created after naming a binary copy is never overwritten", asyn const here = await pair(); const content = new Uint8Array([0, 255, 1, 128]); await here.vault.createBinary("image.png", content.buffer); + const first = `image (local conflict copy ${here.replicaId}).png`; 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) { + if (path === first && !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(first), new Uint8Array([7, 8, 9])); assert.deepEqual(here.vault.readBytes("image.png"), content); }); @@ -305,7 +341,10 @@ 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"); + assert.equal(path, `plan (local conflict copy ${here.replicaId}).md`); + await here.vault.modify(here.vault.getAbstractFileByPath(path) as TFile, "copy changed again\n"); + const next = await here.controller.preserveConflictCopy(path); + assert.equal(next, `plan (local conflict copy ${here.replicaId} 2).md`, "namespaced copies flatten too"); }); test("concurrent settling reports one resolution, not a spurious missing-conflict error", async () => { diff --git a/test/connectSync.transport.test.ts b/test/connectSync.transport.test.ts index f6063dc..db8e68c 100644 --- a/test/connectSync.transport.test.ts +++ b/test/connectSync.transport.test.ts @@ -281,6 +281,14 @@ test("a rejected access token is renewed once and the request repeated", async ( error instanceof HttpStatusError && error.code === "mirror_access_rejected" && error.status === 401); }); +test("mobile lazy JSON getters cannot hide a transient plain-text HTTP error", async () => { + const nativeResponse = { status: 503, headers: { "Retry-After": "7" }, arrayBuffer: new ArrayBuffer(0), + text: "Service temporarily unavailable", get json(): unknown { throw new SyntaxError("native JSON getter cannot parse plain text"); } }; + const transport = new ObsidianSyncTransport(syncUrl, "test-token", async () => nativeResponse); + await assert.rejects(transport.openSession(), (error: unknown) => error instanceof HttpStatusError + && error.status === 503 && error.code === "authority_unavailable" && error.retryAfterMs === 7000 && isTransientError(error)); +}); + test("server errors are classified as transient, with their HTTP status", async () => { const transport = new ObsidianSyncTransport(syncUrl, "t", (async () => response(503, {})) as never); await assert.rejects(transport.openSession(), (error: unknown) => @@ -330,6 +338,81 @@ test("Obsidian HTTP transport downloads bounded binary parts and cleans up the t ]); }); +test("failed/cancelled object PUTs close their source without corrupting retained native request bytes", async () => { + for (const failure of ["http", "abort", "cleanup_error"] as const) { + const bytes = new Uint8Array([1, 2, 3]); + const file = descriptor("Media/cancelled.png", bytes); + const transferId = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"; + let closed = false; + let nativeBody: ArrayBuffer | undefined; + const source = (async function* () { + try { yield bytes; } finally { + closed = true; + bytes.fill(0); + if (failure === "cleanup_error") throw new Error("source cleanup failed"); + } + })(); + const transport = new ObsidianSyncTransport(syncUrl, "test-token", async (request) => { + if (request.url.endsWith("/uploads")) return response(200, { + protocol_version: 1, type: "file_transfer", transfer_id: transferId, direction: "upload", protection: "transport_tls", + total_size: 3, strategy: { kind: "object_put" }, received: [], uploaded_parts: [], + }); + if (request.url.endsWith("/parts")) return response(200, { + protocol_version: 1, type: "file_part", transfer_id: transferId, part_index: 0, offset: 0, content_length: 3, + method: "PUT", url: "https://objects.example/part", headers: {}, expires_at: "2099-01-01T00:00:00.000Z", + }); + if (request.url === "https://objects.example/part") { + nativeBody = request.body as ArrayBuffer; + if (failure === "abort") throw new DOMException("cancelled", "AbortError"); + return response(503); + } + throw new Error("unexpected test request"); + }); + await assert.rejects(transport.uploadFile({ protocol_version: 1, type: "open_file_upload", transfer_id: transferId, + path: file.path, size: file.size, content_digest: file.content_digest }, source), failure === "abort" ? /cancelled/ : /HTTP 503/); + assert.equal(closed, true, "source cleanup must run on cancellation/failed transfer"); + assert.deepEqual(new Uint8Array(nativeBody!), new Uint8Array([1, 2, 3]), "late native PUT must retain the original snapshot"); + } +}); + +test("resumed multipart uploads do not allocate output buffers for already received parts", async () => { + const partSize = 256 * 1024; + const bytes = new Uint8Array(4 * partSize).fill(11); + const file = descriptor("Media/resume.png", bytes); + const transferId = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"; + const transport = new ObsidianSyncTransport(syncUrl, "test-token", async (request) => { + if (request.url.endsWith("/uploads")) return response(200, { + protocol_version: 1, type: "file_transfer", transfer_id: transferId, direction: "upload", protection: "transport_tls", + total_size: bytes.length, strategy: { kind: "object_multipart", part_size: partSize }, received: [0, 1, 2], + uploaded_parts: [1, 2, 3].map((part_number) => ({ part_number, etag: `part-${part_number}` })), + }); + if (request.url.endsWith("/parts")) return response(200, { + protocol_version: 1, type: "file_part", transfer_id: transferId, part_index: 3, offset: 3 * partSize, + content_length: partSize, method: "PUT", url: "https://objects.example/last", headers: {}, expires_at: "2099-01-01T00:00:00.000Z", + }); + if (request.url === "https://objects.example/last") { + assert.deepEqual(new Uint8Array(request.body as ArrayBuffer), bytes.subarray(3 * partSize)); + return response(200, {}, new ArrayBuffer(0), { etag: "part-4" }); + } + if (request.url.endsWith("/commit")) { + assert.deepEqual((JSON.parse(request.body as string) as { parts: unknown }).parts, + [1, 2, 3, 4].map((part_number) => ({ part_number, etag: `part-${part_number}` }))); + return response(200, { protocol_version: 1, type: "file_upload_committed", transfer_id: transferId, file }); + } + throw new Error("unexpected request"); + }); + const NativeArrayBuffer = globalThis.ArrayBuffer; + let allocated = 0; + globalThis.ArrayBuffer = class extends NativeArrayBuffer { + constructor(length = 0) { super(length); allocated += length; } + }; + try { + await transport.uploadFile({ protocol_version: 1, type: "open_file_upload", transfer_id: transferId, + path: file.path, size: file.size, content_digest: file.content_digest }, (async function* () { yield bytes; })()); + } finally { globalThis.ArrayBuffer = NativeArrayBuffer; } + assert.equal(allocated, partSize, "only the outstanding part needs an output buffer"); +}); + test("multipart uploads do not repeatedly copy the whole unconsumed source tail", async () => { const bytes = new Uint8Array(8 * 1024 * 1024).fill(7); const file = descriptor("Media/large.png", bytes); diff --git a/test/schemaCache.test.ts b/test/schemaCache.test.ts new file mode 100644 index 0000000..4c71020 --- /dev/null +++ b/test/schemaCache.test.ts @@ -0,0 +1,89 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import MdbasePlugin from "../main"; +import { MemoryVault } from "./memoryVault"; +import type { MdbaseConfig } from "../src/mdbaseCore"; + +type Schema = { config: MdbaseConfig }; +function fixture(vault: MemoryVault) { + const plugin = new MdbasePlugin({ vault } as never, {} as never); + return plugin as unknown as { + getConfigAndTypes(): Promise; + invalidateSchemaCache(): void; + }; +} + +function deferred() { + let resolve!: () => void; + const promise = new Promise(done => { resolve = done; }); + return { promise, resolve }; +} + +test("invalidated schema loads and their coalesced callers cannot replace newer rules", async () => { + const vault = new MemoryVault(); + const file = await vault.create("mdbase.yaml", "spec_version: 0.3.0\nname: old\n"); + const cache = fixture(vault); + const entered = deferred(); + const release = deferred(); + const read = vault.cachedRead.bind(vault); + let first = true; + vault.cachedRead = async (target) => { + const document = await read(target); + if (target.path === file.path && first) { + first = false; + entered.resolve(); + await release.promise; + } + return document; + }; + const old = cache.getConfigAndTypes(); + await entered.promise; + const coalesced = cache.getConfigAndTypes(); + await vault.modify(file, "spec_version: 0.3.0\nname: new\n"); + cache.invalidateSchemaCache(); + const current = await cache.getConfigAndTypes(); + release.resolve(); + assert.equal(current?.config.name, "new"); + assert.equal(await old, current, "older waiter must receive current rules, not republish its stale load"); + assert.equal(await coalesced, current, "coalesced waiters need the same invalidation fence"); + assert.equal(await cache.getConfigAndTypes(), current); +}); + +test("errors from an invalidated type read cannot replace a newer successful load", async () => { + const vault = new MemoryVault(); + await vault.create("mdbase.yaml", "spec_version: 0.3.0\nname: rules\n"); + const file = await vault.create("_types/task.md", "---\nkind: mdbase.type\nname: task\nschema:\n value:\n type: object\n properties:\n title:\n type: string\n---\n"); + const cache = fixture(vault); + const entered = deferred(); + const release = deferred(); + const read = vault.cachedRead.bind(vault); + let first = true; + vault.cachedRead = async (target) => { + if (target.path === file.path && first) { + first = false; + entered.resolve(); + await release.promise; + throw new Error("the old type read was invalidated"); + } + return read(target); + }; + const old = cache.getConfigAndTypes(); + await entered.promise; + cache.invalidateSchemaCache(); + const current = await cache.getConfigAndTypes(); + release.resolve(); + assert.ok(current); + assert.equal(await old, current); + assert.equal(await cache.getConfigAndTypes(), current); +}); + +test("an invalidated no-config result cannot conceal a newly created collection", async () => { + const vault = new MemoryVault(); + const cache = fixture(vault); + const old = cache.getConfigAndTypes(); + cache.invalidateSchemaCache(); + await vault.create("mdbase.yaml", "spec_version: 0.3.0\nname: created\n"); + const current = await cache.getConfigAndTypes(); + assert.equal(current?.config.name, "created"); + assert.equal(await old, current); +}); diff --git a/test/settingsTab.test.ts b/test/settingsTab.test.ts index 543be54..47f6ef6 100644 --- a/test/settingsTab.test.ts +++ b/test/settingsTab.test.ts @@ -21,6 +21,8 @@ function fixture() { }, createDiv(this: HTMLElement, options = {}) { return this.createEl("div", options); }, setAttr(this: HTMLElement, name: string, value: string) { this.setAttribute(name, value); }, + setText(this: HTMLElement, value: string) { this.textContent = value; }, + addClass(this: HTMLElement, ...names: string[]) { this.classList.add(...names); }, empty(this: HTMLElement) { this.replaceChildren(); }, }); const notices = (Notice as unknown as { messages: string[] }).messages; @@ -31,16 +33,18 @@ function fixture() { saveSettings: async () => undefined, requestSync: () => undefined, getMirrorProfile: () => ({ name: "Notes", mode: "read_write", controlUrl: "https://connect.example" }), - openWorkspace: async () => ({ reconnectCollection: async () => undefined }), + openWorkspace: async (_destination: string) => ({ reconnectCollection: async () => undefined }), connectSync: { getSelectiveSync: () => policy }, sync: { isSyncing: () => false, configureSelectiveSync: async (next: typeof policy) => { policy = next; }, }, }; - const tab = new MdbaseSettingTab({ vault: { getAllLoadedFiles: () => [] } } as never, plugin as never); + let settingsClosed = 0; + const app = { vault: { getAllLoadedFiles: () => [] }, setting: { close: () => { settingsClosed++; } } }; + const tab = new MdbaseSettingTab(app as never, plugin as never); tab.display(); - return { dom, plugin, tab, root: tab.containerEl, notices, policy: () => policy }; + return { dom, plugin, tab, root: tab.containerEl, notices, policy: () => policy, settingsClosed: () => settingsClosed }; } function button(root: HTMLElement, label: string): HTMLButtonElement { @@ -51,6 +55,27 @@ function button(root: HTMLElement, label: string): HTMLButtonElement { const settle = () => new Promise(resolve => setImmediate(resolve)); +test("Open sync and Reconnect close settings before handing off to the workspace", async () => { + for (const connected of [false, true]) { + const f = fixture(); + if (!connected) Object.assign(f.plugin, { getMirrorProfile: () => null }); + let opened = 0; + let reconnected = 0; + f.plugin.openWorkspace = async (destination) => { + assert.equal(destination, "sync"); + assert.equal(f.settingsClosed(), 1, "approval and cancellation must not stay hidden behind settings"); + opened++; + return { reconnectCollection: async () => { reconnected++; } }; + }; + f.tab.display(); + button(f.root, connected ? "Reconnect" : "Open sync").click(); + await settle(); + assert.equal(opened, 1); + assert.equal(reconnected, connected ? 1 : 0); + f.dom.window.close(); + } +}); + test("failed exclusion changes report only failure and leave the saved scope unchanged", async () => { const f = fixture(); f.plugin.sync.configureSelectiveSync = async () => { throw new Error("Settings could not be saved"); }; @@ -86,6 +111,53 @@ test("applying exclusions waits for persistence and prevents duplicate requests" f.dom.window.close(); }); +test("disconnect stays disabled through its decision and completion, without duplicate requests", async () => { + const f = fixture(); + let disconnected = 0; + let finish: () => void = () => assert.fail("Disconnect not started"); + Object.assign(f.plugin.sync, { + state: { message: "Disconnected. Local files kept." }, + disconnect: async () => { disconnected++; await new Promise(resolve => { finish = resolve; }); }, + }); + const disconnect = button(f.root, "Disconnect…"); + disconnect.click(); + assert.equal(disconnect.disabled, true, "only one disconnect decision at a time"); + button(f.dom.window.document.body, "Keep files").click(); + await settle(); + assert.equal(disconnect.disabled, true, "do not offer another disconnect while cleanup is running"); + assert.equal(disconnect.textContent, "Disconnecting…"); + disconnect.click(); + assert.equal(disconnected, 1); + finish(); + await settle(); + assert.deepEqual(f.notices, ["Disconnected. Local files kept."]); + assert.equal(button(f.root, "Disconnect…").disabled, false); + f.dom.window.close(); +}); + +test("cancelling disconnect restores its original action without rerendering settings", async () => { + const f = fixture(); + const disconnect = button(f.root, "Disconnect…"); + disconnect.click(); + button(f.dom.window.document.body, "Cancel").click(); + await settle(); + assert.equal(button(f.root, "Disconnect…"), disconnect, "native focus can return to the same button"); + assert.equal(disconnect.disabled, false); + assert.deepEqual(f.notices, []); + f.dom.window.close(); +}); + +test("Open sync failures report a notice instead of an unhandled settings rejection", async () => { + const f = fixture(); + Object.assign(f.plugin, { getMirrorProfile: () => null }); + f.plugin.openWorkspace = async () => { throw new Error("Workspace could not open"); }; + f.tab.display(); + button(f.root, "Open sync").click(); + await settle(); + assert.deepEqual(f.notices, ["Workspace could not open"]); + f.dom.window.close(); +}); + test("reconnect failures restore the settings action and report the error", async () => { const f = fixture(); f.plugin.openWorkspace = async () => { throw new Error("Workspace could not open"); }; diff --git a/test/syncReliability.test.ts b/test/syncReliability.test.ts index 6be7ef8..27d3630 100644 --- a/test/syncReliability.test.ts +++ b/test/syncReliability.test.ts @@ -93,6 +93,33 @@ async function device(hosted: MemoryAuthority, collectionId: string, options: De return { vault, controller, state, states, secrets, replicaId, profile: () => profile, syncOnce }; } +/** An independently loaded controller for the same physical vault (another window). */ +function sameVaultController(hosted: MemoryAuthority, here: Awaited>, options: { + profile?: MirrorProfile; + enrollmentClient?: Partial; +} = {}) { + let profile: MirrorProfile | null = structuredClone(options.profile ?? here.profile()); + assert.ok(profile); + here.secrets.setSecret(`mdbase-connect-access-${profile.replicaId}`, "access"); + here.secrets.setSecret(`mdbase-connect-refresh-${profile.replicaId}`, "refresh"); + const controller = new ConnectSyncController({ vault: here.vault, secretStorage: here.secrets } as never, { + getMirrorProfile: () => profile && structuredClone(profile), + saveMirrorProfile: async (next) => { profile = next; }, + deviceId: () => "this-device", + }, { + stateStoreFactory: (current) => { + let state = here.states.get(current.replicaId); + if (!state) { state = new MemoryMirrorStateStore(); here.states.set(current.replicaId, state); } + return state; + }, + blobStoreFactory: () => new MemoryMirrorBlobStore(), + fileSystem: new ObsidianMirrorFileSystem(here.vault as never), + transportFactory: (current) => hosted.transport(current.replicaId), + ...(options.enrollmentClient ? { enrollmentClient: options.enrollmentClient as MirrorEnrollmentClient } : {}), + }); + return { controller, profile: () => profile }; +} + test("the remote change probe uses the state store's lean checkpoint port", async () => { class ProbeState extends MemoryMirrorStateStore { reads = 0; @@ -121,7 +148,6 @@ test("the remote change probe uses the state store's lean checkpoint port", asyn assert.equal(changes, 1); here.controller.dispose(); }); - /** A second device that edits through the bare SDK engine. */ function otherDevice(hosted: MemoryAuthority) { const replica = hosted.registerReplica({ name: "Other", mode: "read_write" }); @@ -229,13 +255,13 @@ test("the same line edited on two devices keeps both versions and loses nothing" const [resolution] = await here.controller.autoResolveConflicts(); assert.equal(resolution?.outcome, "kept_both"); - assert.equal(resolution?.copyPath, "plan (local conflict copy).md"); + assert.match(resolution!.copyPath!, /^plan \(local conflict copy [a-zA-Z0-9%_-]+\)\.md$/); assert.equal(here.vault.read("plan.md"), "remote line\n"); - assert.equal(here.vault.read("plan (local conflict copy).md"), "local line\n"); + assert.equal(here.vault.read(resolution!.copyPath!), "local line\n"); await here.syncOnce(); await there.mirror.sync(); - assert.equal(there.vault.read("plan (local conflict copy).md"), "local line\n", "the kept copy reaches every device"); + assert.equal(there.vault.read(resolution!.copyPath!), "local line\n", "the kept copy reaches every device"); }); test("an edit beats a deletion in either direction", async () => { @@ -317,6 +343,43 @@ test("the mirror's own writes are recognised as echoes, not edits", async () => assert.equal(controller.consumeEngineWrite("notes/other.md"), false); }); +test("bulk mirror echo tracking expires ordered entries without scanning every live path", () => { + const controller = new ConnectSyncController({ vault: new MemoryVault() } as never, { + getMirrorProfile: () => null, saveMirrorProfile: async () => undefined, + }); + const tracker = controller as unknown as { + engineWrites: Map; noteEngineWrite(path: string): void; + }; + let clock = 10_000; + const now = performance.now; + const wallNow = Date.now; + performance.now = () => clock; + Date.now = () => clock; + let visited = 0; + const iterator = tracker.engineWrites[Symbol.iterator].bind(tracker.engineWrites); + tracker.engineWrites[Symbol.iterator] = function* () { + for (const entry of iterator()) { visited++; yield entry; } + }; + try { + for (let index = 0; index < 10_000; index++) tracker.noteEngineWrite(`${index}.md`); + assert.ok(visited <= 20_000, `Bulk writes visited ${visited} live echo entries`); + clock += 1_000; + tracker.noteEngineWrite("0.md"); // Refreshing an old key must move it to the tail. + clock += 1_001; + tracker.noteEngineWrite("new.md"); + assert.equal(tracker.engineWrites.size, 2, "expired entries behind a refreshed key must be removed"); + Date.now = () => 9e12; + assert.equal(controller.consumeEngineWrite("0.md"), true, "wall-clock jumps do not change the echo's age"); + assert.equal(controller.consumeEngineWrite("0.md"), false, "one echo only; the next edit is real"); + clock += 2_001; + assert.equal(controller.consumeEngineWrite("new.md"), false, "expired writes cannot hide an edit"); + } finally { + performance.now = now; + Date.now = wallNow; + controller.dispose(); + } +}); + test("text downloads cannot follow a TFile renamed while Vault.process is queued", async () => { const vault = new MemoryVault(); const file = await vault.create("note.md", "base\n"); @@ -575,6 +638,125 @@ test("disconnect cannot retire a mirror while another controller holds its SDK l other.dispose(); }); +test("another replica enrollment on the same vault still shares the directory lease", async () => { + const hosted = new MemoryAuthority(); + const id = await collectionId(hosted); + const entered = deferred(); + const gate = deferred(); + const here = await device(hosted, id, { + wrapTransport: (transport) => ({ ...transport, openSession: async () => { + entered.release(); await gate.promise; return transport.openSession(); + } }), + }); + const running = here.controller.inspect(); + await entered.promise; + const replica = hosted.registerReplica({ name: "New approval", mode: "read_write" }); + const other = sameVaultController(hosted, here, { profile: { ...here.profile()!, replicaId: replica } }); + try { + await assert.rejects(other.controller.inspect(), (error: unknown) => (error as { code?: string }).code === "mirror_busy"); + } finally { gate.release(); await running; } + here.controller.dispose(); other.controller.dispose(); +}); + +test("reauthorization cannot migrate credentials and checkpoint during another window's SDK operation", async () => { + const hosted = new MemoryAuthority(); + const id = await collectionId(hosted); + const entered = deferred(); + const gate = deferred(); + const here = await device(hosted, id, { + wrapTransport: (transport) => ({ ...transport, openSession: async () => { + entered.release(); await gate.promise; return transport.openSession(); + } }), + }); + const running = here.controller.inspect(); + await entered.promise; + const replica = hosted.registerReplica({ name: "New approval", mode: "read_write" }); + const other = sameVaultController(hosted, here, { enrollmentClient: { enroll: async () => ({ + ...here.profile()!, replicaId: replica, accessToken: "new-access", refreshCredential: "new-refresh", + }) } }); + try { + await assert.rejects(other.controller.reauthorize({ onVerification: () => undefined }), (error: unknown) => + (error as { code?: string }).code === "mirror_busy"); + assert.equal(other.profile()?.replicaId, here.replicaId); + assert.equal(here.secrets.getSecret(`mdbase-connect-access-${here.replicaId}`), "access"); + } finally { gate.release(); await running; } + here.controller.dispose(); other.controller.dispose(); +}); + +test("a renewal in another window cannot restore credentials after the vault disconnected", async () => { + const hosted = new MemoryAuthority(); + const id = await collectionId(hosted); + const here = await device(hosted, id); + const entered = deferred(); + const gate = deferred(); + const other = sameVaultController(hosted, here, { enrollmentClient: { renew: async (enrollment) => { + entered.release(); await gate.promise; + return { ...enrollment, accessToken: "late-token" }; + } } }); + const renewing = other.controller.reconnect(); + const completed = Promise.allSettled([renewing]); + await entered.promise; + await here.controller.disconnect(false); + gate.release(); + const [result] = await completed; + assert.equal(result!.status, "rejected"); + assert.equal(here.secrets.getSecret(`mdbase-connect-access-${here.replicaId}`), "", "shared credentials stay retired even though the other window cached its old profile"); + here.controller.dispose(); other.controller.dispose(); +}); + +test("a retired replica's late renewal cannot undo another window's new approval", async () => { + const hosted = new MemoryAuthority(); + const id = await collectionId(hosted); + const approved = hosted.registerReplica({ name: "Reapproved", mode: "read_write" }); + const here = await device(hosted, id, { enrollmentClient: { enroll: async () => ({ + controlUrl: "https://connect.example", syncUrl: `https://sync.example/v1/authorities/${id}/sync`, + collectionId: id, replicaId: approved, mode: "read_write", name: "Reapproved", + enrollmentId: "22222222-2222-4222-8222-222222222222", accessToken: "approved-access", + refreshCredential: "approved-refresh", accessTokenExpiresAt: "2099-01-01T00:00:00.000Z", + }) } }); + const entered = deferred(); + const gate = deferred(); + const other = sameVaultController(hosted, here, { enrollmentClient: { renew: async (enrollment) => { + entered.release(); await gate.promise; return { ...enrollment, accessToken: "late-token" }; + } } }); + const renewing = other.controller.reconnect(); + const completed = Promise.allSettled([renewing]); + await entered.promise; + await here.controller.reauthorize({ onVerification: () => undefined }); + gate.release(); + const [result] = await completed; + assert.equal(result!.status, "rejected"); + assert.equal(here.profile()?.replicaId, approved); + assert.equal(here.secrets.getSecret(`mdbase-connect-access-${here.replicaId}`), ""); + here.controller.dispose(); other.controller.dispose(); +}); + +test("token renewal inside an SDK operation can commit under the lease it already owns", async () => { + const hosted = new MemoryAuthority(); + const id = await collectionId(hosted); + let here!: Awaited>; + let renewals = 0; + let renewed = false; + here = await device(hosted, id, { + enrollmentClient: { renew: async (enrollment) => { + renewals++; return { ...enrollment, accessToken: "fresh-token" }; + } }, + wrapTransport: (transport) => ({ ...transport, snapshot: async (snapshotId, page) => { + if (!renewed) { + renewed = true; + // This is the same credentials callback used after an HTTP 401. + const source = (here.controller as unknown as { transportCredentials(profile: MirrorProfile): { renew(token: string): Promise } }).transportCredentials(here.profile()!); + assert.equal(await source.renew("access"), "fresh-token"); + } + return transport.snapshot(snapshotId, page); + } }), + }); + await here.controller.inspect(); + assert.equal(renewals, 1); + assert.equal(here.secrets.getSecret(`mdbase-connect-access-${here.replicaId}`), "fresh-token"); + here.controller.dispose(); +}); + 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: [] }]); diff --git a/test/syncUx.test.ts b/test/syncUx.test.ts index 0b60ba1..bbd5b94 100644 --- a/test/syncUx.test.ts +++ b/test/syncUx.test.ts @@ -111,6 +111,16 @@ test("sync indicator gives transfer, attention, waiting, and synced states stabl assert.match(transferring.detail, /large\.bin/); }); +test("checking a new sync plan does not claim the old healthy checkpoint is already Synced", () => { + const base = { connected: true, status: status(), progress: null, fileProgress: null, problem: null, validationIssues: 0, localChangeObserved: false, busy: true }; + const indicator = syncIndicator(base); + assert.equal(indicator.state, "syncing"); + assert.equal(indicator.label, "mdbase: Checking…"); + assert.match(indicator.detail, /Checking/); + assert.equal(syncIndicator({ ...base, paused: true }).label, "mdbase: Stopping…", "honour a pause requested while checking finishes"); + assert.match(syncIndicator({ ...base, fileProgress: { direction: "upload", path: "a.md", transferredBytes: 1, totalBytes: 2 } as const }).label, /Uploading/); +}); + test("an explicit pause cannot claim Synced just because the last checkpoint is healthy", () => { const base = { connected: true, status: status(), progress: null, fileProgress: null, problem: null, validationIssues: 0, localChangeObserved: false, paused: true }; const indicator = syncIndicator(base); diff --git a/test/v3-foundations.test.ts b/test/v3-foundations.test.ts index 03fe633..9967205 100644 --- a/test/v3-foundations.test.ts +++ b/test/v3-foundations.test.ts @@ -1420,7 +1420,7 @@ test("conflict copy uses a collision-safe sibling without changing the original" const vault = new MemoryVault(); await vault.createFolder("notes"); await vault.create("notes/conflict.md", "local version\n"); - await vault.create("notes/conflict (local conflict copy).md", "older copy\n"); + await vault.create("notes/conflict (local conflict copy replica).md", "older copy\n"); const profile = { version: 1 as const, syncUrl: "https://sync.example/v1/authorities/collection/sync", @@ -1442,7 +1442,8 @@ test("conflict copy uses a collision-safe sibling without changing the original" const copied = await controller.preserveConflictCopy("notes/conflict.md"); - assert.equal(copied, "notes/conflict (local conflict copy 2).md"); + assert.equal(copied, "notes/conflict (local conflict copy replica 2).md"); + assert.equal(vault.read("notes/conflict (local conflict copy replica).md"), "older copy\n"); assert.equal(vault.read(copied), "local version\n"); assert.equal(vault.read("notes/conflict.md"), "local version\n"); }); diff --git a/test/workspaceView.test.ts b/test/workspaceView.test.ts index d9af8b8..43a4172 100644 --- a/test/workspaceView.test.ts +++ b/test/workspaceView.test.ts @@ -2,6 +2,7 @@ import assert from "node:assert/strict"; import { test } from "node:test"; import { JSDOM } from "jsdom"; import { CreateTypedNoteModal } from "../src/createTypedNoteModal"; +import { DisconnectMirrorModal } from "../src/modals"; import { MdbaseWorkspaceView } from "../src/workspaceView"; import { createDefaultTypeModel } from "../src/typeModel"; import { typeDefFromDraft } from "../src/typeImpact"; @@ -600,6 +601,32 @@ test("conflict choices respect absent versions and name destructive outcomes", a } }); +test("conflict decisions wait for active sync while their comparison remains readable", async () => { + const f = fixture(true); + f.state.mirrorStatus = { state: "attention", local_issues: [], conflicts: [{ entity: "record", object_id: "record", decision_id: "decision", path: "note.md" }] }; + let syncing = false; + Object.assign(f.host.connectSync, { + isSyncing: () => syncing, + conflictComparison: async () => ({ entity: "record", objectId: "record", decisionId: "decision", local: { state: "exact", document: "Local edit" }, remote: { state: "exact", document: "Hosted edit" } }), + }); + f.state.render(); + button(f.root, "Resolve…").click(); + await settle(); + for (const busySession of [true, false]) { + syncing = !busySession; + f.host.sync.update({ busy: busySession }); + f.state.render(); + for (const label of ["Keep local", "Use hosted", "Keep both"]) assert.equal(button(f.root, label).disabled, true, label); + assert.equal(button(f.root, "Hide").disabled, false, "review remains available without committing a stale decision"); + assert.match(f.text(), /Local edit.*Hosted edit/); + } + syncing = false; + f.host.sync.update({ busy: false }); + f.state.render(); + assert.equal(button(f.root, "Keep both").disabled, false); + f.dom.window.close(); +}); + test("the single save bar updates validity while typing without replacing the focused input", async () => { const f = fixture(); f.state.destination = "types"; @@ -948,6 +975,28 @@ test("sync actions and filters preserve focus across progress and review renders f.dom.window.close(); }); +test("popout inputs retain their selection even when DOM constructors belong to another window", () => { + const popout = fixture(true); + // A second realm represents the main window where the plugin module executes. + const main = fixture(); + popout.host.getIssues = () => [{ path: "notes.md", severity: "error", code: "required", message: "Missing title" }]; + popout.state.destination = "issues"; + popout.state.render(); + let search = popout.root.querySelector("[data-focus-key='issue-search']")!; + search.value = "notes"; + search.dispatchEvent(new popout.dom.window.Event("input")); + search = popout.root.querySelector("[data-focus-key='issue-search']")!; + search.focus(); + search.setSelectionRange(1, 3); + popout.state.render(); + const restored = popout.root.querySelector("[data-focus-key='issue-search']")!; + assert.equal(popout.dom.window.document.activeElement, restored); + assert.equal(restored.selectionStart, 1); + assert.equal(restored.selectionEnd, 3); + popout.dom.window.close(); + main.dom.window.close(); +}); + test("quoted transfer paths cannot break focus restoration while comparing changes", () => { const f = fixture(true); (f.view as unknown as { app: { vault: { getAbstractFileByPath(path: string): unknown } } }).app.vault.getAbstractFileByPath = () => ({}); @@ -983,6 +1032,38 @@ test("pending record updates can be compared before syncing", async () => { f.dom.window.close(); }); +test("pending comparisons cannot replace a newer plan's versions or loading state", async () => { + for (const concurrent of [false, true]) for (const rejectOld of [false, true]) { + const f = fixture(true); + const requests: Array<{ resolve(value: unknown): void; reject(error: Error): void }> = []; + const preview = () => ({ phase: "incremental", plan: { actions: [{}], issues: [], summary: { blocking_issues: 0 } }, entries: [{ kind: "document", path: "note.md", direction: "download", action: "update", detail: "Download change", recordId: "record" }], collisions: [], local_issues: [] }); + const comparison = (version: string) => ({ entity: "record", objectId: "record", decisionId: "", local: { state: "exact", document: `${version} local line` }, remote: { state: "exact", document: `${version} hosted line` } }); + (f.view as unknown as { app: { vault: { getAbstractFileByPath(path: string): unknown } } }).app.vault.getAbstractFileByPath = () => ({}); + Object.assign(f.host.connectSync, { recordComparison: () => new Promise((resolve, reject) => requests.push({ resolve, reject })) }); + f.state.mirrorPreview = preview(); + f.state.render(); + button(f.root, "Compare").click(); + f.state.mirrorPreview = preview(); + f.state.render(); + if (concurrent) button(f.root, "Compare").click(); + if (rejectOld) requests[0].reject(new Error("Outdated request failed")); + else requests[0].resolve(comparison("Outdated")); + await settle(); + assert.doesNotMatch(f.text(), /Outdated local line|Outdated hosted line/, "old results must not appear under the new plan"); + assert.equal(f.state.transientMessage, "", "obsolete errors must not interrupt the newer review"); + if (concurrent) { + assert.equal(button(f.root, "Loading…").disabled, true, "old cleanup must not enable a newer pending request"); + } else { + assert.equal(button(f.root, "Compare").disabled, false); + button(f.root, "Compare").click(); + } + requests[1].resolve(comparison("Newest")); + await settle(); + assert.match(f.text(), /Newest local line.*Newest hosted line/); + f.dom.window.close(); + } +}); + test("collapsed history does not construct hidden transfer ledgers", () => { const f = fixture(true); const at = new Date().toISOString(); @@ -1242,6 +1323,20 @@ test("empty collections offer contract packs rather than invented starter types" f.dom.window.close(); }); +test("disconnect names the trash boundary and retains the safe keep-files default", async () => { + const f = fixture(); + for (const [label, expected] of [["Cancel", null], ["Keep files", "keep"], ["Trash unchanged files", "remove"]] as const) { + const modal = new DisconnectMirrorModal({} as never); + const choice = modal.choose("Project notes"); + assert.match(modal.contentEl.textContent!, /move unchanged synced files to trash.*Local edits are kept either way/); + assert.ok(button(modal.contentEl, "Keep files").classList.contains("mod-cta")); + assert.ok(button(modal.contentEl, "Trash unchanged files").classList.contains("mod-warning")); + button(modal.contentEl, label).click(); + assert.equal(await choice, expected); + } + f.dom.window.close(); +}); + test("native-style creation modal retains inputs across errors and preserves boolean and enum types", async () => { const f = fixture(); const config = { spec_version: "0.3.0", settings: { types_folder: "_types", explicit_type_keys: ["type"], exclude: [] } };