From 1266edf8a6ab8f6d2967290f02437b171f97b8ba Mon Sep 17 00:00:00 2001 From: callumalpass Date: Fri, 7 Aug 2026 01:31:02 +1000 Subject: [PATCH 1/3] refactor(sync): consume the engine-owned plan --- main.js | 242 ++++++++++++++++++------------------ main.ts | 12 +- scripts/check-mobile.mjs | 5 +- src/connectSync.ts | 49 ++++++-- src/syncPreview.ts | 119 ++++++++++++++++++ src/workspaceView.ts | 52 ++++++-- test/syncPreview.test.ts | 109 ++++++++++++++++ test/v3-foundations.test.ts | 39 +++++- 8 files changed, 480 insertions(+), 147 deletions(-) create mode 100644 src/syncPreview.ts create mode 100644 test/syncPreview.test.ts diff --git a/main.js b/main.js index cd1b760..71f2d83 100644 --- a/main.js +++ b/main.js @@ -3,180 +3,176 @@ THIS IS A GENERATED/BUNDLED FILE BY ESBUILD if you want to view the source, please visit the github repository of this plugin */ -var Qw=Object.create;var Ni=Object.defineProperty;var Zw=Object.getOwnPropertyDescriptor;var e0=Object.getOwnPropertyNames;var t0=Object.getPrototypeOf,r0=Object.prototype.hasOwnProperty;var n0=(r,e,t)=>e in r?Ni(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var A=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),i0=(r,e)=>{for(var t in e)Ni(r,t,{get:e[t],enumerable:!0})},tp=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of e0(e))!r0.call(r,i)&&i!==t&&Ni(r,i,{get:()=>e[i],enumerable:!(n=Zw(e,i))||n.enumerable});return r};var ln=(r,e,t)=>(t=r!=null?Qw(t0(r)):{},tp(e||!r||!r.__esModule?Ni(t,"default",{value:r,enumerable:!0}):t,r)),s0=r=>tp(Ni({},"__esModule",{value:!0}),r);var T=(r,e,t)=>n0(r,typeof e!="symbol"?e+"":e,t);var ji=A(le=>{"use strict";Object.defineProperty(le,"__esModule",{value:!0});le.regexpCode=le.getEsmExportName=le.getProperty=le.safeStringify=le.stringify=le.strConcat=le.addCodeArg=le.str=le._=le.nil=le._Code=le.Name=le.IDENTIFIER=le._CodeOrName=void 0;var Di=class{};le._CodeOrName=Di;le.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var dn=class extends Di{constructor(e){if(super(),!le.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}}};le.Name=dn;var At=class extends Di{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 dn&&(t[n.str]=(t[n.str]||0)+1),t),{})}};le._Code=At;le.nil=new At("");function rp(r,...e){let t=[r[0]],n=0;for(;n{"use strict";Object.defineProperty(dt,"__esModule",{value:!0});dt.ValueScope=dt.ValueScopeName=dt.Scope=dt.varKinds=dt.UsedValueState=void 0;var lt=ji(),Mc=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},po;(function(r){r[r.Started=0]="Started",r[r.Completed=1]="Completed"})(po||(dt.UsedValueState=po={}));dt.varKinds={const:new lt.Name("const"),let:new lt.Name("let"),var:new lt.Name("var")};var ho=class{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t}toName(e){return e instanceof lt.Name?e:this.name(e)}name(e){return new lt.Name(this._newName(e))}_newName(e){let t=this._names[e]||this._nameGroup(e);return`${e}${t.index++}`}_nameGroup(e){var t,n;if(!((n=(t=this._parent)===null||t===void 0?void 0:t._prefixes)===null||n===void 0)&&n.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};dt.Scope=ho;var mo=class extends lt.Name{constructor(e,t){super(t),this.prefix=e}setValue(e,{property:t,itemIndex:n}){this.value=e,this.scopePath=(0,lt._)`.${new lt.Name(t)}[${n}]`}};dt.ValueScopeName=mo;var h0=(0,lt._)`\n`,Nc=class extends ho{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?h0:lt.nil}}get(){return this._scope}name(e){return new mo(e,this._newName(e))}value(e,t){var n;if(t.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let i=this.toName(e),{prefix:s}=i,o=(n=t.key)!==null&&n!==void 0?n:t.ref,a=this._values[s];if(a){let u=a.get(o);if(u)return u}else a=this._values[s]=new Map;a.set(o,i);let c=this._scope[s]||(this._scope[s]=[]),l=c.length;return c[l]=t.ref,i.setValue(t,{property:s,itemIndex:l}),i}getValue(e,t){let n=this._values[e];if(n)return n.get(t)}scopeRefs(e,t=this._values){return this._reduceValues(t,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,lt._)`${e}${n.scopePath}`})}scopeCode(e=this._values,t,n){return this._reduceValues(e,i=>{if(i.value===void 0)throw new Error(`CodeGen: name "${i}" has no value`);return i.value.code},t,n)}_reduceValues(e,t,n={},i){let s=lt.nil;for(let o in e){let a=e[o];if(!a)continue;let c=n[o]=n[o]||new Map;a.forEach(l=>{if(c.has(l))return;c.set(l,po.Started);let u=t(l);if(u){let d=this.opts.es5?dt.varKinds.var:dt.varKinds.const;s=(0,lt._)`${s}${d} ${l} = ${u};${this.opts._n}`}else if(u=i==null?void 0:i(l))s=(0,lt._)`${s}${u}${this.opts._n}`;else throw new Mc(l);c.set(l,po.Completed)})}return s}};dt.ValueScope=Nc});var K=A(Q=>{"use strict";Object.defineProperty(Q,"__esModule",{value:!0});Q.or=Q.and=Q.not=Q.CodeGen=Q.operators=Q.varKinds=Q.ValueScopeName=Q.ValueScope=Q.Scope=Q.Name=Q.regexpCode=Q.stringify=Q.getProperty=Q.nil=Q.strConcat=Q.str=Q._=void 0;var ie=ji(),Dt=Lc(),qr=ji();Object.defineProperty(Q,"_",{enumerable:!0,get:function(){return qr._}});Object.defineProperty(Q,"str",{enumerable:!0,get:function(){return qr.str}});Object.defineProperty(Q,"strConcat",{enumerable:!0,get:function(){return qr.strConcat}});Object.defineProperty(Q,"nil",{enumerable:!0,get:function(){return qr.nil}});Object.defineProperty(Q,"getProperty",{enumerable:!0,get:function(){return qr.getProperty}});Object.defineProperty(Q,"stringify",{enumerable:!0,get:function(){return qr.stringify}});Object.defineProperty(Q,"regexpCode",{enumerable:!0,get:function(){return qr.regexpCode}});Object.defineProperty(Q,"Name",{enumerable:!0,get:function(){return qr.Name}});var _o=Lc();Object.defineProperty(Q,"Scope",{enumerable:!0,get:function(){return _o.Scope}});Object.defineProperty(Q,"ValueScope",{enumerable:!0,get:function(){return _o.ValueScope}});Object.defineProperty(Q,"ValueScopeName",{enumerable:!0,get:function(){return _o.ValueScopeName}});Object.defineProperty(Q,"varKinds",{enumerable:!0,get:function(){return _o.varKinds}});Q.operators={GT:new ie._Code(">"),GTE:new ie._Code(">="),LT:new ie._Code("<"),LTE:new ie._Code("<="),EQ:new ie._Code("==="),NEQ:new ie._Code("!=="),NOT:new ie._Code("!"),OR:new ie._Code("||"),AND:new ie._Code("&&"),ADD:new ie._Code("+")};var _r=class{optimizeNodes(){return this}optimizeNames(e,t){return this}},Dc=class extends _r{constructor(e,t,n){super(),this.varKind=e,this.name=t,this.rhs=n}render({es5:e,_n:t}){let n=e?Dt.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=Ln(this.rhs,e,t)),this}get names(){return this.rhs instanceof ie._CodeOrName?this.rhs.names:{}}},yo=class extends _r{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 ie.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Ln(this.rhs,e,t),this}get names(){let e=this.lhs instanceof ie.Name?{}:{...this.lhs.names};return bo(e,this.rhs)}},qc=class extends yo{constructor(e,t,n,i){super(e,n,i),this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},jc=class extends _r{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Fc=class extends _r{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Vc=class extends _r{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Uc=class extends _r{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=Ln(this.code,e,t),this}get names(){return this.code instanceof ie._CodeOrName?this.code.names:{}}},Fi=class extends _r{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)||(m0(e,s.names),n.splice(i,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>pn(e,t.names),{})}},wr=class extends Fi{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Bc=class extends Fi{},Nn=class extends wr{};Nn.kind="else";var un=class r extends wr{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 Nn(n):n}if(t)return e===!1?t instanceof r?t:t.nodes:this.nodes.length?this:new r(ip(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=Ln(this.condition,e,t),this}get names(){let e=super.names;return bo(e,this.condition),this.else&&pn(e,this.else.names),e}};un.kind="if";var fn=class extends wr{};fn.kind="for";var zc=class extends fn{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=Ln(this.iteration,e,t),this}get names(){return pn(super.names,this.iteration.names)}},Hc=class extends fn{constructor(e,t,n,i){super(),this.varKind=e,this.name=t,this.from=n,this.to=i}render(e){let t=e.es5?Dt.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=bo(super.names,this.from);return bo(e,this.to)}},go=class extends fn{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=Ln(this.iterable,e,t),this}get names(){return pn(super.names,this.iterable.names)}},Vi=class extends wr{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)}};Vi.kind="func";var Ui=class extends Fi{render(e){return"return "+super.render(e)}};Ui.kind="return";var Kc=class extends wr{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&&pn(e,this.catch.names),this.finally&&pn(e,this.finally.names),e}},Bi=class extends wr{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};Bi.kind="catch";var zi=class extends wr{render(e){return"finally"+super.render(e)}};zi.kind="finally";var Wc=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?` -`:""},this._extScope=e,this._scope=new Dt.Scope({parent:e}),this._nodes=[new Bc]}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 Dc(e,s,n)),s}const(e,t,n){return this._def(Dt.varKinds.const,e,t,n)}let(e,t,n){return this._def(Dt.varKinds.let,e,t,n)}var(e,t,n){return this._def(Dt.varKinds.var,e,t,n)}assign(e,t,n){return this._leafNode(new yo(e,t,n))}add(e,t){return this._leafNode(new qc(e,Q.operators.ADD,t))}code(e){return typeof e=="function"?e():e!==ie.nil&&this._leafNode(new Uc(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,ie.addCodeArg)(t,i));return t.push("}"),new ie._Code(t)}if(e,t,n){if(this._blockNode(new un(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 un(e))}else(){return this._elseNode(new Nn)}endIf(){return this._endBlockNode(un,Nn)}_for(e,t){return this._blockNode(e),t&&this.code(t).endFor(),this}for(e,t){return this._for(new zc(e),t)}forRange(e,t,n,i,s=this.opts.es5?Dt.varKinds.var:Dt.varKinds.let){let o=this._scope.toName(e);return this._for(new Hc(s,o,t,n),()=>i(o))}forOf(e,t,n,i=Dt.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let o=t instanceof ie.Name?t:this.var("_arr",t);return this.forRange("_i",0,(0,ie._)`${o}.length`,a=>{this.var(s,(0,ie._)`${o}[${a}]`),n(s)})}return this._for(new go("of",i,s,t),()=>n(s))}forIn(e,t,n,i=this.opts.es5?Dt.varKinds.var:Dt.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,ie._)`Object.keys(${t})`,n);let s=this._scope.toName(e);return this._for(new go("in",i,s,t),()=>n(s))}endFor(){return this._endBlockNode(fn)}label(e){return this._leafNode(new jc(e))}break(e){return this._leafNode(new Fc(e))}return(e){let t=new Ui;if(this._blockNode(t),this.code(e),t.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Ui)}try(e,t,n){if(!t&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let i=new Kc;if(this._blockNode(i),this.code(e),t){let s=this.name("e");this._currNode=i.catch=new Bi(s),t(s)}return n&&(this._currNode=i.finally=new zi,this.code(n)),this._endBlockNode(Bi,zi)}throw(e){return this._leafNode(new Vc(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=ie.nil,n,i){return this._blockNode(new Vi(e,t,n)),i&&this.code(i).endFunc(),this}endFunc(){return this._endBlockNode(Vi)}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 un))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}};Q.CodeGen=Wc;function pn(r,e){for(let t in e)r[t]=(r[t]||0)+(e[t]||0);return r}function bo(r,e){return e instanceof ie._CodeOrName?pn(r,e.names):r}function Ln(r,e,t){if(r instanceof ie.Name)return n(r);if(!i(r))return r;return new ie._Code(r._items.reduce((s,o)=>(o instanceof ie.Name&&(o=n(o)),o instanceof ie._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 ie._Code&&s._items.some(o=>o instanceof ie.Name&&e[o.str]===1&&t[o.str]!==void 0)}}function m0(r,e){for(let t in e)r[t]=(r[t]||0)-(e[t]||0)}function ip(r){return typeof r=="boolean"||typeof r=="number"||r===null?!r:(0,ie._)`!${Gc(r)}`}Q.not=ip;var y0=sp(Q.operators.AND);function g0(...r){return r.reduce(y0)}Q.and=g0;var b0=sp(Q.operators.OR);function _0(...r){return r.reduce(b0)}Q.or=_0;function sp(r){return(e,t)=>e===ie.nil?t:t===ie.nil?e:(0,ie._)`${Gc(e)} ${r} ${Gc(t)}`}function Gc(r){return r instanceof ie.Name?r:(0,ie._)`(${r})`}});var ee=A(Z=>{"use strict";Object.defineProperty(Z,"__esModule",{value:!0});Z.checkStrictMode=Z.getErrorPath=Z.Type=Z.useFunc=Z.setEvaluated=Z.evaluatedPropsToName=Z.mergeEvaluated=Z.eachItem=Z.unescapeJsonPointer=Z.escapeJsonPointer=Z.escapeFragment=Z.unescapeFragment=Z.schemaRefOrVal=Z.schemaHasRulesButRef=Z.schemaHasRules=Z.checkUnknownRules=Z.alwaysValidSchema=Z.toHash=void 0;var me=K(),w0=ji();function v0(r){let e={};for(let t of r)e[t]=!0;return e}Z.toHash=v0;function $0(r,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(cp(r,e),!lp(e,r.self.RULES.all))}Z.alwaysValidSchema=$0;function cp(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]||fp(r,`unknown keyword: "${s}"`)}Z.checkUnknownRules=cp;function lp(r,e){if(typeof r=="boolean")return!r;for(let t in r)if(e[t])return!0;return!1}Z.schemaHasRules=lp;function S0(r,e){if(typeof r=="boolean")return!r;for(let t in r)if(t!=="$ref"&&e.all[t])return!0;return!1}Z.schemaHasRulesButRef=S0;function E0({topSchemaRef:r,schemaPath:e},t,n,i){if(!i){if(typeof t=="number"||typeof t=="boolean")return t;if(typeof t=="string")return(0,me._)`${t}`}return(0,me._)`${r}${e}${(0,me.getProperty)(n)}`}Z.schemaRefOrVal=E0;function A0(r){return dp(decodeURIComponent(r))}Z.unescapeFragment=A0;function k0(r){return encodeURIComponent(Yc(r))}Z.escapeFragment=k0;function Yc(r){return typeof r=="number"?`${r}`:r.replace(/~/g,"~0").replace(/\//g,"~1")}Z.escapeJsonPointer=Yc;function dp(r){return r.replace(/~1/g,"/").replace(/~0/g,"~")}Z.unescapeJsonPointer=dp;function x0(r,e){if(Array.isArray(r))for(let t of r)e(t);else e(r)}Z.eachItem=x0;function op({mergeNames:r,mergeToName:e,mergeValues:t,resultToName:n}){return(i,s,o,a)=>{let c=o===void 0?s:o instanceof me.Name?(s instanceof me.Name?r(i,s,o):e(i,s,o),o):s instanceof me.Name?(e(i,o,s),s):t(s,o);return a===me.Name&&!(c instanceof me.Name)?n(i,c):c}}Z.mergeEvaluated={props:op({mergeNames:(r,e,t)=>r.if((0,me._)`${t} !== true && ${e} !== undefined`,()=>{r.if((0,me._)`${e} === true`,()=>r.assign(t,!0),()=>r.assign(t,(0,me._)`${t} || {}`).code((0,me._)`Object.assign(${t}, ${e})`))}),mergeToName:(r,e,t)=>r.if((0,me._)`${t} !== true`,()=>{e===!0?r.assign(t,!0):(r.assign(t,(0,me._)`${t} || {}`),Xc(r,t,e))}),mergeValues:(r,e)=>r===!0?!0:{...r,...e},resultToName:up}),items:op({mergeNames:(r,e,t)=>r.if((0,me._)`${t} !== true && ${e} !== undefined`,()=>r.assign(t,(0,me._)`${e} === true ? true : ${t} > ${e} ? ${t} : ${e}`)),mergeToName:(r,e,t)=>r.if((0,me._)`${t} !== true`,()=>r.assign(t,e===!0?!0:(0,me._)`${t} > ${e} ? ${t} : ${e}`)),mergeValues:(r,e)=>r===!0?!0:Math.max(r,e),resultToName:(r,e)=>r.var("items",e)})};function up(r,e){if(e===!0)return r.var("props",!0);let t=r.var("props",(0,me._)`{}`);return e!==void 0&&Xc(r,t,e),t}Z.evaluatedPropsToName=up;function Xc(r,e,t){Object.keys(t).forEach(n=>r.assign((0,me._)`${e}${(0,me.getProperty)(n)}`,!0))}Z.setEvaluated=Xc;var ap={};function P0(r,e){return r.scopeValue("func",{ref:e,code:ap[e.code]||(ap[e.code]=new w0._Code(e.code))})}Z.useFunc=P0;var Jc;(function(r){r[r.Num=0]="Num",r[r.Str=1]="Str"})(Jc||(Z.Type=Jc={}));function I0(r,e,t){if(r instanceof me.Name){let n=e===Jc.Num;return t?n?(0,me._)`"[" + ${r} + "]"`:(0,me._)`"['" + ${r} + "']"`:n?(0,me._)`"/" + ${r}`:(0,me._)`"/" + ${r}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return t?(0,me.getProperty)(r).toString():"/"+Yc(r)}Z.getErrorPath=I0;function fp(r,e,t=r.opts.strictSchema){if(t){if(e=`strict mode: ${e}`,t===!0)throw new Error(e);r.self.logger.warn(e)}}Z.checkStrictMode=fp});var kt=A(Qc=>{"use strict";Object.defineProperty(Qc,"__esModule",{value:!0});var He=K(),O0={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")};Qc.default=O0});var Hi=A(Ke=>{"use strict";Object.defineProperty(Ke,"__esModule",{value:!0});Ke.extendErrors=Ke.resetErrorsCount=Ke.reportExtraError=Ke.reportError=Ke.keyword$DataError=Ke.keywordError=void 0;var oe=K(),wo=ee(),tt=kt();Ke.keywordError={message:({keyword:r})=>(0,oe.str)`must pass "${r}" keyword validation`};Ke.keyword$DataError={message:({keyword:r,schemaType:e})=>e?(0,oe.str)`"${r}" keyword must be ${e} ($data)`:(0,oe.str)`"${r}" keyword is invalid ($data)`};function T0(r,e=Ke.keywordError,t,n){let{it:i}=r,{gen:s,compositeRule:o,allErrors:a}=i,c=mp(r,e,t);(n!=null?n:o||a)?pp(s,c):hp(i,(0,oe._)`[${c}]`)}Ke.reportError=T0;function R0(r,e=Ke.keywordError,t){let{it:n}=r,{gen:i,compositeRule:s,allErrors:o}=n,a=mp(r,e,t);pp(i,a),s||o||hp(n,tt.default.vErrors)}Ke.reportExtraError=R0;function C0(r,e){r.assign(tt.default.errors,e),r.if((0,oe._)`${tt.default.vErrors} !== null`,()=>r.if(e,()=>r.assign((0,oe._)`${tt.default.vErrors}.length`,e),()=>r.assign(tt.default.vErrors,null)))}Ke.resetErrorsCount=C0;function M0({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,tt.default.errors,a=>{r.const(o,(0,oe._)`${tt.default.vErrors}[${a}]`),r.if((0,oe._)`${o}.instancePath === undefined`,()=>r.assign((0,oe._)`${o}.instancePath`,(0,oe.strConcat)(tt.default.instancePath,s.errorPath))),r.assign((0,oe._)`${o}.schemaPath`,(0,oe.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(r.assign((0,oe._)`${o}.schema`,t),r.assign((0,oe._)`${o}.data`,n))})}Ke.extendErrors=M0;function pp(r,e){let t=r.const("err",e);r.if((0,oe._)`${tt.default.vErrors} === null`,()=>r.assign(tt.default.vErrors,(0,oe._)`[${t}]`),(0,oe._)`${tt.default.vErrors}.push(${t})`),r.code((0,oe._)`${tt.default.errors}++`)}function hp(r,e){let{gen:t,validateName:n,schemaEnv:i}=r;i.$async?t.throw((0,oe._)`new ${r.ValidationError}(${e})`):(t.assign((0,oe._)`${n}.errors`,e),t.return(!1))}var hn={keyword:new oe.Name("keyword"),schemaPath:new oe.Name("schemaPath"),params:new oe.Name("params"),propertyName:new oe.Name("propertyName"),message:new oe.Name("message"),schema:new oe.Name("schema"),parentSchema:new oe.Name("parentSchema")};function mp(r,e,t){let{createErrors:n}=r.it;return n===!1?(0,oe._)`{}`:N0(r,e,t)}function N0(r,e,t={}){let{gen:n,it:i}=r,s=[L0(i,t),D0(r,t)];return q0(r,e,s),n.object(...s)}function L0({errorPath:r},{instancePath:e}){let t=e?(0,oe.str)`${r}${(0,wo.getErrorPath)(e,wo.Type.Str)}`:r;return[tt.default.instancePath,(0,oe.strConcat)(tt.default.instancePath,t)]}function D0({keyword:r,it:{errSchemaPath:e}},{schemaPath:t,parentSchema:n}){let i=n?e:(0,oe.str)`${e}/${r}`;return t&&(i=(0,oe.str)`${i}${(0,wo.getErrorPath)(t,wo.Type.Str)}`),[hn.schemaPath,i]}function q0(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([hn.keyword,i],[hn.params,typeof e=="function"?e(r):e||(0,oe._)`{}`]),c.messages&&n.push([hn.message,typeof t=="function"?t(r):t]),c.verbose&&n.push([hn.schema,o],[hn.parentSchema,(0,oe._)`${u}${d}`],[tt.default.data,s]),l&&n.push([hn.propertyName,l])}});var gp=A(Dn=>{"use strict";Object.defineProperty(Dn,"__esModule",{value:!0});Dn.boolOrEmptySchema=Dn.topBoolOrEmptySchema=void 0;var j0=Hi(),F0=K(),V0=kt(),U0={message:"boolean schema is false"};function B0(r){let{gen:e,schema:t,validateName:n}=r;t===!1?yp(r,!1):typeof t=="object"&&t.$async===!0?e.return(V0.default.data):(e.assign((0,F0._)`${n}.errors`,null),e.return(!0))}Dn.topBoolOrEmptySchema=B0;function z0(r,e){let{gen:t,schema:n}=r;n===!1?(t.var(e,!1),yp(r)):t.var(e,!0)}Dn.boolOrEmptySchema=z0;function yp(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,j0.reportError)(i,U0,void 0,e)}});var Zc=A(qn=>{"use strict";Object.defineProperty(qn,"__esModule",{value:!0});qn.getRules=qn.isJSONType=void 0;var H0=["string","number","integer","boolean","null","object","array"],K0=new Set(H0);function W0(r){return typeof r=="string"&&K0.has(r)}qn.isJSONType=W0;function G0(){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:{}}}qn.getRules=G0});var el=A(jr=>{"use strict";Object.defineProperty(jr,"__esModule",{value:!0});jr.shouldUseRule=jr.shouldUseGroup=jr.schemaHasRulesForType=void 0;function J0({schema:r,self:e},t){let n=e.RULES.types[t];return n&&n!==!0&&bp(r,n)}jr.schemaHasRulesForType=J0;function bp(r,e){return e.rules.some(t=>_p(r,t))}jr.shouldUseGroup=bp;function _p(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))}jr.shouldUseRule=_p});var Ki=A(We=>{"use strict";Object.defineProperty(We,"__esModule",{value:!0});We.reportTypeError=We.checkDataTypes=We.checkDataType=We.coerceAndCheckDataType=We.getJSONTypes=We.getSchemaTypes=We.DataType=void 0;var Y0=Zc(),X0=el(),Q0=Hi(),G=K(),wp=ee(),jn;(function(r){r[r.Correct=0]="Correct",r[r.Wrong=1]="Wrong"})(jn||(We.DataType=jn={}));function Z0(r){let e=vp(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}We.getSchemaTypes=Z0;function vp(r){let e=Array.isArray(r)?r:r?[r]:[];if(e.every(Y0.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}We.getJSONTypes=vp;function ev(r,e){let{gen:t,data:n,opts:i}=r,s=tv(e,i.coerceTypes),o=e.length>0&&!(s.length===0&&e.length===1&&(0,X0.schemaHasRulesForType)(r,e[0]));if(o){let a=rl(e,n,i.strictNumbers,jn.Wrong);t.if(a,()=>{s.length?rv(r,e,s):nl(r)})}return o}We.coerceAndCheckDataType=ev;var $p=new Set(["string","number","integer","boolean","null"]);function tv(r,e){return e?r.filter(t=>$p.has(t)||e==="array"&&t==="array"):[]}function rv(r,e,t){let{gen:n,data:i,opts:s}=r,o=n.let("dataType",(0,G._)`typeof ${i}`),a=n.let("coerced",(0,G._)`undefined`);s.coerceTypes==="array"&&n.if((0,G._)`${o} == 'object' && Array.isArray(${i}) && ${i}.length == 1`,()=>n.assign(i,(0,G._)`${i}[0]`).assign(o,(0,G._)`typeof ${i}`).if(rl(e,i,s.strictNumbers),()=>n.assign(a,i))),n.if((0,G._)`${a} !== undefined`);for(let l of t)($p.has(l)||l==="array"&&s.coerceTypes==="array")&&c(l);n.else(),nl(r),n.endIf(),n.if((0,G._)`${a} !== undefined`,()=>{n.assign(i,a),nv(r,a)});function c(l){switch(l){case"string":n.elseIf((0,G._)`${o} == "number" || ${o} == "boolean"`).assign(a,(0,G._)`"" + ${i}`).elseIf((0,G._)`${i} === null`).assign(a,(0,G._)`""`);return;case"number":n.elseIf((0,G._)`${o} == "boolean" || ${i} === null - || (${o} == "string" && ${i} && ${i} == +${i})`).assign(a,(0,G._)`+${i}`);return;case"integer":n.elseIf((0,G._)`${o} === "boolean" || ${i} === null - || (${o} === "string" && ${i} && ${i} == +${i} && !(${i} % 1))`).assign(a,(0,G._)`+${i}`);return;case"boolean":n.elseIf((0,G._)`${i} === "false" || ${i} === 0 || ${i} === null`).assign(a,!1).elseIf((0,G._)`${i} === "true" || ${i} === 1`).assign(a,!0);return;case"null":n.elseIf((0,G._)`${i} === "" || ${i} === 0 || ${i} === false`),n.assign(a,null);return;case"array":n.elseIf((0,G._)`${o} === "string" || ${o} === "number" - || ${o} === "boolean" || ${i} === null`).assign(a,(0,G._)`[${i}]`)}}}function nv({gen:r,parentData:e,parentDataProperty:t},n){r.if((0,G._)`${e} !== undefined`,()=>r.assign((0,G._)`${e}[${t}]`,n))}function tl(r,e,t,n=jn.Correct){let i=n===jn.Correct?G.operators.EQ:G.operators.NEQ,s;switch(r){case"null":return(0,G._)`${e} ${i} null`;case"array":s=(0,G._)`Array.isArray(${e})`;break;case"object":s=(0,G._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=o((0,G._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=o();break;default:return(0,G._)`typeof ${e} ${i} ${r}`}return n===jn.Correct?s:(0,G.not)(s);function o(a=G.nil){return(0,G.and)((0,G._)`typeof ${e} == "number"`,a,t?(0,G._)`isFinite(${e})`:G.nil)}}We.checkDataType=tl;function rl(r,e,t,n){if(r.length===1)return tl(r[0],e,t,n);let i,s=(0,wp.toHash)(r);if(s.array&&s.object){let o=(0,G._)`typeof ${e} != "object"`;i=s.null?o:(0,G._)`!${e} || ${o}`,delete s.null,delete s.array,delete s.object}else i=G.nil;s.number&&delete s.integer;for(let o in s)i=(0,G.and)(i,tl(o,e,t,n));return i}We.checkDataTypes=rl;var iv={message:({schema:r})=>`must be ${r}`,params:({schema:r,schemaValue:e})=>typeof r=="string"?(0,G._)`{type: ${r}}`:(0,G._)`{type: ${e}}`};function nl(r){let e=sv(r);(0,Q0.reportError)(e,iv)}We.reportTypeError=nl;function sv(r){let{gen:e,data:t,schema:n}=r,i=(0,wp.schemaRefOrVal)(r,n,"type");return{gen:e,keyword:"type",data:t,schema:n.type,schemaCode:i,schemaValue:i,parentSchema:n,params:{},it:r}}});var Ep=A(vo=>{"use strict";Object.defineProperty(vo,"__esModule",{value:!0});vo.assignDefaults=void 0;var Fn=K(),ov=ee();function av(r,e){let{properties:t,items:n}=r.schema;if(e==="object"&&t)for(let i in t)Sp(r,i,t[i].default);else e==="array"&&Array.isArray(n)&&n.forEach((i,s)=>Sp(r,s,i.default))}vo.assignDefaults=av;function Sp(r,e,t){let{gen:n,compositeRule:i,data:s,opts:o}=r;if(t===void 0)return;let a=(0,Fn._)`${s}${(0,Fn.getProperty)(e)}`;if(i){(0,ov.checkStrictMode)(r,`default is ignored for: ${a}`);return}let c=(0,Fn._)`${a} === undefined`;o.useDefaults==="empty"&&(c=(0,Fn._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,Fn._)`${a} = ${(0,Fn.stringify)(t)}`)}});var xt=A(he=>{"use strict";Object.defineProperty(he,"__esModule",{value:!0});he.validateUnion=he.validateArray=he.usePattern=he.callValidateCode=he.schemaProperties=he.allSchemaProperties=he.noPropertyInData=he.propertyInData=he.isOwnProperty=he.hasPropFunc=he.reportMissingProp=he.checkMissingProp=he.checkReportMissingProp=void 0;var _e=K(),il=ee(),Fr=kt(),cv=ee();function lv(r,e){let{gen:t,data:n,it:i}=r;t.if(ol(t,n,e,i.opts.ownProperties),()=>{r.setParams({missingProperty:(0,_e._)`${e}`},!0),r.error()})}he.checkReportMissingProp=lv;function dv({gen:r,data:e,it:{opts:t}},n,i){return(0,_e.or)(...n.map(s=>(0,_e.and)(ol(r,e,s,t.ownProperties),(0,_e._)`${i} = ${s}`)))}he.checkMissingProp=dv;function uv(r,e){r.setParams({missingProperty:e},!0),r.error()}he.reportMissingProp=uv;function Ap(r){return r.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,_e._)`Object.prototype.hasOwnProperty`})}he.hasPropFunc=Ap;function sl(r,e,t){return(0,_e._)`${Ap(r)}.call(${e}, ${t})`}he.isOwnProperty=sl;function fv(r,e,t,n){let i=(0,_e._)`${e}${(0,_e.getProperty)(t)} !== undefined`;return n?(0,_e._)`${i} && ${sl(r,e,t)}`:i}he.propertyInData=fv;function ol(r,e,t,n){let i=(0,_e._)`${e}${(0,_e.getProperty)(t)} === undefined`;return n?(0,_e.or)(i,(0,_e.not)(sl(r,e,t))):i}he.noPropertyInData=ol;function kp(r){return r?Object.keys(r).filter(e=>e!=="__proto__"):[]}he.allSchemaProperties=kp;function pv(r,e){return kp(e).filter(t=>!(0,il.alwaysValidSchema)(r,e[t]))}he.schemaProperties=pv;function hv({schemaCode:r,data:e,it:{gen:t,topSchemaRef:n,schemaPath:i,errorPath:s},it:o},a,c,l){let u=l?(0,_e._)`${r}, ${e}, ${n}${i}`:e,d=[[Fr.default.instancePath,(0,_e.strConcat)(Fr.default.instancePath,s)],[Fr.default.parentData,o.parentData],[Fr.default.parentDataProperty,o.parentDataProperty],[Fr.default.rootData,Fr.default.rootData]];o.opts.dynamicRef&&d.push([Fr.default.dynamicAnchors,Fr.default.dynamicAnchors]);let f=(0,_e._)`${u}, ${t.object(...d)}`;return c!==_e.nil?(0,_e._)`${a}.call(${c}, ${f})`:(0,_e._)`${a}(${f})`}he.callValidateCode=hv;var mv=(0,_e._)`new RegExp`;function yv({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,_e._)`${i.code==="new RegExp"?mv:(0,cv.useFunc)(r,i)}(${t}, ${n})`})}he.usePattern=yv;function gv(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,_e._)`${t}.length`);e.forRange("i",0,c,l=>{r.subschema({keyword:n,dataProp:l,dataPropType:il.Type.Num},s),e.if((0,_e.not)(s),a)})}}he.validateArray=gv;function bv(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,il.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,_e._)`${o} || ${a}`),r.mergeValidEvaluated(u,a)||e.if((0,_e.not)(o))})),r.result(o,()=>r.reset(),()=>r.error(!0))}he.validateUnion=bv});var Ip=A(sr=>{"use strict";Object.defineProperty(sr,"__esModule",{value:!0});sr.validateKeywordUsage=sr.validSchemaType=sr.funcKeywordCode=sr.macroKeywordCode=void 0;var rt=K(),mn=kt(),_v=xt(),wv=Hi();function vv(r,e){let{gen:t,keyword:n,schema:i,parentSchema:s,it:o}=r,a=e.macro.call(o.self,i,s,o),c=Pp(t,n,a);o.opts.validateSchema!==!1&&o.self.validateSchema(a,!0);let l=t.name("valid");r.subschema({schema:a,schemaPath:rt.nil,errSchemaPath:`${o.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},l),r.pass(l,()=>r.error(!0))}sr.macroKeywordCode=vv;function $v(r,e){var t;let{gen:n,keyword:i,schema:s,parentSchema:o,$data:a,it:c}=r;Ev(c,e);let l=!a&&e.compile?e.compile.call(c.self,s,o,c):e.validate,u=Pp(n,i,l),d=n.let("valid");r.block$data(d,f),r.ok((t=e.valid)!==null&&t!==void 0?t:d);function f(){if(e.errors===!1)h(),e.modifying&&xp(r),y(()=>r.error());else{let b=e.async?p():m();e.modifying&&xp(r),y(()=>Sv(r,b))}}function p(){let b=n.let("ruleErrs",null);return n.try(()=>h((0,rt._)`await `),g=>n.assign(d,!1).if((0,rt._)`${g} instanceof ${c.ValidationError}`,()=>n.assign(b,(0,rt._)`${g}.errors`),()=>n.throw(g))),b}function m(){let b=(0,rt._)`${u}.errors`;return n.assign(b,null),h(rt.nil),b}function h(b=e.async?(0,rt._)`await `:rt.nil){let g=c.opts.passContext?mn.default.this:mn.default.self,_=!("compile"in e&&!a||e.schema===!1);n.assign(d,(0,rt._)`${b}${(0,_v.callValidateCode)(r,u,g,_)}`,e.modifying)}function y(b){var g;n.if((0,rt.not)((g=e.valid)!==null&&g!==void 0?g:d),b)}}sr.funcKeywordCode=$v;function xp(r){let{gen:e,data:t,it:n}=r;e.if(n.parentData,()=>e.assign(t,(0,rt._)`${n.parentData}[${n.parentDataProperty}]`))}function Sv(r,e){let{gen:t}=r;t.if((0,rt._)`Array.isArray(${e})`,()=>{t.assign(mn.default.vErrors,(0,rt._)`${mn.default.vErrors} === null ? ${e} : ${mn.default.vErrors}.concat(${e})`).assign(mn.default.errors,(0,rt._)`${mn.default.vErrors}.length`),(0,wv.extendErrors)(r)},()=>r.error())}function Ev({schemaEnv:r},e){if(e.async&&!r.$async)throw new Error("async keyword in sync schema")}function Pp(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,rt.stringify)(t)})}function Av(r,e,t=!1){return!e.length||e.some(n=>n==="array"?Array.isArray(r):n==="object"?r&&typeof r=="object"&&!Array.isArray(r):typeof r==n||t&&typeof r=="undefined")}sr.validSchemaType=Av;function kv({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!=null&&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)}}sr.validateKeywordUsage=kv});var Tp=A(Vr=>{"use strict";Object.defineProperty(Vr,"__esModule",{value:!0});Vr.extendSubschemaMode=Vr.extendSubschemaData=Vr.getSubschema=void 0;var or=K(),Op=ee();function xv(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,or._)`${r.schemaPath}${(0,or.getProperty)(e)}`,errSchemaPath:`${r.errSchemaPath}/${e}`}:{schema:a[t],schemaPath:(0,or._)`${r.schemaPath}${(0,or.getProperty)(e)}${(0,or.getProperty)(t)}`,errSchemaPath:`${r.errSchemaPath}/${e}/${(0,Op.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')}Vr.getSubschema=xv;function Pv(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,or._)`${e.data}${(0,or.getProperty)(t)}`,!0);c(f),r.errorPath=(0,or.str)`${l}${(0,Op.getErrorPath)(t,n,d.jsPropertySyntax)}`,r.parentDataProperty=(0,or._)`${t}`,r.dataPathArr=[...u,r.parentDataProperty]}if(i!==void 0){let l=i instanceof or.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]}}Vr.extendSubschemaData=Pv;function Iv(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}Vr.extendSubschemaMode=Iv});var al=A((OC,Rp)=>{"use strict";Rp.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 Mp=A((TC,Cp)=>{"use strict";var Ur=Cp.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(){};$o(e,n,i,r,"",r)};Ur.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Ur.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Ur.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Ur.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 $o(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 Ur.arrayKeywords)for(var f=0;f{"use strict";Object.defineProperty(ut,"__esModule",{value:!0});ut.getSchemaRefs=ut.resolveUrl=ut.normalizeId=ut._getFullPath=ut.getFullPath=ut.inlineRef=void 0;var Tv=ee(),Rv=al(),Cv=Mp(),Mv=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function Nv(r,e=!0){return typeof r=="boolean"?!0:e===!0?!cl(r):e?Np(r)<=e:!1}ut.inlineRef=Nv;var Lv=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function cl(r){for(let e in r){if(Lv.has(e))return!0;let t=r[e];if(Array.isArray(t)&&t.some(cl)||typeof t=="object"&&cl(t))return!0}return!1}function Np(r){let e=0;for(let t in r){if(t==="$ref")return 1/0;if(e++,!Mv.has(t)&&(typeof r[t]=="object"&&(0,Tv.eachItem)(r[t],n=>e+=Np(n)),e===1/0))return 1/0}return e}function Lp(r,e="",t){t!==!1&&(e=Vn(e));let n=r.parse(e);return Dp(r,n)}ut.getFullPath=Lp;function Dp(r,e){return r.serialize(e).split("#")[0]+"#"}ut._getFullPath=Dp;var Dv=/#\/?$/;function Vn(r){return r?r.replace(Dv,""):""}ut.normalizeId=Vn;function qv(r,e,t){return t=Vn(t),r.resolve(e,t)}ut.resolveUrl=qv;var jv=/^[a-z_][-a-z0-9._]*$/i;function Fv(r,e){if(typeof r=="boolean")return{};let{schemaId:t,uriResolver:n}=this.opts,i=Vn(r[t]||e),s={"":i},o=Lp(n,i,!1),a={},c=new Set;return Cv(r,{allKeys:!0},(d,f,p,m)=>{if(m===void 0)return;let h=o+f,y=s[m];typeof d[t]=="string"&&(y=b.call(this,d[t])),g.call(this,d.$anchor),g.call(this,d.$dynamicAnchor),s[f]=y;function b(_){let k=this.opts.uriResolver.resolve;if(_=Vn(y?k(y,_):_),c.has(_))throw u(_);c.add(_);let v=this.refs[_];return typeof v=="string"&&(v=this.refs[v]),typeof v=="object"?l(d,v.schema,_):_!==Vn(h)&&(_[0]==="#"?(l(d,a[_],_),a[_]=d):this.refs[_]=h),_}function g(_){if(typeof _=="string"){if(!jv.test(_))throw new Error(`invalid anchor "${_}"`);b.call(this,`#${_}`)}}}),a;function l(d,f,p){if(f!==void 0&&!Rv(d,f))throw u(p)}function u(d){return new Error(`reference "${d}" resolves to more than one schema`)}}ut.getSchemaRefs=Fv});var Un=A(Br=>{"use strict";Object.defineProperty(Br,"__esModule",{value:!0});Br.getData=Br.KeywordCxt=Br.validateFunctionCode=void 0;var Up=gp(),qp=Ki(),dl=el(),So=Ki(),Vv=Ep(),Ji=Ip(),ll=Tp(),B=K(),H=kt(),Uv=Wi(),vr=ee(),Gi=Hi();function Bv(r){if(Hp(r)&&(Kp(r),zp(r))){Kv(r);return}Bp(r,()=>(0,Up.topBoolOrEmptySchema)(r))}Br.validateFunctionCode=Bv;function Bp({gen:r,validateName:e,schema:t,schemaEnv:n,opts:i},s){i.code.es5?r.func(e,(0,B._)`${H.default.data}, ${H.default.valCxt}`,n.$async,()=>{r.code((0,B._)`"use strict"; ${jp(t,i)}`),Hv(r,i),r.code(s)}):r.func(e,(0,B._)`${H.default.data}, ${zv(i)}`,n.$async,()=>r.code(jp(t,i)).code(s))}function zv(r){return(0,B._)`{${H.default.instancePath}="", ${H.default.parentData}, ${H.default.parentDataProperty}, ${H.default.rootData}=${H.default.data}${r.dynamicRef?(0,B._)`, ${H.default.dynamicAnchors}={}`:B.nil}}={}`}function Hv(r,e){r.if(H.default.valCxt,()=>{r.var(H.default.instancePath,(0,B._)`${H.default.valCxt}.${H.default.instancePath}`),r.var(H.default.parentData,(0,B._)`${H.default.valCxt}.${H.default.parentData}`),r.var(H.default.parentDataProperty,(0,B._)`${H.default.valCxt}.${H.default.parentDataProperty}`),r.var(H.default.rootData,(0,B._)`${H.default.valCxt}.${H.default.rootData}`),e.dynamicRef&&r.var(H.default.dynamicAnchors,(0,B._)`${H.default.valCxt}.${H.default.dynamicAnchors}`)},()=>{r.var(H.default.instancePath,(0,B._)`""`),r.var(H.default.parentData,(0,B._)`undefined`),r.var(H.default.parentDataProperty,(0,B._)`undefined`),r.var(H.default.rootData,H.default.data),e.dynamicRef&&r.var(H.default.dynamicAnchors,(0,B._)`{}`)})}function Kv(r){let{schema:e,opts:t,gen:n}=r;Bp(r,()=>{t.$comment&&e.$comment&&Gp(r),Xv(r),n.let(H.default.vErrors,null),n.let(H.default.errors,0),t.unevaluated&&Wv(r),Wp(r),e$(r)})}function Wv(r){let{gen:e,validateName:t}=r;r.evaluated=e.const("evaluated",(0,B._)`${t}.evaluated`),e.if((0,B._)`${r.evaluated}.dynamicProps`,()=>e.assign((0,B._)`${r.evaluated}.props`,(0,B._)`undefined`)),e.if((0,B._)`${r.evaluated}.dynamicItems`,()=>e.assign((0,B._)`${r.evaluated}.items`,(0,B._)`undefined`))}function jp(r,e){let t=typeof r=="object"&&r[e.schemaId];return t&&(e.code.source||e.code.process)?(0,B._)`/*# sourceURL=${t} */`:B.nil}function Gv(r,e){if(Hp(r)&&(Kp(r),zp(r))){Jv(r,e);return}(0,Up.boolOrEmptySchema)(r,e)}function zp({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 Hp(r){return typeof r.schema!="boolean"}function Jv(r,e){let{schema:t,gen:n,opts:i}=r;i.$comment&&t.$comment&&Gp(r),Qv(r),Zv(r);let s=n.const("_errs",H.default.errors);Wp(r,s),n.var(e,(0,B._)`${s} === ${H.default.errors}`)}function Kp(r){(0,vr.checkUnknownRules)(r),Yv(r)}function Wp(r,e){if(r.opts.jtd)return Fp(r,[],!1,e);let t=(0,qp.getSchemaTypes)(r.schema),n=(0,qp.coerceAndCheckDataType)(r,t);Fp(r,t,!n,e)}function Yv(r){let{schema:e,errSchemaPath:t,opts:n,self:i}=r;e.$ref&&n.ignoreKeywordsWithRef&&(0,vr.schemaHasRulesButRef)(e,i.RULES)&&i.logger.warn(`$ref: keywords ignored in schema at path "${t}"`)}function Xv(r){let{schema:e,opts:t}=r;e.default!==void 0&&t.useDefaults&&t.strictSchema&&(0,vr.checkStrictMode)(r,"default is ignored in the schema root")}function Qv(r){let e=r.schema[r.opts.schemaId];e&&(r.baseId=(0,Uv.resolveUrl)(r.opts.uriResolver,r.baseId,e))}function Zv(r){if(r.schema.$async&&!r.schemaEnv.$async)throw new Error("async schema in sync schema")}function Gp({gen:r,schemaEnv:e,schema:t,errSchemaPath:n,opts:i}){let s=t.$comment;if(i.$comment===!0)r.code((0,B._)`${H.default.self}.logger.log(${s})`);else if(typeof i.$comment=="function"){let o=(0,B.str)`${n}/$comment`,a=r.scopeValue("root",{ref:e.root});r.code((0,B._)`${H.default.self}.opts.$comment(${s}, ${o}, ${a}.schema)`)}}function e$(r){let{gen:e,schemaEnv:t,validateName:n,ValidationError:i,opts:s}=r;t.$async?e.if((0,B._)`${H.default.errors} === 0`,()=>e.return(H.default.data),()=>e.throw((0,B._)`new ${i}(${H.default.vErrors})`)):(e.assign((0,B._)`${n}.errors`,H.default.vErrors),s.unevaluated&&t$(r),e.return((0,B._)`${H.default.errors} === 0`))}function t$({gen:r,evaluated:e,props:t,items:n}){t instanceof B.Name&&r.assign((0,B._)`${e}.props`,t),n instanceof B.Name&&r.assign((0,B._)`${e}.items`,n)}function Fp(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,vr.schemaHasRulesButRef)(s,u))){i.block(()=>Yp(r,"$ref",u.all.$ref.definition));return}c.jtd||r$(r,e),i.block(()=>{for(let f of u.rules)d(f);d(u.post)});function d(f){(0,dl.shouldUseGroup)(s,f)&&(f.type?(i.if((0,So.checkDataType)(f.type,o,c.strictNumbers)),Vp(r,f),e.length===1&&e[0]===f.type&&t&&(i.else(),(0,So.reportTypeError)(r)),i.endIf()):Vp(r,f),a||i.if((0,B._)`${H.default.errors} === ${n||0}`))}}function Vp(r,e){let{gen:t,schema:n,opts:{useDefaults:i}}=r;i&&(0,Vv.assignDefaults)(r,e.type),t.block(()=>{for(let s of e.rules)(0,dl.shouldUseRule)(n,s)&&Yp(r,s.keyword,s.definition,e.type)})}function r$(r,e){r.schemaEnv.meta||!r.opts.strictTypes||(n$(r,e),r.opts.allowUnionTypes||i$(r,e),s$(r,r.dataTypes))}function n$(r,e){if(e.length){if(!r.dataTypes.length){r.dataTypes=e;return}e.forEach(t=>{Jp(r.dataTypes,t)||ul(r,`type "${t}" not allowed by context "${r.dataTypes.join(",")}"`)}),a$(r,e)}}function i$(r,e){e.length>1&&!(e.length===2&&e.includes("null"))&&ul(r,"use allowUnionTypes to allow union type keyword")}function s$(r,e){let t=r.self.RULES.all;for(let n in t){let i=t[n];if(typeof i=="object"&&(0,dl.shouldUseRule)(r.schema,i)){let{type:s}=i.definition;s.length&&!s.some(o=>o$(e,o))&&ul(r,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function o$(r,e){return r.includes(e)||e==="number"&&r.includes("integer")}function Jp(r,e){return r.includes(e)||e==="integer"&&r.includes("number")}function a$(r,e){let t=[];for(let n of r.dataTypes)Jp(e,n)?t.push(n):e.includes("integer")&&n==="number"&&t.push("integer");r.dataTypes=t}function ul(r,e){let t=r.schemaEnv.baseId+r.errSchemaPath;e+=` at "${t}" (strictTypes)`,(0,vr.checkStrictMode)(r,e,r.opts.strictTypes)}var Eo=class{constructor(e,t,n){if((0,Ji.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,vr.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",Xp(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,Ji.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",H.default.errors))}result(e,t,n){this.failResult((0,B.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,B.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,B._)`${t} !== undefined && (${(0,B.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?Gi.reportExtraError:Gi.reportError)(this,this.def.error,t)}$dataError(){(0,Gi.reportError)(this,this.def.$dataError||Gi.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,Gi.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=B.nil){this.gen.block(()=>{this.check$data(e,n),t()})}check$data(e=B.nil,t=B.nil){if(!this.$data)return;let{gen:n,schemaCode:i,schemaType:s,def:o}=this;n.if((0,B.or)((0,B._)`${i} === undefined`,t)),e!==B.nil&&n.assign(e,!0),(s.length||o.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==B.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:t,schemaType:n,def:i,it:s}=this;return(0,B.or)(o(),a());function o(){if(n.length){if(!(t instanceof B.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,B._)`${(0,So.checkDataTypes)(c,t,s.opts.strictNumbers,So.DataType.Wrong)}`}return B.nil}function a(){if(i.validateSchema){let c=e.scopeValue("validate$data",{ref:i.validateSchema});return(0,B._)`!${c}(${t})`}return B.nil}}subschema(e,t){let n=(0,ll.getSubschema)(this.it,e);(0,ll.extendSubschemaData)(n,this.it,e),(0,ll.extendSubschemaMode)(n,e);let i={...this.it,...n,items:void 0,props:void 0};return Gv(i,t),i}mergeEvaluated(e,t){let{it:n,gen:i}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=vr.mergeEvaluated.props(i,e.props,n.props,t)),n.items!==!0&&e.items!==void 0&&(n.items=vr.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,B.Name)),!0}};Br.KeywordCxt=Eo;function Yp(r,e,t,n){let i=new Eo(r,t,e);"code"in t?t.code(i,n):i.$data&&t.validate?(0,Ji.funcKeywordCode)(i,t):"macro"in t?(0,Ji.macroKeywordCode)(i,t):(t.compile||t.validate)&&(0,Ji.funcKeywordCode)(i,t)}var c$=/^\/(?:[^~]|~0|~1)*$/,l$=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Xp(r,{dataLevel:e,dataNames:t,dataPathArr:n}){let i,s;if(r==="")return H.default.rootData;if(r[0]==="/"){if(!c$.test(r))throw new Error(`Invalid JSON-pointer: ${r}`);i=r,s=H.default.rootData}else{let l=l$.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,B._)`${s}${(0,B.getProperty)((0,vr.unescapeJsonPointer)(l))}`,o=(0,B._)`${o} && ${s}`);return o;function c(l,u){return`Cannot access ${l} ${u} levels up, current level is ${e}`}}Br.getData=Xp});var Yi=A(pl=>{"use strict";Object.defineProperty(pl,"__esModule",{value:!0});var fl=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};pl.default=fl});var Bn=A(yl=>{"use strict";Object.defineProperty(yl,"__esModule",{value:!0});var hl=Wi(),ml=class extends Error{constructor(e,t,n,i){super(i||`can't resolve reference ${n} from id ${t}`),this.missingRef=(0,hl.resolveUrl)(e,t,n),this.missingSchema=(0,hl.normalizeId)((0,hl.getFullPath)(e,this.missingRef))}};yl.default=ml});var Xi=A(Pt=>{"use strict";Object.defineProperty(Pt,"__esModule",{value:!0});Pt.resolveSchema=Pt.getCompilingSchema=Pt.resolveRef=Pt.compileSchema=Pt.SchemaEnv=void 0;var qt=K(),d$=Yi(),yn=kt(),jt=Wi(),Qp=ee(),u$=Un(),zn=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,jt.normalizeId)(n==null?void 0:n[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n==null?void 0:n.$async,this.refs={}}};Pt.SchemaEnv=zn;function bl(r){let e=Zp.call(this,r);if(e)return e;let t=(0,jt.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:d$.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:yn.default.data,parentData:yn.default.parentData,parentDataProperty:yn.default.parentDataProperty,dataNames:[yn.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,u$.validateFunctionCode)(l),o.optimize(this.opts.code.optimize);let d=o.toString();u=`${o.scopeRefs(yn.default.scope)}return ${d}`,this.opts.code.process&&(u=this.opts.code.process(u,r));let p=new Function(`${yn.default.self}`,`${yn.default.scope}`,u)(this,this.scope.get());if(this.scope.value(c,{ref:p}),p.errors=null,p.schema=r.schema,p.schemaEnv=r,r.$async&&(p.$async=!0),this.opts.code.source===!0&&(p.source={validateName:c,validateCode:d,scopeValues:o._values}),this.opts.unevaluated){let{props:m,items:h}=l;p.evaluated={props:m instanceof qt.Name?void 0:m,items:h instanceof qt.Name?void 0:h,dynamicProps:m instanceof qt.Name,dynamicItems:h 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)}}Pt.compileSchema=bl;function f$(r,e,t){var n;t=(0,jt.resolveUrl)(this.opts.uriResolver,e,t);let i=r.refs[t];if(i)return i;let s=m$.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 zn({schema:o,schemaId:a,root:r,baseId:e}))}if(s!==void 0)return r.refs[t]=p$.call(this,s)}Pt.resolveRef=f$;function p$(r){return(0,jt.inlineRef)(r.schema,this.opts.inlineRefs)?r.schema:r.validate?r:bl.call(this,r)}function Zp(r){for(let e of this._compilations)if(h$(e,r))return e}Pt.getCompilingSchema=Zp;function h$(r,e){return r.schema===e.schema&&r.root===e.root&&r.baseId===e.baseId}function m$(r,e){let t;for(;typeof(t=this.refs[e])=="string";)e=t;return t||this.schemas[e]||Ao.call(this,r,e)}function Ao(r,e){let t=this.opts.uriResolver.parse(e),n=(0,jt._getFullPath)(this.opts.uriResolver,t),i=(0,jt.getFullPath)(this.opts.uriResolver,r.baseId,void 0);if(Object.keys(r.schema).length>0&&n===i)return gl.call(this,t,r);let s=(0,jt.normalizeId)(n),o=this.refs[s]||this.schemas[s];if(typeof o=="string"){let a=Ao.call(this,r,o);return typeof(a==null?void 0:a.schema)!="object"?void 0:gl.call(this,t,a)}if(typeof(o==null?void 0:o.schema)=="object"){if(o.validate||bl.call(this,o),s===(0,jt.normalizeId)(e)){let{schema:a}=o,{schemaId:c}=this.opts,l=a[c];return l&&(i=(0,jt.resolveUrl)(this.opts.uriResolver,i,l)),new zn({schema:a,schemaId:c,root:r,baseId:i})}return gl.call(this,t,o)}}Pt.resolveSchema=Ao;var y$=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function gl(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,Qp.unescapeFragment)(a)];if(c===void 0)return;t=c;let l=typeof t=="object"&&t[this.opts.schemaId];!y$.has(a)&&l&&(e=(0,jt.resolveUrl)(this.opts.uriResolver,e,l))}let s;if(typeof t!="boolean"&&t.$ref&&!(0,Qp.schemaHasRulesButRef)(t,this.RULES)){let a=(0,jt.resolveUrl)(this.opts.uriResolver,e,t.$ref);s=Ao.call(this,n,a)}let{schemaId:o}=this.opts;if(s=s||new zn({schema:t,schemaId:o,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var eh=A((DC,g$)=>{g$.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 vl=A((qC,oh)=>{"use strict";var b$=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),rh=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),_l=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),nh=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),_$=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function wl(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 w$=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function th(r){return r.length=0,!0}function v$(r,e,t){if(r.length){let n=wl(r);if(n!=="")e.push(n);else return t.error=!0,!1;r.length=0}return!0}function $$(r){let e=0,t={error:!1,address:"",zone:""},n=[],i=[],s=!1,o=!1,a=v$;for(let c=0;c7){t.error=!0;break}c>0&&r[c-1]===":"&&(s=!0),n.push(":");continue}else if(l==="%"){if(!a(i,n,t))break;a=th}else{i.push(l);continue}}return i.length&&(a===th?t.zone=i.join(""):o?n.push(i.join("")):n.push(wl(i))),t.address=n.join(""),t}function ih(r){if(S$(r,":")<2)return{host:r,isIPV6:!1};let e=$$(r);if(e.error)return{host:r,isIPV6:!1};{let t=e.address,n=e.address;return e.zone&&(t+="%"+e.zone,n+="%25"+e.zone),{host:t,isIPV6:!0,escapedHost:n}}}function S$(r,e){let t=0;for(let n=0;nA$[n])}function P$(r,e=!1){if(r.indexOf("%")===-1)return r;let t="";for(let n=0;n{"use strict";var{isUUID:R$}=vl(),C$=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,M$=["http","https","ws","wss","urn","urn:uuid"];function N$(r){return M$.indexOf(r)!==-1}function $l(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 ah(r){return r.host||(r.error=r.error||"HTTP URIs must have a host."),r}function ch(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 L$(r){return r.secure=$l(r),r.resourceName=(r.path||"/")+(r.query?"?"+r.query:""),r.path=void 0,r.query=void 0,r}function D$(r){if((r.port===($l(r)?443:80)||r.port==="")&&(r.port=void 0),typeof r.secure=="boolean"&&(r.scheme=r.secure?"wss":"ws",r.secure=void 0),r.resourceName){let[e,t]=r.resourceName.split("?");r.path=e&&e!=="/"?e:void 0,r.query=t,r.resourceName=void 0}return r.fragment=void 0,r}function q$(r,e){if(!r.path)return r.error="URN can not be parsed",r;let t=r.path.match(C$);if(t){let n=e.scheme||r.scheme||"urn";r.nid=t[1].toLowerCase(),r.nss=t[2];let i=`${n}:${e.nid||r.nid}`,s=Sl(i);r.path=void 0,s&&(r=s.parse(r,e))}else r.error=r.error||"URN can not be parsed.";return r}function j$(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=Sl(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 F$(r,e){let t=r;return t.uuid=t.nss,t.nss=void 0,!e.tolerant&&(!t.uuid||!R$(t.uuid))&&(t.error=t.error||"UUID is not valid."),t}function V$(r){let e=r;return e.nss=(r.uuid||"").toLowerCase(),e}var lh={scheme:"http",domainHost:!0,parse:ah,serialize:ch},U$={scheme:"https",domainHost:lh.domainHost,parse:ah,serialize:ch},ko={scheme:"ws",domainHost:!0,parse:L$,serialize:D$},B$={scheme:"wss",domainHost:ko.domainHost,parse:ko.parse,serialize:ko.serialize},z$={scheme:"urn",parse:q$,serialize:j$,skipNormalize:!0},H$={scheme:"urn:uuid",parse:F$,serialize:V$,skipNormalize:!0},xo={http:lh,https:U$,ws:ko,wss:B$,urn:z$,"urn:uuid":H$};Object.setPrototypeOf(xo,null);function Sl(r){return r&&(xo[r]||xo[r.toLowerCase()])||void 0}dh.exports={wsIsSecure:$l,SCHEMES:xo,isValidSchemeName:N$,getSchemeHandler:Sl}});var yh=A((FC,Oo)=>{"use strict";var{normalizeIPv6:K$,removeDotSegments:Qi,recomposeAuthority:W$,normalizePercentEncoding:G$,normalizePathEncoding:J$,escapePreservingEscapes:Y$,reescapeHostDelimiters:X$,isIPv4:Q$,nonSimpleDomain:Z$}=vl(),{SCHEMES:eS,getSchemeHandler:ph}=uh();function tS(r,e){return typeof r=="string"?r=cS(r,e):typeof r=="object"&&(r=Io(gn(r,e),e)),r}function rS(r,e,t){let n=t?Object.assign({scheme:"null"},t):{scheme:"null"},{parsed:i,malformedAuthorityOrPort:s}=Po(r,n),{parsed:o,malformedAuthorityOrPort:a}=Po(e,n);if(s||a)throw new Error(i.error||o.error||"URI is malformed.");let c=hh(i,o,n,!0);return n.skipEscape=!0,gn(c,n)}function hh(r,e,t,n){let i={};return n||(r=Io(gn(r,t),t),e=Io(gn(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=Qi(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=Qi(e.path||""),i.query=e.query):(e.path?(e.path[0]==="/"?i.path=Qi(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=Qi(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 nS(r,e,t){let n=fh(r,t),i=fh(e,t);return n!==void 0&&i!==void 0&&n.toLowerCase()===i.toLowerCase()}function gn(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=[],s=ph(n.scheme||t.scheme);s&&s.serialize&&s.serialize(t,n),t.path!==void 0&&(n.skipEscape?t.path=G$(t.path):(t.path=Y$(t.path),t.scheme!==void 0&&(t.path=t.path.split("%3A").join(":")))),n.reference!=="suffix"&&t.scheme&&i.push(t.scheme,":");let o=W$(t);if(o!==void 0&&(n.reference!=="suffix"&&i.push("//"),i.push(o),t.path&&t.path[0]!=="/"&&i.push("/")),t.path!==void 0){let a=t.path;!n.absolutePath&&(!s||!s.absolutePath)&&(a=Qi(a)),o===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),i.push(a)}return t.query!==void 0&&i.push("?",t.query),t.fragment!==void 0&&i.push("#",t.fragment),i.join("")}var iS=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,sS=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,oS=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function aS(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 Po(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;t.reference==="suffix"&&(t.scheme?r=t.scheme+":"+r:r="//"+r);let o=r.match(sS);o!==null&&o[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",i=!0);let a=r.match(oS);if(a!==null){let l=a[1],u=l.replace(/[\t\n\r]/g,"");u.length>=2&&(u.slice(0,2)!=="//"?(n.error=n.error||"URI authority must not contain a literal backslash.",i=!0):l.length!==u.length&&(n.error=n.error||"URI authority introducer must not contain whitespace.",i=!0))}let c=r.match(iS);if(c){n.scheme=c[1],n.userinfo=c[3],n.host=c[4],n.port=parseInt(c[5],10),n.path=c[6]||"",n.query=c[7],n.fragment=c[8],isNaN(n.port)&&(n.port=c[5]);let l=aS(n,c);if(l!==void 0&&(n.error=n.error||l,i=!0),n.host)if(Q$(n.host)===!1){let f=K$(n.host);n.host=f.host.toLowerCase(),s=f.isIPV6}else s=!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 u=ph(t.scheme||n.scheme);if(!t.unicodeSupport&&(!u||!u.unicodeSupport)&&n.host&&(t.domainHost||u&&u.domainHost)&&s===!1&&Z$(n.host))try{n.host=new URL("http://"+n.host).hostname}catch(d){n.error=n.error||"Host's domain name can not be converted to ASCII: "+d}if((!u||u&&!u.skipNormalize)&&(r.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=X$(unescape(n.host),s))),n.path&&(n.path=J$(n.path)),n.fragment))try{n.fragment=encodeURI(decodeURIComponent(n.fragment))}catch(d){n.error=n.error||"URI malformed"}u&&u.parse&&u.parse(n,t)}else n.error=n.error||"URI can not be parsed.";return{parsed:n,malformedAuthorityOrPort:i}}function Io(r,e){return Po(r,e).parsed}function cS(r,e){return mh(r,e).normalized}function mh(r,e){let{parsed:t,malformedAuthorityOrPort:n}=Po(r,e);return{normalized:n?r:gn(t,e),malformedAuthorityOrPort:n}}function fh(r,e){if(typeof r=="string"){let{normalized:t,malformedAuthorityOrPort:n}=mh(r,e);return n?void 0:t}if(typeof r=="object")return gn(r,e)}var El={SCHEMES:eS,normalize:tS,resolve:rS,resolveComponent:hh,equal:nS,serialize:gn,parse:Io};Oo.exports=El;Oo.exports.default=El;Oo.exports.fastUri=El});var bh=A(Al=>{"use strict";Object.defineProperty(Al,"__esModule",{value:!0});var gh=yh();gh.code='require("ajv/dist/runtime/uri").default';Al.default=gh});var Pl=A(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 lS=Un();Object.defineProperty(Fe,"KeywordCxt",{enumerable:!0,get:function(){return lS.KeywordCxt}});var Hn=K();Object.defineProperty(Fe,"_",{enumerable:!0,get:function(){return Hn._}});Object.defineProperty(Fe,"str",{enumerable:!0,get:function(){return Hn.str}});Object.defineProperty(Fe,"stringify",{enumerable:!0,get:function(){return Hn.stringify}});Object.defineProperty(Fe,"nil",{enumerable:!0,get:function(){return Hn.nil}});Object.defineProperty(Fe,"Name",{enumerable:!0,get:function(){return Hn.Name}});Object.defineProperty(Fe,"CodeGen",{enumerable:!0,get:function(){return Hn.CodeGen}});var dS=Yi(),Sh=Bn(),uS=Zc(),Zi=Xi(),fS=K(),es=Wi(),To=Ki(),xl=ee(),_h=eh(),pS=bh(),Eh=(r,e)=>new RegExp(r,e);Eh.code="new RegExp";var hS=["removeAdditional","useDefaults","coerceTypes"],mS=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),yS={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."},gS={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},wh=200;function bS(r){var e,t,n,i,s,o,a,c,l,u,d,f,p,m,h,y,b,g,_,k,v,E,O,w,x;let $=r.strict,L=(e=r.code)===null||e===void 0?void 0:e.optimize,F=L===!0||L===void 0?1:L||0,z=(n=(t=r.code)===null||t===void 0?void 0:t.regExp)!==null&&n!==void 0?n:Eh,P=(i=r.uriResolver)!==null&&i!==void 0?i:pS.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:(m=(p=r.strictRequired)!==null&&p!==void 0?p:$)!==null&&m!==void 0?m:!1,code:r.code?{...r.code,optimize:F,regExp:z}:{optimize:F,regExp:z},loopRequired:(h=r.loopRequired)!==null&&h!==void 0?h:wh,loopEnum:(y=r.loopEnum)!==null&&y!==void 0?y:wh,meta:(b=r.meta)!==null&&b!==void 0?b:!0,messages:(g=r.messages)!==null&&g!==void 0?g:!0,inlineRefs:(_=r.inlineRefs)!==null&&_!==void 0?_:!0,schemaId:(k=r.schemaId)!==null&&k!==void 0?k:"$id",addUsedSchema:(v=r.addUsedSchema)!==null&&v!==void 0?v:!0,validateSchema:(E=r.validateSchema)!==null&&E!==void 0?E:!0,validateFormats:(O=r.validateFormats)!==null&&O!==void 0?O:!0,unicodeRegExp:(w=r.unicodeRegExp)!==null&&w!==void 0?w:!0,int32range:(x=r.int32range)!==null&&x!==void 0?x:!0,uriResolver:P}}var ts=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,...bS(e)};let{es5:t,lines:n}=this.opts.code;this.scope=new fS.ValueScope({scope:{},prefixes:mS,es5:t,lines:n}),this.logger=ES(e.logger);let i=e.validateFormats;e.validateFormats=!1,this.RULES=(0,uS.getRules)(),vh.call(this,yS,e,"NOT SUPPORTED"),vh.call(this,gS,e,"DEPRECATED","warn"),this._metaOpts=$S.call(this),e.formats&&wS.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&vS.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),_S.call(this),e.validateFormats=i}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:t,schemaId:n}=this.opts,i=_h;n==="id"&&(i={..._h},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 Sh.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,es.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=$h.call(this,e))=="string";)e=t;if(t===void 0){let{schemaId:n}=this.opts,i=new Zi.SchemaEnv({schema:{},schemaId:n});if(t=Zi.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=$h.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,es.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(kS.call(this,n,t),!t)return(0,xl.eachItem)(n,s=>kl.call(this,s)),this;PS.call(this,t);let i={...t,type:(0,To.getJSONTypes)(t.type),schemaType:(0,To.getJSONTypes)(t.schemaType)};return(0,xl.eachItem)(n,i.type.length===0?s=>kl.call(this,s,i):s=>i.type.forEach(o=>kl.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]=Ah(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,es.normalizeId)(o||n);let l=es.getSchemaRefs.call(this,e,n);return c=new Zi.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):Zi.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{Zi.compileSchema.call(this,e)}finally{this.opts=t}}};ts.ValidationError=dS.default;ts.MissingRefError=Sh.default;Fe.default=ts;function vh(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 $h(r){return r=(0,es.normalizeId)(r),this.schemas[r]||this.refs[r]}function _S(){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 wS(){for(let r in this.opts.formats){let e=this.opts.formats[r];e&&this.addFormat(r,e)}}function vS(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 $S(){let r={...this.opts};for(let e of hS)delete r[e];return r}var SS={log(){},warn(){},error(){}};function ES(r){if(r===!1)return SS;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 AS=/^[a-z_$][a-z0-9_$:-]*$/i;function kS(r,e){let{RULES:t}=this;if((0,xl.eachItem)(r,n=>{if(t.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!AS.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 kl(r,e,t){var n;let i=e==null?void 0: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,To.getJSONTypes)(e.type),schemaType:(0,To.getJSONTypes)(e.schemaType)}};e.before?xS.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 xS(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 PS(r){let{metaSchema:e}=r;e!==void 0&&(r.$data&&this.opts.$data&&(e=Ah(e)),r.validateSchema=this.compile(e,!0))}var IS={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Ah(r){return{anyOf:[r,IS]}}});var kh=A(Il=>{"use strict";Object.defineProperty(Il,"__esModule",{value:!0});var OS={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Il.default=OS});var Mo=A(bn=>{"use strict";Object.defineProperty(bn,"__esModule",{value:!0});bn.callRef=bn.getValidate=void 0;var TS=Bn(),xh=xt(),ft=K(),Kn=kt(),Ph=Xi(),Ro=ee(),RS={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=Ph.resolveRef.call(c,l,i,t);if(u===void 0)throw new TS.default(n.opts.uriResolver,i,t);if(u instanceof Ph.SchemaEnv)return f(u);return p(u);function d(){if(s===l)return Co(r,o,s,s.$async);let m=e.scopeValue("root",{ref:l});return Co(r,(0,ft._)`${m}.validate`,l,l.$async)}function f(m){let h=Ih(r,m);Co(r,h,m,m.$async)}function p(m){let h=e.scopeValue("schema",a.code.source===!0?{ref:m,code:(0,ft.stringify)(m)}:{ref:m}),y=e.name("valid"),b=r.subschema({schema:m,dataTypes:[],schemaPath:ft.nil,topSchemaRef:h,errSchemaPath:t},y);r.mergeEvaluated(b),r.ok(y)}}};function Ih(r,e){let{gen:t}=r;return e.validate?t.scopeValue("validate",{ref:e.validate}):(0,ft._)`${t.scopeValue("wrapper",{ref:e})}.validate`}bn.getValidate=Ih;function Co(r,e,t,n){let{gen:i,it:s}=r,{allErrors:o,schemaEnv:a,opts:c}=s,l=c.passContext?Kn.default.this:ft.nil;n?u():d();function u(){if(!a.$async)throw new Error("async schema referenced by sync schema");let m=i.let("valid");i.try(()=>{i.code((0,ft._)`await ${(0,xh.callValidateCode)(r,e,l)}`),p(e),o||i.assign(m,!0)},h=>{i.if((0,ft._)`!(${h} instanceof ${s.ValidationError})`,()=>i.throw(h)),f(h),o||i.assign(m,!1)}),r.ok(m)}function d(){r.result((0,xh.callValidateCode)(r,e,l),()=>p(e),()=>f(e))}function f(m){let h=(0,ft._)`${m}.errors`;i.assign(Kn.default.vErrors,(0,ft._)`${Kn.default.vErrors} === null ? ${h} : ${Kn.default.vErrors}.concat(${h})`),i.assign(Kn.default.errors,(0,ft._)`${Kn.default.vErrors}.length`)}function p(m){var h;if(!s.opts.unevaluated)return;let y=(h=t==null?void 0:t.validate)===null||h===void 0?void 0:h.evaluated;if(s.props!==!0)if(y&&!y.dynamicProps)y.props!==void 0&&(s.props=Ro.mergeEvaluated.props(i,y.props,s.props));else{let b=i.var("props",(0,ft._)`${m}.evaluated.props`);s.props=Ro.mergeEvaluated.props(i,b,s.props,ft.Name)}if(s.items!==!0)if(y&&!y.dynamicItems)y.items!==void 0&&(s.items=Ro.mergeEvaluated.items(i,y.items,s.items));else{let b=i.var("items",(0,ft._)`${m}.evaluated.items`);s.items=Ro.mergeEvaluated.items(i,b,s.items,ft.Name)}}}bn.callRef=Co;bn.default=RS});var Tl=A(Ol=>{"use strict";Object.defineProperty(Ol,"__esModule",{value:!0});var CS=kh(),MS=Mo(),NS=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",CS.default,MS.default];Ol.default=NS});var Oh=A(Rl=>{"use strict";Object.defineProperty(Rl,"__esModule",{value:!0});var No=K(),zr=No.operators,Lo={maximum:{okStr:"<=",ok:zr.LTE,fail:zr.GT},minimum:{okStr:">=",ok:zr.GTE,fail:zr.LT},exclusiveMaximum:{okStr:"<",ok:zr.LT,fail:zr.GTE},exclusiveMinimum:{okStr:">",ok:zr.GT,fail:zr.LTE}},LS={message:({keyword:r,schemaCode:e})=>(0,No.str)`must be ${Lo[r].okStr} ${e}`,params:({keyword:r,schemaCode:e})=>(0,No._)`{comparison: ${Lo[r].okStr}, limit: ${e}}`},DS={keyword:Object.keys(Lo),type:"number",schemaType:"number",$data:!0,error:LS,code(r){let{keyword:e,data:t,schemaCode:n}=r;r.fail$data((0,No._)`${t} ${Lo[e].fail} ${n} || isNaN(${t})`)}};Rl.default=DS});var Th=A(Cl=>{"use strict";Object.defineProperty(Cl,"__esModule",{value:!0});var rs=K(),qS={message:({schemaCode:r})=>(0,rs.str)`must be multiple of ${r}`,params:({schemaCode:r})=>(0,rs._)`{multipleOf: ${r}}`},jS={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:qS,code(r){let{gen:e,data:t,schemaCode:n,it:i}=r,s=i.opts.multipleOfPrecision,o=e.let("res"),a=s?(0,rs._)`Math.abs(Math.round(${o}) - ${o}) > 1e-${s}`:(0,rs._)`${o} !== parseInt(${o})`;r.fail$data((0,rs._)`(${n} === 0 || (${o} = ${t}/${n}, ${a}))`)}};Cl.default=jS});var Ch=A(Ml=>{"use strict";Object.defineProperty(Ml,"__esModule",{value:!0});function Rh(r){let e=r.length,t=0,n=0,i;for(;n=55296&&i<=56319&&n{"use strict";Object.defineProperty(Nl,"__esModule",{value:!0});var _n=K(),FS=ee(),VS=Ch(),US={message({keyword:r,schemaCode:e}){let t=r==="maxLength"?"more":"fewer";return(0,_n.str)`must NOT have ${t} than ${e} characters`},params:({schemaCode:r})=>(0,_n._)`{limit: ${r}}`},BS={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:US,code(r){let{keyword:e,data:t,schemaCode:n,it:i}=r,s=e==="maxLength"?_n.operators.GT:_n.operators.LT,o=i.opts.unicode===!1?(0,_n._)`${t}.length`:(0,_n._)`${(0,FS.useFunc)(r.gen,VS.default)}(${t})`;r.fail$data((0,_n._)`${o} ${s} ${n}`)}};Nl.default=BS});var Nh=A(Ll=>{"use strict";Object.defineProperty(Ll,"__esModule",{value:!0});var zS=xt(),HS=ee(),Wn=K(),KS={message:({schemaCode:r})=>(0,Wn.str)`must match pattern "${r}"`,params:({schemaCode:r})=>(0,Wn._)`{pattern: ${r}}`},WS={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:KS,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,Wn._)`new RegExp`:(0,HS.useFunc)(e,c),u=e.let("valid");e.try(()=>e.assign(u,(0,Wn._)`${l}(${s}, ${a}).test(${t})`),()=>e.assign(u,!1)),r.fail$data((0,Wn._)`!${u}`)}else{let c=(0,zS.usePattern)(r,i);r.fail$data((0,Wn._)`!${c}.test(${t})`)}}};Ll.default=WS});var Lh=A(Dl=>{"use strict";Object.defineProperty(Dl,"__esModule",{value:!0});var ns=K(),GS={message({keyword:r,schemaCode:e}){let t=r==="maxProperties"?"more":"fewer";return(0,ns.str)`must NOT have ${t} than ${e} properties`},params:({schemaCode:r})=>(0,ns._)`{limit: ${r}}`},JS={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:GS,code(r){let{keyword:e,data:t,schemaCode:n}=r,i=e==="maxProperties"?ns.operators.GT:ns.operators.LT;r.fail$data((0,ns._)`Object.keys(${t}).length ${i} ${n}`)}};Dl.default=JS});var Dh=A(ql=>{"use strict";Object.defineProperty(ql,"__esModule",{value:!0});var is=xt(),ss=K(),YS=ee(),XS={message:({params:{missingProperty:r}})=>(0,ss.str)`must have required property '${r}'`,params:({params:{missingProperty:r}})=>(0,ss._)`{missingProperty: ${r}}`},QS={keyword:"required",type:"object",schemaType:"array",$data:!0,error:XS,code(r){let{gen:e,schema:t,schemaCode:n,data:i,$data:s,it:o}=r,{opts:a}=o;if(!s&&t.length===0)return;let c=t.length>=a.loopRequired;if(o.allErrors?l():u(),a.strictRequired){let p=r.parentSchema.properties,{definedProperties:m}=r.it;for(let h of t)if((p==null?void 0:p[h])===void 0&&!m.has(h)){let y=o.schemaEnv.baseId+o.errSchemaPath,b=`required property "${h}" is not defined at "${y}" (strictRequired)`;(0,YS.checkStrictMode)(o,b,o.opts.strictRequired)}}function l(){if(c||s)r.block$data(ss.nil,d);else for(let p of t)(0,is.checkReportMissingProp)(r,p)}function u(){let p=e.let("missing");if(c||s){let m=e.let("valid",!0);r.block$data(m,()=>f(p,m)),r.ok(m)}else e.if((0,is.checkMissingProp)(r,t,p)),(0,is.reportMissingProp)(r,p),e.else()}function d(){e.forOf("prop",n,p=>{r.setParams({missingProperty:p}),e.if((0,is.noPropertyInData)(e,i,p,a.ownProperties),()=>r.error())})}function f(p,m){r.setParams({missingProperty:p}),e.forOf(p,n,()=>{e.assign(m,(0,is.propertyInData)(e,i,p,a.ownProperties)),e.if((0,ss.not)(m),()=>{r.error(),e.break()})},ss.nil)}}};ql.default=QS});var qh=A(jl=>{"use strict";Object.defineProperty(jl,"__esModule",{value:!0});var os=K(),ZS={message({keyword:r,schemaCode:e}){let t=r==="maxItems"?"more":"fewer";return(0,os.str)`must NOT have ${t} than ${e} items`},params:({schemaCode:r})=>(0,os._)`{limit: ${r}}`},eE={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:ZS,code(r){let{keyword:e,data:t,schemaCode:n}=r,i=e==="maxItems"?os.operators.GT:os.operators.LT;r.fail$data((0,os._)`${t}.length ${i} ${n}`)}};jl.default=eE});var Do=A(Fl=>{"use strict";Object.defineProperty(Fl,"__esModule",{value:!0});var jh=al();jh.code='require("ajv/dist/runtime/equal").default';Fl.default=jh});var Fh=A(Ul=>{"use strict";Object.defineProperty(Ul,"__esModule",{value:!0});var Vl=Ki(),Ve=K(),tE=ee(),rE=Do(),nE={message:({params:{i:r,j:e}})=>(0,Ve.str)`must NOT have duplicate items (items ## ${e} and ${r} are identical)`,params:({params:{i:r,j:e}})=>(0,Ve._)`{i: ${r}, j: ${e}}`},iE={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:nE,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,Vl.getSchemaTypes)(s.items):[];r.block$data(c,u,(0,Ve._)`${o} === false`),r.ok(c);function u(){let m=e.let("i",(0,Ve._)`${t}.length`),h=e.let("j");r.setParams({i:m,j:h}),e.assign(c,!0),e.if((0,Ve._)`${m} > 1`,()=>(d()?f:p)(m,h))}function d(){return l.length>0&&!l.some(m=>m==="object"||m==="array")}function f(m,h){let y=e.name("item"),b=(0,Vl.checkDataTypes)(l,y,a.opts.strictNumbers,Vl.DataType.Wrong),g=e.const("indices",(0,Ve._)`{}`);e.for((0,Ve._)`;${m}--;`,()=>{e.let(y,(0,Ve._)`${t}[${m}]`),e.if(b,(0,Ve._)`continue`),l.length>1&&e.if((0,Ve._)`typeof ${y} == "string"`,(0,Ve._)`${y} += "_"`),e.if((0,Ve._)`typeof ${g}[${y}] == "number"`,()=>{e.assign(h,(0,Ve._)`${g}[${y}]`),r.error(),e.assign(c,!1).break()}).code((0,Ve._)`${g}[${y}] = ${m}`)})}function p(m,h){let y=(0,tE.useFunc)(e,rE.default),b=e.name("outer");e.label(b).for((0,Ve._)`;${m}--;`,()=>e.for((0,Ve._)`${h} = ${m}; ${h}--;`,()=>e.if((0,Ve._)`${y}(${t}[${m}], ${t}[${h}])`,()=>{r.error(),e.assign(c,!1).break(b)})))}}};Ul.default=iE});var Vh=A(zl=>{"use strict";Object.defineProperty(zl,"__esModule",{value:!0});var Bl=K(),sE=ee(),oE=Do(),aE={message:"must be equal to constant",params:({schemaCode:r})=>(0,Bl._)`{allowedValue: ${r}}`},cE={keyword:"const",$data:!0,error:aE,code(r){let{gen:e,data:t,$data:n,schemaCode:i,schema:s}=r;n||s&&typeof s=="object"?r.fail$data((0,Bl._)`!${(0,sE.useFunc)(e,oE.default)}(${t}, ${i})`):r.fail((0,Bl._)`${s} !== ${t}`)}};zl.default=cE});var Uh=A(Hl=>{"use strict";Object.defineProperty(Hl,"__esModule",{value:!0});var as=K(),lE=ee(),dE=Do(),uE={message:"must be equal to one of the allowed values",params:({schemaCode:r})=>(0,as._)`{allowedValues: ${r}}`},fE={keyword:"enum",schemaType:"array",$data:!0,error:uE,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!=null?c:c=(0,lE.useFunc)(e,dE.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,as.or)(...i.map((m,h)=>f(p,h)))}r.pass(u);function d(){e.assign(u,!1),e.forOf("v",s,p=>e.if((0,as._)`${l()}(${t}, ${p})`,()=>e.assign(u,!0).break()))}function f(p,m){let h=i[m];return typeof h=="object"&&h!==null?(0,as._)`${l()}(${t}, ${p}[${m}])`:(0,as._)`${t} === ${h}`}}};Hl.default=fE});var Wl=A(Kl=>{"use strict";Object.defineProperty(Kl,"__esModule",{value:!0});var pE=Oh(),hE=Th(),mE=Mh(),yE=Nh(),gE=Lh(),bE=Dh(),_E=qh(),wE=Fh(),vE=Vh(),$E=Uh(),SE=[pE.default,hE.default,mE.default,yE.default,gE.default,bE.default,_E.default,wE.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},vE.default,$E.default];Kl.default=SE});var Jl=A(cs=>{"use strict";Object.defineProperty(cs,"__esModule",{value:!0});cs.validateAdditionalItems=void 0;var wn=K(),Gl=ee(),EE={message:({params:{len:r}})=>(0,wn.str)`must NOT have more than ${r} items`,params:({params:{len:r}})=>(0,wn._)`{limit: ${r}}`},AE={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:EE,code(r){let{parentSchema:e,it:t}=r,{items:n}=e;if(!Array.isArray(n)){(0,Gl.checkStrictMode)(t,'"additionalItems" is ignored when "items" is not an array of schemas');return}Bh(r,n)}};function Bh(r,e){let{gen:t,schema:n,data:i,keyword:s,it:o}=r;o.items=!0;let a=t.const("len",(0,wn._)`${i}.length`);if(n===!1)r.setParams({len:e.length}),r.pass((0,wn._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,Gl.alwaysValidSchema)(o,n)){let l=t.var("valid",(0,wn._)`${a} <= ${e.length}`);t.if((0,wn.not)(l),()=>c(l)),r.ok(l)}function c(l){t.forRange("i",e.length,a,u=>{r.subschema({keyword:s,dataProp:u,dataPropType:Gl.Type.Num},l),o.allErrors||t.if((0,wn.not)(l),()=>t.break())})}}cs.validateAdditionalItems=Bh;cs.default=AE});var Yl=A(ls=>{"use strict";Object.defineProperty(ls,"__esModule",{value:!0});ls.validateTuple=void 0;var zh=K(),qo=ee(),kE=xt(),xE={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(r){let{schema:e,it:t}=r;if(Array.isArray(e))return Hh(r,"additionalItems",e);t.items=!0,!(0,qo.alwaysValidSchema)(t,e)&&r.ok((0,kE.validateArray)(r))}};function Hh(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=qo.mergeEvaluated.items(n,t.length,a.items));let c=n.name("valid"),l=n.const("len",(0,zh._)`${s}.length`);t.forEach((d,f)=>{(0,qo.alwaysValidSchema)(a,d)||(n.if((0,zh._)`${l} > ${f}`,()=>r.subschema({keyword:o,schemaProp:f,dataProp:f},c)),r.ok(c))});function u(d){let{opts:f,errSchemaPath:p}=a,m=t.length,h=m===d.minItems&&(m===d.maxItems||d[e]===!1);if(f.strictTuples&&!h){let y=`"${o}" is ${m}-tuple, but minItems or maxItems/${e} are not specified or different at path "${p}"`;(0,qo.checkStrictMode)(a,y,f.strictTuples)}}}ls.validateTuple=Hh;ls.default=xE});var Kh=A(Xl=>{"use strict";Object.defineProperty(Xl,"__esModule",{value:!0});var PE=Yl(),IE={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:r=>(0,PE.validateTuple)(r,"items")};Xl.default=IE});var Gh=A(Ql=>{"use strict";Object.defineProperty(Ql,"__esModule",{value:!0});var Wh=K(),OE=ee(),TE=xt(),RE=Jl(),CE={message:({params:{len:r}})=>(0,Wh.str)`must NOT have more than ${r} items`,params:({params:{len:r}})=>(0,Wh._)`{limit: ${r}}`},ME={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:CE,code(r){let{schema:e,parentSchema:t,it:n}=r,{prefixItems:i}=t;n.items=!0,!(0,OE.alwaysValidSchema)(n,e)&&(i?(0,RE.validateAdditionalItems)(r,i):r.ok((0,TE.validateArray)(r)))}};Ql.default=ME});var Jh=A(Zl=>{"use strict";Object.defineProperty(Zl,"__esModule",{value:!0});var It=K(),jo=ee(),NE={message:({params:{min:r,max:e}})=>e===void 0?(0,It.str)`must contain at least ${r} valid item(s)`:(0,It.str)`must contain at least ${r} and no more than ${e} valid item(s)`,params:({params:{min:r,max:e}})=>e===void 0?(0,It._)`{minContains: ${r}}`:(0,It._)`{minContains: ${r}, maxContains: ${e}}`},LE={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:NE,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,It._)`${i}.length`);if(r.setParams({min:o,max:a}),a===void 0&&o===0){(0,jo.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&o>a){(0,jo.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),r.fail();return}if((0,jo.alwaysValidSchema)(s,t)){let h=(0,It._)`${u} >= ${o}`;a!==void 0&&(h=(0,It._)`${h} && ${u} <= ${a}`),r.pass(h);return}s.items=!0;let d=e.name("valid");a===void 0&&o===1?p(d,()=>e.if(d,()=>e.break())):o===0?(e.let(d,!0),a!==void 0&&e.if((0,It._)`${i}.length > 0`,f)):(e.let(d,!1),f()),r.result(d,()=>r.reset());function f(){let h=e.name("_valid"),y=e.let("count",0);p(h,()=>e.if(h,()=>m(y)))}function p(h,y){e.forRange("i",0,u,b=>{r.subschema({keyword:"contains",dataProp:b,dataPropType:jo.Type.Num,compositeRule:!0},h),y()})}function m(h){e.code((0,It._)`${h}++`),a===void 0?e.if((0,It._)`${h} >= ${o}`,()=>e.assign(d,!0).break()):(e.if((0,It._)`${h} > ${a}`,()=>e.assign(d,!1).break()),o===1?e.assign(d,!0):e.if((0,It._)`${h} >= ${o}`,()=>e.assign(d,!0)))}}};Zl.default=LE});var Fo=A(ar=>{"use strict";Object.defineProperty(ar,"__esModule",{value:!0});ar.validateSchemaDeps=ar.validatePropertyDeps=ar.error=void 0;var ed=K(),DE=ee(),ds=xt();ar.error={message:({params:{property:r,depsCount:e,deps:t}})=>{let n=e===1?"property":"properties";return(0,ed.str)`must have ${n} ${t} when property ${r} is present`},params:({params:{property:r,depsCount:e,deps:t,missingProperty:n}})=>(0,ed._)`{property: ${r}, +var V0=Object.create;var Fi=Object.defineProperty;var B0=Object.getOwnPropertyDescriptor;var z0=Object.getOwnPropertyNames;var H0=Object.getPrototypeOf,K0=Object.prototype.hasOwnProperty;var W0=(r,e,t)=>e in r?Fi(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var vp=(r,e)=>()=>(r&&(e=r(r=0)),e);var A=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),G0=(r,e)=>{for(var t in e)Fi(r,t,{get:e[t],enumerable:!0})},$p=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of z0(e))!K0.call(r,i)&&i!==t&&Fi(r,i,{get:()=>e[i],enumerable:!(n=B0(e,i))||n.enumerable});return r};var dn=(r,e,t)=>(t=r!=null?V0(H0(r)):{},$p(e||!r||!r.__esModule?Fi(t,"default",{value:r,enumerable:!0}):t,r)),J0=r=>$p(Fi({},"__esModule",{value:!0}),r);var I=(r,e,t)=>W0(r,typeof e!="symbol"?e+"":e,t);var zi=A(ce=>{"use strict";Object.defineProperty(ce,"__esModule",{value:!0});ce.regexpCode=ce.getEsmExportName=ce.getProperty=ce.safeStringify=ce.stringify=ce.strConcat=ce.addCodeArg=ce.str=ce._=ce.nil=ce._Code=ce.Name=ce.IDENTIFIER=ce._CodeOrName=void 0;var Vi=class{};ce._CodeOrName=Vi;ce.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var un=class extends Vi{constructor(e){if(super(),!ce.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}}};ce.Name=un;var vt=class extends Vi{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 un&&(t[n.str]=(t[n.str]||0)+1),t),{})}};ce._Code=vt;ce.nil=new vt("");function Sp(r,...e){let t=[r[0]],n=0;for(;n{"use strict";Object.defineProperty(ot,"__esModule",{value:!0});ot.ValueScope=ot.ValueScopeName=ot.Scope=ot.varKinds=ot.UsedValueState=void 0;var st=zi(),Wc=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},_o;(function(r){r[r.Started=0]="Started",r[r.Completed=1]="Completed"})(_o||(ot.UsedValueState=_o={}));ot.varKinds={const:new st.Name("const"),let:new st.Name("let"),var:new st.Name("var")};var bo=class{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t}toName(e){return e instanceof st.Name?e:this.name(e)}name(e){return new st.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}}};ot.Scope=bo;var wo=class extends st.Name{constructor(e,t){super(t),this.prefix=e}setValue(e,{property:t,itemIndex:n}){this.value=e,this.scopePath=(0,st._)`.${new st.Name(t)}[${n}]`}};ot.ValueScopeName=wo;var iv=(0,st._)`\n`,Gc=class extends bo{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?iv:st.nil}}get(){return this._scope}name(e){return new wo(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 d=a.get(o);if(d)return d}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,st._)`${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=st.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,_o.Started);let d=t(l);if(d){let u=this.opts.es5?ot.varKinds.var:ot.varKinds.const;s=(0,st._)`${s}${u} ${l} = ${d};${this.opts._n}`}else if(d=i==null?void 0:i(l))s=(0,st._)`${s}${d}${this.opts._n}`;else throw new Wc(l);c.set(l,_o.Completed)})}return s}};ot.ValueScope=Gc});var H=A(Y=>{"use strict";Object.defineProperty(Y,"__esModule",{value:!0});Y.or=Y.and=Y.not=Y.CodeGen=Y.operators=Y.varKinds=Y.ValueScopeName=Y.ValueScope=Y.Scope=Y.Name=Y.regexpCode=Y.stringify=Y.getProperty=Y.nil=Y.strConcat=Y.str=Y._=void 0;var ie=zi(),Tt=Jc(),Dr=zi();Object.defineProperty(Y,"_",{enumerable:!0,get:function(){return Dr._}});Object.defineProperty(Y,"str",{enumerable:!0,get:function(){return Dr.str}});Object.defineProperty(Y,"strConcat",{enumerable:!0,get:function(){return Dr.strConcat}});Object.defineProperty(Y,"nil",{enumerable:!0,get:function(){return Dr.nil}});Object.defineProperty(Y,"getProperty",{enumerable:!0,get:function(){return Dr.getProperty}});Object.defineProperty(Y,"stringify",{enumerable:!0,get:function(){return Dr.stringify}});Object.defineProperty(Y,"regexpCode",{enumerable:!0,get:function(){return Dr.regexpCode}});Object.defineProperty(Y,"Name",{enumerable:!0,get:function(){return Dr.Name}});var Eo=Jc();Object.defineProperty(Y,"Scope",{enumerable:!0,get:function(){return Eo.Scope}});Object.defineProperty(Y,"ValueScope",{enumerable:!0,get:function(){return Eo.ValueScope}});Object.defineProperty(Y,"ValueScopeName",{enumerable:!0,get:function(){return Eo.ValueScopeName}});Object.defineProperty(Y,"varKinds",{enumerable:!0,get:function(){return Eo.varKinds}});Y.operators={GT:new ie._Code(">"),GTE:new ie._Code(">="),LT:new ie._Code("<"),LTE:new ie._Code("<="),EQ:new ie._Code("==="),NEQ:new ie._Code("!=="),NOT:new ie._Code("!"),OR:new ie._Code("||"),AND:new ie._Code("&&"),ADD:new ie._Code("+")};var yr=class{optimizeNodes(){return this}optimizeNames(e,t){return this}},Yc=class extends yr{constructor(e,t,n){super(),this.varKind=e,this.name=t,this.rhs=n}render({es5:e,_n:t}){let n=e?Tt.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=qn(this.rhs,e,t)),this}get names(){return this.rhs instanceof ie._CodeOrName?this.rhs.names:{}}},vo=class extends yr{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 ie.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=qn(this.rhs,e,t),this}get names(){let e=this.lhs instanceof ie.Name?{}:{...this.lhs.names};return So(e,this.rhs)}},Xc=class extends vo{constructor(e,t,n,i){super(e,n,i),this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Qc=class extends yr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Zc=class extends yr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},el=class extends yr{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},tl=class extends yr{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=qn(this.code,e,t),this}get names(){return this.code instanceof ie._CodeOrName?this.code.names:{}}},Hi=class extends yr{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)||(sv(e,s.names),n.splice(i,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>hn(e,t.names),{})}},gr=class extends Hi{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},rl=class extends Hi{},Dn=class extends gr{};Dn.kind="else";var fn=class r extends gr{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 Dn(n):n}if(t)return e===!1?t instanceof r?t:t.nodes:this.nodes.length?this:new r(Ap(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=qn(this.condition,e,t),this}get names(){let e=super.names;return So(e,this.condition),this.else&&hn(e,this.else.names),e}};fn.kind="if";var pn=class extends gr{};pn.kind="for";var nl=class extends pn{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=qn(this.iteration,e,t),this}get names(){return hn(super.names,this.iteration.names)}},il=class extends pn{constructor(e,t,n,i){super(),this.varKind=e,this.name=t,this.from=n,this.to=i}render(e){let t=e.es5?Tt.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=So(super.names,this.from);return So(e,this.to)}},$o=class extends pn{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=qn(this.iterable,e,t),this}get names(){return hn(super.names,this.iterable.names)}},Ki=class extends gr{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)}};Ki.kind="func";var Wi=class extends Hi{render(e){return"return "+super.render(e)}};Wi.kind="return";var sl=class extends gr{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&&hn(e,this.catch.names),this.finally&&hn(e,this.finally.names),e}},Gi=class extends gr{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};Gi.kind="catch";var Ji=class extends gr{render(e){return"finally"+super.render(e)}};Ji.kind="finally";var ol=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?` +`:""},this._extScope=e,this._scope=new Tt.Scope({parent:e}),this._nodes=[new rl]}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 Yc(e,s,n)),s}const(e,t,n){return this._def(Tt.varKinds.const,e,t,n)}let(e,t,n){return this._def(Tt.varKinds.let,e,t,n)}var(e,t,n){return this._def(Tt.varKinds.var,e,t,n)}assign(e,t,n){return this._leafNode(new vo(e,t,n))}add(e,t){return this._leafNode(new Xc(e,Y.operators.ADD,t))}code(e){return typeof e=="function"?e():e!==ie.nil&&this._leafNode(new tl(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,ie.addCodeArg)(t,i));return t.push("}"),new ie._Code(t)}if(e,t,n){if(this._blockNode(new fn(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 fn(e))}else(){return this._elseNode(new Dn)}endIf(){return this._endBlockNode(fn,Dn)}_for(e,t){return this._blockNode(e),t&&this.code(t).endFor(),this}for(e,t){return this._for(new nl(e),t)}forRange(e,t,n,i,s=this.opts.es5?Tt.varKinds.var:Tt.varKinds.let){let o=this._scope.toName(e);return this._for(new il(s,o,t,n),()=>i(o))}forOf(e,t,n,i=Tt.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let o=t instanceof ie.Name?t:this.var("_arr",t);return this.forRange("_i",0,(0,ie._)`${o}.length`,a=>{this.var(s,(0,ie._)`${o}[${a}]`),n(s)})}return this._for(new $o("of",i,s,t),()=>n(s))}forIn(e,t,n,i=this.opts.es5?Tt.varKinds.var:Tt.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,ie._)`Object.keys(${t})`,n);let s=this._scope.toName(e);return this._for(new $o("in",i,s,t),()=>n(s))}endFor(){return this._endBlockNode(pn)}label(e){return this._leafNode(new Qc(e))}break(e){return this._leafNode(new Zc(e))}return(e){let t=new Wi;if(this._blockNode(t),this.code(e),t.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Wi)}try(e,t,n){if(!t&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let i=new sl;if(this._blockNode(i),this.code(e),t){let s=this.name("e");this._currNode=i.catch=new Gi(s),t(s)}return n&&(this._currNode=i.finally=new Ji,this.code(n)),this._endBlockNode(Gi,Ji)}throw(e){return this._leafNode(new el(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=ie.nil,n,i){return this._blockNode(new Ki(e,t,n)),i&&this.code(i).endFunc(),this}endFunc(){return this._endBlockNode(Ki)}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 fn))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=ol;function hn(r,e){for(let t in e)r[t]=(r[t]||0)+(e[t]||0);return r}function So(r,e){return e instanceof ie._CodeOrName?hn(r,e.names):r}function qn(r,e,t){if(r instanceof ie.Name)return n(r);if(!i(r))return r;return new ie._Code(r._items.reduce((s,o)=>(o instanceof ie.Name&&(o=n(o)),o instanceof ie._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 ie._Code&&s._items.some(o=>o instanceof ie.Name&&e[o.str]===1&&t[o.str]!==void 0)}}function sv(r,e){for(let t in e)r[t]=(r[t]||0)-(e[t]||0)}function Ap(r){return typeof r=="boolean"||typeof r=="number"||r===null?!r:(0,ie._)`!${al(r)}`}Y.not=Ap;var ov=xp(Y.operators.AND);function av(...r){return r.reduce(ov)}Y.and=av;var cv=xp(Y.operators.OR);function lv(...r){return r.reduce(cv)}Y.or=lv;function xp(r){return(e,t)=>e===ie.nil?t:t===ie.nil?e:(0,ie._)`${al(e)} ${r} ${al(t)}`}function al(r){return r instanceof ie.Name?r:(0,ie._)`(${r})`}});var Q=A(X=>{"use strict";Object.defineProperty(X,"__esModule",{value:!0});X.checkStrictMode=X.getErrorPath=X.Type=X.useFunc=X.setEvaluated=X.evaluatedPropsToName=X.mergeEvaluated=X.eachItem=X.unescapeJsonPointer=X.escapeJsonPointer=X.escapeFragment=X.unescapeFragment=X.schemaRefOrVal=X.schemaHasRulesButRef=X.schemaHasRules=X.checkUnknownRules=X.alwaysValidSchema=X.toHash=void 0;var pe=H(),dv=zi();function uv(r){let e={};for(let t of r)e[t]=!0;return e}X.toHash=uv;function fv(r,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(Ip(r,e),!Op(e,r.self.RULES.all))}X.alwaysValidSchema=fv;function Ip(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]||Mp(r,`unknown keyword: "${s}"`)}X.checkUnknownRules=Ip;function Op(r,e){if(typeof r=="boolean")return!r;for(let t in r)if(e[t])return!0;return!1}X.schemaHasRules=Op;function pv(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=pv;function hv({topSchemaRef:r,schemaPath:e},t,n,i){if(!i){if(typeof t=="number"||typeof t=="boolean")return t;if(typeof t=="string")return(0,pe._)`${t}`}return(0,pe._)`${r}${e}${(0,pe.getProperty)(n)}`}X.schemaRefOrVal=hv;function mv(r){return Rp(decodeURIComponent(r))}X.unescapeFragment=mv;function yv(r){return encodeURIComponent(ll(r))}X.escapeFragment=yv;function ll(r){return typeof r=="number"?`${r}`:r.replace(/~/g,"~0").replace(/\//g,"~1")}X.escapeJsonPointer=ll;function Rp(r){return r.replace(/~1/g,"/").replace(/~0/g,"~")}X.unescapeJsonPointer=Rp;function gv(r,e){if(Array.isArray(r))for(let t of r)e(t);else e(r)}X.eachItem=gv;function kp({mergeNames:r,mergeToName:e,mergeValues:t,resultToName:n}){return(i,s,o,a)=>{let c=o===void 0?s:o instanceof pe.Name?(s instanceof pe.Name?r(i,s,o):e(i,s,o),o):s instanceof pe.Name?(e(i,o,s),s):t(s,o);return a===pe.Name&&!(c instanceof pe.Name)?n(i,c):c}}X.mergeEvaluated={props:kp({mergeNames:(r,e,t)=>r.if((0,pe._)`${t} !== true && ${e} !== undefined`,()=>{r.if((0,pe._)`${e} === true`,()=>r.assign(t,!0),()=>r.assign(t,(0,pe._)`${t} || {}`).code((0,pe._)`Object.assign(${t}, ${e})`))}),mergeToName:(r,e,t)=>r.if((0,pe._)`${t} !== true`,()=>{e===!0?r.assign(t,!0):(r.assign(t,(0,pe._)`${t} || {}`),dl(r,t,e))}),mergeValues:(r,e)=>r===!0?!0:{...r,...e},resultToName:Tp}),items:kp({mergeNames:(r,e,t)=>r.if((0,pe._)`${t} !== true && ${e} !== undefined`,()=>r.assign(t,(0,pe._)`${e} === true ? true : ${t} > ${e} ? ${t} : ${e}`)),mergeToName:(r,e,t)=>r.if((0,pe._)`${t} !== true`,()=>r.assign(t,e===!0?!0:(0,pe._)`${t} > ${e} ? ${t} : ${e}`)),mergeValues:(r,e)=>r===!0?!0:Math.max(r,e),resultToName:(r,e)=>r.var("items",e)})};function Tp(r,e){if(e===!0)return r.var("props",!0);let t=r.var("props",(0,pe._)`{}`);return e!==void 0&&dl(r,t,e),t}X.evaluatedPropsToName=Tp;function dl(r,e,t){Object.keys(t).forEach(n=>r.assign((0,pe._)`${e}${(0,pe.getProperty)(n)}`,!0))}X.setEvaluated=dl;var Pp={};function _v(r,e){return r.scopeValue("func",{ref:e,code:Pp[e.code]||(Pp[e.code]=new dv._Code(e.code))})}X.useFunc=_v;var cl;(function(r){r[r.Num=0]="Num",r[r.Str=1]="Str"})(cl||(X.Type=cl={}));function bv(r,e,t){if(r instanceof pe.Name){let n=e===cl.Num;return t?n?(0,pe._)`"[" + ${r} + "]"`:(0,pe._)`"['" + ${r} + "']"`:n?(0,pe._)`"/" + ${r}`:(0,pe._)`"/" + ${r}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return t?(0,pe.getProperty)(r).toString():"/"+ll(r)}X.getErrorPath=bv;function Mp(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=Mp});var $t=A(ul=>{"use strict";Object.defineProperty(ul,"__esModule",{value:!0});var Be=H(),wv={data:new Be.Name("data"),valCxt:new Be.Name("valCxt"),instancePath:new Be.Name("instancePath"),parentData:new Be.Name("parentData"),parentDataProperty:new Be.Name("parentDataProperty"),rootData:new Be.Name("rootData"),dynamicAnchors:new Be.Name("dynamicAnchors"),vErrors:new Be.Name("vErrors"),errors:new Be.Name("errors"),this:new Be.Name("this"),self:new Be.Name("self"),scope:new Be.Name("scope"),json:new Be.Name("json"),jsonPos:new Be.Name("jsonPos"),jsonLen:new Be.Name("jsonLen"),jsonPart:new Be.Name("jsonPart")};ul.default=wv});var Yi=A(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 ae=H(),Ao=Q(),Ye=$t();ze.keywordError={message:({keyword:r})=>(0,ae.str)`must pass "${r}" keyword validation`};ze.keyword$DataError={message:({keyword:r,schemaType:e})=>e?(0,ae.str)`"${r}" keyword must be ${e} ($data)`:(0,ae.str)`"${r}" keyword is invalid ($data)`};function vv(r,e=ze.keywordError,t,n){let{it:i}=r,{gen:s,compositeRule:o,allErrors:a}=i,c=Lp(r,e,t);(n!=null?n:o||a)?Cp(s,c):Np(i,(0,ae._)`[${c}]`)}ze.reportError=vv;function $v(r,e=ze.keywordError,t){let{it:n}=r,{gen:i,compositeRule:s,allErrors:o}=n,a=Lp(r,e,t);Cp(i,a),s||o||Np(n,Ye.default.vErrors)}ze.reportExtraError=$v;function Sv(r,e){r.assign(Ye.default.errors,e),r.if((0,ae._)`${Ye.default.vErrors} !== null`,()=>r.if(e,()=>r.assign((0,ae._)`${Ye.default.vErrors}.length`,e),()=>r.assign(Ye.default.vErrors,null)))}ze.resetErrorsCount=Sv;function Ev({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,Ye.default.errors,a=>{r.const(o,(0,ae._)`${Ye.default.vErrors}[${a}]`),r.if((0,ae._)`${o}.instancePath === undefined`,()=>r.assign((0,ae._)`${o}.instancePath`,(0,ae.strConcat)(Ye.default.instancePath,s.errorPath))),r.assign((0,ae._)`${o}.schemaPath`,(0,ae.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(r.assign((0,ae._)`${o}.schema`,t),r.assign((0,ae._)`${o}.data`,n))})}ze.extendErrors=Ev;function Cp(r,e){let t=r.const("err",e);r.if((0,ae._)`${Ye.default.vErrors} === null`,()=>r.assign(Ye.default.vErrors,(0,ae._)`[${t}]`),(0,ae._)`${Ye.default.vErrors}.push(${t})`),r.code((0,ae._)`${Ye.default.errors}++`)}function Np(r,e){let{gen:t,validateName:n,schemaEnv:i}=r;i.$async?t.throw((0,ae._)`new ${r.ValidationError}(${e})`):(t.assign((0,ae._)`${n}.errors`,e),t.return(!1))}var mn={keyword:new ae.Name("keyword"),schemaPath:new ae.Name("schemaPath"),params:new ae.Name("params"),propertyName:new ae.Name("propertyName"),message:new ae.Name("message"),schema:new ae.Name("schema"),parentSchema:new ae.Name("parentSchema")};function Lp(r,e,t){let{createErrors:n}=r.it;return n===!1?(0,ae._)`{}`:Av(r,e,t)}function Av(r,e,t={}){let{gen:n,it:i}=r,s=[xv(i,t),kv(r,t)];return Pv(r,e,s),n.object(...s)}function xv({errorPath:r},{instancePath:e}){let t=e?(0,ae.str)`${r}${(0,Ao.getErrorPath)(e,Ao.Type.Str)}`:r;return[Ye.default.instancePath,(0,ae.strConcat)(Ye.default.instancePath,t)]}function kv({keyword:r,it:{errSchemaPath:e}},{schemaPath:t,parentSchema:n}){let i=n?e:(0,ae.str)`${e}/${r}`;return t&&(i=(0,ae.str)`${i}${(0,Ao.getErrorPath)(t,Ao.Type.Str)}`),[mn.schemaPath,i]}function Pv(r,{params:e,message:t},n){let{keyword:i,data:s,schemaValue:o,it:a}=r,{opts:c,propertyName:l,topSchemaRef:d,schemaPath:u}=a;n.push([mn.keyword,i],[mn.params,typeof e=="function"?e(r):e||(0,ae._)`{}`]),c.messages&&n.push([mn.message,typeof t=="function"?t(r):t]),c.verbose&&n.push([mn.schema,o],[mn.parentSchema,(0,ae._)`${d}${u}`],[Ye.default.data,s]),l&&n.push([mn.propertyName,l])}});var Dp=A(Fn=>{"use strict";Object.defineProperty(Fn,"__esModule",{value:!0});Fn.boolOrEmptySchema=Fn.topBoolOrEmptySchema=void 0;var Iv=Yi(),Ov=H(),Rv=$t(),Tv={message:"boolean schema is false"};function Mv(r){let{gen:e,schema:t,validateName:n}=r;t===!1?jp(r,!1):typeof t=="object"&&t.$async===!0?e.return(Rv.default.data):(e.assign((0,Ov._)`${n}.errors`,null),e.return(!0))}Fn.topBoolOrEmptySchema=Mv;function Cv(r,e){let{gen:t,schema:n}=r;n===!1?(t.var(e,!1),jp(r)):t.var(e,!0)}Fn.boolOrEmptySchema=Cv;function jp(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,Iv.reportError)(i,Tv,void 0,e)}});var fl=A(Un=>{"use strict";Object.defineProperty(Un,"__esModule",{value:!0});Un.getRules=Un.isJSONType=void 0;var Nv=["string","number","integer","boolean","null","object","array"],Lv=new Set(Nv);function jv(r){return typeof r=="string"&&Lv.has(r)}Un.isJSONType=jv;function Dv(){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:{}}}Un.getRules=Dv});var pl=A(qr=>{"use strict";Object.defineProperty(qr,"__esModule",{value:!0});qr.shouldUseRule=qr.shouldUseGroup=qr.schemaHasRulesForType=void 0;function qv({schema:r,self:e},t){let n=e.RULES.types[t];return n&&n!==!0&&qp(r,n)}qr.schemaHasRulesForType=qv;function qp(r,e){return e.rules.some(t=>Fp(r,t))}qr.shouldUseGroup=qp;function Fp(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))}qr.shouldUseRule=Fp});var Xi=A(He=>{"use strict";Object.defineProperty(He,"__esModule",{value:!0});He.reportTypeError=He.checkDataTypes=He.checkDataType=He.coerceAndCheckDataType=He.getJSONTypes=He.getSchemaTypes=He.DataType=void 0;var Fv=fl(),Uv=pl(),Vv=Yi(),W=H(),Up=Q(),Vn;(function(r){r[r.Correct=0]="Correct",r[r.Wrong=1]="Wrong"})(Vn||(He.DataType=Vn={}));function Bv(r){let e=Vp(r.type);if(e.includes("null")){if(r.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&r.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');r.nullable===!0&&e.push("null")}return e}He.getSchemaTypes=Bv;function Vp(r){let e=Array.isArray(r)?r:r?[r]:[];if(e.every(Fv.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}He.getJSONTypes=Vp;function zv(r,e){let{gen:t,data:n,opts:i}=r,s=Hv(e,i.coerceTypes),o=e.length>0&&!(s.length===0&&e.length===1&&(0,Uv.schemaHasRulesForType)(r,e[0]));if(o){let a=ml(e,n,i.strictNumbers,Vn.Wrong);t.if(a,()=>{s.length?Kv(r,e,s):yl(r)})}return o}He.coerceAndCheckDataType=zv;var Bp=new Set(["string","number","integer","boolean","null"]);function Hv(r,e){return e?r.filter(t=>Bp.has(t)||e==="array"&&t==="array"):[]}function Kv(r,e,t){let{gen:n,data:i,opts:s}=r,o=n.let("dataType",(0,W._)`typeof ${i}`),a=n.let("coerced",(0,W._)`undefined`);s.coerceTypes==="array"&&n.if((0,W._)`${o} == 'object' && Array.isArray(${i}) && ${i}.length == 1`,()=>n.assign(i,(0,W._)`${i}[0]`).assign(o,(0,W._)`typeof ${i}`).if(ml(e,i,s.strictNumbers),()=>n.assign(a,i))),n.if((0,W._)`${a} !== undefined`);for(let l of t)(Bp.has(l)||l==="array"&&s.coerceTypes==="array")&&c(l);n.else(),yl(r),n.endIf(),n.if((0,W._)`${a} !== undefined`,()=>{n.assign(i,a),Wv(r,a)});function c(l){switch(l){case"string":n.elseIf((0,W._)`${o} == "number" || ${o} == "boolean"`).assign(a,(0,W._)`"" + ${i}`).elseIf((0,W._)`${i} === null`).assign(a,(0,W._)`""`);return;case"number":n.elseIf((0,W._)`${o} == "boolean" || ${i} === null + || (${o} == "string" && ${i} && ${i} == +${i})`).assign(a,(0,W._)`+${i}`);return;case"integer":n.elseIf((0,W._)`${o} === "boolean" || ${i} === null + || (${o} === "string" && ${i} && ${i} == +${i} && !(${i} % 1))`).assign(a,(0,W._)`+${i}`);return;case"boolean":n.elseIf((0,W._)`${i} === "false" || ${i} === 0 || ${i} === null`).assign(a,!1).elseIf((0,W._)`${i} === "true" || ${i} === 1`).assign(a,!0);return;case"null":n.elseIf((0,W._)`${i} === "" || ${i} === 0 || ${i} === false`),n.assign(a,null);return;case"array":n.elseIf((0,W._)`${o} === "string" || ${o} === "number" + || ${o} === "boolean" || ${i} === null`).assign(a,(0,W._)`[${i}]`)}}}function Wv({gen:r,parentData:e,parentDataProperty:t},n){r.if((0,W._)`${e} !== undefined`,()=>r.assign((0,W._)`${e}[${t}]`,n))}function hl(r,e,t,n=Vn.Correct){let i=n===Vn.Correct?W.operators.EQ:W.operators.NEQ,s;switch(r){case"null":return(0,W._)`${e} ${i} null`;case"array":s=(0,W._)`Array.isArray(${e})`;break;case"object":s=(0,W._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=o((0,W._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=o();break;default:return(0,W._)`typeof ${e} ${i} ${r}`}return n===Vn.Correct?s:(0,W.not)(s);function o(a=W.nil){return(0,W.and)((0,W._)`typeof ${e} == "number"`,a,t?(0,W._)`isFinite(${e})`:W.nil)}}He.checkDataType=hl;function ml(r,e,t,n){if(r.length===1)return hl(r[0],e,t,n);let i,s=(0,Up.toHash)(r);if(s.array&&s.object){let o=(0,W._)`typeof ${e} != "object"`;i=s.null?o:(0,W._)`!${e} || ${o}`,delete s.null,delete s.array,delete s.object}else i=W.nil;s.number&&delete s.integer;for(let o in s)i=(0,W.and)(i,hl(o,e,t,n));return i}He.checkDataTypes=ml;var Gv={message:({schema:r})=>`must be ${r}`,params:({schema:r,schemaValue:e})=>typeof r=="string"?(0,W._)`{type: ${r}}`:(0,W._)`{type: ${e}}`};function yl(r){let e=Jv(r);(0,Vv.reportError)(e,Gv)}He.reportTypeError=yl;function Jv(r){let{gen:e,data:t,schema:n}=r,i=(0,Up.schemaRefOrVal)(r,n,"type");return{gen:e,keyword:"type",data:t,schema:n.type,schemaCode:i,schemaValue:i,parentSchema:n,params:{},it:r}}});var Hp=A(xo=>{"use strict";Object.defineProperty(xo,"__esModule",{value:!0});xo.assignDefaults=void 0;var Bn=H(),Yv=Q();function Xv(r,e){let{properties:t,items:n}=r.schema;if(e==="object"&&t)for(let i in t)zp(r,i,t[i].default);else e==="array"&&Array.isArray(n)&&n.forEach((i,s)=>zp(r,s,i.default))}xo.assignDefaults=Xv;function zp(r,e,t){let{gen:n,compositeRule:i,data:s,opts:o}=r;if(t===void 0)return;let a=(0,Bn._)`${s}${(0,Bn.getProperty)(e)}`;if(i){(0,Yv.checkStrictMode)(r,`default is ignored for: ${a}`);return}let c=(0,Bn._)`${a} === undefined`;o.useDefaults==="empty"&&(c=(0,Bn._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,Bn._)`${a} = ${(0,Bn.stringify)(t)}`)}});var St=A(ue=>{"use strict";Object.defineProperty(ue,"__esModule",{value:!0});ue.validateUnion=ue.validateArray=ue.usePattern=ue.callValidateCode=ue.schemaProperties=ue.allSchemaProperties=ue.noPropertyInData=ue.propertyInData=ue.isOwnProperty=ue.hasPropFunc=ue.reportMissingProp=ue.checkMissingProp=ue.checkReportMissingProp=void 0;var ge=H(),gl=Q(),Fr=$t(),Qv=Q();function Zv(r,e){let{gen:t,data:n,it:i}=r;t.if(bl(t,n,e,i.opts.ownProperties),()=>{r.setParams({missingProperty:(0,ge._)`${e}`},!0),r.error()})}ue.checkReportMissingProp=Zv;function e$({gen:r,data:e,it:{opts:t}},n,i){return(0,ge.or)(...n.map(s=>(0,ge.and)(bl(r,e,s,t.ownProperties),(0,ge._)`${i} = ${s}`)))}ue.checkMissingProp=e$;function t$(r,e){r.setParams({missingProperty:e},!0),r.error()}ue.reportMissingProp=t$;function Kp(r){return r.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,ge._)`Object.prototype.hasOwnProperty`})}ue.hasPropFunc=Kp;function _l(r,e,t){return(0,ge._)`${Kp(r)}.call(${e}, ${t})`}ue.isOwnProperty=_l;function r$(r,e,t,n){let i=(0,ge._)`${e}${(0,ge.getProperty)(t)} !== undefined`;return n?(0,ge._)`${i} && ${_l(r,e,t)}`:i}ue.propertyInData=r$;function bl(r,e,t,n){let i=(0,ge._)`${e}${(0,ge.getProperty)(t)} === undefined`;return n?(0,ge.or)(i,(0,ge.not)(_l(r,e,t))):i}ue.noPropertyInData=bl;function Wp(r){return r?Object.keys(r).filter(e=>e!=="__proto__"):[]}ue.allSchemaProperties=Wp;function n$(r,e){return Wp(e).filter(t=>!(0,gl.alwaysValidSchema)(r,e[t]))}ue.schemaProperties=n$;function i$({schemaCode:r,data:e,it:{gen:t,topSchemaRef:n,schemaPath:i,errorPath:s},it:o},a,c,l){let d=l?(0,ge._)`${r}, ${e}, ${n}${i}`:e,u=[[Fr.default.instancePath,(0,ge.strConcat)(Fr.default.instancePath,s)],[Fr.default.parentData,o.parentData],[Fr.default.parentDataProperty,o.parentDataProperty],[Fr.default.rootData,Fr.default.rootData]];o.opts.dynamicRef&&u.push([Fr.default.dynamicAnchors,Fr.default.dynamicAnchors]);let f=(0,ge._)`${d}, ${t.object(...u)}`;return c!==ge.nil?(0,ge._)`${a}.call(${c}, ${f})`:(0,ge._)`${a}(${f})`}ue.callValidateCode=i$;var s$=(0,ge._)`new RegExp`;function o$({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,ge._)`${i.code==="new RegExp"?s$:(0,Qv.useFunc)(r,i)}(${t}, ${n})`})}ue.usePattern=o$;function a$(r){let{gen:e,data:t,keyword:n,it:i}=r,s=e.name("valid");if(i.allErrors){let a=e.let("valid",!0);return o(()=>e.assign(a,!1)),a}return e.var(s,!0),o(()=>e.break()),s;function o(a){let c=e.const("len",(0,ge._)`${t}.length`);e.forRange("i",0,c,l=>{r.subschema({keyword:n,dataProp:l,dataPropType:gl.Type.Num},s),e.if((0,ge.not)(s),a)})}}ue.validateArray=a$;function c$(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,gl.alwaysValidSchema)(i,c))&&!i.opts.unevaluated)return;let o=e.let("valid",!1),a=e.name("_valid");e.block(()=>t.forEach((c,l)=>{let d=r.subschema({keyword:n,schemaProp:l,compositeRule:!0},a);e.assign(o,(0,ge._)`${o} || ${a}`),r.mergeValidEvaluated(d,a)||e.if((0,ge.not)(o))})),r.result(o,()=>r.reset(),()=>r.error(!0))}ue.validateUnion=c$});var Yp=A(Zt=>{"use strict";Object.defineProperty(Zt,"__esModule",{value:!0});Zt.validateKeywordUsage=Zt.validSchemaType=Zt.funcKeywordCode=Zt.macroKeywordCode=void 0;var Xe=H(),yn=$t(),l$=St(),d$=Yi();function u$(r,e){let{gen:t,keyword:n,schema:i,parentSchema:s,it:o}=r,a=e.macro.call(o.self,i,s,o),c=Jp(t,n,a);o.opts.validateSchema!==!1&&o.self.validateSchema(a,!0);let l=t.name("valid");r.subschema({schema:a,schemaPath:Xe.nil,errSchemaPath:`${o.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},l),r.pass(l,()=>r.error(!0))}Zt.macroKeywordCode=u$;function f$(r,e){var t;let{gen:n,keyword:i,schema:s,parentSchema:o,$data:a,it:c}=r;h$(c,e);let l=!a&&e.compile?e.compile.call(c.self,s,o,c):e.validate,d=Jp(n,i,l),u=n.let("valid");r.block$data(u,f),r.ok((t=e.valid)!==null&&t!==void 0?t:u);function f(){if(e.errors===!1)h(),e.modifying&&Gp(r),m(()=>r.error());else{let g=e.async?p():y();e.modifying&&Gp(r),m(()=>p$(r,g))}}function p(){let g=n.let("ruleErrs",null);return n.try(()=>h((0,Xe._)`await `),_=>n.assign(u,!1).if((0,Xe._)`${_} instanceof ${c.ValidationError}`,()=>n.assign(g,(0,Xe._)`${_}.errors`),()=>n.throw(_))),g}function y(){let g=(0,Xe._)`${d}.errors`;return n.assign(g,null),h(Xe.nil),g}function h(g=e.async?(0,Xe._)`await `:Xe.nil){let _=c.opts.passContext?yn.default.this:yn.default.self,w=!("compile"in e&&!a||e.schema===!1);n.assign(u,(0,Xe._)`${g}${(0,l$.callValidateCode)(r,d,_,w)}`,e.modifying)}function m(g){var _;n.if((0,Xe.not)((_=e.valid)!==null&&_!==void 0?_:u),g)}}Zt.funcKeywordCode=f$;function Gp(r){let{gen:e,data:t,it:n}=r;e.if(n.parentData,()=>e.assign(t,(0,Xe._)`${n.parentData}[${n.parentDataProperty}]`))}function p$(r,e){let{gen:t}=r;t.if((0,Xe._)`Array.isArray(${e})`,()=>{t.assign(yn.default.vErrors,(0,Xe._)`${yn.default.vErrors} === null ? ${e} : ${yn.default.vErrors}.concat(${e})`).assign(yn.default.errors,(0,Xe._)`${yn.default.vErrors}.length`),(0,d$.extendErrors)(r)},()=>r.error())}function h$({schemaEnv:r},e){if(e.async&&!r.$async)throw new Error("async keyword in sync schema")}function Jp(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,Xe.stringify)(t)})}function m$(r,e,t=!1){return!e.length||e.some(n=>n==="array"?Array.isArray(r):n==="object"?r&&typeof r=="object"&&!Array.isArray(r):typeof r==n||t&&typeof r=="undefined")}Zt.validSchemaType=m$;function y$({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!=null&&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)}}Zt.validateKeywordUsage=y$});var Qp=A(Ur=>{"use strict";Object.defineProperty(Ur,"__esModule",{value:!0});Ur.extendSubschemaMode=Ur.extendSubschemaData=Ur.getSubschema=void 0;var er=H(),Xp=Q();function g$(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,er._)`${r.schemaPath}${(0,er.getProperty)(e)}`,errSchemaPath:`${r.errSchemaPath}/${e}`}:{schema:a[t],schemaPath:(0,er._)`${r.schemaPath}${(0,er.getProperty)(e)}${(0,er.getProperty)(t)}`,errSchemaPath:`${r.errSchemaPath}/${e}/${(0,Xp.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')}Ur.getSubschema=g$;function _$(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:d,opts:u}=e,f=a.let("data",(0,er._)`${e.data}${(0,er.getProperty)(t)}`,!0);c(f),r.errorPath=(0,er.str)`${l}${(0,Xp.getErrorPath)(t,n,u.jsPropertySyntax)}`,r.parentDataProperty=(0,er._)`${t}`,r.dataPathArr=[...d,r.parentDataProperty]}if(i!==void 0){let l=i instanceof er.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]}}Ur.extendSubschemaData=_$;function b$(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}Ur.extendSubschemaMode=b$});var wl=A((XC,Zp)=>{"use strict";Zp.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 th=A((QC,eh)=>{"use strict";var Vr=eh.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(){};ko(e,n,i,r,"",r)};Vr.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Vr.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Vr.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Vr.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 ko(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 d in n){var u=n[d];if(Array.isArray(u)){if(d in Vr.arrayKeywords)for(var f=0;f{"use strict";Object.defineProperty(at,"__esModule",{value:!0});at.getSchemaRefs=at.resolveUrl=at.normalizeId=at._getFullPath=at.getFullPath=at.inlineRef=void 0;var v$=Q(),$$=wl(),S$=th(),E$=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function A$(r,e=!0){return typeof r=="boolean"?!0:e===!0?!vl(r):e?rh(r)<=e:!1}at.inlineRef=A$;var x$=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function vl(r){for(let e in r){if(x$.has(e))return!0;let t=r[e];if(Array.isArray(t)&&t.some(vl)||typeof t=="object"&&vl(t))return!0}return!1}function rh(r){let e=0;for(let t in r){if(t==="$ref")return 1/0;if(e++,!E$.has(t)&&(typeof r[t]=="object"&&(0,v$.eachItem)(r[t],n=>e+=rh(n)),e===1/0))return 1/0}return e}function nh(r,e="",t){t!==!1&&(e=zn(e));let n=r.parse(e);return ih(r,n)}at.getFullPath=nh;function ih(r,e){return r.serialize(e).split("#")[0]+"#"}at._getFullPath=ih;var k$=/#\/?$/;function zn(r){return r?r.replace(k$,""):""}at.normalizeId=zn;function P$(r,e,t){return t=zn(t),r.resolve(e,t)}at.resolveUrl=P$;var I$=/^[a-z_][-a-z0-9._]*$/i;function O$(r,e){if(typeof r=="boolean")return{};let{schemaId:t,uriResolver:n}=this.opts,i=zn(r[t]||e),s={"":i},o=nh(n,i,!1),a={},c=new Set;return S$(r,{allKeys:!0},(u,f,p,y)=>{if(y===void 0)return;let h=o+f,m=s[y];typeof u[t]=="string"&&(m=g.call(this,u[t])),_.call(this,u.$anchor),_.call(this,u.$dynamicAnchor),s[f]=m;function g(w){let k=this.opts.uriResolver.resolve;if(w=zn(m?k(m,w):w),c.has(w))throw d(w);c.add(w);let v=this.refs[w];return typeof v=="string"&&(v=this.refs[v]),typeof v=="object"?l(u,v.schema,w):w!==zn(h)&&(w[0]==="#"?(l(u,a[w],w),a[w]=u):this.refs[w]=h),w}function _(w){if(typeof w=="string"){if(!I$.test(w))throw new Error(`invalid anchor "${w}"`);g.call(this,`#${w}`)}}}),a;function l(u,f,p){if(f!==void 0&&!$$(u,f))throw d(p)}function d(u){return new Error(`reference "${u}" resolves to more than one schema`)}}at.getSchemaRefs=O$});var Hn=A(Br=>{"use strict";Object.defineProperty(Br,"__esModule",{value:!0});Br.getData=Br.KeywordCxt=Br.validateFunctionCode=void 0;var lh=Dp(),sh=Xi(),Sl=pl(),Po=Xi(),R$=Hp(),es=Yp(),$l=Qp(),F=H(),z=$t(),T$=Qi(),_r=Q(),Zi=Yi();function M$(r){if(fh(r)&&(ph(r),uh(r))){L$(r);return}dh(r,()=>(0,lh.topBoolOrEmptySchema)(r))}Br.validateFunctionCode=M$;function dh({gen:r,validateName:e,schema:t,schemaEnv:n,opts:i},s){i.code.es5?r.func(e,(0,F._)`${z.default.data}, ${z.default.valCxt}`,n.$async,()=>{r.code((0,F._)`"use strict"; ${oh(t,i)}`),N$(r,i),r.code(s)}):r.func(e,(0,F._)`${z.default.data}, ${C$(i)}`,n.$async,()=>r.code(oh(t,i)).code(s))}function C$(r){return(0,F._)`{${z.default.instancePath}="", ${z.default.parentData}, ${z.default.parentDataProperty}, ${z.default.rootData}=${z.default.data}${r.dynamicRef?(0,F._)`, ${z.default.dynamicAnchors}={}`:F.nil}}={}`}function N$(r,e){r.if(z.default.valCxt,()=>{r.var(z.default.instancePath,(0,F._)`${z.default.valCxt}.${z.default.instancePath}`),r.var(z.default.parentData,(0,F._)`${z.default.valCxt}.${z.default.parentData}`),r.var(z.default.parentDataProperty,(0,F._)`${z.default.valCxt}.${z.default.parentDataProperty}`),r.var(z.default.rootData,(0,F._)`${z.default.valCxt}.${z.default.rootData}`),e.dynamicRef&&r.var(z.default.dynamicAnchors,(0,F._)`${z.default.valCxt}.${z.default.dynamicAnchors}`)},()=>{r.var(z.default.instancePath,(0,F._)`""`),r.var(z.default.parentData,(0,F._)`undefined`),r.var(z.default.parentDataProperty,(0,F._)`undefined`),r.var(z.default.rootData,z.default.data),e.dynamicRef&&r.var(z.default.dynamicAnchors,(0,F._)`{}`)})}function L$(r){let{schema:e,opts:t,gen:n}=r;dh(r,()=>{t.$comment&&e.$comment&&mh(r),U$(r),n.let(z.default.vErrors,null),n.let(z.default.errors,0),t.unevaluated&&j$(r),hh(r),z$(r)})}function j$(r){let{gen:e,validateName:t}=r;r.evaluated=e.const("evaluated",(0,F._)`${t}.evaluated`),e.if((0,F._)`${r.evaluated}.dynamicProps`,()=>e.assign((0,F._)`${r.evaluated}.props`,(0,F._)`undefined`)),e.if((0,F._)`${r.evaluated}.dynamicItems`,()=>e.assign((0,F._)`${r.evaluated}.items`,(0,F._)`undefined`))}function oh(r,e){let t=typeof r=="object"&&r[e.schemaId];return t&&(e.code.source||e.code.process)?(0,F._)`/*# sourceURL=${t} */`:F.nil}function D$(r,e){if(fh(r)&&(ph(r),uh(r))){q$(r,e);return}(0,lh.boolOrEmptySchema)(r,e)}function uh({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 fh(r){return typeof r.schema!="boolean"}function q$(r,e){let{schema:t,gen:n,opts:i}=r;i.$comment&&t.$comment&&mh(r),V$(r),B$(r);let s=n.const("_errs",z.default.errors);hh(r,s),n.var(e,(0,F._)`${s} === ${z.default.errors}`)}function ph(r){(0,_r.checkUnknownRules)(r),F$(r)}function hh(r,e){if(r.opts.jtd)return ah(r,[],!1,e);let t=(0,sh.getSchemaTypes)(r.schema),n=(0,sh.coerceAndCheckDataType)(r,t);ah(r,t,!n,e)}function F$(r){let{schema:e,errSchemaPath:t,opts:n,self:i}=r;e.$ref&&n.ignoreKeywordsWithRef&&(0,_r.schemaHasRulesButRef)(e,i.RULES)&&i.logger.warn(`$ref: keywords ignored in schema at path "${t}"`)}function U$(r){let{schema:e,opts:t}=r;e.default!==void 0&&t.useDefaults&&t.strictSchema&&(0,_r.checkStrictMode)(r,"default is ignored in the schema root")}function V$(r){let e=r.schema[r.opts.schemaId];e&&(r.baseId=(0,T$.resolveUrl)(r.opts.uriResolver,r.baseId,e))}function B$(r){if(r.schema.$async&&!r.schemaEnv.$async)throw new Error("async schema in sync schema")}function mh({gen:r,schemaEnv:e,schema:t,errSchemaPath:n,opts:i}){let s=t.$comment;if(i.$comment===!0)r.code((0,F._)`${z.default.self}.logger.log(${s})`);else if(typeof i.$comment=="function"){let o=(0,F.str)`${n}/$comment`,a=r.scopeValue("root",{ref:e.root});r.code((0,F._)`${z.default.self}.opts.$comment(${s}, ${o}, ${a}.schema)`)}}function z$(r){let{gen:e,schemaEnv:t,validateName:n,ValidationError:i,opts:s}=r;t.$async?e.if((0,F._)`${z.default.errors} === 0`,()=>e.return(z.default.data),()=>e.throw((0,F._)`new ${i}(${z.default.vErrors})`)):(e.assign((0,F._)`${n}.errors`,z.default.vErrors),s.unevaluated&&H$(r),e.return((0,F._)`${z.default.errors} === 0`))}function H$({gen:r,evaluated:e,props:t,items:n}){t instanceof F.Name&&r.assign((0,F._)`${e}.props`,t),n instanceof F.Name&&r.assign((0,F._)`${e}.items`,n)}function ah(r,e,t,n){let{gen:i,schema:s,data:o,allErrors:a,opts:c,self:l}=r,{RULES:d}=l;if(s.$ref&&(c.ignoreKeywordsWithRef||!(0,_r.schemaHasRulesButRef)(s,d))){i.block(()=>gh(r,"$ref",d.all.$ref.definition));return}c.jtd||K$(r,e),i.block(()=>{for(let f of d.rules)u(f);u(d.post)});function u(f){(0,Sl.shouldUseGroup)(s,f)&&(f.type?(i.if((0,Po.checkDataType)(f.type,o,c.strictNumbers)),ch(r,f),e.length===1&&e[0]===f.type&&t&&(i.else(),(0,Po.reportTypeError)(r)),i.endIf()):ch(r,f),a||i.if((0,F._)`${z.default.errors} === ${n||0}`))}}function ch(r,e){let{gen:t,schema:n,opts:{useDefaults:i}}=r;i&&(0,R$.assignDefaults)(r,e.type),t.block(()=>{for(let s of e.rules)(0,Sl.shouldUseRule)(n,s)&&gh(r,s.keyword,s.definition,e.type)})}function K$(r,e){r.schemaEnv.meta||!r.opts.strictTypes||(W$(r,e),r.opts.allowUnionTypes||G$(r,e),J$(r,r.dataTypes))}function W$(r,e){if(e.length){if(!r.dataTypes.length){r.dataTypes=e;return}e.forEach(t=>{yh(r.dataTypes,t)||El(r,`type "${t}" not allowed by context "${r.dataTypes.join(",")}"`)}),X$(r,e)}}function G$(r,e){e.length>1&&!(e.length===2&&e.includes("null"))&&El(r,"use allowUnionTypes to allow union type keyword")}function J$(r,e){let t=r.self.RULES.all;for(let n in t){let i=t[n];if(typeof i=="object"&&(0,Sl.shouldUseRule)(r.schema,i)){let{type:s}=i.definition;s.length&&!s.some(o=>Y$(e,o))&&El(r,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function Y$(r,e){return r.includes(e)||e==="number"&&r.includes("integer")}function yh(r,e){return r.includes(e)||e==="integer"&&r.includes("number")}function X$(r,e){let t=[];for(let n of r.dataTypes)yh(e,n)?t.push(n):e.includes("integer")&&n==="number"&&t.push("integer");r.dataTypes=t}function El(r,e){let t=r.schemaEnv.baseId+r.errSchemaPath;e+=` at "${t}" (strictTypes)`,(0,_r.checkStrictMode)(r,e,r.opts.strictTypes)}var Io=class{constructor(e,t,n){if((0,es.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,_r.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",_h(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,es.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",z.default.errors))}result(e,t,n){this.failResult((0,F.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,F.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,F._)`${t} !== undefined && (${(0,F.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?Zi.reportExtraError:Zi.reportError)(this,this.def.error,t)}$dataError(){(0,Zi.reportError)(this,this.def.$dataError||Zi.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,Zi.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=F.nil){this.gen.block(()=>{this.check$data(e,n),t()})}check$data(e=F.nil,t=F.nil){if(!this.$data)return;let{gen:n,schemaCode:i,schemaType:s,def:o}=this;n.if((0,F.or)((0,F._)`${i} === undefined`,t)),e!==F.nil&&n.assign(e,!0),(s.length||o.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==F.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:t,schemaType:n,def:i,it:s}=this;return(0,F.or)(o(),a());function o(){if(n.length){if(!(t instanceof F.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,F._)`${(0,Po.checkDataTypes)(c,t,s.opts.strictNumbers,Po.DataType.Wrong)}`}return F.nil}function a(){if(i.validateSchema){let c=e.scopeValue("validate$data",{ref:i.validateSchema});return(0,F._)`!${c}(${t})`}return F.nil}}subschema(e,t){let n=(0,$l.getSubschema)(this.it,e);(0,$l.extendSubschemaData)(n,this.it,e),(0,$l.extendSubschemaMode)(n,e);let i={...this.it,...n,items:void 0,props:void 0};return D$(i,t),i}mergeEvaluated(e,t){let{it:n,gen:i}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=_r.mergeEvaluated.props(i,e.props,n.props,t)),n.items!==!0&&e.items!==void 0&&(n.items=_r.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,F.Name)),!0}};Br.KeywordCxt=Io;function gh(r,e,t,n){let i=new Io(r,t,e);"code"in t?t.code(i,n):i.$data&&t.validate?(0,es.funcKeywordCode)(i,t):"macro"in t?(0,es.macroKeywordCode)(i,t):(t.compile||t.validate)&&(0,es.funcKeywordCode)(i,t)}var Q$=/^\/(?:[^~]|~0|~1)*$/,Z$=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function _h(r,{dataLevel:e,dataNames:t,dataPathArr:n}){let i,s;if(r==="")return z.default.rootData;if(r[0]==="/"){if(!Q$.test(r))throw new Error(`Invalid JSON-pointer: ${r}`);i=r,s=z.default.rootData}else{let l=Z$.exec(r);if(!l)throw new Error(`Invalid JSON-pointer: ${r}`);let d=+l[1];if(i=l[2],i==="#"){if(d>=e)throw new Error(c("property/index",d));return n[e-d]}if(d>e)throw new Error(c("data",d));if(s=t[e-d],!i)return s}let o=s,a=i.split("/");for(let l of a)l&&(s=(0,F._)`${s}${(0,F.getProperty)((0,_r.unescapeJsonPointer)(l))}`,o=(0,F._)`${o} && ${s}`);return o;function c(l,d){return`Cannot access ${l} ${d} levels up, current level is ${e}`}}Br.getData=_h});var ts=A(xl=>{"use strict";Object.defineProperty(xl,"__esModule",{value:!0});var Al=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};xl.default=Al});var Kn=A(Il=>{"use strict";Object.defineProperty(Il,"__esModule",{value:!0});var kl=Qi(),Pl=class extends Error{constructor(e,t,n,i){super(i||`can't resolve reference ${n} from id ${t}`),this.missingRef=(0,kl.resolveUrl)(e,t,n),this.missingSchema=(0,kl.normalizeId)((0,kl.getFullPath)(e,this.missingRef))}};Il.default=Pl});var rs=A(Et=>{"use strict";Object.defineProperty(Et,"__esModule",{value:!0});Et.resolveSchema=Et.getCompilingSchema=Et.resolveRef=Et.compileSchema=Et.SchemaEnv=void 0;var Mt=H(),eS=ts(),gn=$t(),Ct=Qi(),bh=Q(),tS=Hn(),Wn=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,Ct.normalizeId)(n==null?void 0:n[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n==null?void 0:n.$async,this.refs={}}};Et.SchemaEnv=Wn;function Rl(r){let e=wh.call(this,r);if(e)return e;let t=(0,Ct.getFullPath)(this.opts.uriResolver,r.root.baseId),{es5:n,lines:i}=this.opts.code,{ownProperties:s}=this.opts,o=new Mt.CodeGen(this.scope,{es5:n,lines:i,ownProperties:s}),a;r.$async&&(a=o.scopeValue("Error",{ref:eS.default,code:(0,Mt._)`require("ajv/dist/runtime/validation_error").default`}));let c=o.scopeName("validate");r.validateName=c;let l={gen:o,allErrors:this.opts.allErrors,data:gn.default.data,parentData:gn.default.parentData,parentDataProperty:gn.default.parentDataProperty,dataNames:[gn.default.data],dataPathArr:[Mt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:o.scopeValue("schema",this.opts.code.source===!0?{ref:r.schema,code:(0,Mt.stringify)(r.schema)}:{ref:r.schema}),validateName:c,ValidationError:a,schema:r.schema,schemaEnv:r,rootId:t,baseId:r.baseId||t,schemaPath:Mt.nil,errSchemaPath:r.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Mt._)`""`,opts:this.opts,self:this},d;try{this._compilations.add(r),(0,tS.validateFunctionCode)(l),o.optimize(this.opts.code.optimize);let u=o.toString();d=`${o.scopeRefs(gn.default.scope)}return ${u}`,this.opts.code.process&&(d=this.opts.code.process(d,r));let p=new Function(`${gn.default.self}`,`${gn.default.scope}`,d)(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:u,scopeValues:o._values}),this.opts.unevaluated){let{props:y,items:h}=l;p.evaluated={props:y instanceof Mt.Name?void 0:y,items:h instanceof Mt.Name?void 0:h,dynamicProps:y instanceof Mt.Name,dynamicItems:h instanceof Mt.Name},p.source&&(p.source.evaluated=(0,Mt.stringify)(p.evaluated))}return r.validate=p,r}catch(u){throw delete r.validate,delete r.validateName,d&&this.logger.error("Error compiling schema, function code:",d),u}finally{this._compilations.delete(r)}}Et.compileSchema=Rl;function rS(r,e,t){var n;t=(0,Ct.resolveUrl)(this.opts.uriResolver,e,t);let i=r.refs[t];if(i)return i;let s=sS.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 Wn({schema:o,schemaId:a,root:r,baseId:e}))}if(s!==void 0)return r.refs[t]=nS.call(this,s)}Et.resolveRef=rS;function nS(r){return(0,Ct.inlineRef)(r.schema,this.opts.inlineRefs)?r.schema:r.validate?r:Rl.call(this,r)}function wh(r){for(let e of this._compilations)if(iS(e,r))return e}Et.getCompilingSchema=wh;function iS(r,e){return r.schema===e.schema&&r.root===e.root&&r.baseId===e.baseId}function sS(r,e){let t;for(;typeof(t=this.refs[e])=="string";)e=t;return t||this.schemas[e]||Oo.call(this,r,e)}function Oo(r,e){let t=this.opts.uriResolver.parse(e),n=(0,Ct._getFullPath)(this.opts.uriResolver,t),i=(0,Ct.getFullPath)(this.opts.uriResolver,r.baseId,void 0);if(Object.keys(r.schema).length>0&&n===i)return Ol.call(this,t,r);let s=(0,Ct.normalizeId)(n),o=this.refs[s]||this.schemas[s];if(typeof o=="string"){let a=Oo.call(this,r,o);return typeof(a==null?void 0:a.schema)!="object"?void 0:Ol.call(this,t,a)}if(typeof(o==null?void 0:o.schema)=="object"){if(o.validate||Rl.call(this,o),s===(0,Ct.normalizeId)(e)){let{schema:a}=o,{schemaId:c}=this.opts,l=a[c];return l&&(i=(0,Ct.resolveUrl)(this.opts.uriResolver,i,l)),new Wn({schema:a,schemaId:c,root:r,baseId:i})}return Ol.call(this,t,o)}}Et.resolveSchema=Oo;var oS=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Ol(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,bh.unescapeFragment)(a)];if(c===void 0)return;t=c;let l=typeof t=="object"&&t[this.opts.schemaId];!oS.has(a)&&l&&(e=(0,Ct.resolveUrl)(this.opts.uriResolver,e,l))}let s;if(typeof t!="boolean"&&t.$ref&&!(0,bh.schemaHasRulesButRef)(t,this.RULES)){let a=(0,Ct.resolveUrl)(this.opts.uriResolver,e,t.$ref);s=Oo.call(this,n,a)}let{schemaId:o}=this.opts;if(s=s||new Wn({schema:t,schemaId:o,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var vh=A((iN,aS)=>{aS.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 Cl=A((sN,kh)=>{"use strict";var cS=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Sh=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),Tl=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),Eh=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),lS=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function Ml(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 dS=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function $h(r){return r.length=0,!0}function uS(r,e,t){if(r.length){let n=Ml(r);if(n!=="")e.push(n);else return t.error=!0,!1;r.length=0}return!0}function fS(r){let e=0,t={error:!1,address:"",zone:""},n=[],i=[],s=!1,o=!1,a=uS;for(let c=0;c7){t.error=!0;break}c>0&&r[c-1]===":"&&(s=!0),n.push(":");continue}else if(l==="%"){if(!a(i,n,t))break;a=$h}else{i.push(l);continue}}return i.length&&(a===$h?t.zone=i.join(""):o?n.push(i.join("")):n.push(Ml(i))),t.address=n.join(""),t}function Ah(r){if(pS(r,":")<2)return{host:r,isIPV6:!1};let e=fS(r);if(e.error)return{host:r,isIPV6:!1};{let t=e.address,n=e.address;return e.zone&&(t+="%"+e.zone,n+="%25"+e.zone),{host:t,isIPV6:!0,escapedHost:n}}}function pS(r,e){let t=0;for(let n=0;nmS[n])}function _S(r,e=!1){if(r.indexOf("%")===-1)return r;let t="";for(let n=0;n{"use strict";var{isUUID:$S}=Cl(),SS=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,ES=["http","https","ws","wss","urn","urn:uuid"];function AS(r){return ES.indexOf(r)!==-1}function Nl(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 Ph(r){return r.host||(r.error=r.error||"HTTP URIs must have a host."),r}function Ih(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 xS(r){return r.secure=Nl(r),r.resourceName=(r.path||"/")+(r.query?"?"+r.query:""),r.path=void 0,r.query=void 0,r}function kS(r){if((r.port===(Nl(r)?443:80)||r.port==="")&&(r.port=void 0),typeof r.secure=="boolean"&&(r.scheme=r.secure?"wss":"ws",r.secure=void 0),r.resourceName){let[e,t]=r.resourceName.split("?");r.path=e&&e!=="/"?e:void 0,r.query=t,r.resourceName=void 0}return r.fragment=void 0,r}function PS(r,e){if(!r.path)return r.error="URN can not be parsed",r;let t=r.path.match(SS);if(t){let n=e.scheme||r.scheme||"urn";r.nid=t[1].toLowerCase(),r.nss=t[2];let i=`${n}:${e.nid||r.nid}`,s=Ll(i);r.path=void 0,s&&(r=s.parse(r,e))}else r.error=r.error||"URN can not be parsed.";return r}function IS(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=Ll(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 OS(r,e){let t=r;return t.uuid=t.nss,t.nss=void 0,!e.tolerant&&(!t.uuid||!$S(t.uuid))&&(t.error=t.error||"UUID is not valid."),t}function RS(r){let e=r;return e.nss=(r.uuid||"").toLowerCase(),e}var Oh={scheme:"http",domainHost:!0,parse:Ph,serialize:Ih},TS={scheme:"https",domainHost:Oh.domainHost,parse:Ph,serialize:Ih},Ro={scheme:"ws",domainHost:!0,parse:xS,serialize:kS},MS={scheme:"wss",domainHost:Ro.domainHost,parse:Ro.parse,serialize:Ro.serialize},CS={scheme:"urn",parse:PS,serialize:IS,skipNormalize:!0},NS={scheme:"urn:uuid",parse:OS,serialize:RS,skipNormalize:!0},To={http:Oh,https:TS,ws:Ro,wss:MS,urn:CS,"urn:uuid":NS};Object.setPrototypeOf(To,null);function Ll(r){return r&&(To[r]||To[r.toLowerCase()])||void 0}Rh.exports={wsIsSecure:Nl,SCHEMES:To,isValidSchemeName:AS,getSchemeHandler:Ll}});var jh=A((aN,No)=>{"use strict";var{normalizeIPv6:LS,removeDotSegments:ns,recomposeAuthority:jS,normalizePercentEncoding:DS,normalizePathEncoding:qS,escapePreservingEscapes:FS,reescapeHostDelimiters:US,isIPv4:VS,nonSimpleDomain:BS}=Cl(),{SCHEMES:zS,getSchemeHandler:Ch}=Th();function HS(r,e){return typeof r=="string"?r=QS(r,e):typeof r=="object"&&(r=Co(_n(r,e),e)),r}function KS(r,e,t){let n=t?Object.assign({scheme:"null"},t):{scheme:"null"},{parsed:i,malformedAuthorityOrPort:s}=Mo(r,n),{parsed:o,malformedAuthorityOrPort:a}=Mo(e,n);if(s||a)throw new Error(i.error||o.error||"URI is malformed.");let c=Nh(i,o,n,!0);return n.skipEscape=!0,_n(c,n)}function Nh(r,e,t,n){let i={};return n||(r=Co(_n(r,t),t),e=Co(_n(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=ns(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=ns(e.path||""),i.query=e.query):(e.path?(e.path[0]==="/"?i.path=ns(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=ns(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 WS(r,e,t){let n=Mh(r,t),i=Mh(e,t);return n!==void 0&&i!==void 0&&n.toLowerCase()===i.toLowerCase()}function _n(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=[],s=Ch(n.scheme||t.scheme);s&&s.serialize&&s.serialize(t,n),t.path!==void 0&&(n.skipEscape?t.path=DS(t.path):(t.path=FS(t.path),t.scheme!==void 0&&(t.path=t.path.split("%3A").join(":")))),n.reference!=="suffix"&&t.scheme&&i.push(t.scheme,":");let o=jS(t);if(o!==void 0&&(n.reference!=="suffix"&&i.push("//"),i.push(o),t.path&&t.path[0]!=="/"&&i.push("/")),t.path!==void 0){let a=t.path;!n.absolutePath&&(!s||!s.absolutePath)&&(a=ns(a)),o===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),i.push(a)}return t.query!==void 0&&i.push("?",t.query),t.fragment!==void 0&&i.push("#",t.fragment),i.join("")}var GS=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,JS=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,YS=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function XS(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 Mo(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;t.reference==="suffix"&&(t.scheme?r=t.scheme+":"+r:r="//"+r);let o=r.match(JS);o!==null&&o[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",i=!0);let a=r.match(YS);if(a!==null){let l=a[1],d=l.replace(/[\t\n\r]/g,"");d.length>=2&&(d.slice(0,2)!=="//"?(n.error=n.error||"URI authority must not contain a literal backslash.",i=!0):l.length!==d.length&&(n.error=n.error||"URI authority introducer must not contain whitespace.",i=!0))}let c=r.match(GS);if(c){n.scheme=c[1],n.userinfo=c[3],n.host=c[4],n.port=parseInt(c[5],10),n.path=c[6]||"",n.query=c[7],n.fragment=c[8],isNaN(n.port)&&(n.port=c[5]);let l=XS(n,c);if(l!==void 0&&(n.error=n.error||l,i=!0),n.host)if(VS(n.host)===!1){let f=LS(n.host);n.host=f.host.toLowerCase(),s=f.isIPV6}else s=!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 d=Ch(t.scheme||n.scheme);if(!t.unicodeSupport&&(!d||!d.unicodeSupport)&&n.host&&(t.domainHost||d&&d.domainHost)&&s===!1&&BS(n.host))try{n.host=new URL("http://"+n.host).hostname}catch(u){n.error=n.error||"Host's domain name can not be converted to ASCII: "+u}if((!d||d&&!d.skipNormalize)&&(r.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=US(unescape(n.host),s))),n.path&&(n.path=qS(n.path)),n.fragment))try{n.fragment=encodeURI(decodeURIComponent(n.fragment))}catch(u){n.error=n.error||"URI malformed"}d&&d.parse&&d.parse(n,t)}else n.error=n.error||"URI can not be parsed.";return{parsed:n,malformedAuthorityOrPort:i}}function Co(r,e){return Mo(r,e).parsed}function QS(r,e){return Lh(r,e).normalized}function Lh(r,e){let{parsed:t,malformedAuthorityOrPort:n}=Mo(r,e);return{normalized:n?r:_n(t,e),malformedAuthorityOrPort:n}}function Mh(r,e){if(typeof r=="string"){let{normalized:t,malformedAuthorityOrPort:n}=Lh(r,e);return n?void 0:t}if(typeof r=="object")return _n(r,e)}var jl={SCHEMES:zS,normalize:HS,resolve:KS,resolveComponent:Nh,equal:WS,serialize:_n,parse:Co};No.exports=jl;No.exports.default=jl;No.exports.fastUri=jl});var qh=A(Dl=>{"use strict";Object.defineProperty(Dl,"__esModule",{value:!0});var Dh=jh();Dh.code='require("ajv/dist/runtime/uri").default';Dl.default=Dh});var Ul=A(je=>{"use strict";Object.defineProperty(je,"__esModule",{value:!0});je.CodeGen=je.Name=je.nil=je.stringify=je.str=je._=je.KeywordCxt=void 0;var ZS=Hn();Object.defineProperty(je,"KeywordCxt",{enumerable:!0,get:function(){return ZS.KeywordCxt}});var Gn=H();Object.defineProperty(je,"_",{enumerable:!0,get:function(){return Gn._}});Object.defineProperty(je,"str",{enumerable:!0,get:function(){return Gn.str}});Object.defineProperty(je,"stringify",{enumerable:!0,get:function(){return Gn.stringify}});Object.defineProperty(je,"nil",{enumerable:!0,get:function(){return Gn.nil}});Object.defineProperty(je,"Name",{enumerable:!0,get:function(){return Gn.Name}});Object.defineProperty(je,"CodeGen",{enumerable:!0,get:function(){return Gn.CodeGen}});var eE=ts(),zh=Kn(),tE=fl(),is=rs(),rE=H(),ss=Qi(),Lo=Xi(),Fl=Q(),Fh=vh(),nE=qh(),Hh=(r,e)=>new RegExp(r,e);Hh.code="new RegExp";var iE=["removeAdditional","useDefaults","coerceTypes"],sE=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),oE={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."},aE={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Uh=200;function cE(r){var e,t,n,i,s,o,a,c,l,d,u,f,p,y,h,m,g,_,w,k,v,P,O,$,R;let S=r.strict,V=(e=r.code)===null||e===void 0?void 0:e.optimize,B=V===!0||V===void 0?1:V||0,T=(n=(t=r.code)===null||t===void 0?void 0:t.regExp)!==null&&n!==void 0?n:Hh,E=(i=r.uriResolver)!==null&&i!==void 0?i:nE.default;return{strictSchema:(o=(s=r.strictSchema)!==null&&s!==void 0?s:S)!==null&&o!==void 0?o:!0,strictNumbers:(c=(a=r.strictNumbers)!==null&&a!==void 0?a:S)!==null&&c!==void 0?c:!0,strictTypes:(d=(l=r.strictTypes)!==null&&l!==void 0?l:S)!==null&&d!==void 0?d:"log",strictTuples:(f=(u=r.strictTuples)!==null&&u!==void 0?u:S)!==null&&f!==void 0?f:"log",strictRequired:(y=(p=r.strictRequired)!==null&&p!==void 0?p:S)!==null&&y!==void 0?y:!1,code:r.code?{...r.code,optimize:B,regExp:T}:{optimize:B,regExp:T},loopRequired:(h=r.loopRequired)!==null&&h!==void 0?h:Uh,loopEnum:(m=r.loopEnum)!==null&&m!==void 0?m:Uh,meta:(g=r.meta)!==null&&g!==void 0?g:!0,messages:(_=r.messages)!==null&&_!==void 0?_:!0,inlineRefs:(w=r.inlineRefs)!==null&&w!==void 0?w:!0,schemaId:(k=r.schemaId)!==null&&k!==void 0?k:"$id",addUsedSchema:(v=r.addUsedSchema)!==null&&v!==void 0?v:!0,validateSchema:(P=r.validateSchema)!==null&&P!==void 0?P:!0,validateFormats:(O=r.validateFormats)!==null&&O!==void 0?O:!0,unicodeRegExp:($=r.unicodeRegExp)!==null&&$!==void 0?$:!0,int32range:(R=r.int32range)!==null&&R!==void 0?R:!0,uriResolver:E}}var os=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,...cE(e)};let{es5:t,lines:n}=this.opts.code;this.scope=new rE.ValueScope({scope:{},prefixes:sE,es5:t,lines:n}),this.logger=hE(e.logger);let i=e.validateFormats;e.validateFormats=!1,this.RULES=(0,tE.getRules)(),Vh.call(this,oE,e,"NOT SUPPORTED"),Vh.call(this,aE,e,"DEPRECATED","warn"),this._metaOpts=fE.call(this),e.formats&&dE.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&uE.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),lE.call(this),e.validateFormats=i}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:t,schemaId:n}=this.opts,i=Fh;n==="id"&&(i={...Fh},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(d,u){await s.call(this,d.$schema);let f=this._addSchema(d,u);return f.validate||o.call(this,f)}async function s(d){d&&!this.getSchema(d)&&await i.call(this,{$ref:d},!0)}async function o(d){try{return this._compileSchemaEnv(d)}catch(u){if(!(u instanceof zh.default))throw u;return a.call(this,u),await c.call(this,u.missingSchema),o.call(this,d)}}function a({missingSchema:d,missingRef:u}){if(this.refs[d])throw new Error(`AnySchema ${d} is loaded but ${u} cannot be resolved`)}async function c(d){let u=await l.call(this,d);this.refs[d]||await s.call(this,u.$schema),this.refs[d]||this.addSchema(u,d,t)}async function l(d){let u=this._loading[d];if(u)return u;try{return await(this._loading[d]=n(d))}finally{delete this._loading[d]}}}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,ss.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=Bh.call(this,e))=="string";)e=t;if(t===void 0){let{schemaId:n}=this.opts,i=new is.SchemaEnv({schema:{},schemaId:n});if(t=is.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=Bh.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,ss.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(yE.call(this,n,t),!t)return(0,Fl.eachItem)(n,s=>ql.call(this,s)),this;_E.call(this,t);let i={...t,type:(0,Lo.getJSONTypes)(t.type),schemaType:(0,Lo.getJSONTypes)(t.schemaType)};return(0,Fl.eachItem)(n,i.type.length===0?s=>ql.call(this,s,i):s=>i.type.forEach(o=>ql.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,d=o[a];l&&d&&(o[a]=Kh(d))}}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,ss.normalizeId)(o||n);let l=ss.getSchemaRefs.call(this,e,n);return c=new is.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):is.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{is.compileSchema.call(this,e)}finally{this.opts=t}}};os.ValidationError=eE.default;os.MissingRefError=zh.default;je.default=os;function Vh(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 Bh(r){return r=(0,ss.normalizeId)(r),this.schemas[r]||this.refs[r]}function lE(){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 dE(){for(let r in this.opts.formats){let e=this.opts.formats[r];e&&this.addFormat(r,e)}}function uE(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 fE(){let r={...this.opts};for(let e of iE)delete r[e];return r}var pE={log(){},warn(){},error(){}};function hE(r){if(r===!1)return pE;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 mE=/^[a-z_$][a-z0-9_$:-]*$/i;function yE(r,e){let{RULES:t}=this;if((0,Fl.eachItem)(r,n=>{if(t.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!mE.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 ql(r,e,t){var n;let i=e==null?void 0: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,Lo.getJSONTypes)(e.type),schemaType:(0,Lo.getJSONTypes)(e.schemaType)}};e.before?gE.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 gE(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 _E(r){let{metaSchema:e}=r;e!==void 0&&(r.$data&&this.opts.$data&&(e=Kh(e)),r.validateSchema=this.compile(e,!0))}var bE={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Kh(r){return{anyOf:[r,bE]}}});var Wh=A(Vl=>{"use strict";Object.defineProperty(Vl,"__esModule",{value:!0});var wE={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Vl.default=wE});var qo=A(bn=>{"use strict";Object.defineProperty(bn,"__esModule",{value:!0});bn.callRef=bn.getValidate=void 0;var vE=Kn(),Gh=St(),ct=H(),Jn=$t(),Jh=rs(),jo=Q(),$E={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 u();let d=Jh.resolveRef.call(c,l,i,t);if(d===void 0)throw new vE.default(n.opts.uriResolver,i,t);if(d instanceof Jh.SchemaEnv)return f(d);return p(d);function u(){if(s===l)return Do(r,o,s,s.$async);let y=e.scopeValue("root",{ref:l});return Do(r,(0,ct._)`${y}.validate`,l,l.$async)}function f(y){let h=Yh(r,y);Do(r,h,y,y.$async)}function p(y){let h=e.scopeValue("schema",a.code.source===!0?{ref:y,code:(0,ct.stringify)(y)}:{ref:y}),m=e.name("valid"),g=r.subschema({schema:y,dataTypes:[],schemaPath:ct.nil,topSchemaRef:h,errSchemaPath:t},m);r.mergeEvaluated(g),r.ok(m)}}};function Yh(r,e){let{gen:t}=r;return e.validate?t.scopeValue("validate",{ref:e.validate}):(0,ct._)`${t.scopeValue("wrapper",{ref:e})}.validate`}bn.getValidate=Yh;function Do(r,e,t,n){let{gen:i,it:s}=r,{allErrors:o,schemaEnv:a,opts:c}=s,l=c.passContext?Jn.default.this:ct.nil;n?d():u();function d(){if(!a.$async)throw new Error("async schema referenced by sync schema");let y=i.let("valid");i.try(()=>{i.code((0,ct._)`await ${(0,Gh.callValidateCode)(r,e,l)}`),p(e),o||i.assign(y,!0)},h=>{i.if((0,ct._)`!(${h} instanceof ${s.ValidationError})`,()=>i.throw(h)),f(h),o||i.assign(y,!1)}),r.ok(y)}function u(){r.result((0,Gh.callValidateCode)(r,e,l),()=>p(e),()=>f(e))}function f(y){let h=(0,ct._)`${y}.errors`;i.assign(Jn.default.vErrors,(0,ct._)`${Jn.default.vErrors} === null ? ${h} : ${Jn.default.vErrors}.concat(${h})`),i.assign(Jn.default.errors,(0,ct._)`${Jn.default.vErrors}.length`)}function p(y){var h;if(!s.opts.unevaluated)return;let m=(h=t==null?void 0:t.validate)===null||h===void 0?void 0:h.evaluated;if(s.props!==!0)if(m&&!m.dynamicProps)m.props!==void 0&&(s.props=jo.mergeEvaluated.props(i,m.props,s.props));else{let g=i.var("props",(0,ct._)`${y}.evaluated.props`);s.props=jo.mergeEvaluated.props(i,g,s.props,ct.Name)}if(s.items!==!0)if(m&&!m.dynamicItems)m.items!==void 0&&(s.items=jo.mergeEvaluated.items(i,m.items,s.items));else{let g=i.var("items",(0,ct._)`${y}.evaluated.items`);s.items=jo.mergeEvaluated.items(i,g,s.items,ct.Name)}}}bn.callRef=Do;bn.default=$E});var zl=A(Bl=>{"use strict";Object.defineProperty(Bl,"__esModule",{value:!0});var SE=Wh(),EE=qo(),AE=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",SE.default,EE.default];Bl.default=AE});var Xh=A(Hl=>{"use strict";Object.defineProperty(Hl,"__esModule",{value:!0});var Fo=H(),zr=Fo.operators,Uo={maximum:{okStr:"<=",ok:zr.LTE,fail:zr.GT},minimum:{okStr:">=",ok:zr.GTE,fail:zr.LT},exclusiveMaximum:{okStr:"<",ok:zr.LT,fail:zr.GTE},exclusiveMinimum:{okStr:">",ok:zr.GT,fail:zr.LTE}},xE={message:({keyword:r,schemaCode:e})=>(0,Fo.str)`must be ${Uo[r].okStr} ${e}`,params:({keyword:r,schemaCode:e})=>(0,Fo._)`{comparison: ${Uo[r].okStr}, limit: ${e}}`},kE={keyword:Object.keys(Uo),type:"number",schemaType:"number",$data:!0,error:xE,code(r){let{keyword:e,data:t,schemaCode:n}=r;r.fail$data((0,Fo._)`${t} ${Uo[e].fail} ${n} || isNaN(${t})`)}};Hl.default=kE});var Qh=A(Kl=>{"use strict";Object.defineProperty(Kl,"__esModule",{value:!0});var as=H(),PE={message:({schemaCode:r})=>(0,as.str)`must be multiple of ${r}`,params:({schemaCode:r})=>(0,as._)`{multipleOf: ${r}}`},IE={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:PE,code(r){let{gen:e,data:t,schemaCode:n,it:i}=r,s=i.opts.multipleOfPrecision,o=e.let("res"),a=s?(0,as._)`Math.abs(Math.round(${o}) - ${o}) > 1e-${s}`:(0,as._)`${o} !== parseInt(${o})`;r.fail$data((0,as._)`(${n} === 0 || (${o} = ${t}/${n}, ${a}))`)}};Kl.default=IE});var em=A(Wl=>{"use strict";Object.defineProperty(Wl,"__esModule",{value:!0});function Zh(r){let e=r.length,t=0,n=0,i;for(;n=55296&&i<=56319&&n{"use strict";Object.defineProperty(Gl,"__esModule",{value:!0});var wn=H(),OE=Q(),RE=em(),TE={message({keyword:r,schemaCode:e}){let t=r==="maxLength"?"more":"fewer";return(0,wn.str)`must NOT have ${t} than ${e} characters`},params:({schemaCode:r})=>(0,wn._)`{limit: ${r}}`},ME={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:TE,code(r){let{keyword:e,data:t,schemaCode:n,it:i}=r,s=e==="maxLength"?wn.operators.GT:wn.operators.LT,o=i.opts.unicode===!1?(0,wn._)`${t}.length`:(0,wn._)`${(0,OE.useFunc)(r.gen,RE.default)}(${t})`;r.fail$data((0,wn._)`${o} ${s} ${n}`)}};Gl.default=ME});var rm=A(Jl=>{"use strict";Object.defineProperty(Jl,"__esModule",{value:!0});var CE=St(),NE=Q(),Yn=H(),LE={message:({schemaCode:r})=>(0,Yn.str)`must match pattern "${r}"`,params:({schemaCode:r})=>(0,Yn._)`{pattern: ${r}}`},jE={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:LE,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,Yn._)`new RegExp`:(0,NE.useFunc)(e,c),d=e.let("valid");e.try(()=>e.assign(d,(0,Yn._)`${l}(${s}, ${a}).test(${t})`),()=>e.assign(d,!1)),r.fail$data((0,Yn._)`!${d}`)}else{let c=(0,CE.usePattern)(r,i);r.fail$data((0,Yn._)`!${c}.test(${t})`)}}};Jl.default=jE});var nm=A(Yl=>{"use strict";Object.defineProperty(Yl,"__esModule",{value:!0});var cs=H(),DE={message({keyword:r,schemaCode:e}){let t=r==="maxProperties"?"more":"fewer";return(0,cs.str)`must NOT have ${t} than ${e} properties`},params:({schemaCode:r})=>(0,cs._)`{limit: ${r}}`},qE={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:DE,code(r){let{keyword:e,data:t,schemaCode:n}=r,i=e==="maxProperties"?cs.operators.GT:cs.operators.LT;r.fail$data((0,cs._)`Object.keys(${t}).length ${i} ${n}`)}};Yl.default=qE});var im=A(Xl=>{"use strict";Object.defineProperty(Xl,"__esModule",{value:!0});var ls=St(),ds=H(),FE=Q(),UE={message:({params:{missingProperty:r}})=>(0,ds.str)`must have required property '${r}'`,params:({params:{missingProperty:r}})=>(0,ds._)`{missingProperty: ${r}}`},VE={keyword:"required",type:"object",schemaType:"array",$data:!0,error:UE,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():d(),a.strictRequired){let p=r.parentSchema.properties,{definedProperties:y}=r.it;for(let h of t)if((p==null?void 0:p[h])===void 0&&!y.has(h)){let m=o.schemaEnv.baseId+o.errSchemaPath,g=`required property "${h}" is not defined at "${m}" (strictRequired)`;(0,FE.checkStrictMode)(o,g,o.opts.strictRequired)}}function l(){if(c||s)r.block$data(ds.nil,u);else for(let p of t)(0,ls.checkReportMissingProp)(r,p)}function d(){let p=e.let("missing");if(c||s){let y=e.let("valid",!0);r.block$data(y,()=>f(p,y)),r.ok(y)}else e.if((0,ls.checkMissingProp)(r,t,p)),(0,ls.reportMissingProp)(r,p),e.else()}function u(){e.forOf("prop",n,p=>{r.setParams({missingProperty:p}),e.if((0,ls.noPropertyInData)(e,i,p,a.ownProperties),()=>r.error())})}function f(p,y){r.setParams({missingProperty:p}),e.forOf(p,n,()=>{e.assign(y,(0,ls.propertyInData)(e,i,p,a.ownProperties)),e.if((0,ds.not)(y),()=>{r.error(),e.break()})},ds.nil)}}};Xl.default=VE});var sm=A(Ql=>{"use strict";Object.defineProperty(Ql,"__esModule",{value:!0});var us=H(),BE={message({keyword:r,schemaCode:e}){let t=r==="maxItems"?"more":"fewer";return(0,us.str)`must NOT have ${t} than ${e} items`},params:({schemaCode:r})=>(0,us._)`{limit: ${r}}`},zE={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:BE,code(r){let{keyword:e,data:t,schemaCode:n}=r,i=e==="maxItems"?us.operators.GT:us.operators.LT;r.fail$data((0,us._)`${t}.length ${i} ${n}`)}};Ql.default=zE});var Vo=A(Zl=>{"use strict";Object.defineProperty(Zl,"__esModule",{value:!0});var om=wl();om.code='require("ajv/dist/runtime/equal").default';Zl.default=om});var am=A(td=>{"use strict";Object.defineProperty(td,"__esModule",{value:!0});var ed=Xi(),De=H(),HE=Q(),KE=Vo(),WE={message:({params:{i:r,j:e}})=>(0,De.str)`must NOT have duplicate items (items ## ${e} and ${r} are identical)`,params:({params:{i:r,j:e}})=>(0,De._)`{i: ${r}, j: ${e}}`},GE={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:WE,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,ed.getSchemaTypes)(s.items):[];r.block$data(c,d,(0,De._)`${o} === false`),r.ok(c);function d(){let y=e.let("i",(0,De._)`${t}.length`),h=e.let("j");r.setParams({i:y,j:h}),e.assign(c,!0),e.if((0,De._)`${y} > 1`,()=>(u()?f:p)(y,h))}function u(){return l.length>0&&!l.some(y=>y==="object"||y==="array")}function f(y,h){let m=e.name("item"),g=(0,ed.checkDataTypes)(l,m,a.opts.strictNumbers,ed.DataType.Wrong),_=e.const("indices",(0,De._)`{}`);e.for((0,De._)`;${y}--;`,()=>{e.let(m,(0,De._)`${t}[${y}]`),e.if(g,(0,De._)`continue`),l.length>1&&e.if((0,De._)`typeof ${m} == "string"`,(0,De._)`${m} += "_"`),e.if((0,De._)`typeof ${_}[${m}] == "number"`,()=>{e.assign(h,(0,De._)`${_}[${m}]`),r.error(),e.assign(c,!1).break()}).code((0,De._)`${_}[${m}] = ${y}`)})}function p(y,h){let m=(0,HE.useFunc)(e,KE.default),g=e.name("outer");e.label(g).for((0,De._)`;${y}--;`,()=>e.for((0,De._)`${h} = ${y}; ${h}--;`,()=>e.if((0,De._)`${m}(${t}[${y}], ${t}[${h}])`,()=>{r.error(),e.assign(c,!1).break(g)})))}}};td.default=GE});var cm=A(nd=>{"use strict";Object.defineProperty(nd,"__esModule",{value:!0});var rd=H(),JE=Q(),YE=Vo(),XE={message:"must be equal to constant",params:({schemaCode:r})=>(0,rd._)`{allowedValue: ${r}}`},QE={keyword:"const",$data:!0,error:XE,code(r){let{gen:e,data:t,$data:n,schemaCode:i,schema:s}=r;n||s&&typeof s=="object"?r.fail$data((0,rd._)`!${(0,JE.useFunc)(e,YE.default)}(${t}, ${i})`):r.fail((0,rd._)`${s} !== ${t}`)}};nd.default=QE});var lm=A(id=>{"use strict";Object.defineProperty(id,"__esModule",{value:!0});var fs=H(),ZE=Q(),eA=Vo(),tA={message:"must be equal to one of the allowed values",params:({schemaCode:r})=>(0,fs._)`{allowedValues: ${r}}`},rA={keyword:"enum",schemaType:"array",$data:!0,error:tA,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!=null?c:c=(0,ZE.useFunc)(e,eA.default),d;if(a||n)d=e.let("valid"),r.block$data(d,u);else{if(!Array.isArray(i))throw new Error("ajv implementation error");let p=e.const("vSchema",s);d=(0,fs.or)(...i.map((y,h)=>f(p,h)))}r.pass(d);function u(){e.assign(d,!1),e.forOf("v",s,p=>e.if((0,fs._)`${l()}(${t}, ${p})`,()=>e.assign(d,!0).break()))}function f(p,y){let h=i[y];return typeof h=="object"&&h!==null?(0,fs._)`${l()}(${t}, ${p}[${y}])`:(0,fs._)`${t} === ${h}`}}};id.default=rA});var od=A(sd=>{"use strict";Object.defineProperty(sd,"__esModule",{value:!0});var nA=Xh(),iA=Qh(),sA=tm(),oA=rm(),aA=nm(),cA=im(),lA=sm(),dA=am(),uA=cm(),fA=lm(),pA=[nA.default,iA.default,sA.default,oA.default,aA.default,cA.default,lA.default,dA.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},uA.default,fA.default];sd.default=pA});var cd=A(ps=>{"use strict";Object.defineProperty(ps,"__esModule",{value:!0});ps.validateAdditionalItems=void 0;var vn=H(),ad=Q(),hA={message:({params:{len:r}})=>(0,vn.str)`must NOT have more than ${r} items`,params:({params:{len:r}})=>(0,vn._)`{limit: ${r}}`},mA={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:hA,code(r){let{parentSchema:e,it:t}=r,{items:n}=e;if(!Array.isArray(n)){(0,ad.checkStrictMode)(t,'"additionalItems" is ignored when "items" is not an array of schemas');return}dm(r,n)}};function dm(r,e){let{gen:t,schema:n,data:i,keyword:s,it:o}=r;o.items=!0;let a=t.const("len",(0,vn._)`${i}.length`);if(n===!1)r.setParams({len:e.length}),r.pass((0,vn._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,ad.alwaysValidSchema)(o,n)){let l=t.var("valid",(0,vn._)`${a} <= ${e.length}`);t.if((0,vn.not)(l),()=>c(l)),r.ok(l)}function c(l){t.forRange("i",e.length,a,d=>{r.subschema({keyword:s,dataProp:d,dataPropType:ad.Type.Num},l),o.allErrors||t.if((0,vn.not)(l),()=>t.break())})}}ps.validateAdditionalItems=dm;ps.default=mA});var ld=A(hs=>{"use strict";Object.defineProperty(hs,"__esModule",{value:!0});hs.validateTuple=void 0;var um=H(),Bo=Q(),yA=St(),gA={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(r){let{schema:e,it:t}=r;if(Array.isArray(e))return fm(r,"additionalItems",e);t.items=!0,!(0,Bo.alwaysValidSchema)(t,e)&&r.ok((0,yA.validateArray)(r))}};function fm(r,e,t=r.schema){let{gen:n,parentSchema:i,data:s,keyword:o,it:a}=r;d(i),a.opts.unevaluated&&t.length&&a.items!==!0&&(a.items=Bo.mergeEvaluated.items(n,t.length,a.items));let c=n.name("valid"),l=n.const("len",(0,um._)`${s}.length`);t.forEach((u,f)=>{(0,Bo.alwaysValidSchema)(a,u)||(n.if((0,um._)`${l} > ${f}`,()=>r.subschema({keyword:o,schemaProp:f,dataProp:f},c)),r.ok(c))});function d(u){let{opts:f,errSchemaPath:p}=a,y=t.length,h=y===u.minItems&&(y===u.maxItems||u[e]===!1);if(f.strictTuples&&!h){let m=`"${o}" is ${y}-tuple, but minItems or maxItems/${e} are not specified or different at path "${p}"`;(0,Bo.checkStrictMode)(a,m,f.strictTuples)}}}hs.validateTuple=fm;hs.default=gA});var pm=A(dd=>{"use strict";Object.defineProperty(dd,"__esModule",{value:!0});var _A=ld(),bA={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:r=>(0,_A.validateTuple)(r,"items")};dd.default=bA});var mm=A(ud=>{"use strict";Object.defineProperty(ud,"__esModule",{value:!0});var hm=H(),wA=Q(),vA=St(),$A=cd(),SA={message:({params:{len:r}})=>(0,hm.str)`must NOT have more than ${r} items`,params:({params:{len:r}})=>(0,hm._)`{limit: ${r}}`},EA={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:SA,code(r){let{schema:e,parentSchema:t,it:n}=r,{prefixItems:i}=t;n.items=!0,!(0,wA.alwaysValidSchema)(n,e)&&(i?(0,$A.validateAdditionalItems)(r,i):r.ok((0,vA.validateArray)(r)))}};ud.default=EA});var ym=A(fd=>{"use strict";Object.defineProperty(fd,"__esModule",{value:!0});var At=H(),zo=Q(),AA={message:({params:{min:r,max:e}})=>e===void 0?(0,At.str)`must contain at least ${r} valid item(s)`:(0,At.str)`must contain at least ${r} and no more than ${e} valid item(s)`,params:({params:{min:r,max:e}})=>e===void 0?(0,At._)`{minContains: ${r}}`:(0,At._)`{minContains: ${r}, maxContains: ${e}}`},xA={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:AA,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 d=e.const("len",(0,At._)`${i}.length`);if(r.setParams({min:o,max:a}),a===void 0&&o===0){(0,zo.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&o>a){(0,zo.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),r.fail();return}if((0,zo.alwaysValidSchema)(s,t)){let h=(0,At._)`${d} >= ${o}`;a!==void 0&&(h=(0,At._)`${h} && ${d} <= ${a}`),r.pass(h);return}s.items=!0;let u=e.name("valid");a===void 0&&o===1?p(u,()=>e.if(u,()=>e.break())):o===0?(e.let(u,!0),a!==void 0&&e.if((0,At._)`${i}.length > 0`,f)):(e.let(u,!1),f()),r.result(u,()=>r.reset());function f(){let h=e.name("_valid"),m=e.let("count",0);p(h,()=>e.if(h,()=>y(m)))}function p(h,m){e.forRange("i",0,d,g=>{r.subschema({keyword:"contains",dataProp:g,dataPropType:zo.Type.Num,compositeRule:!0},h),m()})}function y(h){e.code((0,At._)`${h}++`),a===void 0?e.if((0,At._)`${h} >= ${o}`,()=>e.assign(u,!0).break()):(e.if((0,At._)`${h} > ${a}`,()=>e.assign(u,!1).break()),o===1?e.assign(u,!0):e.if((0,At._)`${h} >= ${o}`,()=>e.assign(u,!0)))}}};fd.default=xA});var Ho=A(tr=>{"use strict";Object.defineProperty(tr,"__esModule",{value:!0});tr.validateSchemaDeps=tr.validatePropertyDeps=tr.error=void 0;var pd=H(),kA=Q(),ms=St();tr.error={message:({params:{property:r,depsCount:e,deps:t}})=>{let n=e===1?"property":"properties";return(0,pd.str)`must have ${n} ${t} when property ${r} is present`},params:({params:{property:r,depsCount:e,deps:t,missingProperty:n}})=>(0,pd._)`{property: ${r}, missingProperty: ${n}, depsCount: ${e}, - deps: ${t}}`};var qE={keyword:"dependencies",type:"object",schemaType:"object",error:ar.error,code(r){let[e,t]=jE(r);Yh(r,e),Xh(r,t)}};function jE({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 Yh(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,ds.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,ds.checkReportMissingProp)(r,l)}):(t.if((0,ed._)`${c} && (${(0,ds.checkMissingProp)(r,a,s)})`),(0,ds.reportMissingProp)(r,s),t.else())}}ar.validatePropertyDeps=Yh;function Xh(r,e=r.schema){let{gen:t,data:n,keyword:i,it:s}=r,o=t.name("valid");for(let a in e)(0,DE.alwaysValidSchema)(s,e[a])||(t.if((0,ds.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))}ar.validateSchemaDeps=Xh;ar.default=qE});var Zh=A(td=>{"use strict";Object.defineProperty(td,"__esModule",{value:!0});var Qh=K(),FE=ee(),VE={message:"property name must be valid",params:({params:r})=>(0,Qh._)`{propertyName: ${r.propertyName}}`},UE={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:VE,code(r){let{gen:e,schema:t,data:n,it:i}=r;if((0,FE.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,Qh.not)(s),()=>{r.error(!0),i.allErrors||e.break()})}),r.ok(s)}};td.default=UE});var nd=A(rd=>{"use strict";Object.defineProperty(rd,"__esModule",{value:!0});var Vo=xt(),Ft=K(),BE=kt(),Uo=ee(),zE={message:"must NOT have additional properties",params:({params:r})=>(0,Ft._)`{additionalProperty: ${r.additionalProperty}}`},HE={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:zE,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,Uo.alwaysValidSchema)(o,t))return;let l=(0,Vo.allSchemaProperties)(n.properties),u=(0,Vo.allSchemaProperties)(n.patternProperties);d(),r.ok((0,Ft._)`${s} === ${BE.default.errors}`);function d(){e.forIn("key",i,y=>{!l.length&&!u.length?m(y):e.if(f(y),()=>m(y))})}function f(y){let b;if(l.length>8){let g=(0,Uo.schemaRefOrVal)(o,n.properties,"properties");b=(0,Vo.isOwnProperty)(e,g,y)}else l.length?b=(0,Ft.or)(...l.map(g=>(0,Ft._)`${y} === ${g}`)):b=Ft.nil;return u.length&&(b=(0,Ft.or)(b,...u.map(g=>(0,Ft._)`${(0,Vo.usePattern)(r,g)}.test(${y})`))),(0,Ft.not)(b)}function p(y){e.code((0,Ft._)`delete ${i}[${y}]`)}function m(y){if(c.removeAdditional==="all"||c.removeAdditional&&t===!1){p(y);return}if(t===!1){r.setParams({additionalProperty:y}),r.error(),a||e.break();return}if(typeof t=="object"&&!(0,Uo.alwaysValidSchema)(o,t)){let b=e.name("valid");c.removeAdditional==="failing"?(h(y,b,!1),e.if((0,Ft.not)(b),()=>{r.reset(),p(y)})):(h(y,b),a||e.if((0,Ft.not)(b),()=>e.break()))}}function h(y,b,g){let _={keyword:"additionalProperties",dataProp:y,dataPropType:Uo.Type.Str};g===!1&&Object.assign(_,{compositeRule:!0,createErrors:!1,allErrors:!1}),r.subschema(_,b)}}};rd.default=HE});var rm=A(sd=>{"use strict";Object.defineProperty(sd,"__esModule",{value:!0});var KE=Un(),em=xt(),id=ee(),tm=nd(),WE={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&&tm.default.code(new KE.KeywordCxt(s,tm.default,"additionalProperties"));let o=(0,em.allSchemaProperties)(t);for(let d of o)s.definedProperties.add(d);s.opts.unevaluated&&o.length&&s.props!==!0&&(s.props=id.mergeEvaluated.props(e,(0,id.toHash)(o),s.props));let a=o.filter(d=>!(0,id.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,em.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)}}};sd.default=WE});var om=A(od=>{"use strict";Object.defineProperty(od,"__esModule",{value:!0});var nm=xt(),Bo=K(),im=ee(),sm=ee(),GE={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,nm.allSchemaProperties)(t),c=a.filter(h=>(0,im.alwaysValidSchema)(s,t[h]));if(a.length===0||c.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let l=o.strictSchema&&!o.allowMatchingProperties&&i.properties,u=e.name("valid");s.props!==!0&&!(s.props instanceof Bo.Name)&&(s.props=(0,sm.evaluatedPropsToName)(e,s.props));let{props:d}=s;f();function f(){for(let h of a)l&&p(h),s.allErrors?m(h):(e.var(u,!0),m(h),e.if(u))}function p(h){for(let y in l)new RegExp(h).test(y)&&(0,im.checkStrictMode)(s,`property ${y} matches pattern ${h} (use allowMatchingProperties)`)}function m(h){e.forIn("key",n,y=>{e.if((0,Bo._)`${(0,nm.usePattern)(r,h)}.test(${y})`,()=>{let b=c.includes(h);b||r.subschema({keyword:"patternProperties",schemaProp:h,dataProp:y,dataPropType:sm.Type.Str},u),s.opts.unevaluated&&d!==!0?e.assign((0,Bo._)`${d}[${y}]`,!0):!b&&!s.allErrors&&e.if((0,Bo.not)(u),()=>e.break())})})}}};od.default=GE});var am=A(ad=>{"use strict";Object.defineProperty(ad,"__esModule",{value:!0});var JE=ee(),YE={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(r){let{gen:e,schema:t,it:n}=r;if((0,JE.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"}};ad.default=YE});var cm=A(cd=>{"use strict";Object.defineProperty(cd,"__esModule",{value:!0});var XE=xt(),QE={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:XE.validateUnion,error:{message:"must match a schema in anyOf"}};cd.default=QE});var lm=A(ld=>{"use strict";Object.defineProperty(ld,"__esModule",{value:!0});var zo=K(),ZE=ee(),eA={message:"must match exactly one schema in oneOf",params:({params:r})=>(0,zo._)`{passingSchemas: ${r.passing}}`},tA={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:eA,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,ZE.alwaysValidSchema)(i,u)?e.var(c,!0):f=r.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,zo._)`${c} && ${o}`).assign(o,!1).assign(a,(0,zo._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(o,!0),e.assign(a,d),f&&r.mergeEvaluated(f,zo.Name)})})}}};ld.default=tA});var dm=A(dd=>{"use strict";Object.defineProperty(dd,"__esModule",{value:!0});var rA=ee(),nA={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,rA.alwaysValidSchema)(n,s))return;let a=r.subschema({keyword:"allOf",schemaProp:o},i);r.ok(i),r.mergeEvaluated(a)})}};dd.default=nA});var pm=A(ud=>{"use strict";Object.defineProperty(ud,"__esModule",{value:!0});var Ho=K(),fm=ee(),iA={message:({params:r})=>(0,Ho.str)`must match "${r.ifClause}" schema`,params:({params:r})=>(0,Ho._)`{failingKeyword: ${r.ifClause}}`},sA={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:iA,code(r){let{gen:e,parentSchema:t,it:n}=r;t.then===void 0&&t.else===void 0&&(0,fm.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let i=um(n,"then"),s=um(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,Ho.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,Ho._)`${u}`):r.setParams({ifClause:u})}}}};function um(r,e){let t=r.schema[e];return t!==void 0&&!(0,fm.alwaysValidSchema)(r,t)}ud.default=sA});var hm=A(fd=>{"use strict";Object.defineProperty(fd,"__esModule",{value:!0});var oA=ee(),aA={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:r,parentSchema:e,it:t}){e.if===void 0&&(0,oA.checkStrictMode)(t,`"${r}" without "if" is ignored`)}};fd.default=aA});var hd=A(pd=>{"use strict";Object.defineProperty(pd,"__esModule",{value:!0});var cA=Jl(),lA=Kh(),dA=Yl(),uA=Gh(),fA=Jh(),pA=Fo(),hA=Zh(),mA=nd(),yA=rm(),gA=om(),bA=am(),_A=cm(),wA=lm(),vA=dm(),$A=pm(),SA=hm();function EA(r=!1){let e=[bA.default,_A.default,wA.default,vA.default,$A.default,SA.default,hA.default,mA.default,pA.default,yA.default,gA.default];return r?e.push(lA.default,uA.default):e.push(cA.default,dA.default),e.push(fA.default),e}pd.default=EA});var yd=A(us=>{"use strict";Object.defineProperty(us,"__esModule",{value:!0});us.dynamicAnchor=void 0;var md=K(),AA=kt(),mm=Xi(),kA=Mo(),xA={keyword:"$dynamicAnchor",schemaType:"string",code:r=>ym(r,r.schema)};function ym(r,e){let{gen:t,it:n}=r;n.schemaEnv.root.dynamicAnchors[e]=!0;let i=(0,md._)`${AA.default.dynamicAnchors}${(0,md.getProperty)(e)}`,s=n.errSchemaPath==="#"?n.validateName:PA(r);t.if((0,md._)`!${i}`,()=>t.assign(i,s))}us.dynamicAnchor=ym;function PA(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 mm.SchemaEnv({schema:t,schemaId:c,root:i,baseId:s,localRefs:o,meta:a});return mm.compileSchema.call(n,l),(0,kA.getValidate)(r,l)}us.default=xA});var gd=A(fs=>{"use strict";Object.defineProperty(fs,"__esModule",{value:!0});fs.dynamicRef=void 0;var gm=K(),IA=kt(),bm=Mo(),OA={keyword:"$dynamicRef",schemaType:"string",code:r=>_m(r,r.schema)};function _m(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,gm._)`${IA.default.dynamicAnchors}${(0,gm.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,bm.callRef)(r,c),t.let(l,!0)}):()=>(0,bm.callRef)(r,c)}}fs.dynamicRef=_m;fs.default=OA});var wm=A(bd=>{"use strict";Object.defineProperty(bd,"__esModule",{value:!0});var TA=yd(),RA=ee(),CA={keyword:"$recursiveAnchor",schemaType:"boolean",code(r){r.schema?(0,TA.dynamicAnchor)(r,""):(0,RA.checkStrictMode)(r.it,"$recursiveAnchor: false is ignored")}};bd.default=CA});var vm=A(_d=>{"use strict";Object.defineProperty(_d,"__esModule",{value:!0});var MA=gd(),NA={keyword:"$recursiveRef",schemaType:"string",code:r=>(0,MA.dynamicRef)(r,r.schema)};_d.default=NA});var $m=A(wd=>{"use strict";Object.defineProperty(wd,"__esModule",{value:!0});var LA=yd(),DA=gd(),qA=wm(),jA=vm(),FA=[LA.default,DA.default,qA.default,jA.default];wd.default=FA});var Em=A(vd=>{"use strict";Object.defineProperty(vd,"__esModule",{value:!0});var Sm=Fo(),VA={keyword:"dependentRequired",type:"object",schemaType:"object",error:Sm.error,code:r=>(0,Sm.validatePropertyDeps)(r)};vd.default=VA});var Am=A($d=>{"use strict";Object.defineProperty($d,"__esModule",{value:!0});var UA=Fo(),BA={keyword:"dependentSchemas",type:"object",schemaType:"object",code:r=>(0,UA.validateSchemaDeps)(r)};$d.default=BA});var km=A(Sd=>{"use strict";Object.defineProperty(Sd,"__esModule",{value:!0});var zA=ee(),HA={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword:r,parentSchema:e,it:t}){e.contains===void 0&&(0,zA.checkStrictMode)(t,`"${r}" without "contains" is ignored`)}};Sd.default=HA});var xm=A(Ed=>{"use strict";Object.defineProperty(Ed,"__esModule",{value:!0});var KA=Em(),WA=Am(),GA=km(),JA=[KA.default,WA.default,GA.default];Ed.default=JA});var Im=A(Ad=>{"use strict";Object.defineProperty(Ad,"__esModule",{value:!0});var Hr=K(),Pm=ee(),YA=kt(),XA={message:"must NOT have unevaluated properties",params:({params:r})=>(0,Hr._)`{unevaluatedProperty: ${r.unevaluatedProperty}}`},QA={keyword:"unevaluatedProperties",type:"object",schemaType:["boolean","object"],trackErrors:!0,error:XA,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 Hr.Name?e.if((0,Hr._)`${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,Hr._)`${i} === ${YA.default.errors}`);function c(d){if(t===!1){r.setParams({unevaluatedProperty:d}),r.error(),o||e.break();return}if(!(0,Pm.alwaysValidSchema)(s,t)){let f=e.name("valid");r.subschema({keyword:"unevaluatedProperties",dataProp:d,dataPropType:Pm.Type.Str},f),o||e.if((0,Hr.not)(f),()=>e.break())}}function l(d,f){return(0,Hr._)`!${d} || !${d}[${f}]`}function u(d,f){let p=[];for(let m in d)d[m]===!0&&p.push((0,Hr._)`${f} !== ${m}`);return(0,Hr.and)(...p)}}};Ad.default=QA});var Tm=A(kd=>{"use strict";Object.defineProperty(kd,"__esModule",{value:!0});var vn=K(),Om=ee(),ZA={message:({params:{len:r}})=>(0,vn.str)`must NOT have more than ${r} items`,params:({params:{len:r}})=>(0,vn._)`{limit: ${r}}`},e1={keyword:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error:ZA,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,vn._)`${n}.length`);if(t===!1)r.setParams({len:s}),r.fail((0,vn._)`${o} > ${s}`);else if(typeof t=="object"&&!(0,Om.alwaysValidSchema)(i,t)){let c=e.var("valid",(0,vn._)`${o} <= ${s}`);e.if((0,vn.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:Om.Type.Num},c),i.allErrors||e.if((0,vn.not)(c),()=>e.break())})}}};kd.default=e1});var Rm=A(xd=>{"use strict";Object.defineProperty(xd,"__esModule",{value:!0});var t1=Im(),r1=Tm(),n1=[t1.default,r1.default];xd.default=n1});var Cm=A(Pd=>{"use strict";Object.defineProperty(Pd,"__esModule",{value:!0});var xe=K(),i1={message:({schemaCode:r})=>(0,xe.str)`must match format "${r}"`,params:({schemaCode:r})=>(0,xe._)`{format: ${r}}`},s1={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:i1,code(r,e){let{gen:t,data:n,$data:i,schema:s,schemaCode:o,it:a}=r,{opts:c,errSchemaPath:l,schemaEnv:u,self:d}=a;if(!c.validateFormats)return;i?f():p();function f(){let m=t.scopeValue("formats",{ref:d.formats,code:c.code.formats}),h=t.const("fDef",(0,xe._)`${m}[${o}]`),y=t.let("fType"),b=t.let("format");t.if((0,xe._)`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>t.assign(y,(0,xe._)`${h}.type || "string"`).assign(b,(0,xe._)`${h}.validate`),()=>t.assign(y,(0,xe._)`"string"`).assign(b,h)),r.fail$data((0,xe.or)(g(),_()));function g(){return c.strictSchema===!1?xe.nil:(0,xe._)`${o} && !${b}`}function _(){let k=u.$async?(0,xe._)`(${h}.async ? await ${b}(${n}) : ${b}(${n}))`:(0,xe._)`${b}(${n})`,v=(0,xe._)`(typeof ${b} == "function" ? ${k} : ${b}.test(${n}))`;return(0,xe._)`${b} && ${b} !== true && ${y} === ${e} && !${v}`}}function p(){let m=d.formats[s];if(!m){g();return}if(m===!0)return;let[h,y,b]=_(m);h===e&&r.pass(k());function g(){if(c.strictSchema===!1){d.logger.warn(v());return}throw new Error(v());function v(){return`unknown format "${s}" ignored in schema at path "${l}"`}}function _(v){let E=v instanceof RegExp?(0,xe.regexpCode)(v):c.code.formats?(0,xe._)`${c.code.formats}${(0,xe.getProperty)(s)}`:void 0,O=t.scopeValue("formats",{key:s,ref:v,code:E});return typeof v=="object"&&!(v instanceof RegExp)?[v.type||"string",v.validate,(0,xe._)`${O}.validate`]:["string",v,O]}function k(){if(typeof m=="object"&&!(m instanceof RegExp)&&m.async){if(!u.$async)throw new Error("async format in sync schema");return(0,xe._)`await ${b}(${n})`}return typeof y=="function"?(0,xe._)`${b}(${n})`:(0,xe._)`${b}.test(${n})`}}}};Pd.default=s1});var Od=A(Id=>{"use strict";Object.defineProperty(Id,"__esModule",{value:!0});var o1=Cm(),a1=[o1.default];Id.default=a1});var Td=A(Gn=>{"use strict";Object.defineProperty(Gn,"__esModule",{value:!0});Gn.contentVocabulary=Gn.metadataVocabulary=void 0;Gn.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Gn.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var Nm=A(Rd=>{"use strict";Object.defineProperty(Rd,"__esModule",{value:!0});var c1=Tl(),l1=Wl(),d1=hd(),u1=$m(),f1=xm(),p1=Rm(),h1=Od(),Mm=Td(),m1=[u1.default,c1.default,l1.default,(0,d1.default)(!0),h1.default,Mm.metadataVocabulary,Mm.contentVocabulary,f1.default,p1.default];Rd.default=m1});var Dm=A(Ko=>{"use strict";Object.defineProperty(Ko,"__esModule",{value:!0});Ko.DiscrError=void 0;var Lm;(function(r){r.Tag="tag",r.Mapping="mapping"})(Lm||(Ko.DiscrError=Lm={}))});var Nd=A(Md=>{"use strict";Object.defineProperty(Md,"__esModule",{value:!0});var Jn=K(),Cd=Dm(),qm=Xi(),y1=Bn(),g1=ee(),b1={message:({params:{discrError:r,tagName:e}})=>r===Cd.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:r,tag:e,tagName:t}})=>(0,Jn._)`{error: ${r}, tag: ${t}, tagValue: ${e}}`},_1={keyword:"discriminator",type:"object",schemaType:"object",error:b1,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,Jn._)`${t}${(0,Jn.getProperty)(a)}`);e.if((0,Jn._)`typeof ${l} == "string"`,()=>u(),()=>r.error(!1,{discrError:Cd.DiscrError.Tag,tag:l,tagName:a})),r.ok(c);function u(){let p=f();e.if(!1);for(let m in p)e.elseIf((0,Jn._)`${l} === ${m}`),e.assign(c,d(p[m]));e.else(),r.error(!1,{discrError:Cd.DiscrError.Mapping,tag:l,tagName:a}),e.endIf()}function d(p){let m=e.name("valid"),h=r.subschema({keyword:"oneOf",schemaProp:p},m);return r.mergeEvaluated(h,Jn.Name),m}function f(){var p;let m={},h=b(i),y=!0;for(let k=0;k{w1.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 Fm=A((VM,v1)=>{v1.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 Vm=A((UM,$1)=>{$1.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 Um=A((BM,S1)=>{S1.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 Bm=A((zM,E1)=>{E1.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 zm=A((HM,A1)=>{A1.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 Hm=A((KM,k1)=>{k1.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 Km=A((WM,x1)=>{x1.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 Wm=A(Ld=>{"use strict";Object.defineProperty(Ld,"__esModule",{value:!0});var P1=jm(),I1=Fm(),O1=Vm(),T1=Um(),R1=Bm(),C1=zm(),M1=Hm(),N1=Km(),L1=["/properties"];function D1(r){return[P1,I1,O1,T1,R1,e(this,C1),M1,e(this,N1)].forEach(t=>this.addMetaSchema(t,void 0,!1)),this;function e(t,n){return r?t.$dataMetaSchema(n,L1):n}}Ld.default=D1});var jd=A((we,qd)=>{"use strict";Object.defineProperty(we,"__esModule",{value:!0});we.MissingRefError=we.ValidationError=we.CodeGen=we.Name=we.nil=we.stringify=we.str=we._=we.KeywordCxt=we.Ajv2020=void 0;var q1=Pl(),j1=Nm(),F1=Nd(),V1=Wm(),Dd="https://json-schema.org/draft/2020-12/schema",Yn=class extends q1.default{constructor(e={}){super({...e,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){super._addVocabularies(),j1.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(F1.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data:e,meta:t}=this.opts;t&&(V1.default.call(this,e),this.refs["http://json-schema.org/schema"]=Dd)}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Dd)?Dd:void 0)}};we.Ajv2020=Yn;qd.exports=we=Yn;qd.exports.Ajv2020=Yn;Object.defineProperty(we,"__esModule",{value:!0});we.default=Yn;var U1=Un();Object.defineProperty(we,"KeywordCxt",{enumerable:!0,get:function(){return U1.KeywordCxt}});var Xn=K();Object.defineProperty(we,"_",{enumerable:!0,get:function(){return Xn._}});Object.defineProperty(we,"str",{enumerable:!0,get:function(){return Xn.str}});Object.defineProperty(we,"stringify",{enumerable:!0,get:function(){return Xn.stringify}});Object.defineProperty(we,"nil",{enumerable:!0,get:function(){return Xn.nil}});Object.defineProperty(we,"Name",{enumerable:!0,get:function(){return Xn.Name}});Object.defineProperty(we,"CodeGen",{enumerable:!0,get:function(){return Xn.CodeGen}});var B1=Yi();Object.defineProperty(we,"ValidationError",{enumerable:!0,get:function(){return B1.default}});var z1=Bn();Object.defineProperty(we,"MissingRefError",{enumerable:!0,get:function(){return z1.default}})});var ty=A(lr=>{"use strict";Object.defineProperty(lr,"__esModule",{value:!0});lr.formatNames=lr.fastFormats=lr.fullFormats=void 0;function cr(r,e){return{validate:r,compare:e}}lr.fullFormats={date:cr(Xm,Bd),time:cr(Vd(!0),zd),"date-time":cr(Gm(!0),Zm),"iso-time":cr(Vd(),Qm),"iso-date-time":cr(Gm(),ey),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:Y1,"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:nk,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:X1,int32:{type:"number",validate:ek},int64:{type:"number",validate:tk},float:{type:"number",validate:Ym},double:{type:"number",validate:Ym},password:!0,binary:!0};lr.fastFormats={...lr.fullFormats,date:cr(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Bd),time:cr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,zd),"date-time":cr(/^\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,Zm),"iso-time":cr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,Qm),"iso-date-time":cr(/^\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,ey),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};lr.formatNames=Object.keys(lr.fullFormats);function H1(r){return r%4===0&&(r%100!==0||r%400===0)}var K1=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,W1=[0,31,28,31,30,31,30,31,31,30,31,30,31];function Xm(r){let e=K1.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&&H1(t)?29:W1[n])}function Bd(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 zd(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 Qm(r,e){if(!(r&&e))return;let t=Fd.exec(r),n=Fd.exec(e);if(t&&n)return r=t[1]+t[2]+t[3],e=n[1]+n[2]+n[3],r>e?1:r=Q1}function tk(r){return Number.isInteger(r)}function Ym(){return!0}var rk=/[^\\]\\Z/;function nk(r){if(rk.test(r))return!1;try{return new RegExp(r),!0}catch(e){return!1}}});var ny=A(Hd=>{"use strict";Object.defineProperty(Hd,"__esModule",{value:!0});var ik=Tl(),sk=Wl(),ok=hd(),ak=Od(),ry=Td(),ck=[ik.default,sk.default,(0,ok.default)(),ak.default,ry.metadataVocabulary,ry.contentVocabulary];Hd.default=ck});var iy=A((XM,lk)=>{lk.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 oy=A((ve,Kd)=>{"use strict";Object.defineProperty(ve,"__esModule",{value:!0});ve.MissingRefError=ve.ValidationError=ve.CodeGen=ve.Name=ve.nil=ve.stringify=ve.str=ve._=ve.KeywordCxt=ve.Ajv=void 0;var dk=Pl(),uk=ny(),fk=Nd(),sy=iy(),pk=["/properties"],Wo="http://json-schema.org/draft-07/schema",Qn=class extends dk.default{_addVocabularies(){super._addVocabularies(),uk.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(fk.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(sy,pk):sy;this.addMetaSchema(e,Wo,!1),this.refs["http://json-schema.org/schema"]=Wo}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Wo)?Wo:void 0)}};ve.Ajv=Qn;Kd.exports=ve=Qn;Kd.exports.Ajv=Qn;Object.defineProperty(ve,"__esModule",{value:!0});ve.default=Qn;var hk=Un();Object.defineProperty(ve,"KeywordCxt",{enumerable:!0,get:function(){return hk.KeywordCxt}});var Zn=K();Object.defineProperty(ve,"_",{enumerable:!0,get:function(){return Zn._}});Object.defineProperty(ve,"str",{enumerable:!0,get:function(){return Zn.str}});Object.defineProperty(ve,"stringify",{enumerable:!0,get:function(){return Zn.stringify}});Object.defineProperty(ve,"nil",{enumerable:!0,get:function(){return Zn.nil}});Object.defineProperty(ve,"Name",{enumerable:!0,get:function(){return Zn.Name}});Object.defineProperty(ve,"CodeGen",{enumerable:!0,get:function(){return Zn.CodeGen}});var mk=Yi();Object.defineProperty(ve,"ValidationError",{enumerable:!0,get:function(){return mk.default}});var yk=Bn();Object.defineProperty(ve,"MissingRefError",{enumerable:!0,get:function(){return yk.default}})});var ay=A(ei=>{"use strict";Object.defineProperty(ei,"__esModule",{value:!0});ei.formatLimitDefinition=void 0;var gk=oy(),Vt=K(),Kr=Vt.operators,Go={formatMaximum:{okStr:"<=",ok:Kr.LTE,fail:Kr.GT},formatMinimum:{okStr:">=",ok:Kr.GTE,fail:Kr.LT},formatExclusiveMaximum:{okStr:"<",ok:Kr.LT,fail:Kr.GTE},formatExclusiveMinimum:{okStr:">",ok:Kr.GT,fail:Kr.LTE}},bk={message:({keyword:r,schemaCode:e})=>(0,Vt.str)`should be ${Go[r].okStr} ${e}`,params:({keyword:r,schemaCode:e})=>(0,Vt._)`{comparison: ${Go[r].okStr}, limit: ${e}}`};ei.formatLimitDefinition={keyword:Object.keys(Go),type:"string",schemaType:"string",$data:!0,error:bk,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 gk.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,Vt._)`${f}[${c.schemaCode}]`);r.fail$data((0,Vt.or)((0,Vt._)`typeof ${p} != "object"`,(0,Vt._)`${p} instanceof RegExp`,(0,Vt._)`typeof ${p}.compare != "function"`,d(p)))}function u(){let f=c.schema,p=a.formats[f];if(!p||p===!0)return;if(typeof p!="object"||p instanceof RegExp||typeof p.compare!="function")throw new Error(`"${i}": format "${f}" does not define "compare" function`);let m=e.scopeValue("formats",{key:f,ref:p,code:o.code.formats?(0,Vt._)`${o.code.formats}${(0,Vt.getProperty)(f)}`:void 0});r.fail$data(d(m))}function d(f){return(0,Vt._)`${f}.compare(${t}, ${n}) ${Go[i].fail} 0`}},dependencies:["format"]};var _k=r=>(r.addKeyword(ei.formatLimitDefinition),r);ei.default=_k});var Jd=A((ps,dy)=>{"use strict";Object.defineProperty(ps,"__esModule",{value:!0});var ti=ty(),wk=ay(),Wd=K(),cy=new Wd.Name("fullFormats"),vk=new Wd.Name("fastFormats"),Gd=(r,e={keywords:!0})=>{if(Array.isArray(e))return ly(r,e,ti.fullFormats,cy),r;let[t,n]=e.mode==="fast"?[ti.fastFormats,vk]:[ti.fullFormats,cy],i=e.formats||ti.formatNames;return ly(r,i,t,n),e.keywords&&(0,wk.default)(r),r};Gd.get=(r,e="full")=>{let n=(e==="fast"?ti.fastFormats:ti.fullFormats)[r];if(!n)throw new Error(`Unknown format "${r}"`);return n};function ly(r,e,t,n){var i,s;(i=(s=r.opts.code).formats)!==null&&i!==void 0||(s.formats=(0,Wd._)`require("ajv-formats/dist/formats").${n}`);for(let o of e)r.addFormat(o,t[o])}dy.exports=ps=Gd;Object.defineProperty(ps,"__esModule",{value:!0});ps.default=Gd});var ii=A((sN,gy)=>{"use strict";var Ek="2.0.0",Ak=Number.MAX_SAFE_INTEGER||9007199254740991,kk=16,xk=250,Pk=["major","premajor","minor","preminor","patch","prepatch","prerelease"];gy.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:kk,MAX_SAFE_BUILD_LENGTH:xk,MAX_SAFE_INTEGER:Ak,RELEASE_TYPES:Pk,SEMVER_SPEC_VERSION:Ek,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var hs=A((oN,by)=>{"use strict";var Ik=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...r)=>console.error("SEMVER",...r):()=>{};by.exports=Ik});var si=A((ur,_y)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:Zd,MAX_SAFE_BUILD_LENGTH:Ok,MAX_LENGTH:Tk}=ii(),Rk=hs();ur=_y.exports={};var Ck=ur.re=[],Mk=ur.safeRe=[],q=ur.src=[],Nk=ur.safeSrc=[],j=ur.t={},Lk=0,eu="[a-zA-Z0-9-]",Dk=[["\\s",1],["\\d",Tk],[eu,Ok]],qk=r=>{for(let[e,t]of Dk)r=r.split(`${e}*`).join(`${e}{0,${t}}`).split(`${e}+`).join(`${e}{1,${t}}`);return r},W=(r,e,t)=>{let n=qk(e),i=Lk++;Rk(r,i,e),j[r]=i,q[i]=e,Nk[i]=n,Ck[i]=new RegExp(e,t?"g":void 0),Mk[i]=new RegExp(n,t?"g":void 0)};W("NUMERICIDENTIFIER","0|[1-9]\\d*");W("NUMERICIDENTIFIERLOOSE","\\d+");W("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${eu}*`);W("MAINVERSION",`(${q[j.NUMERICIDENTIFIER]})\\.(${q[j.NUMERICIDENTIFIER]})\\.(${q[j.NUMERICIDENTIFIER]})`);W("MAINVERSIONLOOSE",`(${q[j.NUMERICIDENTIFIERLOOSE]})\\.(${q[j.NUMERICIDENTIFIERLOOSE]})\\.(${q[j.NUMERICIDENTIFIERLOOSE]})`);W("PRERELEASEIDENTIFIER",`(?:${q[j.NONNUMERICIDENTIFIER]}|${q[j.NUMERICIDENTIFIER]})`);W("PRERELEASEIDENTIFIERLOOSE",`(?:${q[j.NONNUMERICIDENTIFIER]}|${q[j.NUMERICIDENTIFIERLOOSE]})`);W("PRERELEASE",`(?:-(${q[j.PRERELEASEIDENTIFIER]}(?:\\.${q[j.PRERELEASEIDENTIFIER]})*))`);W("PRERELEASELOOSE",`(?:-?(${q[j.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${q[j.PRERELEASEIDENTIFIERLOOSE]})*))`);W("BUILDIDENTIFIER",`${eu}+`);W("BUILD",`(?:\\+(${q[j.BUILDIDENTIFIER]}(?:\\.${q[j.BUILDIDENTIFIER]})*))`);W("FULLPLAIN",`v?${q[j.MAINVERSION]}${q[j.PRERELEASE]}?${q[j.BUILD]}?`);W("FULL",`^${q[j.FULLPLAIN]}$`);W("LOOSEPLAIN",`[v=\\s]*${q[j.MAINVERSIONLOOSE]}${q[j.PRERELEASELOOSE]}?${q[j.BUILD]}?`);W("LOOSE",`^${q[j.LOOSEPLAIN]}$`);W("GTLT","((?:<|>)?=?)");W("XRANGEIDENTIFIERLOOSE",`${q[j.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);W("XRANGEIDENTIFIER",`${q[j.NUMERICIDENTIFIER]}|x|X|\\*`);W("XRANGEPLAIN",`[v=\\s]*(${q[j.XRANGEIDENTIFIER]})(?:\\.(${q[j.XRANGEIDENTIFIER]})(?:\\.(${q[j.XRANGEIDENTIFIER]})(?:${q[j.PRERELEASE]})?${q[j.BUILD]}?)?)?`);W("XRANGEPLAINLOOSE",`[v=\\s]*(${q[j.XRANGEIDENTIFIERLOOSE]})(?:\\.(${q[j.XRANGEIDENTIFIERLOOSE]})(?:\\.(${q[j.XRANGEIDENTIFIERLOOSE]})(?:${q[j.PRERELEASELOOSE]})?${q[j.BUILD]}?)?)?`);W("XRANGE",`^${q[j.GTLT]}\\s*${q[j.XRANGEPLAIN]}$`);W("XRANGELOOSE",`^${q[j.GTLT]}\\s*${q[j.XRANGEPLAINLOOSE]}$`);W("COERCEPLAIN",`(^|[^\\d])(\\d{1,${Zd}})(?:\\.(\\d{1,${Zd}}))?(?:\\.(\\d{1,${Zd}}))?`);W("COERCE",`${q[j.COERCEPLAIN]}(?:$|[^\\d])`);W("COERCEFULL",q[j.COERCEPLAIN]+`(?:${q[j.PRERELEASE]})?(?:${q[j.BUILD]})?(?:$|[^\\d])`);W("COERCERTL",q[j.COERCE],!0);W("COERCERTLFULL",q[j.COERCEFULL],!0);W("LONETILDE","(?:~>?)");W("TILDETRIM",`(\\s*)${q[j.LONETILDE]}\\s+`,!0);ur.tildeTrimReplace="$1~";W("TILDE",`^${q[j.LONETILDE]}${q[j.XRANGEPLAIN]}$`);W("TILDELOOSE",`^${q[j.LONETILDE]}${q[j.XRANGEPLAINLOOSE]}$`);W("LONECARET","(?:\\^)");W("CARETTRIM",`(\\s*)${q[j.LONECARET]}\\s+`,!0);ur.caretTrimReplace="$1^";W("CARET",`^${q[j.LONECARET]}${q[j.XRANGEPLAIN]}$`);W("CARETLOOSE",`^${q[j.LONECARET]}${q[j.XRANGEPLAINLOOSE]}$`);W("COMPARATORLOOSE",`^${q[j.GTLT]}\\s*(${q[j.LOOSEPLAIN]})$|^$`);W("COMPARATOR",`^${q[j.GTLT]}\\s*(${q[j.FULLPLAIN]})$|^$`);W("COMPARATORTRIM",`(\\s*)${q[j.GTLT]}\\s*(${q[j.LOOSEPLAIN]}|${q[j.XRANGEPLAIN]})`,!0);ur.comparatorTrimReplace="$1$2$3";W("HYPHENRANGE",`^\\s*(${q[j.XRANGEPLAIN]})\\s+-\\s+(${q[j.XRANGEPLAIN]})\\s*$`);W("HYPHENRANGELOOSE",`^\\s*(${q[j.XRANGEPLAINLOOSE]})\\s+-\\s+(${q[j.XRANGEPLAINLOOSE]})\\s*$`);W("STAR","(<|>)?=?\\s*\\*");W("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");W("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")});var Xo=A((aN,wy)=>{"use strict";var jk=Object.freeze({loose:!0}),Fk=Object.freeze({}),Vk=r=>r?typeof r!="object"?jk:r:Fk;wy.exports=Vk});var tu=A((cN,Sy)=>{"use strict";var vy=/^[0-9]+$/,$y=(r,e)=>{if(typeof r=="number"&&typeof e=="number")return r===e?0:r$y(e,r);Sy.exports={compareIdentifiers:$y,rcompareIdentifiers:Uk}});var Ue=A((lN,Ay)=>{"use strict";var Qo=hs(),{MAX_LENGTH:Ey,MAX_SAFE_INTEGER:Zo}=ii(),{safeRe:ea,t:ta}=si(),Bk=Xo(),{compareIdentifiers:ru}=tu(),zk=(r,e)=>{let t=e.split(".");if(t.length>r.length)return!1;for(let n=0;nEy)throw new TypeError(`version is longer than ${Ey} characters`);Qo("SemVer",e,t),this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease;let n=e.trim().match(t.loose?ea[ta.LOOSE]:ea[ta.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>Zo||this.major<0)throw new TypeError("Invalid major version");if(this.minor>Zo||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>Zo||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(Qo("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 ru(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(Qo("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 ru(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?ea[ta.PRERELEASELOOSE]:ea[ta.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]),zk(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}};Ay.exports=nu});var Gr=A((dN,xy)=>{"use strict";var ky=Ue(),Hk=(r,e,t=!1)=>{if(r instanceof ky)return r;try{return new ky(r,e)}catch(n){if(!t)return null;throw n}};xy.exports=Hk});var Iy=A((uN,Py)=>{"use strict";var Kk=Gr(),Wk=(r,e)=>{let t=Kk(r,e);return t?t.version:null};Py.exports=Wk});var Ty=A((fN,Oy)=>{"use strict";var Gk=Gr(),Jk=(r,e)=>{let t=Gk(r.trim().replace(/^[=v]+/,""),e);return t?t.version:null};Oy.exports=Jk});var My=A((pN,Cy)=>{"use strict";var Ry=Ue(),Yk=(r,e,t,n,i)=>{typeof t=="string"&&(i=n,n=t,t=void 0);try{return new Ry(r instanceof Ry?r.version:r,t).inc(e,n,i).version}catch(s){return null}};Cy.exports=Yk});var Dy=A((hN,Ly)=>{"use strict";var Ny=Gr(),Xk=(r,e)=>{let t=Ny(r,null,!0),n=Ny(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"};Ly.exports=Xk});var jy=A((mN,qy)=>{"use strict";var Qk=Ue(),Zk=(r,e)=>new Qk(r,e).major;qy.exports=Zk});var Vy=A((yN,Fy)=>{"use strict";var ex=Ue(),tx=(r,e)=>new ex(r,e).minor;Fy.exports=tx});var By=A((gN,Uy)=>{"use strict";var rx=Ue(),nx=(r,e)=>new rx(r,e).patch;Uy.exports=nx});var Hy=A((bN,zy)=>{"use strict";var ix=Gr(),sx=(r,e)=>{let t=ix(r,e);return t&&t.prerelease.length?t.prerelease:null};zy.exports=sx});var Ot=A((_N,Wy)=>{"use strict";var Ky=Ue(),ox=(r,e,t)=>new Ky(r,t).compare(new Ky(e,t));Wy.exports=ox});var Jy=A((wN,Gy)=>{"use strict";var ax=Ot(),cx=(r,e,t)=>ax(e,r,t);Gy.exports=cx});var Xy=A((vN,Yy)=>{"use strict";var lx=Ot(),dx=(r,e)=>lx(r,e,!0);Yy.exports=dx});var ra=A(($N,Zy)=>{"use strict";var Qy=Ue(),ux=(r,e,t)=>{let n=new Qy(r,t),i=new Qy(e,t);return n.compare(i)||n.compareBuild(i)};Zy.exports=ux});var tg=A((SN,eg)=>{"use strict";var fx=ra(),px=(r,e)=>r.sort((t,n)=>fx(t,n,e));eg.exports=px});var ng=A((EN,rg)=>{"use strict";var hx=ra(),mx=(r,e)=>r.sort((t,n)=>hx(n,t,e));rg.exports=mx});var ms=A((AN,ig)=>{"use strict";var yx=Ot(),gx=(r,e,t)=>yx(r,e,t)>0;ig.exports=gx});var na=A((kN,sg)=>{"use strict";var bx=Ot(),_x=(r,e,t)=>bx(r,e,t)<0;sg.exports=_x});var iu=A((xN,og)=>{"use strict";var wx=Ot(),vx=(r,e,t)=>wx(r,e,t)===0;og.exports=vx});var su=A((PN,ag)=>{"use strict";var $x=Ot(),Sx=(r,e,t)=>$x(r,e,t)!==0;ag.exports=Sx});var ia=A((IN,cg)=>{"use strict";var Ex=Ot(),Ax=(r,e,t)=>Ex(r,e,t)>=0;cg.exports=Ax});var sa=A((ON,lg)=>{"use strict";var kx=Ot(),xx=(r,e,t)=>kx(r,e,t)<=0;lg.exports=xx});var ou=A((TN,dg)=>{"use strict";var Px=iu(),Ix=su(),Ox=ms(),Tx=ia(),Rx=na(),Cx=sa(),Mx=(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 Px(r,t,n);case"!=":return Ix(r,t,n);case">":return Ox(r,t,n);case">=":return Tx(r,t,n);case"<":return Rx(r,t,n);case"<=":return Cx(r,t,n);default:throw new TypeError(`Invalid operator: ${e}`)}};dg.exports=Mx});var fg=A((RN,ug)=>{"use strict";var Nx=Ue(),Lx=Gr(),{safeRe:oa,t:aa}=si(),Dx=(r,e)=>{if(r instanceof Nx)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?oa[aa.COERCEFULL]:oa[aa.COERCE]);else{let c=e.includePrerelease?oa[aa.COERCERTLFULL]:oa[aa.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 Lx(`${n}.${i}.${s}${o}${a}`,e)};ug.exports=Dx});var hg=A((CN,pg)=>{"use strict";var qx=Gr(),jx=ii(),Fx=Ue(),Vx=(r,e,t)=>{if(!jx.RELEASE_TYPES.includes(e))return null;let n=Ux(r,t);return n&&Bx(n,e)},Ux=(r,e)=>{let t=r instanceof Fx?r.version:r;return qx(t,e)},Bx=(r,e)=>{if(zx(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()},zx=r=>r.startsWith("pre");pg.exports=Vx});var yg=A((MN,mg)=>{"use strict";var au=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}};mg.exports=au});var Tt=A((NN,wg)=>{"use strict";var Hx=/\s+/g,cu=class r{constructor(e,t){if(t=Wx(t),e instanceof r)return e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease?e:new r(e.raw,t);if(e instanceof lu)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(Hx," "),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=>!bg(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&&rP(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(tP,"");let n=((this.options.includePrerelease&&Zx)|(this.options.loose&&eP))+":"+e,i=gg.get(n);if(i)return i;let s=this.options.loose,o=s?nt[Be.HYPHENRANGELOOSE]:nt[Be.HYPHENRANGE];e=e.replace(o,pP(this.options.includePrerelease)),$e("hyphen replace",e),e=e.replace(nt[Be.COMPARATORTRIM],Yx),$e("comparator trim",e),e=e.replace(nt[Be.TILDETRIM],Xx),$e("tilde trim",e),e=e.replace(nt[Be.CARETTRIM],Qx),$e("caret trim",e);let a=e.split(" ").map(d=>nP(d,this.options)).join(" ").split(/\s+/).map(d=>fP(d,this.options));s&&(a=a.filter(d=>($e("loose invalid filter",d,this.options),!!d.match(nt[Be.COMPARATORLOOSE])))),$e("range list",a);let c=new Map,l=a.map(d=>new lu(d,this.options));for(let d of l){if(bg(d))return[d];c.set(d.value,d)}c.size>1&&c.has("")&&c.delete("");let u=[...c.values()];return gg.set(n,u),u}intersects(e,t){if(!(e instanceof r))throw new TypeError("a Range is required");return this.set.some(n=>_g(n,t)&&e.set.some(i=>_g(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 Gx(e,this.options)}catch(t){return!1}for(let t=0;tr.value==="<0.0.0-0",rP=r=>r.value==="",_g=(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},nP=(r,e)=>(r=r.replace(nt[Be.BUILD],""),$e("comp",r,e),r=aP(r,e),$e("caret",r),r=sP(r,e),$e("tildes",r),r=lP(r,e),$e("xrange",r),r=uP(r,e),$e("stars",r),r),Ce=r=>!r||r.toLowerCase()==="x"||r==="*",iP=(r,e,t)=>Ce(r)&&!Ce(e)||Ce(e)&&t&&!Ce(t),sP=(r,e)=>r.trim().split(/\s+/).map(t=>oP(t,e)).join(" "),oP=(r,e)=>{let t=e.loose?nt[Be.TILDELOOSE]:nt[Be.TILDE],n=e.includePrerelease?"-0":"";return r.replace(t,(i,s,o,a,c)=>{$e("tilde",r,i,s,o,a,c);let l;return Ce(s)?l="":Ce(o)?l=`>=${s}.0.0${n} <${+s+1}.0.0-0`:Ce(a)?l=`>=${s}.${o}.0${n} <${s}.${+o+1}.0-0`:c?($e("replaceTilde pr",c),l=`>=${s}.${o}.${a}-${c} <${s}.${+o+1}.0-0`):l=`>=${s}.${o}.${a} <${s}.${+o+1}.0-0`,$e("tilde return",l),l})},aP=(r,e)=>r.trim().split(/\s+/).map(t=>cP(t,e)).join(" "),cP=(r,e)=>{$e("caret",r,e);let t=e.loose?nt[Be.CARETLOOSE]:nt[Be.CARET],n=e.includePrerelease?"-0":"";return r.replace(t,(i,s,o,a,c)=>{$e("caret",r,i,s,o,a,c);let l;return Ce(s)?l="":Ce(o)?l=`>=${s}.0.0${n} <${+s+1}.0.0-0`:Ce(a)?s==="0"?l=`>=${s}.${o}.0${n} <${s}.${+o+1}.0-0`:l=`>=${s}.${o}.0${n} <${+s+1}.0.0-0`:c?($e("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`):($e("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`),$e("caret return",l),l})},lP=(r,e)=>($e("replaceXRanges",r,e),r.split(/\s+/).map(t=>dP(t,e)).join(" ")),dP=(r,e)=>{r=r.trim();let t=e.loose?nt[Be.XRANGELOOSE]:nt[Be.XRANGE];return r.replace(t,(n,i,s,o,a,c)=>{if($e("xRange",r,n,i,s,o,a,c),iP(s,o,a))return r;let l=Ce(s),u=l||Ce(o),d=u||Ce(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`),$e("xRange return",n),n})},uP=(r,e)=>($e("replaceStars",r,e),r.trim().replace(nt[Be.STAR],"")),fP=(r,e)=>($e("replaceGTE0",r,e),r.trim().replace(nt[e.includePrerelease?Be.GTE0PRE:Be.GTE0],"")),pP=r=>(e,t,n,i,s,o,a,c,l,u,d,f)=>(Ce(n)?t="":Ce(i)?t=`>=${n}.0.0${r?"-0":""}`:Ce(s)?t=`>=${n}.${i}.0${r?"-0":""}`:o?t=`>=${t}`:t=`>=${t}${r?"-0":""}`,Ce(l)?c="":Ce(u)?c=`<${+l+1}.0.0-0`:Ce(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()),hP=(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 ys=A((LN,kg)=>{"use strict";var gs=Symbol("SemVer ANY"),fu=class r{static get ANY(){return gs}constructor(e,t){if(t=vg(t),e instanceof r){if(e.loose===!!t.loose)return e;e=e.value}e=e.trim().split(/\s+/).join(" "),uu("comparator",e,t),this.options=t,this.loose=!!t.loose,this.parse(e),this.semver===gs?this.value="":this.value=this.operator+this.semver.version,uu("comp",this)}parse(e){let t=this.options.loose?$g[Sg.COMPARATORLOOSE]:$g[Sg.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 Eg(n[2],this.options.loose):this.semver=gs}toString(){return this.value}test(e){if(uu("Comparator.test",e,this.options.loose),this.semver===gs||e===gs)return!0;if(typeof e=="string")try{e=new Eg(e,this.options)}catch(t){return!1}return du(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 Ag(e.value,t).test(this.value):e.operator===""?e.value===""?!0:new Ag(this.value,t).test(e.semver):(t=vg(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("=")||du(this.semver,"<",e.semver,t)&&this.operator.startsWith(">")&&e.operator.startsWith("<")||du(this.semver,">",e.semver,t)&&this.operator.startsWith("<")&&e.operator.startsWith(">")))}};kg.exports=fu;var vg=Xo(),{safeRe:$g,t:Sg}=si(),du=ou(),uu=hs(),Eg=Ue(),Ag=Tt()});var bs=A((DN,xg)=>{"use strict";var mP=Tt(),yP=(r,e,t)=>{try{e=new mP(e,t)}catch(n){return!1}return e.test(r)};xg.exports=yP});var Ig=A((qN,Pg)=>{"use strict";var gP=Tt(),bP=(r,e)=>new gP(r,e).set.map(t=>t.map(n=>n.value).join(" ").trim().split(" "));Pg.exports=bP});var Tg=A((jN,Og)=>{"use strict";var _P=Ue(),wP=Tt(),vP=(r,e,t)=>{let n=null,i=null,s=null;try{s=new wP(e,t)}catch(o){return null}return r.forEach(o=>{s.test(o)&&(!n||i.compare(o)===-1)&&(n=o,i=new _P(n,t))}),n};Og.exports=vP});var Cg=A((FN,Rg)=>{"use strict";var $P=Ue(),SP=Tt(),EP=(r,e,t)=>{let n=null,i=null,s=null;try{s=new SP(e,t)}catch(o){return null}return r.forEach(o=>{s.test(o)&&(!n||i.compare(o)===1)&&(n=o,i=new $P(n,t))}),n};Rg.exports=EP});var Lg=A((VN,Ng)=>{"use strict";var pu=Ue(),AP=Tt(),Mg=ms(),kP=(r,e)=>{r=new AP(r,e);let t=new pu("0.0.0");if(r.test(t)||(t=new pu("0.0.0-0"),r.test(t)))return t;t=null;for(let n=0;n{let a=new pu(o.semver.version);switch(o.operator){case">":a.prerelease.length===0?a.patch++:a.prerelease.push(0),a.raw=a.format();case"":case">=":(!s||Mg(a,s))&&(s=a);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${o.operator}`)}}),s&&(!t||Mg(t,s))&&(t=s)}return t&&r.test(t)?t:null};Ng.exports=kP});var qg=A((UN,Dg)=>{"use strict";var xP=Tt(),PP=(r,e)=>{try{return new xP(r,e).range||"*"}catch(t){return null}};Dg.exports=PP});var ca=A((BN,Ug)=>{"use strict";var IP=Ue(),Vg=ys(),{ANY:OP}=Vg,TP=Tt(),RP=bs(),jg=ms(),Fg=na(),CP=sa(),MP=ia(),NP=(r,e,t,n)=>{r=new IP(r,n),e=new TP(e,n);let i,s,o,a,c;switch(t){case">":i=jg,s=CP,o=Fg,a=">",c=">=";break;case"<":i=Fg,s=MP,o=jg,a="<",c="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(RP(r,e,n))return!1;for(let l=0;l{p.semver===OP&&(p=new Vg(">=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};Ug.exports=NP});var zg=A((zN,Bg)=>{"use strict";var LP=ca(),DP=(r,e,t)=>LP(r,e,">",t);Bg.exports=DP});var Kg=A((HN,Hg)=>{"use strict";var qP=ca(),jP=(r,e,t)=>qP(r,e,"<",t);Hg.exports=jP});var Jg=A((KN,Gg)=>{"use strict";var Wg=Tt(),FP=(r,e,t)=>(r=new Wg(r,t),e=new Wg(e,t),r.intersects(e,t));Gg.exports=FP});var Xg=A((WN,Yg)=>{"use strict";var VP=bs(),UP=Ot();Yg.exports=(r,e,t)=>{let n=[],i=null,s=null,o=r.sort((u,d)=>UP(u,d,t));for(let u of o)VP(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 Qg=Tt(),yu=ys(),{ANY:hu}=yu,mu=bs(),gu=Ot(),BP=(r,e,t={})=>{if(r===e)return!0;r=new Qg(r,t),e=new Qg(e,t);let n=!1;e:for(let i of r.set){for(let s of e.set){let o=HP(i,s,t);if(n=n||o!==null,o)continue e}if(n)return!1}return!0},zP=[new yu(">=0.0.0-0")],Zg=[new yu(">=0.0.0")],HP=(r,e,t)=>{if(r===e)return!0;if(r.length===1&&r[0].semver===hu){if(e.length===1&&e[0].semver===hu)return!0;t.includePrerelease?r=zP:r=Zg}if(e.length===1&&e[0].semver===hu){if(t.includePrerelease)return!0;e=Zg}let n=new Set,i,s;for(let p of r)p.operator===">"||p.operator===">="?i=eb(i,p,t):p.operator==="<"||p.operator==="<="?s=tb(s,p,t):n.add(p.semver);if(n.size>1)return null;let o;if(i&&s){if(o=gu(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&&!mu(p,String(i),t)||s&&!mu(p,String(s),t))return null;for(let m of e)if(!mu(p,String(m),t))return!1;return!0}let a,c,l,u,d=s&&!t.includePrerelease&&s.semver.prerelease.length?s.semver:!1,f=i&&!t.includePrerelease&&i.semver.prerelease.length?i.semver:!1;d&&d.prerelease.length===1&&s.operator==="<"&&d.prerelease[0]===0&&(d=!1);for(let p of e){if(u=u||p.operator===">"||p.operator===">=",l=l||p.operator==="<"||p.operator==="<=",i){if(f&&p.semver.prerelease&&p.semver.prerelease.length&&p.semver.major===f.major&&p.semver.minor===f.minor&&p.semver.patch===f.patch&&(f=!1),p.operator===">"||p.operator===">="){if(a=eb(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=tb(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)},eb=(r,e,t)=>{if(!r)return e;let n=gu(r.semver,e.semver,t);return n>0?r:n<0||e.operator===">"&&r.operator===">="?e:r},tb=(r,e,t)=>{if(!r)return e;let n=gu(r.semver,e.semver,t);return n<0?r:n>0||e.operator==="<"&&r.operator==="<="?e:r};rb.exports=BP});var ab=A((JN,ob)=>{"use strict";var bu=si(),ib=ii(),KP=Ue(),sb=tu(),WP=Gr(),GP=Iy(),JP=Ty(),YP=My(),XP=Dy(),QP=jy(),ZP=Vy(),eI=By(),tI=Hy(),rI=Ot(),nI=Jy(),iI=Xy(),sI=ra(),oI=tg(),aI=ng(),cI=ms(),lI=na(),dI=iu(),uI=su(),fI=ia(),pI=sa(),hI=ou(),mI=fg(),yI=hg(),gI=ys(),bI=Tt(),_I=bs(),wI=Ig(),vI=Tg(),$I=Cg(),SI=Lg(),EI=qg(),AI=ca(),kI=zg(),xI=Kg(),PI=Jg(),II=Xg(),OI=nb();ob.exports={parse:WP,valid:GP,clean:JP,inc:YP,diff:XP,major:QP,minor:ZP,patch:eI,prerelease:tI,compare:rI,rcompare:nI,compareLoose:iI,compareBuild:sI,sort:oI,rsort:aI,gt:cI,lt:lI,eq:dI,neq:uI,gte:fI,lte:pI,cmp:hI,coerce:mI,truncate:yI,Comparator:gI,Range:bI,satisfies:_I,toComparators:wI,maxSatisfying:vI,minSatisfying:$I,minVersion:SI,validRange:EI,outside:AI,gtr:kI,ltr:xI,intersects:PI,simplifyRange:II,subset:OI,SemVer:KP,re:bu.re,src:bu.src,tokens:bu.t,SEMVER_SPEC_VERSION:ib.SEMVER_SPEC_VERSION,RELEASE_TYPES:ib.RELEASE_TYPES,compareIdentifiers:sb.compareIdentifiers,rcompareIdentifiers:sb.rcompareIdentifiers}});var ws=A((p2,gb)=>{"use strict";var pb="[^\\\\/]",jI="(?=.)",hb="[^/]",Su="(?:\\/|$)",mb="(?:^|\\/)",Eu=`\\.{1,2}${Su}`,FI="(?!\\.)",VI=`(?!${mb}${Eu})`,UI=`(?!\\.{0,1}${Su})`,BI=`(?!${Eu})`,zI="[^.\\/]",HI=`${hb}*?`,KI="/",yb={DOT_LITERAL:"\\.",PLUS_LITERAL:"\\+",QMARK_LITERAL:"\\?",SLASH_LITERAL:"\\/",ONE_CHAR:jI,QMARK:hb,END_ANCHOR:Su,DOTS_SLASH:Eu,NO_DOT:FI,NO_DOTS:VI,NO_DOT_SLASH:UI,NO_DOTS_SLASH:BI,QMARK_NO_DOT:zI,STAR:HI,START_ANCHOR:mb,SEP:KI},WI={...yb,SLASH_LITERAL:"[\\\\/]",QMARK:pb,STAR:`${pb}*?`,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:"\\"},GI={__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"};gb.exports={DEFAULT_MAX_EXTGLOB_RECURSION:0,MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:GI,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?WI:yb}}});var vs=A(pt=>{"use strict";var{REGEX_BACKSLASH:JI,REGEX_REMOVE_BACKSLASH:YI,REGEX_SPECIAL_CHARS:XI,REGEX_SPECIAL_CHARS_GLOBAL:QI}=ws();pt.isObject=r=>r!==null&&typeof r=="object"&&!Array.isArray(r);pt.hasRegexChars=r=>XI.test(r);pt.isRegexChar=r=>r.length===1&&pt.hasRegexChars(r);pt.escapeRegex=r=>r.replace(QI,"\\$1");pt.toPosixSlashes=r=>r.replace(JI,"/");pt.isWindows=()=>{if(typeof navigator!="undefined"&&navigator.platform){let r=navigator.platform.toLowerCase();return r==="win32"||r==="windows"}return typeof process!="undefined"&&process.platform?process.platform==="win32":!1};pt.removeBackslashes=r=>r.replace(YI,e=>e==="\\"?"":e);pt.escapeLast=(r,e,t)=>{let n=r.lastIndexOf(e,t);return n===-1?r:r[n-1]==="\\"?pt.escapeLast(r,e,n-1):`${r.slice(0,n)}\\${r.slice(n)}`};pt.removePrefix=(r,e={})=>{let t=r;return t.startsWith("./")&&(t=t.slice(2),e.prefix="./"),t};pt.wrapOutput=(r,e={},t={})=>{let n=t.contains?"":"^",i=t.contains?"":"$",s=`${n}(?:${r})${i}`;return e.negated===!0&&(s=`(?:^(?!${s}).*$)`),s};pt.basename=(r,{windows:e}={})=>{let t=r.split(e?/[\\/]/:"/"),n=t[t.length-1];return n===""?t[t.length-2]:n}});var Ab=A((m2,Eb)=>{"use strict";var bb=vs(),{CHAR_ASTERISK:Au,CHAR_AT:ZI,CHAR_BACKWARD_SLASH:$s,CHAR_COMMA:eO,CHAR_DOT:ku,CHAR_EXCLAMATION_MARK:xu,CHAR_FORWARD_SLASH:Sb,CHAR_LEFT_CURLY_BRACE:Pu,CHAR_LEFT_PARENTHESES:Iu,CHAR_LEFT_SQUARE_BRACKET:tO,CHAR_PLUS:rO,CHAR_QUESTION_MARK:_b,CHAR_RIGHT_CURLY_BRACE:nO,CHAR_RIGHT_PARENTHESES:wb,CHAR_RIGHT_SQUARE_BRACKET:iO}=ws(),vb=r=>r===Sb||r===$s,$b=r=>{r.isPrefix!==!0&&(r.depth=r.isGlobstar?1/0:1)},sO=(r,e)=>{let t=e||{},n=r.length-1,i=t.parts===!0||t.scanToEnd===!0,s=[],o=[],a=[],c=r,l=-1,u=0,d=0,f=!1,p=!1,m=!1,h=!1,y=!1,b=!1,g=!1,_=!1,k=!1,v=!1,E=0,O,w,x={value:"",depth:0,isGlob:!1},$=()=>l>=n,L=()=>c.charCodeAt(l+1),F=()=>(O=w,c.charCodeAt(++l));for(;l0&&(P=c.slice(0,u),c=c.slice(u),d-=u),z&&m===!0&&d>0?(z=c.slice(0,d),I=c.slice(d)):m===!0?(z="",I=c):z=c,z&&z!==""&&z!=="/"&&z!==c&&vb(z.charCodeAt(z.length-1))&&(z=z.slice(0,-1)),t.unescape===!0&&(I&&(I=bb.removeBackslashes(I)),z&&g===!0&&(z=bb.removeBackslashes(z)));let ke={prefix:P,input:r,start:u,base:z,glob:I,isBrace:f,isBracket:p,isGlob:m,isExtglob:h,isGlobstar:y,negated:_,negatedExtglob:k};if(t.tokens===!0&&(ke.maxDepth=0,vb(w)||o.push(x),ke.tokens=o),t.parts===!0||t.tokens===!0){let ce;for(let de=0;de{"use strict";var Ss=ws(),_t=vs(),{MAX_LENGTH:fa,POSIX_REGEX_SOURCE:oO,REGEX_NON_SPECIAL_CHARS:aO,REGEX_SPECIAL_CHARS_BACKREF:cO,REPLACEMENTS:kb}=Ss,lO=(r,e)=>{if(typeof e.expandRange=="function")return e.expandRange(...r,e);r.sort();let t=`[${r.join("-")}]`;try{new RegExp(t)}catch(n){return r.map(i=>_t.escapeRegex(i)).join("..")}return t},oi=(r,e)=>`Missing ${r}: "${e}" - use "\\\\${e}" to match literal characters`,xb=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},dO=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},Tu=r=>{let e=r.trim(),t=!0;for(;t===!0;)t=!1,/^@\([^\\()[\]{}|]+\)$/.test(e)&&(e=e.slice(2,-1),t=!0);if(dO(e))return e.replace(/\\(.)/g,"$1")},uO=r=>{let e=r.map(Tu).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}}}}},fO=r=>`${r.length===1?_t.escapeRegex(r[0]):`[${r.map(t=>_t.escapeRegex(t)).join("")}]`}*`,pO=r=>{let e=0,t=[];for(;eo.trim());if(i.length!==1)return;let s=Tu(i[0]);if(!s||s.length!==1)return;t.push(s),e+=n.end+1}if(!(t.length<1))return t},hO=r=>{let e=0,t=r.trim(),n=Ou(t);for(;n;)e++,t=n.body.trim(),n=Ou(t);return e},mO=(r,e)=>{if(e.maxExtglobRecursion===!1)return{risky:!1};let t=typeof e.maxExtglobRecursion=="number"?e.maxExtglobRecursion:Ss.DEFAULT_MAX_EXTGLOB_RECURSION,n=xb(r).map(a=>a.trim());if(n.length>1&&(n.some(a=>a==="")||n.some(a=>/^[*?]+$/.test(a))||uO(n)))return{risky:!0};let i=[],s=!1,o=!0;for(let a of n){let c=pO(a);if(c){s=!0,i.push(...c);continue}let l=Tu(a);if(l&&l.length===1){i.push(l);continue}if(o=!1,hO(a)>t)return{risky:!0}}return s?o?{risky:!0,safeOutput:fO([...new Set(i)])}:{risky:!0}:{risky:!1}},Ru=(r,e)=>{if(typeof r!="string")throw new TypeError("Expected a string");r=kb[r]||r;let t={...e},n=typeof t.maxLength=="number"?Math.min(fa,t.maxLength):fa,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=Ss.globChars(t.windows),l=Ss.extglobChars(c),{DOT_LITERAL:u,PLUS_LITERAL:d,SLASH_LITERAL:f,ONE_CHAR:p,DOTS_SLASH:m,NO_DOT:h,NO_DOT_SLASH:y,NO_DOTS_SLASH:b,QMARK:g,QMARK_NO_DOT:_,STAR:k,START_ANCHOR:v}=c,E=R=>`(${a}(?:(?!${v}${R.dot?m:u}).)*?)`,O=t.dot?"":h,w=t.dot?g:_,x=t.bash===!0?E(t):k;t.capture&&(x=`(${x})`),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=_t.removePrefix(r,$),i=r.length;let L=[],F=[],z=[],P=s,I,ke=()=>$.index===i-1,ce=$.peek=(R=1)=>r[$.index+R],de=$.advance=()=>r[++$.index]||"",Et=()=>r.slice($.index+1),Ze=(R="",fe=0)=>{$.consumed+=R,$.index+=fe},Lt=R=>{$.output+=R.output!=null?R.output:R.value,Ze(R.value)},fo=()=>{let R=1;for(;ce()==="!"&&(ce(2)!=="("||ce(3)==="?");)de(),$.start++,R++;return R%2===0?!1:($.negated=!0,$.start++,!0)},cn=R=>{$[R]++,z.push(R)},U=R=>{$[R]--,z.pop()},M=R=>{if(P.type==="globstar"){let fe=$.braces>0&&(R.type==="comma"||R.type==="brace"),C=R.extglob===!0||L.length&&(R.type==="pipe"||R.type==="paren");R.type!=="slash"&&R.type!=="paren"&&!fe&&!C&&($.output=$.output.slice(0,-P.output.length),P.type="star",P.value="*",P.output=x,$.output+=P.output)}if(L.length&&R.type!=="paren"&&(L[L.length-1].inner+=R.value),(R.value||R.output)&&Lt(R),P&&P.type==="text"&&R.type==="text"){P.output=(P.output||P.value)+R.value,P.value+=R.value;return}R.prev=P,o.push(R),P=R},te=(R,fe)=>{let C={...l[fe],conditions:1,inner:""};C.prev=P,C.parens=$.parens,C.output=$.output,C.startIndex=$.index,C.tokensIndex=o.length;let X=(t.capture?"(":"")+C.open;cn("parens"),M({type:R,value:fe,output:$.output?"":p}),M({type:"paren",extglob:!0,value:de(),output:X}),L.push(C)},et=R=>{let fe=r.slice(R.startIndex,$.index+1),C=r.slice(R.startIndex+2,$.index),X=mO(C,t);if((R.type==="plus"||R.type==="star")&&X.risky){let ye=X.safeOutput?(R.output?"":p)+(t.capture?`(${X.safeOutput})`:X.safeOutput):void 0,nr=o[R.tokensIndex];nr.type="text",nr.value=fe,nr.output=ye||_t.escapeRegex(fe);for(let ir=R.tokensIndex+1;ir1&&R.inner.includes("/")&&(ye=E(t)),(ye!==x||ke()||/^\)+$/.test(Et()))&&(be=R.close=`)$))${ye}`),R.inner.includes("*")&&(Re=Et())&&/^\.[^\\/.]+$/.test(Re)){let nr=Ru(Re,{...e,fastpaths:!1}).output;be=R.close=`)${nr})${ye})`}R.prev.type==="bos"&&($.negatedExtglob=!0)}M({type:"paren",extglob:!0,value:I,output:be}),U("parens")};if(t.fastpaths!==!1&&!/(^[*!]|[/()[\]{}"])/.test(r)){let R=!1,fe=r.replace(cO,(C,X,be,Re,ye,nr)=>Re==="\\"?(R=!0,C):Re==="?"?X?X+Re+(ye?g.repeat(ye.length):""):nr===0?w+(ye?g.repeat(ye.length):""):g.repeat(be.length):Re==="."?u.repeat(be.length):Re==="*"?X?X+Re+(ye?x:""):x:X?C:`\\${C}`);return R===!0&&(t.unescape===!0?fe=fe.replace(/\\/g,""):fe=fe.replace(/\\+/g,C=>C.length%2===0?"\\\\":C?"\\":"")),fe===r&&t.contains===!0?($.output=r,$):($.output=_t.wrapOutput(fe,$,e),$)}for(;!ke();){if(I=de(),I==="\0")continue;if(I==="\\"){let C=ce();if(C==="/"&&t.bash!==!0||C==="."||C===";")continue;if(!C){I+="\\",M({type:"text",value:I});continue}let X=/^\\+/.exec(Et()),be=0;if(X&&X[0].length>2&&(be=X[0].length,$.index+=be,be%2!==0&&(I+="\\")),t.unescape===!0?I=de():I+=de(),$.brackets===0){M({type:"text",value:I});continue}}if($.brackets>0&&(I!=="]"||P.value==="["||P.value==="[^")){if(t.posix!==!1&&I===":"){let C=P.value.slice(1);if(C.includes("[")&&(P.posix=!0,C.includes(":"))){let X=P.value.lastIndexOf("["),be=P.value.slice(0,X),Re=P.value.slice(X+2),ye=oO[Re];if(ye){P.value=be+ye,$.backtrack=!0,de(),!s.output&&o.indexOf(P)===1&&(s.output=p);continue}}}(I==="["&&ce()!==":"||I==="-"&&ce()==="]")&&(I=`\\${I}`),I==="]"&&(P.value==="["||P.value==="[^")&&(I=`\\${I}`),t.posix===!0&&I==="!"&&P.value==="["&&(I="^"),P.value+=I,Lt({value:I});continue}if($.quotes===1&&I!=='"'){I=_t.escapeRegex(I),P.value+=I,Lt({value:I});continue}if(I==='"'){$.quotes=$.quotes===1?0:1,t.keepQuotes===!0&&M({type:"text",value:I});continue}if(I==="("){cn("parens"),M({type:"paren",value:I});continue}if(I===")"){if($.parens===0&&t.strictBrackets===!0)throw new SyntaxError(oi("opening","("));let C=L[L.length-1];if(C&&$.parens===C.parens+1){et(L.pop());continue}M({type:"paren",value:I,output:$.parens?")":"\\)"}),U("parens");continue}if(I==="["){if(t.nobracket===!0||!Et().includes("]")){if(t.nobracket!==!0&&t.strictBrackets===!0)throw new SyntaxError(oi("closing","]"));I=`\\${I}`}else cn("brackets");M({type:"bracket",value:I});continue}if(I==="]"){if(t.nobracket===!0||P&&P.type==="bracket"&&P.value.length===1){M({type:"text",value:I,output:`\\${I}`});continue}if($.brackets===0){if(t.strictBrackets===!0)throw new SyntaxError(oi("opening","["));M({type:"text",value:I,output:`\\${I}`});continue}U("brackets");let C=P.value.slice(1);if(P.posix!==!0&&C[0]==="^"&&!C.includes("/")&&(I=`/${I}`),P.value+=I,Lt({value:I}),t.literalBrackets===!1||_t.hasRegexChars(C))continue;let X=_t.escapeRegex(P.value);if($.output=$.output.slice(0,-P.value.length),t.literalBrackets===!0){$.output+=X,P.value=X;continue}P.value=`(${a}${X}|${P.value})`,$.output+=P.value;continue}if(I==="{"&&t.nobrace!==!0){cn("braces");let C={type:"brace",value:I,output:"(",outputIndex:$.output.length,tokensIndex:$.tokens.length};F.push(C),M(C);continue}if(I==="}"){let C=F[F.length-1];if(t.nobrace===!0||!C){M({type:"text",value:I,output:I});continue}let X=")";if(C.dots===!0){let be=o.slice(),Re=[];for(let ye=be.length-1;ye>=0&&(o.pop(),be[ye].type!=="brace");ye--)be[ye].type!=="dots"&&Re.unshift(be[ye].value);X=lO(Re,t),$.backtrack=!0}if(C.comma!==!0&&C.dots!==!0){let be=$.output.slice(0,C.outputIndex),Re=$.tokens.slice(C.tokensIndex);C.value=C.output="\\{",I=X="\\}",$.output=be;for(let ye of Re)$.output+=ye.output||ye.value}M({type:"brace",value:I,output:X}),U("braces"),F.pop();continue}if(I==="|"){L.length>0&&L[L.length-1].conditions++,M({type:"text",value:I});continue}if(I===","){let C=I,X=F[F.length-1];X&&z[z.length-1]==="braces"&&(X.comma=!0,C="|"),M({type:"comma",value:I,output:C});continue}if(I==="/"){if(P.type==="dot"&&$.index===$.start+1){$.start=$.index+1,$.consumed="",$.output="",o.pop(),P=s;continue}M({type:"slash",value:I,output:f});continue}if(I==="."){if($.braces>0&&P.type==="dot"){P.value==="."&&(P.output=u);let C=F[F.length-1];P.type="dots",P.output+=I,P.value+=I,C.dots=!0;continue}if($.braces+$.parens===0&&P.type!=="bos"&&P.type!=="slash"){M({type:"text",value:I,output:u});continue}M({type:"dot",value:I,output:u});continue}if(I==="?"){if(!(P&&P.value==="(")&&t.noextglob!==!0&&ce()==="("&&ce(2)!=="?"){te("qmark",I);continue}if(P&&P.type==="paren"){let X=ce(),be=I;(P.value==="("&&!/[!=<:]/.test(X)||X==="<"&&!/<([!=]|\w+>)/.test(Et()))&&(be=`\\${I}`),M({type:"text",value:I,output:be});continue}if(t.dot!==!0&&(P.type==="slash"||P.type==="bos")){M({type:"qmark",value:I,output:_});continue}M({type:"qmark",value:I,output:g});continue}if(I==="!"){if(t.noextglob!==!0&&ce()==="("&&(ce(2)!=="?"||!/[!=<:]/.test(ce(3)))){te("negate",I);continue}if(t.nonegate!==!0&&$.index===0){fo();continue}}if(I==="+"){if(t.noextglob!==!0&&ce()==="("&&ce(2)!=="?"){te("plus",I);continue}if(P&&P.value==="("||t.regex===!1){M({type:"plus",value:I,output:d});continue}if(P&&(P.type==="bracket"||P.type==="paren"||P.type==="brace")||$.parens>0){M({type:"plus",value:I});continue}M({type:"plus",value:d});continue}if(I==="@"){if(t.noextglob!==!0&&ce()==="("&&ce(2)!=="?"){M({type:"at",extglob:!0,value:I,output:""});continue}M({type:"text",value:I});continue}if(I!=="*"){(I==="$"||I==="^")&&(I=`\\${I}`);let C=aO.exec(Et());C&&(I+=C[0],$.index+=C[0].length),M({type:"text",value:I});continue}if(P&&(P.type==="globstar"||P.star===!0)){P.type="star",P.star=!0,P.value+=I,P.output=x,$.backtrack=!0,$.globstar=!0,Ze(I);continue}let R=Et();if(t.noextglob!==!0&&/^\([^?]/.test(R)){te("star",I);continue}if(P.type==="star"){if(t.noglobstar===!0){Ze(I);continue}let C=P.prev,X=C.prev,be=C.type==="slash"||C.type==="bos",Re=X&&(X.type==="star"||X.type==="globstar");if(t.bash===!0&&(!be||R[0]&&R[0]!=="/")){M({type:"star",value:I,output:""});continue}let ye=$.braces>0&&(C.type==="comma"||C.type==="brace"),nr=L.length&&(C.type==="pipe"||C.type==="paren");if(!be&&C.type!=="paren"&&!ye&&!nr){M({type:"star",value:I,output:""});continue}for(;R.slice(0,3)==="/**";){let ir=r[$.index+4];if(ir&&ir!=="/")break;R=R.slice(3),Ze("/**",3)}if(C.type==="bos"&&ke()){P.type="globstar",P.value+=I,P.output=E(t),$.output=P.output,$.globstar=!0,Ze(I);continue}if(C.type==="slash"&&C.prev.type!=="bos"&&!Re&&ke()){$.output=$.output.slice(0,-(C.output+P.output).length),C.output=`(?:${C.output}`,P.type="globstar",P.output=E(t)+(t.strictSlashes?")":"|$)"),P.value+=I,$.globstar=!0,$.output+=C.output+P.output,Ze(I);continue}if(C.type==="slash"&&C.prev.type!=="bos"&&R[0]==="/"){let ir=R[1]!==void 0?"|$":"";$.output=$.output.slice(0,-(C.output+P.output).length),C.output=`(?:${C.output}`,P.type="globstar",P.output=`${E(t)}${f}|${f}${ir})`,P.value+=I,$.output+=C.output+P.output,$.globstar=!0,Ze(I+de()),M({type:"slash",value:"/",output:""});continue}if(C.type==="bos"&&R[0]==="/"){P.type="globstar",P.value+=I,P.output=`(?:^|${f}|${E(t)}${f})`,$.output=P.output,$.globstar=!0,Ze(I+de()),M({type:"slash",value:"/",output:""});continue}$.output=$.output.slice(0,-P.output.length),P.type="globstar",P.output=E(t),P.value+=I,$.output+=P.output,$.globstar=!0,Ze(I);continue}let fe={type:"star",value:I,output:x};if(t.bash===!0){fe.output=".*?",(P.type==="bos"||P.type==="slash")&&(fe.output=O+fe.output),M(fe);continue}if(P&&(P.type==="bracket"||P.type==="paren")&&t.regex===!0){fe.output=I,M(fe);continue}($.index===$.start||P.type==="slash"||P.type==="dot")&&(P.type==="dot"?($.output+=y,P.output+=y):t.dot===!0?($.output+=b,P.output+=b):($.output+=O,P.output+=O),ce()!=="*"&&($.output+=p,P.output+=p)),M(fe)}for(;$.brackets>0;){if(t.strictBrackets===!0)throw new SyntaxError(oi("closing","]"));$.output=_t.escapeLast($.output,"["),U("brackets")}for(;$.parens>0;){if(t.strictBrackets===!0)throw new SyntaxError(oi("closing",")"));$.output=_t.escapeLast($.output,"("),U("parens")}for(;$.braces>0;){if(t.strictBrackets===!0)throw new SyntaxError(oi("closing","}"));$.output=_t.escapeLast($.output,"{"),U("braces")}if(t.strictSlashes!==!0&&(P.type==="star"||P.type==="bracket")&&M({type:"maybe_slash",value:"",output:`${f}?`}),$.backtrack===!0){$.output="";for(let R of $.tokens)$.output+=R.output!=null?R.output:R.value,R.suffix&&($.output+=R.suffix)}return $};Ru.fastpaths=(r,e)=>{let t={...e},n=typeof t.maxLength=="number"?Math.min(fa,t.maxLength):fa,i=r.length;if(i>n)throw new SyntaxError(`Input length: ${i}, exceeds maximum allowed length: ${n}`);r=kb[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}=Ss.globChars(t.windows),m=t.dot?u:l,h=t.dot?d:l,y=t.capture?"":"?:",b={negated:!1,prefix:""},g=t.bash===!0?".*?":f;t.capture&&(g=`(${g})`);let _=O=>O.noglobstar===!0?g:`(${y}(?:(?!${p}${O.dot?c:s}).)*?)`,k=O=>{switch(O){case"*":return`${m}${a}${g}`;case".*":return`${s}${a}${g}`;case"*.*":return`${m}${g}${s}${a}${g}`;case"*/*":return`${m}${g}${o}${a}${h}${g}`;case"**":return m+_(t);case"**/*":return`(?:${m}${_(t)}${o})?${h}${a}${g}`;case"**/*.*":return`(?:${m}${_(t)}${o})?${h}${g}${s}${a}${g}`;case"**/.*":return`(?:${m}${_(t)}${o})?${s}${a}${g}`;default:{let w=/^(.*?)\.(\w+)$/.exec(O);if(!w)return;let x=k(w[1]);return x?x+s+w[2]:void 0}}},v=_t.removePrefix(r,b),E=k(v);return E&&t.strictSlashes!==!0&&(E+=`${o}?`),E};Pb.exports=Ru});var Rb=A((g2,Tb)=>{"use strict";var yO=Ab(),Cu=Ib(),Ob=vs(),gO=ws(),bO=r=>r&&typeof r=="object"&&!Array.isArray(r),Pe=(r,e,t=!1)=>{if(Array.isArray(r)){let u=r.map(f=>Pe(f,e,t));return f=>{for(let p of u){let m=p(f);if(m)return m}return!1}}let n=bO(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?Pe.compileRe(r,e):Pe.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=Pe(i.ignore,u,t)}let l=(u,d=!1)=>{let{isMatch:f,match:p,output:m}=Pe.test(u,o,e,{glob:r,posix:s}),h={glob:r,state:a,regex:o,posix:s,input:u,output:m,match:p,isMatch:f};return typeof i.onResult=="function"&&i.onResult(h),f===!1?(h.isMatch=!1,d?h:!1):c(u)?(typeof i.onIgnore=="function"&&i.onIgnore(h),h.isMatch=!1,d?h:!1):(typeof i.onMatch=="function"&&i.onMatch(h),d?h:!0)};return t&&(l.state=a),l};Pe.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?Ob.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=Pe.matchBase(r,e,t,i):a=e.exec(c)),{isMatch:!!a,match:a,output:c}};Pe.matchBase=(r,e,t,n=t&&t.windows)=>(e instanceof RegExp?e:Pe.makeRe(e,t)).test(Ob.basename(r,{windows:n}));Pe.isMatch=(r,e,t)=>Pe(e,t)(r);Pe.parse=(r,e)=>Array.isArray(r)?r.map(t=>Pe.parse(t,e)):Cu(r,{...e,fastpaths:!1});Pe.scan=(r,e)=>yO(r,e);Pe.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=Pe.toRegex(a,e);return n===!0&&(c.state=r),c};Pe.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=Cu.fastpaths(r,e)),i.output||(i=Cu(r,e)),Pe.compileRe(i,e,t,n)};Pe.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/$^/}};Pe.constants=gO;Tb.exports=Pe});var Mu=A((b2,Nb)=>{"use strict";var Cb=Rb(),_O=vs();function Mb(r,e,t=!1){return e&&(e.windows===null||e.windows===void 0)&&(e={...e,windows:_O.isWindows()}),Cb(r,e,t)}Object.assign(Mb,Cb);Nb.exports=Mb});var fC={};i0(fC,{default:()=>Tc});module.exports=s0(fC);var D=require("obsidian");var N=class extends Error{constructor(t,n,i){super(n);T(this,"code");T(this,"details");this.code=t,this.details=i,this.name="InteropError"}toPortableError(t){return{code:this.code,message:this.message,...this.details===void 0?{}:{details:this.details},...t===void 0?{}:{retryable:t}}}},Li=class extends Error{constructor(t,n){super(n.message);T(this,"status");T(this,"error");this.status=t,this.error=n,this.name="ActionHandlerError"}};var uy=ln(jd(),1),fy=ln(Jd(),1);var Yd={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 $k=fy.default;function py(){return Object.fromEntries(Object.entries(Yd).map(([r,e])=>[r,structuredClone(e)]))}function Xd(){let r=new uy.Ajv2020({allErrors:!0,strict:!1,validateFormats:!0});$k(r);let e=py();r.addSchema(e.profile);for(let[t,n]of Object.entries(e))t!=="profile"&&r.addSchema(n);return r}function $r(r,e){let t=String(Yd[e].$id),n=r.getSchema(t);if(!n)throw new Error(`Canonical interoperability schema is unavailable: ${e}`);return n}function Wr(r){return(r!=null?r:[]).map(e=>{var t;return`${e.instancePath||"/"} ${(t=e.message)!=null?t:e.keyword}`}).join("; ")}function dr(r,e){if(!("value"in r))throw new N("contract_digest_conflict",`${e} must be resolved to an inline JSON Schema before runtime registration.`);return structuredClone(r.value)}function hy(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=dr(r.record_schema,"record_schema"),r.binding_schema&&(e.binding_schema=dr(r.binding_schema,"binding_schema"));break;case"event":e.data_schema=dr(r.data_schema,"data_schema"),r.source_schema&&(e.source_schema=dr(r.source_schema,"source_schema"));break;case"action":e.input_schema=dr(r.input_schema,"input_schema"),r.output_schema&&(e.output_schema=dr(r.output_schema,"output_schema")),r.error_schema&&(e.error_schema=dr(r.error_schema,"error_schema")),r.provider_schema&&(e.provider_schema=dr(r.provider_schema,"provider_schema")),r.behavior&&(e.behavior=structuredClone(r.behavior));break}return e}async function Jo(r){return ni(hy(r))}async function ni(r){return`sha256:${await Sk(Qd(r))}`}function my(r,e){return{data:ri(r,e.data_schema,`${e.id} data_schema`),...e.source_schema?{source:ri(r,e.source_schema,`${e.id} source_schema`)}:{}}}function yy(r,e){return{input:ri(r,e.input_schema,`${e.id} input_schema`),...e.output_schema?{output:ri(r,e.output_schema,`${e.id} output_schema`)}:{},...e.error_schema?{error:ri(r,e.error_schema,`${e.id} error_schema`)}:{},...e.provider_schema?{provider:ri(r,e.provider_schema,`${e.id} provider_schema`)}:{}}}function Yo(r,e,t,n){if(!(!r||r(e)))throw new N(t,`${n} failed JSON Schema validation: ${Wr(r.errors)}`)}function ri(r,e,t){try{return r.compile(dr(e,t))}catch(n){throw new N("contract_digest_conflict",`${t} could not be compiled: ${n instanceof Error?n.message:String(n)}`)}}function Qd(r){return r===null||typeof r!="object"?JSON.stringify(r):Array.isArray(r)?`[${r.map(Qd).join(",")}]`:`{${Object.entries(r).filter(([,t])=>t!==void 0).sort(([t],[n])=>tn?1:0).map(([t,n])=>`${JSON.stringify(t)}:${Qd(n)}`).join(",")}}`}async function Sk(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 Er=ln(ab(),1);var _u={delivery:["ephemeral"],ordering:["none"],cancellation:!0,deadlines:!0,provider_discovery:!0,request_deduplication:!0,cross_process_identity:!1},TI=new Set(["specversion","id","source","type","time","subject","datacontenttype","dataschema","data","mdbaseprofile","mdbasecontractversion","mdbasecontractdigest","mdbaseapplication","mdbaseimplementation","mdbaseimplementationversion","mdbaseinstanceid","correlationid","causationid"]),_s=class{constructor(e={}){T(this,"options");T(this,"profileVersion","0.1");T(this,"transport");T(this,"ajv",Xd());T(this,"contractValidator",$r(this.ajv,"contract"));T(this,"eventValidator",$r(this.ajv,"event"));T(this,"actionRequestValidator",$r(this.ajv,"actionRequest"));T(this,"actionInvocationValidator",$r(this.ajv,"actionInvocation"));T(this,"actionOutcomeValidator",$r(this.ajv,"actionOutcome"));T(this,"eventSourceDeclarationValidator",$r(this.ajv,"eventSourceDeclaration"));T(this,"actionProviderDeclarationValidator",$r(this.ajv,"actionProviderDeclaration"));T(this,"contracts",new Map);T(this,"clients",new Map);T(this,"eventSources",new Map);T(this,"actionProviders",new Map);T(this,"subscriptions",new Map);T(this,"activeActions",new Map);T(this,"completedActions",new Map);T(this,"admissionLocks",new Map);T(this,"recentEvents",new Map);T(this,"authorize");T(this,"now");T(this,"idFactory");T(this,"recentEventLimit");T(this,"completedRequestLimit");T(this,"nextSequence",0);T(this,"disposed",!1);var t,n,i,s,o,a,c,l,u,d;this.options=e,this.authorize=(t=e.authorize)!=null?t:(()=>!1),this.now=(n=e.now)!=null?n:(()=>new Date),this.idFactory=(i=e.idFactory)!=null?i:(f=>{var m;this.nextSequence+=1;let p=typeof((m=globalThis.crypto)==null?void 0:m.randomUUID)=="function"?globalThis.crypto.randomUUID():`${this.now().getTime().toString(36)}-${this.nextSequence.toString(36)}`;return`${f}_${p}`}),this.recentEventLimit=Math.max(1,(s=e.recentEventLimit)!=null?s:1e3),this.completedRequestLimit=Math.max(1,(o=e.completedRequestLimit)!=null?o:1e3),this.transport={..._u,...structuredClone((a=e.transport)!=null?a:{}),delivery:[...(l=(c=e.transport)==null?void 0:c.delivery)!=null?l:_u.delivery],ordering:[...(d=(u=e.transport)==null?void 0:u.ordering)!=null?d:_u.ordering]}}connect(e){this.assertActive(),RI(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){var l;let n=this.requireClient(e);if(t.contracts.length===0)throw new N("request_rejected","An event-source declaration must include a contract.");let i=`${e}:${t.declaration_id}`;if(this.eventSources.has(i))throw new N("request_rejected",`Event-source declaration ${t.declaration_id} is already registered.`);let s=new Map;for(let u of t.contracts){let d=await this.prepareEventContract(u.contract),f=cb(u.requirement,d.reference);if(lb(f,d.reference),await this.assertAuthorized({operation:"register_event_source",principal:n.identity,contract:d.reference}),d.sourceValidator&&!d.sourceValidator((l=u.binding)!=null?l:{}))throw new N("request_rejected",`${d.reference.id} source binding is invalid: ${Wr(d.sourceValidator.errors)}`);let p=la(d.reference);if(s.has(p))throw new N("contract_digest_conflict",`Event contract ${p} is repeated by one declaration.`);s.set(p,{contract:d,requirement:f,...u.binding===void 0?{}:{binding:structuredClone(u.binding)},...u.ordering===void 0?{}:{ordering:[...u.ordering]}})}let o={kind:"mdbase.event-source",profile_version:"0.1",declaration_id:t.declaration_id,source:structuredClone(n.identity),contracts:[...s.values()].map(({contract:u,requirement:d,binding:f,ordering:p})=>({requirement:structuredClone(d),resolved:structuredClone(u.reference),...f===void 0?{}:{binding:f},...p===void 0?{}:{ordering:p}}))},a={...o,declaration_digest:await ni(o)};Jr(this.eventSourceDeclarationValidator,a,"request_rejected","Event-source declaration"),this.commitContracts([...s.values()].map(({contract:u})=>u)),this.eventSources.set(i,{id:i,clientId:e,declaration:structuredClone(a),contracts:new Map([...s.entries()].map(([u,d])=>[u,{contract:d.contract,...d.binding===void 0?{}:{binding:d.binding}}]))}),n.sources.add(i);let c=!0;return{declaration:structuredClone(a),dispose:()=>{c&&(c=!1,this.removeEventSource(i))}}}async publishEvent(e,t){var m,h,y,b;let n=this.requireClient(e),i=la(t.contract),s=[...n.sources].map(g=>this.eventSources.get(g)).find(g=>g==null?void 0:g.contracts.has(i));if(!s)throw new N("unknown_contract",`This client has not registered event contract ${t.contract.id} ${t.contract.version}.`);let o=(m=s.contracts.get(i))==null?void 0:m.contract;if(!o)throw new N("unknown_contract",`Event contract ${i} is unavailable.`);if(t.contract.digest&&t.contract.digest!==o.reference.digest)throw new N("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}}),wu(t.data,"invalid_event_data",`Event ${o.reference.id} data`),Yo(o.dataValidator,t.data,"invalid_event_data",`Event ${o.reference.id} data`);let a=(h=t.extensions)!=null?h:{};for(let g of Object.keys(a))if(TI.has(g))throw new N("request_rejected",`Event extension ${g} is reserved.`);let c={...structuredClone(a),specversion:"1.0",id:(y=t.id)!=null?y:this.idFactory("evt"),source:CI(n.identity),type:o.reference.id,time:(b=t.time)!=null?b:this.now().toISOString(),...t.subject===void 0?{}:{subject:t.subject},datacontenttype:"application/json",dataschema:fb(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}};Jr(this.eventValidator,c,"invalid_event_data","Event envelope"),vu(this.transport,c),MI(c,o.reference);let l=`${c.source}\0${c.id}`,u=this.recentEvents.get(l);if(u){if(JSON.stringify(u)!==JSON.stringify(c))throw new N("contract_digest_conflict",`Event ${c.source} ${c.id} was reused with different content.`);return{event:structuredClone(u),deliveries:0,duplicate:!0}}this.recentEvents.set(l,structuredClone(c)),ub(this.recentEvents,this.recentEventLimit);let d=[...this.subscriptions.values()].filter(({subscription:g})=>da(g.contract,o.reference)),f=await Promise.allSettled(d.map(async g=>await this.isAuthorized({operation:"subscribe_event",principal:g.principal,contract:o.reference,...c.subject===void 0?{}:{subject:c.subject}})?(await g.handler(structuredClone(c)),!0):!1)),p=0;for(let g of f)g.status==="fulfilled"&&g.value?p+=1:g.status==="rejected"&&this.report({severity:"error",code:"event_consumer_failed",message:`An event consumer failed while handling ${c.type}.`,contract:o.reference,cause:g.reason});return{event:structuredClone(c),deliveries:p,duplicate:!1}}async subscribeEvents(e,t,n){let i=this.requireClient(e);$u(t.contract),DI(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){var d,f,p,m,h,y,b;let n=this.requireClient(e);if(t.handlers.length===0)throw new N("request_rejected","An action-provider declaration must include a handler.");let i=`${e}:${t.declaration_id}`;if(this.actionProviders.has(i))throw new N("request_rejected",`Action-provider declaration ${t.declaration_id} is already registered.`);let s=[],o=new Set;for(let g of t.handlers){if(o.has(g.handler_id))throw new N("request_rejected",`Handler ${g.handler_id} is repeated.`);o.add(g.handler_id);let _=await this.prepareActionContract(g.contract),k=cb(g.requirement,_.reference);if(lb(k,_.reference),await this.assertAuthorized({operation:"register_action_provider",principal:n.identity,contract:_.reference,provider:n.identity}),_.providerValidator&&!_.providerValidator((d=g.binding)!=null?d:{}))throw new N("request_rejected",`${_.reference.id} provider binding is invalid: ${Wr(_.providerValidator.errors)}`);let v=(p=(f=g.contract.behavior)==null?void 0:f.idempotency)!=null?p:"none";if(((m=g.idempotency)==null?void 0:m.mode)==="request"&&v==="none")throw new N("request_rejected",`${_.reference.id} does not permit request deduplication.`);if(v==="required"&&((h=g.idempotency)==null?void 0:h.mode)!=="request")throw new N("request_rejected",`${_.reference.id} requires a provider with request deduplication.`);let E=(b=(y=g.contract.behavior)==null?void 0:y.cancellation)!=null?b:"none";if(g.cancellation==="cooperative"&&E!=="cooperative")throw new N("request_rejected",`${_.reference.id} does not declare cooperative cancellation.`);s.push({contract:_,declaration:{handler_id:g.handler_id,requirement:k,resolved:structuredClone(_.reference),...g.binding===void 0?{}:{binding:structuredClone(g.binding)},...g.idempotency===void 0?{}:{idempotency:structuredClone(g.idempotency)},...g.cancellation===void 0?{}:{cancellation:g.cancellation},...g.max_concurrency===void 0?{}:{max_concurrency:g.max_concurrency}},handler:g.handler})}let a={kind:"mdbase.action-provider",profile_version:"0.1",declaration_id:t.declaration_id,provider:structuredClone(n.identity),handlers:s.map(({declaration:g})=>structuredClone(g))},c={...a,declaration_digest:await ni(a)};Jr(this.actionProviderDeclarationValidator,c,"request_rejected","Action-provider declaration"),this.commitContracts(s.map(({contract:g})=>g));let l=s.map(({contract:g,declaration:_,handler:k})=>({registrationId:i,clientId:e,declaration:structuredClone(c),handlerDeclaration:structuredClone(_),contract:g,handler:k,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){var a,c,l,u,d,f,p,m,h,y,b,g;let n=this.requireClient(e);$u(t.contract);let i=(a=t.request_id)!=null?a:this.idFactory("req");this.cleanCompletedActions(),wu(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:(c=t.created_at)!=null?c:this.now().toISOString(),...t.correlation_id===void 0?{}:{correlation_id:t.correlation_id},...t.causation_id===void 0?{}:{causation_id:t.causation_id},...t.subject===void 0?{}:{subject:t.subject},...t.idempotency_key===void 0?{}:{idempotency_key:t.idempotency_key},...t.deadline===void 0?{}:{deadline:t.deadline},...t.requested_provider===void 0?{}:{requested_provider:structuredClone(t.requested_provider)},input:structuredClone(t.input)};Jr(this.actionRequestValidator,s,"request_rejected","Action request"),vu(this.transport,s);let o=await this.acquireAdmission(i);try{let _=await ni(NI(s)),k=this.activeActions.get(i);if(k){if(db(e,i,_,k),((l=k.handler.handlerDeclaration.idempotency)==null?void 0:l.mode)!=="request")throw new N("request_rejected",`Action request ${i} is already active without deduplication.`);return structuredClone(await k.promise)}let v=this.completedActions.get(i);if(v){if(db(e,i,_,v),!v.reusable)throw new N("request_rejected",`Action request ${i} was already completed without deduplication.`);return structuredClone(v.outcome)}if(s.deadline&&new Date(s.deadline).getTime()<=this.now().getTime())throw new N("deadline_exceeded",`Action request ${i} passed its deadline before admission.`);if(s.deadline&&!this.transport.deadlines)throw new N("unsupported_transport_capability","The active transport cannot enforce action deadlines.");let E=this.resolveActionCandidates(s.contract,s.requested_provider);E.length===0&&this.throwResolutionFailure(s.contract,s.requested_provider);let O=[];for(let de of E)await this.isAuthorized({operation:"invoke_action",principal:n.identity,contract:de.contract.reference,provider:de.declaration.provider,...s.subject===void 0?{}:{subject:s.subject}})&&O.push(de);if(O.length===0)throw new N("unauthorized",`No authorized provider can execute ${s.contract.id}.`);if(O.length>1)throw new N("ambiguous_provider",`Action ${s.contract.id} has ${O.length} eligible providers; select one explicitly.`);let w=O[0];if(w.handlerDeclaration.max_concurrency!==void 0&&w.active>=w.handlerDeclaration.max_concurrency)throw new N("request_rejected",`Provider ${w.declaration.provider.implementation} is at capacity.`);if(((d=(u=w.contract.artifact.behavior)==null?void 0:u.idempotency)!=null?d:"none")==="required"&&!s.idempotency_key)throw new N("request_rejected",`${w.contract.reference.id} requires an idempotency key.`);Yo(w.contract.inputValidator,s.input,"invalid_action_input",`Action ${w.contract.reference.id} input`);let $={operation:"invoke_action",principal:n.identity,contract:w.contract.reference,provider:w.declaration.provider,...s.subject===void 0?{}:{subject:s.subject}},L=await((p=(f=this.options).authorizationContext)==null?void 0:p.call(f,$)),F={kind:"mdbase.action.invocation",profile_version:"0.1",invocation_id:this.idFactory("inv"),attempt_id:this.idFactory("attempt"),request_id:i,contract:structuredClone(w.contract.reference),caller:structuredClone(n.identity),provider:structuredClone(w.declaration.provider),provider_declaration_digest:w.declaration.declaration_digest,handler_id:w.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},...L===void 0?{}:{authorization_context:L},input:structuredClone(s.input)};Jr(this.actionInvocationValidator,F,"request_rejected","Action invocation"),await((h=(m=this.options).onInvocation)==null?void 0:h.call(m,structuredClone(F)));let z=new AbortController,P;if(F.deadline){let de=Math.max(0,new Date(F.deadline).getTime()-this.now().getTime());P=setTimeout(()=>z.abort(new N("deadline_exceeded",`Action request ${i} exceeded its deadline.`)),de)}w.active+=1;let I=this.executeAction(w,F,z).finally(()=>{P!==void 0&&clearTimeout(P),w.active=Math.max(0,w.active-1),this.activeActions.delete(i)});this.activeActions.set(i,{clientId:e,requestId:i,requestDigest:_,handler:w,invocation:F,controller:z,promise:I}),o();let ke=await I,ce=(b=(y=w.handlerDeclaration.idempotency)==null?void 0:y.retention_seconds)!=null?b:300;return this.completedActions.set(i,{clientId:e,requestDigest:_,outcome:structuredClone(ke),reusable:((g=w.handlerDeclaration.idempotency)==null?void 0:g.mode)==="request",expiresAt:this.now().getTime()+ce*1e3}),ub(this.completedActions,this.completedRequestLimit),structuredClone(ke)}finally{o()}}async executeAction(e,t,n){var i;try{let s=await e.handler(structuredClone(t.input),{invocation:structuredClone(t),signal:n.signal});if(n.signal.aborted){let a=n.signal.reason;return a instanceof N&&a.code==="deadline_exceeded"?this.failureOutcome(t,"failed",a.toPortableError()):this.failureOutcome(t,"cancelled",{code:"cancelled",message:`Action request ${t.request_id} was cancelled.`})}wu(s,"invalid_action_output",`Action ${e.contract.reference.id} output`),Yo(e.contract.outputValidator,s,"invalid_action_output",`Action ${e.contract.reference.id} output`);let o={kind:"mdbase.action.outcome",profile_version:"0.1",outcome_id:this.idFactory("outcome"),request_id:t.request_id,invocation_id:t.invocation_id,attempt_id:t.attempt_id,contract:structuredClone(t.contract),provider:structuredClone(t.provider),provider_declaration_digest:t.provider_declaration_digest,status:"succeeded",completed_at:this.now().toISOString(),output:structuredClone(s)};return Jr(this.actionOutcomeValidator,o,"invalid_action_output","Action outcome"),vu(this.transport,o),o}catch(s){if(s instanceof Li)return e.contract.errorValidator&&!e.contract.errorValidator((i=s.error.details)!=null?i:{})?this.failureOutcome(t,"failed",{code:"handler_failure",message:`Provider returned invalid declared error details: ${Wr(e.contract.errorValidator.errors)}`}):this.failureOutcome(t,s.status,s.error);if(s instanceof N)return this.failureOutcome(t,s.code==="cancelled"?"cancelled":s.code==="outcome_indeterminate"?"outcome_indeterminate":"failed",s.toPortableError());if(n.signal.aborted||qI(s)){let o=n.signal.reason;return o instanceof N&&o.code==="deadline_exceeded"?this.failureOutcome(t,"failed",o.toPortableError()):this.failureOutcome(t,"cancelled",{code:"cancelled",message:`Action request ${t.request_id} was cancelled.`})}return this.report({severity:"error",code:"action_handler_failed",message:`Provider ${t.provider.implementation} failed ${t.contract.id}.`,principal:t.provider,contract:t.contract,cause:s}),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 Jr(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 N("unauthorized",`Action request ${t} belongs to another caller.`);return a?structuredClone(a.outcome):null}if(o.clientId!==e)throw new N("unauthorized",`Action request ${t} belongs to another caller.`);if(await this.assertAuthorized({operation:"cancel_action",principal:i.identity,contract:o.invocation.contract,provider:o.invocation.provider,...o.invocation.subject===void 0?{}:{subject:o.invocation.subject}}),!this.transport.cancellation)throw new N("unsupported_transport_capability","The active transport cannot deliver cancellation.");if(o.handler.handlerDeclaration.cancellation!=="cooperative")throw new N("cancellation_unsupported",`Provider ${o.invocation.provider.implementation} does not support cancellation.`);return o.controller.abort(new N("cancelled",(n==null?void 0:n.trim())||`Action request ${t} was cancelled.`)),structuredClone(await o.promise)}resolveActionCandidates(e,t){let n=[...this.actionProviders.values()].flatMap(({handlers:s})=>s).filter(({contract:s,declaration:o})=>da(e,s.reference)&&LI(t,o.provider)),i=(0,Er.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)=>{var a,c;return s.declaration.provider.application.localeCompare(o.declaration.provider.application)||s.declaration.provider.implementation.localeCompare(o.declaration.provider.implementation)||((a=s.declaration.provider.instance_id)!=null?a:"").localeCompare((c=o.declaration.provider.instance_id)!=null?c:"")||s.handlerDeclaration.handler_id.localeCompare(o.handlerDeclaration.handler_id)}):[]}throwResolutionFailure(e,t){let n=[...this.contracts.values()].filter(i=>i.artifact.contract_type==="action"&&i.reference.id===e.id);throw n.length===0?new N("unknown_contract",`Action contract ${e.id} is unknown.`):n.some(({reference:i})=>da(e,i))?t?new N("requested_provider_unavailable",`The requested provider is unavailable for ${e.id}.`):new N("no_provider",`No provider is registered for ${e.id}.`):new N("unsupported_contract_version",`No ${e.id} artifact satisfies ${e.version}.`)}async prepareEventContract(e){if(this.assertContractArtifact(e),e.contract_type!=="event")throw new N("unknown_contract",`${e.id} is not an event contract.`);let t={id:e.id,version:e.version,digest:await Jo(e)};this.assertNoContractConflict(t);let n=my(this.ajv,e);return{artifact:structuredClone(e),reference:t,dataValidator:n.data,...n.source===void 0?{}:{sourceValidator:n.source}}}async prepareActionContract(e){if(this.assertContractArtifact(e),e.contract_type!=="action")throw new N("unknown_contract",`${e.id} is not an action contract.`);let t={id:e.id,version:e.version,digest:await Jo(e)};this.assertNoContractConflict(t);let n=yy(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(Jr(this.contractValidator,e,"contract_digest_conflict",`Contract ${e.id||""}`),!(0,Er.valid)(e.version))throw new N("unsupported_contract_version",`${e.id} version must be exact SemVer.`)}assertNoContractConflict(e){let t=this.contracts.get(la(e));if(t&&t.reference.digest!==e.digest)throw new N("contract_digest_conflict",`Contract ${e.id} ${e.version} conflicts with the registered artifact.`)}commitContracts(e){var n;let t=new Map;for(let i of e){let s=la(i.reference),o=(n=t.get(s))!=null?n:this.contracts.get(s);if(o&&o.reference.digest!==i.reference.digest)throw new N("contract_digest_conflict",`Contract ${i.reference.id} ${i.reference.version} conflicts within the registration.`);t.set(s,i)}for(let[i,s]of t)this.contracts.has(i)||this.contracts.set(i,s)}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 N("cancelled","The caller unloaded.")),i.handler.clientId===e&&i.handler.handlerDeclaration.cancellation==="cooperative"&&i.controller.abort(new N("cancelled","The provider unloaded."));this.clients.delete(e),t||this.assertActive()}}removeEventSource(e){var n;let t=this.eventSources.get(e);t&&(this.eventSources.delete(e),(n=this.clients.get(t.clientId))==null||n.sources.delete(e))}removeActionProvider(e){var n;let t=this.actionProviders.get(e);if(t){this.actionProviders.delete(e),(n=this.clients.get(t.clientId))==null||n.providers.delete(e);for(let i of this.activeActions.values())i.handler.registrationId===e&&i.handler.handlerDeclaration.cancellation==="cooperative"&&i.controller.abort(new N("cancelled","The provider unloaded."))}}removeSubscription(e){var n;let t=this.subscriptions.get(e);t&&(this.subscriptions.delete(e),(n=this.clients.get(t.clientId))==null||n.subscriptions.delete(e))}requireClient(e){this.assertActive();let t=this.clients.get(e);if(!t||t.disposed)throw new N("transport_unavailable","Interop client is disposed.");return t}assertActive(){if(this.disposed)throw new N("transport_unavailable","Interop bridge is disposed.")}async assertAuthorized(e){if(!await this.isAuthorized(e))throw new N("unauthorized",`${e.operation} is not authorized.`)}async isAuthorized(e){try{return await this.authorize(structuredClone(e))}catch(t){return this.report({severity:"error",code:"authorization_failed",message:`Authorization failed for ${e.operation}.`,principal:e.principal,cause:t}),!1}}cleanCompletedActions(){let e=this.now().getTime();for(let[t,n]of this.completedActions)n.expiresAt<=e&&this.completedActions.delete(t)}async acquireAdmission(e){var a;let t=(a=this.admissionLocks.get(e))!=null?a:Promise.resolve(),n,i=new Promise(c=>{n=c}),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){var t,n;(n=(t=this.options).onDiagnostic)==null||n.call(t,structuredClone(e))}};function Jr(r,e,t,n){if(!r(e))throw new N(t,`${n} is invalid: ${Wr(r.errors)}`)}function RI(r){for(let[e,t]of Object.entries(r))if(t!==void 0&&(typeof t!="string"||t.length===0||!/^[A-Za-z0-9][A-Za-z0-9._:@/-]*$/u.test(t)))throw new N("request_rejected",`Implementation identity ${e} is invalid.`);if(!(0,Er.valid)(r.version))throw new N("request_rejected","Implementation identity version must be exact SemVer.")}function $u(r){if(!/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)+$/u.test(r.id))throw new N("unknown_contract",`Contract ID ${r.id} is invalid.`);if(!(0,Er.validRange)(r.version,{includePrerelease:!0}))throw new N("unsupported_contract_version",`Contract requirement ${r.version} is not a SemVer range.`);if(r.digest&&!/^sha256:[0-9a-f]{64}$/u.test(r.digest))throw new N("contract_digest_conflict","Contract digest is invalid.")}function cb(r,e){let t=r!=null?r:{id:e.id,version:e.version,digest:e.digest};return $u(t),structuredClone(t)}function lb(r,e){if(!da(r,e))throw new N("unsupported_contract_version",`${e.id} ${e.version} does not satisfy its implementation requirement.`)}function da(r,e){return r.id===e.id&&(0,Er.satisfies)(e.version,r.version,{includePrerelease:!0})&&(!r.digest||r.digest===e.digest)}function la(r){return`${r.id}@${r.version}`}function fb(r){return`urn:mdbase:contract:${r.id}:${r.version}:${r.digest}`}function CI(r){return`urn:mdbase:app:${[r.application,r.implementation,...r.instance_id?[r.instance_id]:[]].map(encodeURIComponent).join(":")}`}function MI(r,e){if(r.type!==e.id||r.mdbasecontractversion!==e.version||r.mdbasecontractdigest!==e.digest||r.dataschema!==fb(e))throw new N("contract_digest_conflict","Event contract evidence is inconsistent.")}function NI(r){let{created_at:e,...t}=r;return t}function db(r,e,t,n){if(n.clientId!==r)throw new N("unauthorized",`Action request ${e} belongs to another caller.`);if(n.requestDigest!==t)throw new N("request_rejected",`Action request ${e} was reused with different content.`)}function wu(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 N(e,`${t}${o} must be a finite JSON number.`)}if(typeof s!="object")throw new N(e,`${t}${o} is not a JSON value.`);if(n.has(s))throw new N(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 N(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 vu(r,e){if(r.max_payload_bytes===void 0)return;let t=JSON.stringify(e),n=new TextEncoder().encode(t).byteLength;if(n>r.max_payload_bytes)throw new N("unsupported_transport_capability",`The portable envelope is ${n} bytes; the active transport allows ${r.max_payload_bytes}.`)}function LI(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 DI(r,e){var t,n;if(e){if((t=e.delivery)!=null&&t.some(i=>!r.delivery.includes(i)))throw new N("unsupported_transport_capability","The active transport lacks a required delivery capability.");if((n=e.ordering)!=null&&n.some(i=>!r.ordering.includes(i)))throw new N("unsupported_transport_capability","The active transport lacks a required ordering capability.");for(let i of["cancellation","deadlines","provider_discovery","request_deduplication","cross_process_identity"])if(e[i]===!0&&r[i]!==!0)throw new N("unsupported_transport_capability",`The active transport lacks ${i}.`);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 qI(r){return r instanceof Error&&r.name==="AbortError"}var ua=class{constructor(e,t){this.app=e;this.profileVersion="0.1";this.bridge=new _s({authorize:()=>t(),transport:{delivery:["ephemeral"],ordering:["none"],cancellation:!0,deadlines:!0,provider_discovery:!0,request_deduplication:!0,cross_process_identity:!1},onDiagnostic:n=>{var s;(n.severity==="error"?console.error:console.warn)(`[mdbase/interop] ${n.code}: ${n.message}`,(s=n.cause)!=null?s:"")}}),this.transport=this.bridge.describe().transport}connect(e){var s,o;let t=(s=e.manifest)==null?void 0:s.id,n=(o=e.manifest)==null?void 0:o.version;if(!t||!n)throw new Error("Only a loaded Obsidian plugin with manifest identity can connect to mdbase interop.");let 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()}};var ge=require("obsidian"),Db=ln(jd(),1),qb=ln(Jd(),1),qu=ln(Mu(),1),ma=class extends Error{constructor(t,n){super(n);this.code=t;this.name="MdbasePathError"}},Ut={spec_version:"0.3.0",name:"My mdbase collection",description:"Typed markdown collection",settings:{types_folder:"_types",explicit_type_keys:["type","types"],default_strict:!1,include_subfolders:!0,exclude:["_types",".obsidian",".git","node_modules",".trash",".mdbase"]}},Es=null;function wO(){return Es||(Es=new Db.Ajv2020({allErrors:!0,strict:!1,allowUnionTypes:!0}),(0,qb.default)(Es),Es)}function re(r){return!!r&&typeof r=="object"&&!Array.isArray(r)}function it(r){return JSON.parse(JSON.stringify(r))}function vO(r){if(r===!0)return!0;if(r===!1)return!1;if(r==="warn")return"warn"}function Nu(r){return Array.isArray(r)?`[${r.map(e=>Nu(e)).join(",")}]`:re(r)?`{${Object.keys(r).sort().map(t=>`${JSON.stringify(t)}:${Nu(r[t])}`).join(",")}}`:JSON.stringify(r)}function $O(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 SO(r){let e=new Map,t=new Set,n=i=>{var l,u,d,f;let s=e.get(i);if(s)return s;let o=r.get(i);if(!o)return null;if(t.has(i)){let p={...o,fields:it(o.fields)};return e.set(i,p),p}t.add(i);let a=o.extends?n(o.extends):null;t.delete(i);let c={...o,fields:a?{...it(a.fields),...it(o.fields)}:it(o.fields),display_name_key:(l=o.display_name_key)!=null?l:a==null?void 0:a.display_name_key,path_pattern:(u=o.path_pattern)!=null?u:a==null?void 0:a.path_pattern,filename_pattern:(d=o.filename_pattern)!=null?d:a==null?void 0:a.filename_pattern,strict:o.strict!==void 0?o.strict:a==null?void 0:a.strict,match:(f=o.match)!=null?f:a==null?void 0:a.match};return e.set(i,c),c};for(let i of r.keys())n(i);return e}function jb(r){let e=(0,ge.normalizePath)(r),t=e.lastIndexOf("/");return t>=0?e.slice(0,t):""}function Fb(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 Vb(r){return/^[a-z][a-z0-9+.-]*:\/\//i.test(r)}function Ub(r,e,t){var c;let n=Fb(t);if(!n||Vb(n))return null;let i=new Set,s=(0,ge.normalizePath)(n);i.add(s),s.endsWith(".md")||i.add(`${s}.md`);let o=jb(e);if(o){let l=(0,ge.normalizePath)(`${o}/${n}`);i.add(l),l.endsWith(".md")||i.add(`${l}.md`)}for(let l of i){let u=r.getAbstractFileByPath(l);if(u instanceof ge.TFile)return u}let a=n.replace(/\.md$/i,"");return(c=r.getMarkdownFiles().find(l=>l.basename===a))!=null?c:null}function EO(r,e,t){return Vb(Fb(t))||Ub(r,e,t)!==null}function Ct(r){let e=r.match(/^---[ \t]*\r?\n([\s\S]*?)^---[ \t]*(?:\r?\n|$)/m);if(!e)return{hasFrontmatter:!1,frontmatter:{},body:r};try{let t=e[1],n=(0,ge.parseYaml)(t);return n==null&&t.trim()!==""?{hasFrontmatter:!0,frontmatter:{},body:r.slice(e[0].length),error:"Frontmatter must be a YAML object"}:n!=null&&!re(n)?{hasFrontmatter:!0,frontmatter:{},body:r.slice(e[0].length),error:"Frontmatter must be a YAML object"}:{hasFrontmatter:!0,frontmatter:n!=null?n:{},body:r.slice(e[0].length)}}catch(t){return{hasFrontmatter:!0,frontmatter:{},body:r.slice(e[0].length),error:t instanceof Error?t.message:String(t)}}}function wt(r,e=""){if(Object.keys(r).length===0)return e;let t=(0,ge.stringifyYaml)(r).trimEnd(),n=e.replace(/^\n+/,"");return`--- + deps: ${t}}`};var PA={keyword:"dependencies",type:"object",schemaType:"object",error:tr.error,code(r){let[e,t]=IA(r);gm(r,e),_m(r,t)}};function IA({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 gm(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,ms.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,ms.checkReportMissingProp)(r,l)}):(t.if((0,pd._)`${c} && (${(0,ms.checkMissingProp)(r,a,s)})`),(0,ms.reportMissingProp)(r,s),t.else())}}tr.validatePropertyDeps=gm;function _m(r,e=r.schema){let{gen:t,data:n,keyword:i,it:s}=r,o=t.name("valid");for(let a in e)(0,kA.alwaysValidSchema)(s,e[a])||(t.if((0,ms.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))}tr.validateSchemaDeps=_m;tr.default=PA});var wm=A(hd=>{"use strict";Object.defineProperty(hd,"__esModule",{value:!0});var bm=H(),OA=Q(),RA={message:"property name must be valid",params:({params:r})=>(0,bm._)`{propertyName: ${r.propertyName}}`},TA={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:RA,code(r){let{gen:e,schema:t,data:n,it:i}=r;if((0,OA.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,bm.not)(s),()=>{r.error(!0),i.allErrors||e.break()})}),r.ok(s)}};hd.default=TA});var yd=A(md=>{"use strict";Object.defineProperty(md,"__esModule",{value:!0});var Ko=St(),Nt=H(),MA=$t(),Wo=Q(),CA={message:"must NOT have additional properties",params:({params:r})=>(0,Nt._)`{additionalProperty: ${r.additionalProperty}}`},NA={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:CA,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,Wo.alwaysValidSchema)(o,t))return;let l=(0,Ko.allSchemaProperties)(n.properties),d=(0,Ko.allSchemaProperties)(n.patternProperties);u(),r.ok((0,Nt._)`${s} === ${MA.default.errors}`);function u(){e.forIn("key",i,m=>{!l.length&&!d.length?y(m):e.if(f(m),()=>y(m))})}function f(m){let g;if(l.length>8){let _=(0,Wo.schemaRefOrVal)(o,n.properties,"properties");g=(0,Ko.isOwnProperty)(e,_,m)}else l.length?g=(0,Nt.or)(...l.map(_=>(0,Nt._)`${m} === ${_}`)):g=Nt.nil;return d.length&&(g=(0,Nt.or)(g,...d.map(_=>(0,Nt._)`${(0,Ko.usePattern)(r,_)}.test(${m})`))),(0,Nt.not)(g)}function p(m){e.code((0,Nt._)`delete ${i}[${m}]`)}function y(m){if(c.removeAdditional==="all"||c.removeAdditional&&t===!1){p(m);return}if(t===!1){r.setParams({additionalProperty:m}),r.error(),a||e.break();return}if(typeof t=="object"&&!(0,Wo.alwaysValidSchema)(o,t)){let g=e.name("valid");c.removeAdditional==="failing"?(h(m,g,!1),e.if((0,Nt.not)(g),()=>{r.reset(),p(m)})):(h(m,g),a||e.if((0,Nt.not)(g),()=>e.break()))}}function h(m,g,_){let w={keyword:"additionalProperties",dataProp:m,dataPropType:Wo.Type.Str};_===!1&&Object.assign(w,{compositeRule:!0,createErrors:!1,allErrors:!1}),r.subschema(w,g)}}};md.default=NA});var Sm=A(_d=>{"use strict";Object.defineProperty(_d,"__esModule",{value:!0});var LA=Hn(),vm=St(),gd=Q(),$m=yd(),jA={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&&$m.default.code(new LA.KeywordCxt(s,$m.default,"additionalProperties"));let o=(0,vm.allSchemaProperties)(t);for(let u of o)s.definedProperties.add(u);s.opts.unevaluated&&o.length&&s.props!==!0&&(s.props=gd.mergeEvaluated.props(e,(0,gd.toHash)(o),s.props));let a=o.filter(u=>!(0,gd.alwaysValidSchema)(s,t[u]));if(a.length===0)return;let c=e.name("valid");for(let u of a)l(u)?d(u):(e.if((0,vm.propertyInData)(e,i,u,s.opts.ownProperties)),d(u),s.allErrors||e.else().var(c,!0),e.endIf()),r.it.definedProperties.add(u),r.ok(c);function l(u){return s.opts.useDefaults&&!s.compositeRule&&t[u].default!==void 0}function d(u){r.subschema({keyword:"properties",schemaProp:u,dataProp:u},c)}}};_d.default=jA});var km=A(bd=>{"use strict";Object.defineProperty(bd,"__esModule",{value:!0});var Em=St(),Go=H(),Am=Q(),xm=Q(),DA={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,Em.allSchemaProperties)(t),c=a.filter(h=>(0,Am.alwaysValidSchema)(s,t[h]));if(a.length===0||c.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let l=o.strictSchema&&!o.allowMatchingProperties&&i.properties,d=e.name("valid");s.props!==!0&&!(s.props instanceof Go.Name)&&(s.props=(0,xm.evaluatedPropsToName)(e,s.props));let{props:u}=s;f();function f(){for(let h of a)l&&p(h),s.allErrors?y(h):(e.var(d,!0),y(h),e.if(d))}function p(h){for(let m in l)new RegExp(h).test(m)&&(0,Am.checkStrictMode)(s,`property ${m} matches pattern ${h} (use allowMatchingProperties)`)}function y(h){e.forIn("key",n,m=>{e.if((0,Go._)`${(0,Em.usePattern)(r,h)}.test(${m})`,()=>{let g=c.includes(h);g||r.subschema({keyword:"patternProperties",schemaProp:h,dataProp:m,dataPropType:xm.Type.Str},d),s.opts.unevaluated&&u!==!0?e.assign((0,Go._)`${u}[${m}]`,!0):!g&&!s.allErrors&&e.if((0,Go.not)(d),()=>e.break())})})}}};bd.default=DA});var Pm=A(wd=>{"use strict";Object.defineProperty(wd,"__esModule",{value:!0});var qA=Q(),FA={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(r){let{gen:e,schema:t,it:n}=r;if((0,qA.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"}};wd.default=FA});var Im=A(vd=>{"use strict";Object.defineProperty(vd,"__esModule",{value:!0});var UA=St(),VA={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:UA.validateUnion,error:{message:"must match a schema in anyOf"}};vd.default=VA});var Om=A($d=>{"use strict";Object.defineProperty($d,"__esModule",{value:!0});var Jo=H(),BA=Q(),zA={message:"must match exactly one schema in oneOf",params:({params:r})=>(0,Jo._)`{passingSchemas: ${r.passing}}`},HA={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:zA,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((d,u)=>{let f;(0,BA.alwaysValidSchema)(i,d)?e.var(c,!0):f=r.subschema({keyword:"oneOf",schemaProp:u,compositeRule:!0},c),u>0&&e.if((0,Jo._)`${c} && ${o}`).assign(o,!1).assign(a,(0,Jo._)`[${a}, ${u}]`).else(),e.if(c,()=>{e.assign(o,!0),e.assign(a,u),f&&r.mergeEvaluated(f,Jo.Name)})})}}};$d.default=HA});var Rm=A(Sd=>{"use strict";Object.defineProperty(Sd,"__esModule",{value:!0});var KA=Q(),WA={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,KA.alwaysValidSchema)(n,s))return;let a=r.subschema({keyword:"allOf",schemaProp:o},i);r.ok(i),r.mergeEvaluated(a)})}};Sd.default=WA});var Cm=A(Ed=>{"use strict";Object.defineProperty(Ed,"__esModule",{value:!0});var Yo=H(),Mm=Q(),GA={message:({params:r})=>(0,Yo.str)`must match "${r.ifClause}" schema`,params:({params:r})=>(0,Yo._)`{failingKeyword: ${r.ifClause}}`},JA={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:GA,code(r){let{gen:e,parentSchema:t,it:n}=r;t.then===void 0&&t.else===void 0&&(0,Mm.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let i=Tm(n,"then"),s=Tm(n,"else");if(!i&&!s)return;let o=e.let("valid",!0),a=e.name("_valid");if(c(),r.reset(),i&&s){let d=e.let("ifClause");r.setParams({ifClause:d}),e.if(a,l("then",d),l("else",d))}else i?e.if(a,l("then")):e.if((0,Yo.not)(a),l("else"));r.pass(o,()=>r.error(!0));function c(){let d=r.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);r.mergeEvaluated(d)}function l(d,u){return()=>{let f=r.subschema({keyword:d},a);e.assign(o,a),r.mergeValidEvaluated(f,o),u?e.assign(u,(0,Yo._)`${d}`):r.setParams({ifClause:d})}}}};function Tm(r,e){let t=r.schema[e];return t!==void 0&&!(0,Mm.alwaysValidSchema)(r,t)}Ed.default=JA});var Nm=A(Ad=>{"use strict";Object.defineProperty(Ad,"__esModule",{value:!0});var YA=Q(),XA={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:r,parentSchema:e,it:t}){e.if===void 0&&(0,YA.checkStrictMode)(t,`"${r}" without "if" is ignored`)}};Ad.default=XA});var kd=A(xd=>{"use strict";Object.defineProperty(xd,"__esModule",{value:!0});var QA=cd(),ZA=pm(),ex=ld(),tx=mm(),rx=ym(),nx=Ho(),ix=wm(),sx=yd(),ox=Sm(),ax=km(),cx=Pm(),lx=Im(),dx=Om(),ux=Rm(),fx=Cm(),px=Nm();function hx(r=!1){let e=[cx.default,lx.default,dx.default,ux.default,fx.default,px.default,ix.default,sx.default,nx.default,ox.default,ax.default];return r?e.push(ZA.default,tx.default):e.push(QA.default,ex.default),e.push(rx.default),e}xd.default=hx});var Id=A(ys=>{"use strict";Object.defineProperty(ys,"__esModule",{value:!0});ys.dynamicAnchor=void 0;var Pd=H(),mx=$t(),Lm=rs(),yx=qo(),gx={keyword:"$dynamicAnchor",schemaType:"string",code:r=>jm(r,r.schema)};function jm(r,e){let{gen:t,it:n}=r;n.schemaEnv.root.dynamicAnchors[e]=!0;let i=(0,Pd._)`${mx.default.dynamicAnchors}${(0,Pd.getProperty)(e)}`,s=n.errSchemaPath==="#"?n.validateName:_x(r);t.if((0,Pd._)`!${i}`,()=>t.assign(i,s))}ys.dynamicAnchor=jm;function _x(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 Lm.SchemaEnv({schema:t,schemaId:c,root:i,baseId:s,localRefs:o,meta:a});return Lm.compileSchema.call(n,l),(0,yx.getValidate)(r,l)}ys.default=gx});var Od=A(gs=>{"use strict";Object.defineProperty(gs,"__esModule",{value:!0});gs.dynamicRef=void 0;var Dm=H(),bx=$t(),qm=qo(),wx={keyword:"$dynamicRef",schemaType:"string",code:r=>Fm(r,r.schema)};function Fm(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,Dm._)`${bx.default.dynamicAnchors}${(0,Dm.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,qm.callRef)(r,c),t.let(l,!0)}):()=>(0,qm.callRef)(r,c)}}gs.dynamicRef=Fm;gs.default=wx});var Um=A(Rd=>{"use strict";Object.defineProperty(Rd,"__esModule",{value:!0});var vx=Id(),$x=Q(),Sx={keyword:"$recursiveAnchor",schemaType:"boolean",code(r){r.schema?(0,vx.dynamicAnchor)(r,""):(0,$x.checkStrictMode)(r.it,"$recursiveAnchor: false is ignored")}};Rd.default=Sx});var Vm=A(Td=>{"use strict";Object.defineProperty(Td,"__esModule",{value:!0});var Ex=Od(),Ax={keyword:"$recursiveRef",schemaType:"string",code:r=>(0,Ex.dynamicRef)(r,r.schema)};Td.default=Ax});var Bm=A(Md=>{"use strict";Object.defineProperty(Md,"__esModule",{value:!0});var xx=Id(),kx=Od(),Px=Um(),Ix=Vm(),Ox=[xx.default,kx.default,Px.default,Ix.default];Md.default=Ox});var Hm=A(Cd=>{"use strict";Object.defineProperty(Cd,"__esModule",{value:!0});var zm=Ho(),Rx={keyword:"dependentRequired",type:"object",schemaType:"object",error:zm.error,code:r=>(0,zm.validatePropertyDeps)(r)};Cd.default=Rx});var Km=A(Nd=>{"use strict";Object.defineProperty(Nd,"__esModule",{value:!0});var Tx=Ho(),Mx={keyword:"dependentSchemas",type:"object",schemaType:"object",code:r=>(0,Tx.validateSchemaDeps)(r)};Nd.default=Mx});var Wm=A(Ld=>{"use strict";Object.defineProperty(Ld,"__esModule",{value:!0});var Cx=Q(),Nx={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword:r,parentSchema:e,it:t}){e.contains===void 0&&(0,Cx.checkStrictMode)(t,`"${r}" without "contains" is ignored`)}};Ld.default=Nx});var Gm=A(jd=>{"use strict";Object.defineProperty(jd,"__esModule",{value:!0});var Lx=Hm(),jx=Km(),Dx=Wm(),qx=[Lx.default,jx.default,Dx.default];jd.default=qx});var Ym=A(Dd=>{"use strict";Object.defineProperty(Dd,"__esModule",{value:!0});var Hr=H(),Jm=Q(),Fx=$t(),Ux={message:"must NOT have unevaluated properties",params:({params:r})=>(0,Hr._)`{unevaluatedProperty: ${r.unevaluatedProperty}}`},Vx={keyword:"unevaluatedProperties",type:"object",schemaType:["boolean","object"],trackErrors:!0,error:Ux,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 Hr.Name?e.if((0,Hr._)`${a} !== true`,()=>e.forIn("key",n,u=>e.if(l(a,u),()=>c(u)))):a!==!0&&e.forIn("key",n,u=>a===void 0?c(u):e.if(d(a,u),()=>c(u))),s.props=!0,r.ok((0,Hr._)`${i} === ${Fx.default.errors}`);function c(u){if(t===!1){r.setParams({unevaluatedProperty:u}),r.error(),o||e.break();return}if(!(0,Jm.alwaysValidSchema)(s,t)){let f=e.name("valid");r.subschema({keyword:"unevaluatedProperties",dataProp:u,dataPropType:Jm.Type.Str},f),o||e.if((0,Hr.not)(f),()=>e.break())}}function l(u,f){return(0,Hr._)`!${u} || !${u}[${f}]`}function d(u,f){let p=[];for(let y in u)u[y]===!0&&p.push((0,Hr._)`${f} !== ${y}`);return(0,Hr.and)(...p)}}};Dd.default=Vx});var Qm=A(qd=>{"use strict";Object.defineProperty(qd,"__esModule",{value:!0});var $n=H(),Xm=Q(),Bx={message:({params:{len:r}})=>(0,$n.str)`must NOT have more than ${r} items`,params:({params:{len:r}})=>(0,$n._)`{limit: ${r}}`},zx={keyword:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error:Bx,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,$n._)`${n}.length`);if(t===!1)r.setParams({len:s}),r.fail((0,$n._)`${o} > ${s}`);else if(typeof t=="object"&&!(0,Xm.alwaysValidSchema)(i,t)){let c=e.var("valid",(0,$n._)`${o} <= ${s}`);e.if((0,$n.not)(c),()=>a(c,s)),r.ok(c)}i.items=!0;function a(c,l){e.forRange("i",l,o,d=>{r.subschema({keyword:"unevaluatedItems",dataProp:d,dataPropType:Xm.Type.Num},c),i.allErrors||e.if((0,$n.not)(c),()=>e.break())})}}};qd.default=zx});var Zm=A(Fd=>{"use strict";Object.defineProperty(Fd,"__esModule",{value:!0});var Hx=Ym(),Kx=Qm(),Wx=[Hx.default,Kx.default];Fd.default=Wx});var ey=A(Ud=>{"use strict";Object.defineProperty(Ud,"__esModule",{value:!0});var xe=H(),Gx={message:({schemaCode:r})=>(0,xe.str)`must match format "${r}"`,params:({schemaCode:r})=>(0,xe._)`{format: ${r}}`},Jx={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:Gx,code(r,e){let{gen:t,data:n,$data:i,schema:s,schemaCode:o,it:a}=r,{opts:c,errSchemaPath:l,schemaEnv:d,self:u}=a;if(!c.validateFormats)return;i?f():p();function f(){let y=t.scopeValue("formats",{ref:u.formats,code:c.code.formats}),h=t.const("fDef",(0,xe._)`${y}[${o}]`),m=t.let("fType"),g=t.let("format");t.if((0,xe._)`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>t.assign(m,(0,xe._)`${h}.type || "string"`).assign(g,(0,xe._)`${h}.validate`),()=>t.assign(m,(0,xe._)`"string"`).assign(g,h)),r.fail$data((0,xe.or)(_(),w()));function _(){return c.strictSchema===!1?xe.nil:(0,xe._)`${o} && !${g}`}function w(){let k=d.$async?(0,xe._)`(${h}.async ? await ${g}(${n}) : ${g}(${n}))`:(0,xe._)`${g}(${n})`,v=(0,xe._)`(typeof ${g} == "function" ? ${k} : ${g}.test(${n}))`;return(0,xe._)`${g} && ${g} !== true && ${m} === ${e} && !${v}`}}function p(){let y=u.formats[s];if(!y){_();return}if(y===!0)return;let[h,m,g]=w(y);h===e&&r.pass(k());function _(){if(c.strictSchema===!1){u.logger.warn(v());return}throw new Error(v());function v(){return`unknown format "${s}" ignored in schema at path "${l}"`}}function w(v){let P=v instanceof RegExp?(0,xe.regexpCode)(v):c.code.formats?(0,xe._)`${c.code.formats}${(0,xe.getProperty)(s)}`:void 0,O=t.scopeValue("formats",{key:s,ref:v,code:P});return typeof v=="object"&&!(v instanceof RegExp)?[v.type||"string",v.validate,(0,xe._)`${O}.validate`]:["string",v,O]}function k(){if(typeof y=="object"&&!(y instanceof RegExp)&&y.async){if(!d.$async)throw new Error("async format in sync schema");return(0,xe._)`await ${g}(${n})`}return typeof m=="function"?(0,xe._)`${g}(${n})`:(0,xe._)`${g}.test(${n})`}}}};Ud.default=Jx});var Bd=A(Vd=>{"use strict";Object.defineProperty(Vd,"__esModule",{value:!0});var Yx=ey(),Xx=[Yx.default];Vd.default=Xx});var zd=A(Xn=>{"use strict";Object.defineProperty(Xn,"__esModule",{value:!0});Xn.contentVocabulary=Xn.metadataVocabulary=void 0;Xn.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Xn.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var ry=A(Hd=>{"use strict";Object.defineProperty(Hd,"__esModule",{value:!0});var Qx=zl(),Zx=od(),e1=kd(),t1=Bm(),r1=Gm(),n1=Zm(),i1=Bd(),ty=zd(),s1=[t1.default,Qx.default,Zx.default,(0,e1.default)(!0),i1.default,ty.metadataVocabulary,ty.contentVocabulary,r1.default,n1.default];Hd.default=s1});var iy=A(Xo=>{"use strict";Object.defineProperty(Xo,"__esModule",{value:!0});Xo.DiscrError=void 0;var ny;(function(r){r.Tag="tag",r.Mapping="mapping"})(ny||(Xo.DiscrError=ny={}))});var Gd=A(Wd=>{"use strict";Object.defineProperty(Wd,"__esModule",{value:!0});var Qn=H(),Kd=iy(),sy=rs(),o1=Kn(),a1=Q(),c1={message:({params:{discrError:r,tagName:e}})=>r===Kd.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:r,tag:e,tagName:t}})=>(0,Qn._)`{error: ${r}, tag: ${t}, tagValue: ${e}}`},l1={keyword:"discriminator",type:"object",schemaType:"object",error:c1,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,Qn._)`${t}${(0,Qn.getProperty)(a)}`);e.if((0,Qn._)`typeof ${l} == "string"`,()=>d(),()=>r.error(!1,{discrError:Kd.DiscrError.Tag,tag:l,tagName:a})),r.ok(c);function d(){let p=f();e.if(!1);for(let y in p)e.elseIf((0,Qn._)`${l} === ${y}`),e.assign(c,u(p[y]));e.else(),r.error(!1,{discrError:Kd.DiscrError.Mapping,tag:l,tagName:a}),e.endIf()}function u(p){let y=e.name("valid"),h=r.subschema({keyword:"oneOf",schemaProp:p},y);return r.mergeEvaluated(h,Qn.Name),y}function f(){var p;let y={},h=g(i),m=!0;for(let k=0;k{d1.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 ay=A((c2,u1)=>{u1.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 cy=A((l2,f1)=>{f1.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 ly=A((d2,p1)=>{p1.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 dy=A((u2,h1)=>{h1.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 uy=A((f2,m1)=>{m1.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 fy=A((p2,y1)=>{y1.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 py=A((h2,g1)=>{g1.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 hy=A(Jd=>{"use strict";Object.defineProperty(Jd,"__esModule",{value:!0});var _1=oy(),b1=ay(),w1=cy(),v1=ly(),$1=dy(),S1=uy(),E1=fy(),A1=py(),x1=["/properties"];function k1(r){return[_1,b1,w1,v1,$1,e(this,S1),E1,e(this,A1)].forEach(t=>this.addMetaSchema(t,void 0,!1)),this;function e(t,n){return r?t.$dataMetaSchema(n,x1):n}}Jd.default=k1});var Qd=A((_e,Xd)=>{"use strict";Object.defineProperty(_e,"__esModule",{value:!0});_e.MissingRefError=_e.ValidationError=_e.CodeGen=_e.Name=_e.nil=_e.stringify=_e.str=_e._=_e.KeywordCxt=_e.Ajv2020=void 0;var P1=Ul(),I1=ry(),O1=Gd(),R1=hy(),Yd="https://json-schema.org/draft/2020-12/schema",Zn=class extends P1.default{constructor(e={}){super({...e,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){super._addVocabularies(),I1.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(O1.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data:e,meta:t}=this.opts;t&&(R1.default.call(this,e),this.refs["http://json-schema.org/schema"]=Yd)}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Yd)?Yd:void 0)}};_e.Ajv2020=Zn;Xd.exports=_e=Zn;Xd.exports.Ajv2020=Zn;Object.defineProperty(_e,"__esModule",{value:!0});_e.default=Zn;var T1=Hn();Object.defineProperty(_e,"KeywordCxt",{enumerable:!0,get:function(){return T1.KeywordCxt}});var ei=H();Object.defineProperty(_e,"_",{enumerable:!0,get:function(){return ei._}});Object.defineProperty(_e,"str",{enumerable:!0,get:function(){return ei.str}});Object.defineProperty(_e,"stringify",{enumerable:!0,get:function(){return ei.stringify}});Object.defineProperty(_e,"nil",{enumerable:!0,get:function(){return ei.nil}});Object.defineProperty(_e,"Name",{enumerable:!0,get:function(){return ei.Name}});Object.defineProperty(_e,"CodeGen",{enumerable:!0,get:function(){return ei.CodeGen}});var M1=ts();Object.defineProperty(_e,"ValidationError",{enumerable:!0,get:function(){return M1.default}});var C1=Kn();Object.defineProperty(_e,"MissingRefError",{enumerable:!0,get:function(){return C1.default}})});var $y=A(nr=>{"use strict";Object.defineProperty(nr,"__esModule",{value:!0});nr.formatNames=nr.fastFormats=nr.fullFormats=void 0;function rr(r,e){return{validate:r,compare:e}}nr.fullFormats={date:rr(_y,ru),time:rr(eu(!0),nu),"date-time":rr(my(!0),wy),"iso-time":rr(eu(),by),"iso-date-time":rr(my(),vy),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:F1,"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:W1,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:U1,int32:{type:"number",validate:z1},int64:{type:"number",validate:H1},float:{type:"number",validate:gy},double:{type:"number",validate:gy},password:!0,binary:!0};nr.fastFormats={...nr.fullFormats,date:rr(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,ru),time:rr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,nu),"date-time":rr(/^\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,wy),"iso-time":rr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,by),"iso-date-time":rr(/^\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,vy),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};nr.formatNames=Object.keys(nr.fullFormats);function N1(r){return r%4===0&&(r%100!==0||r%400===0)}var L1=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,j1=[0,31,28,31,30,31,30,31,31,30,31,30,31];function _y(r){let e=L1.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&&N1(t)?29:j1[n])}function ru(r,e){if(r&&e)return r>e?1:r23||d>59||r&&!a)return!1;if(i<=23&&s<=59&&o<60)return!0;let u=s-d*c,f=i-l*c-(u<0?1:0);return(f===23||f===-1)&&(u===59||u===-1)&&o<61}}function nu(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 by(r,e){if(!(r&&e))return;let t=Zd.exec(r),n=Zd.exec(e);if(t&&n)return r=t[1]+t[2]+t[3],e=n[1]+n[2]+n[3],r>e?1:r=V1}function H1(r){return Number.isInteger(r)}function gy(){return!0}var K1=/[^\\]\\Z/;function W1(r){if(K1.test(r))return!1;try{return new RegExp(r),!0}catch(e){return!1}}});var Ey=A(iu=>{"use strict";Object.defineProperty(iu,"__esModule",{value:!0});var G1=zl(),J1=od(),Y1=kd(),X1=Bd(),Sy=zd(),Q1=[G1.default,J1.default,(0,Y1.default)(),X1.default,Sy.metadataVocabulary,Sy.contentVocabulary];iu.default=Q1});var Ay=A((_2,Z1)=>{Z1.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 ky=A((be,su)=>{"use strict";Object.defineProperty(be,"__esModule",{value:!0});be.MissingRefError=be.ValidationError=be.CodeGen=be.Name=be.nil=be.stringify=be.str=be._=be.KeywordCxt=be.Ajv=void 0;var ek=Ul(),tk=Ey(),rk=Gd(),xy=Ay(),nk=["/properties"],Qo="http://json-schema.org/draft-07/schema",ti=class extends ek.default{_addVocabularies(){super._addVocabularies(),tk.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(rk.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(xy,nk):xy;this.addMetaSchema(e,Qo,!1),this.refs["http://json-schema.org/schema"]=Qo}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Qo)?Qo:void 0)}};be.Ajv=ti;su.exports=be=ti;su.exports.Ajv=ti;Object.defineProperty(be,"__esModule",{value:!0});be.default=ti;var ik=Hn();Object.defineProperty(be,"KeywordCxt",{enumerable:!0,get:function(){return ik.KeywordCxt}});var ri=H();Object.defineProperty(be,"_",{enumerable:!0,get:function(){return ri._}});Object.defineProperty(be,"str",{enumerable:!0,get:function(){return ri.str}});Object.defineProperty(be,"stringify",{enumerable:!0,get:function(){return ri.stringify}});Object.defineProperty(be,"nil",{enumerable:!0,get:function(){return ri.nil}});Object.defineProperty(be,"Name",{enumerable:!0,get:function(){return ri.Name}});Object.defineProperty(be,"CodeGen",{enumerable:!0,get:function(){return ri.CodeGen}});var sk=ts();Object.defineProperty(be,"ValidationError",{enumerable:!0,get:function(){return sk.default}});var ok=Kn();Object.defineProperty(be,"MissingRefError",{enumerable:!0,get:function(){return ok.default}})});var Py=A(ni=>{"use strict";Object.defineProperty(ni,"__esModule",{value:!0});ni.formatLimitDefinition=void 0;var ak=ky(),Lt=H(),Kr=Lt.operators,Zo={formatMaximum:{okStr:"<=",ok:Kr.LTE,fail:Kr.GT},formatMinimum:{okStr:">=",ok:Kr.GTE,fail:Kr.LT},formatExclusiveMaximum:{okStr:"<",ok:Kr.LT,fail:Kr.GTE},formatExclusiveMinimum:{okStr:">",ok:Kr.GT,fail:Kr.LTE}},ck={message:({keyword:r,schemaCode:e})=>(0,Lt.str)`should be ${Zo[r].okStr} ${e}`,params:({keyword:r,schemaCode:e})=>(0,Lt._)`{comparison: ${Zo[r].okStr}, limit: ${e}}`};ni.formatLimitDefinition={keyword:Object.keys(Zo),type:"string",schemaType:"string",$data:!0,error:ck,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 ak.KeywordCxt(s,a.RULES.all.format.definition,"format");c.$data?l():d();function l(){let f=e.scopeValue("formats",{ref:a.formats,code:o.code.formats}),p=e.const("fmt",(0,Lt._)`${f}[${c.schemaCode}]`);r.fail$data((0,Lt.or)((0,Lt._)`typeof ${p} != "object"`,(0,Lt._)`${p} instanceof RegExp`,(0,Lt._)`typeof ${p}.compare != "function"`,u(p)))}function d(){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 y=e.scopeValue("formats",{key:f,ref:p,code:o.code.formats?(0,Lt._)`${o.code.formats}${(0,Lt.getProperty)(f)}`:void 0});r.fail$data(u(y))}function u(f){return(0,Lt._)`${f}.compare(${t}, ${n}) ${Zo[i].fail} 0`}},dependencies:["format"]};var lk=r=>(r.addKeyword(ni.formatLimitDefinition),r);ni.default=lk});var cu=A((_s,Ry)=>{"use strict";Object.defineProperty(_s,"__esModule",{value:!0});var ii=$y(),dk=Py(),ou=H(),Iy=new ou.Name("fullFormats"),uk=new ou.Name("fastFormats"),au=(r,e={keywords:!0})=>{if(Array.isArray(e))return Oy(r,e,ii.fullFormats,Iy),r;let[t,n]=e.mode==="fast"?[ii.fastFormats,uk]:[ii.fullFormats,Iy],i=e.formats||ii.formatNames;return Oy(r,i,t,n),e.keywords&&(0,dk.default)(r),r};au.get=(r,e="full")=>{let n=(e==="fast"?ii.fastFormats:ii.fullFormats)[r];if(!n)throw new Error(`Unknown format "${r}"`);return n};function Oy(r,e,t,n){var i,s;(i=(s=r.opts.code).formats)!==null&&i!==void 0||(s.formats=(0,ou._)`require("ajv-formats/dist/formats").${n}`);for(let o of e)r.addFormat(o,t[o])}Ry.exports=_s=au;Object.defineProperty(_s,"__esModule",{value:!0});_s.default=au});var ai=A((x2,Dy)=>{"use strict";var hk="2.0.0",mk=Number.MAX_SAFE_INTEGER||9007199254740991,yk=16,gk=250,_k=["major","premajor","minor","preminor","patch","prepatch","prerelease"];Dy.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:yk,MAX_SAFE_BUILD_LENGTH:gk,MAX_SAFE_INTEGER:mk,RELEASE_TYPES:_k,SEMVER_SPEC_VERSION:hk,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var bs=A((k2,qy)=>{"use strict";var bk=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...r)=>console.error("SEMVER",...r):()=>{};qy.exports=bk});var ci=A((sr,Fy)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:fu,MAX_SAFE_BUILD_LENGTH:wk,MAX_LENGTH:vk}=ai(),$k=bs();sr=Fy.exports={};var Sk=sr.re=[],Ek=sr.safeRe=[],j=sr.src=[],Ak=sr.safeSrc=[],D=sr.t={},xk=0,pu="[a-zA-Z0-9-]",kk=[["\\s",1],["\\d",vk],[pu,wk]],Pk=r=>{for(let[e,t]of kk)r=r.split(`${e}*`).join(`${e}{0,${t}}`).split(`${e}+`).join(`${e}{1,${t}}`);return r},K=(r,e,t)=>{let n=Pk(e),i=xk++;$k(r,i,e),D[r]=i,j[i]=e,Ak[i]=n,Sk[i]=new RegExp(e,t?"g":void 0),Ek[i]=new RegExp(n,t?"g":void 0)};K("NUMERICIDENTIFIER","0|[1-9]\\d*");K("NUMERICIDENTIFIERLOOSE","\\d+");K("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${pu}*`);K("MAINVERSION",`(${j[D.NUMERICIDENTIFIER]})\\.(${j[D.NUMERICIDENTIFIER]})\\.(${j[D.NUMERICIDENTIFIER]})`);K("MAINVERSIONLOOSE",`(${j[D.NUMERICIDENTIFIERLOOSE]})\\.(${j[D.NUMERICIDENTIFIERLOOSE]})\\.(${j[D.NUMERICIDENTIFIERLOOSE]})`);K("PRERELEASEIDENTIFIER",`(?:${j[D.NONNUMERICIDENTIFIER]}|${j[D.NUMERICIDENTIFIER]})`);K("PRERELEASEIDENTIFIERLOOSE",`(?:${j[D.NONNUMERICIDENTIFIER]}|${j[D.NUMERICIDENTIFIERLOOSE]})`);K("PRERELEASE",`(?:-(${j[D.PRERELEASEIDENTIFIER]}(?:\\.${j[D.PRERELEASEIDENTIFIER]})*))`);K("PRERELEASELOOSE",`(?:-?(${j[D.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${j[D.PRERELEASEIDENTIFIERLOOSE]})*))`);K("BUILDIDENTIFIER",`${pu}+`);K("BUILD",`(?:\\+(${j[D.BUILDIDENTIFIER]}(?:\\.${j[D.BUILDIDENTIFIER]})*))`);K("FULLPLAIN",`v?${j[D.MAINVERSION]}${j[D.PRERELEASE]}?${j[D.BUILD]}?`);K("FULL",`^${j[D.FULLPLAIN]}$`);K("LOOSEPLAIN",`[v=\\s]*${j[D.MAINVERSIONLOOSE]}${j[D.PRERELEASELOOSE]}?${j[D.BUILD]}?`);K("LOOSE",`^${j[D.LOOSEPLAIN]}$`);K("GTLT","((?:<|>)?=?)");K("XRANGEIDENTIFIERLOOSE",`${j[D.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);K("XRANGEIDENTIFIER",`${j[D.NUMERICIDENTIFIER]}|x|X|\\*`);K("XRANGEPLAIN",`[v=\\s]*(${j[D.XRANGEIDENTIFIER]})(?:\\.(${j[D.XRANGEIDENTIFIER]})(?:\\.(${j[D.XRANGEIDENTIFIER]})(?:${j[D.PRERELEASE]})?${j[D.BUILD]}?)?)?`);K("XRANGEPLAINLOOSE",`[v=\\s]*(${j[D.XRANGEIDENTIFIERLOOSE]})(?:\\.(${j[D.XRANGEIDENTIFIERLOOSE]})(?:\\.(${j[D.XRANGEIDENTIFIERLOOSE]})(?:${j[D.PRERELEASELOOSE]})?${j[D.BUILD]}?)?)?`);K("XRANGE",`^${j[D.GTLT]}\\s*${j[D.XRANGEPLAIN]}$`);K("XRANGELOOSE",`^${j[D.GTLT]}\\s*${j[D.XRANGEPLAINLOOSE]}$`);K("COERCEPLAIN",`(^|[^\\d])(\\d{1,${fu}})(?:\\.(\\d{1,${fu}}))?(?:\\.(\\d{1,${fu}}))?`);K("COERCE",`${j[D.COERCEPLAIN]}(?:$|[^\\d])`);K("COERCEFULL",j[D.COERCEPLAIN]+`(?:${j[D.PRERELEASE]})?(?:${j[D.BUILD]})?(?:$|[^\\d])`);K("COERCERTL",j[D.COERCE],!0);K("COERCERTLFULL",j[D.COERCEFULL],!0);K("LONETILDE","(?:~>?)");K("TILDETRIM",`(\\s*)${j[D.LONETILDE]}\\s+`,!0);sr.tildeTrimReplace="$1~";K("TILDE",`^${j[D.LONETILDE]}${j[D.XRANGEPLAIN]}$`);K("TILDELOOSE",`^${j[D.LONETILDE]}${j[D.XRANGEPLAINLOOSE]}$`);K("LONECARET","(?:\\^)");K("CARETTRIM",`(\\s*)${j[D.LONECARET]}\\s+`,!0);sr.caretTrimReplace="$1^";K("CARET",`^${j[D.LONECARET]}${j[D.XRANGEPLAIN]}$`);K("CARETLOOSE",`^${j[D.LONECARET]}${j[D.XRANGEPLAINLOOSE]}$`);K("COMPARATORLOOSE",`^${j[D.GTLT]}\\s*(${j[D.LOOSEPLAIN]})$|^$`);K("COMPARATOR",`^${j[D.GTLT]}\\s*(${j[D.FULLPLAIN]})$|^$`);K("COMPARATORTRIM",`(\\s*)${j[D.GTLT]}\\s*(${j[D.LOOSEPLAIN]}|${j[D.XRANGEPLAIN]})`,!0);sr.comparatorTrimReplace="$1$2$3";K("HYPHENRANGE",`^\\s*(${j[D.XRANGEPLAIN]})\\s+-\\s+(${j[D.XRANGEPLAIN]})\\s*$`);K("HYPHENRANGELOOSE",`^\\s*(${j[D.XRANGEPLAINLOOSE]})\\s+-\\s+(${j[D.XRANGEPLAINLOOSE]})\\s*$`);K("STAR","(<|>)?=?\\s*\\*");K("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");K("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")});var ra=A((P2,Uy)=>{"use strict";var Ik=Object.freeze({loose:!0}),Ok=Object.freeze({}),Rk=r=>r?typeof r!="object"?Ik:r:Ok;Uy.exports=Rk});var hu=A((I2,zy)=>{"use strict";var Vy=/^[0-9]+$/,By=(r,e)=>{if(typeof r=="number"&&typeof e=="number")return r===e?0:rBy(e,r);zy.exports={compareIdentifiers:By,rcompareIdentifiers:Tk}});var qe=A((O2,Ky)=>{"use strict";var na=bs(),{MAX_LENGTH:Hy,MAX_SAFE_INTEGER:ia}=ai(),{safeRe:sa,t:oa}=ci(),Mk=ra(),{compareIdentifiers:mu}=hu(),Ck=(r,e)=>{let t=e.split(".");if(t.length>r.length)return!1;for(let n=0;nHy)throw new TypeError(`version is longer than ${Hy} characters`);na("SemVer",e,t),this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease;let n=e.trim().match(t.loose?sa[oa.LOOSE]:sa[oa.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>ia||this.major<0)throw new TypeError("Invalid major version");if(this.minor>ia||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>ia||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(na("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 mu(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(na("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 mu(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?sa[oa.PRERELEASELOOSE]:sa[oa.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]),Ck(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}};Ky.exports=yu});var Gr=A((R2,Gy)=>{"use strict";var Wy=qe(),Nk=(r,e,t=!1)=>{if(r instanceof Wy)return r;try{return new Wy(r,e)}catch(n){if(!t)return null;throw n}};Gy.exports=Nk});var Yy=A((T2,Jy)=>{"use strict";var Lk=Gr(),jk=(r,e)=>{let t=Lk(r,e);return t?t.version:null};Jy.exports=jk});var Qy=A((M2,Xy)=>{"use strict";var Dk=Gr(),qk=(r,e)=>{let t=Dk(r.trim().replace(/^[=v]+/,""),e);return t?t.version:null};Xy.exports=qk});var tg=A((C2,eg)=>{"use strict";var Zy=qe(),Fk=(r,e,t,n,i)=>{typeof t=="string"&&(i=n,n=t,t=void 0);try{return new Zy(r instanceof Zy?r.version:r,t).inc(e,n,i).version}catch(s){return null}};eg.exports=Fk});var ig=A((N2,ng)=>{"use strict";var rg=Gr(),Uk=(r,e)=>{let t=rg(r,null,!0),n=rg(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 d=c?"pre":"";return t.major!==n.major?d+"major":t.minor!==n.minor?d+"minor":t.patch!==n.patch?d+"patch":"prerelease"};ng.exports=Uk});var og=A((L2,sg)=>{"use strict";var Vk=qe(),Bk=(r,e)=>new Vk(r,e).major;sg.exports=Bk});var cg=A((j2,ag)=>{"use strict";var zk=qe(),Hk=(r,e)=>new zk(r,e).minor;ag.exports=Hk});var dg=A((D2,lg)=>{"use strict";var Kk=qe(),Wk=(r,e)=>new Kk(r,e).patch;lg.exports=Wk});var fg=A((q2,ug)=>{"use strict";var Gk=Gr(),Jk=(r,e)=>{let t=Gk(r,e);return t&&t.prerelease.length?t.prerelease:null};ug.exports=Jk});var xt=A((F2,hg)=>{"use strict";var pg=qe(),Yk=(r,e,t)=>new pg(r,t).compare(new pg(e,t));hg.exports=Yk});var yg=A((U2,mg)=>{"use strict";var Xk=xt(),Qk=(r,e,t)=>Xk(e,r,t);mg.exports=Qk});var _g=A((V2,gg)=>{"use strict";var Zk=xt(),eP=(r,e)=>Zk(r,e,!0);gg.exports=eP});var aa=A((B2,wg)=>{"use strict";var bg=qe(),tP=(r,e,t)=>{let n=new bg(r,t),i=new bg(e,t);return n.compare(i)||n.compareBuild(i)};wg.exports=tP});var $g=A((z2,vg)=>{"use strict";var rP=aa(),nP=(r,e)=>r.sort((t,n)=>rP(t,n,e));vg.exports=nP});var Eg=A((H2,Sg)=>{"use strict";var iP=aa(),sP=(r,e)=>r.sort((t,n)=>iP(n,t,e));Sg.exports=sP});var ws=A((K2,Ag)=>{"use strict";var oP=xt(),aP=(r,e,t)=>oP(r,e,t)>0;Ag.exports=aP});var ca=A((W2,xg)=>{"use strict";var cP=xt(),lP=(r,e,t)=>cP(r,e,t)<0;xg.exports=lP});var gu=A((G2,kg)=>{"use strict";var dP=xt(),uP=(r,e,t)=>dP(r,e,t)===0;kg.exports=uP});var _u=A((J2,Pg)=>{"use strict";var fP=xt(),pP=(r,e,t)=>fP(r,e,t)!==0;Pg.exports=pP});var la=A((Y2,Ig)=>{"use strict";var hP=xt(),mP=(r,e,t)=>hP(r,e,t)>=0;Ig.exports=mP});var da=A((X2,Og)=>{"use strict";var yP=xt(),gP=(r,e,t)=>yP(r,e,t)<=0;Og.exports=gP});var bu=A((Q2,Rg)=>{"use strict";var _P=gu(),bP=_u(),wP=ws(),vP=la(),$P=ca(),SP=da(),EP=(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 _P(r,t,n);case"!=":return bP(r,t,n);case">":return wP(r,t,n);case">=":return vP(r,t,n);case"<":return $P(r,t,n);case"<=":return SP(r,t,n);default:throw new TypeError(`Invalid operator: ${e}`)}};Rg.exports=EP});var Mg=A((Z2,Tg)=>{"use strict";var AP=qe(),xP=Gr(),{safeRe:ua,t:fa}=ci(),kP=(r,e)=>{if(r instanceof AP)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?ua[fa.COERCEFULL]:ua[fa.COERCE]);else{let c=e.includePrerelease?ua[fa.COERCERTLFULL]:ua[fa.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 xP(`${n}.${i}.${s}${o}${a}`,e)};Tg.exports=kP});var Ng=A((eL,Cg)=>{"use strict";var PP=Gr(),IP=ai(),OP=qe(),RP=(r,e,t)=>{if(!IP.RELEASE_TYPES.includes(e))return null;let n=TP(r,t);return n&&MP(n,e)},TP=(r,e)=>{let t=r instanceof OP?r.version:r;return PP(t,e)},MP=(r,e)=>{if(CP(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()},CP=r=>r.startsWith("pre");Cg.exports=RP});var jg=A((tL,Lg)=>{"use strict";var wu=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}};Lg.exports=wu});var kt=A((rL,Ug)=>{"use strict";var NP=/\s+/g,vu=class r{constructor(e,t){if(t=jP(t),e instanceof r)return e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease?e:new r(e.raw,t);if(e instanceof $u)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(NP," "),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=>!qg(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&&KP(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(HP,"");let n=((this.options.includePrerelease&&BP)|(this.options.loose&&zP))+":"+e,i=Dg.get(n);if(i)return i;let s=this.options.loose,o=s?Qe[Fe.HYPHENRANGELOOSE]:Qe[Fe.HYPHENRANGE];e=e.replace(o,nI(this.options.includePrerelease)),we("hyphen replace",e),e=e.replace(Qe[Fe.COMPARATORTRIM],FP),we("comparator trim",e),e=e.replace(Qe[Fe.TILDETRIM],UP),we("tilde trim",e),e=e.replace(Qe[Fe.CARETTRIM],VP),we("caret trim",e);let a=e.split(" ").map(u=>WP(u,this.options)).join(" ").split(/\s+/).map(u=>rI(u,this.options));s&&(a=a.filter(u=>(we("loose invalid filter",u,this.options),!!u.match(Qe[Fe.COMPARATORLOOSE])))),we("range list",a);let c=new Map,l=a.map(u=>new $u(u,this.options));for(let u of l){if(qg(u))return[u];c.set(u.value,u)}c.size>1&&c.has("")&&c.delete("");let d=[...c.values()];return Dg.set(n,d),d}intersects(e,t){if(!(e instanceof r))throw new TypeError("a Range is required");return this.set.some(n=>Fg(n,t)&&e.set.some(i=>Fg(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 DP(e,this.options)}catch(t){return!1}for(let t=0;tr.value==="<0.0.0-0",KP=r=>r.value==="",Fg=(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},WP=(r,e)=>(r=r.replace(Qe[Fe.BUILD],""),we("comp",r,e),r=XP(r,e),we("caret",r),r=JP(r,e),we("tildes",r),r=ZP(r,e),we("xrange",r),r=tI(r,e),we("stars",r),r),Re=r=>!r||r.toLowerCase()==="x"||r==="*",GP=(r,e,t)=>Re(r)&&!Re(e)||Re(e)&&t&&!Re(t),JP=(r,e)=>r.trim().split(/\s+/).map(t=>YP(t,e)).join(" "),YP=(r,e)=>{let t=e.loose?Qe[Fe.TILDELOOSE]:Qe[Fe.TILDE],n=e.includePrerelease?"-0":"";return r.replace(t,(i,s,o,a,c)=>{we("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?(we("replaceTilde pr",c),l=`>=${s}.${o}.${a}-${c} <${s}.${+o+1}.0-0`):l=`>=${s}.${o}.${a} <${s}.${+o+1}.0-0`,we("tilde return",l),l})},XP=(r,e)=>r.trim().split(/\s+/).map(t=>QP(t,e)).join(" "),QP=(r,e)=>{we("caret",r,e);let t=e.loose?Qe[Fe.CARETLOOSE]:Qe[Fe.CARET],n=e.includePrerelease?"-0":"";return r.replace(t,(i,s,o,a,c)=>{we("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?(we("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`):(we("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`),we("caret return",l),l})},ZP=(r,e)=>(we("replaceXRanges",r,e),r.split(/\s+/).map(t=>eI(t,e)).join(" ")),eI=(r,e)=>{r=r.trim();let t=e.loose?Qe[Fe.XRANGELOOSE]:Qe[Fe.XRANGE];return r.replace(t,(n,i,s,o,a,c)=>{if(we("xRange",r,n,i,s,o,a,c),GP(s,o,a))return r;let l=Re(s),d=l||Re(o),u=d||Re(a),f=u;return i==="="&&f&&(i=""),c=e.includePrerelease?"-0":"",l?i===">"||i==="<"?n="<0.0.0-0":n="*":i&&f?(d&&(o=0),a=0,i===">"?(i=">=",d?(s=+s+1,o=0,a=0):(o=+o+1,a=0)):i==="<="&&(i="<",d?s=+s+1:o=+o+1),i==="<"&&(c="-0"),n=`${i+s}.${o}.${a}${c}`):d?n=`>=${s}.0.0${c} <${+s+1}.0.0-0`:u&&(n=`>=${s}.${o}.0${c} <${s}.${+o+1}.0-0`),we("xRange return",n),n})},tI=(r,e)=>(we("replaceStars",r,e),r.trim().replace(Qe[Fe.STAR],"")),rI=(r,e)=>(we("replaceGTE0",r,e),r.trim().replace(Qe[e.includePrerelease?Fe.GTE0PRE:Fe.GTE0],"")),nI=r=>(e,t,n,i,s,o,a,c,l,d,u,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(d)?c=`<${+l+1}.0.0-0`:Re(u)?c=`<${l}.${+d+1}.0-0`:f?c=`<=${l}.${d}.${u}-${f}`:r?c=`<${l}.${d}.${+u+1}-0`:c=`<=${c}`,`${t} ${c}`.trim()),iI=(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 vs=A((nL,Wg)=>{"use strict";var $s=Symbol("SemVer ANY"),Au=class r{static get ANY(){return $s}constructor(e,t){if(t=Vg(t),e instanceof r){if(e.loose===!!t.loose)return e;e=e.value}e=e.trim().split(/\s+/).join(" "),Eu("comparator",e,t),this.options=t,this.loose=!!t.loose,this.parse(e),this.semver===$s?this.value="":this.value=this.operator+this.semver.version,Eu("comp",this)}parse(e){let t=this.options.loose?Bg[zg.COMPARATORLOOSE]:Bg[zg.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 Hg(n[2],this.options.loose):this.semver=$s}toString(){return this.value}test(e){if(Eu("Comparator.test",e,this.options.loose),this.semver===$s||e===$s)return!0;if(typeof e=="string")try{e=new Hg(e,this.options)}catch(t){return!1}return Su(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 Kg(e.value,t).test(this.value):e.operator===""?e.value===""?!0:new Kg(this.value,t).test(e.semver):(t=Vg(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("=")||Su(this.semver,"<",e.semver,t)&&this.operator.startsWith(">")&&e.operator.startsWith("<")||Su(this.semver,">",e.semver,t)&&this.operator.startsWith("<")&&e.operator.startsWith(">")))}};Wg.exports=Au;var Vg=ra(),{safeRe:Bg,t:zg}=ci(),Su=bu(),Eu=bs(),Hg=qe(),Kg=kt()});var Ss=A((iL,Gg)=>{"use strict";var sI=kt(),oI=(r,e,t)=>{try{e=new sI(e,t)}catch(n){return!1}return e.test(r)};Gg.exports=oI});var Yg=A((sL,Jg)=>{"use strict";var aI=kt(),cI=(r,e)=>new aI(r,e).set.map(t=>t.map(n=>n.value).join(" ").trim().split(" "));Jg.exports=cI});var Qg=A((oL,Xg)=>{"use strict";var lI=qe(),dI=kt(),uI=(r,e,t)=>{let n=null,i=null,s=null;try{s=new dI(e,t)}catch(o){return null}return r.forEach(o=>{s.test(o)&&(!n||i.compare(o)===-1)&&(n=o,i=new lI(n,t))}),n};Xg.exports=uI});var e_=A((aL,Zg)=>{"use strict";var fI=qe(),pI=kt(),hI=(r,e,t)=>{let n=null,i=null,s=null;try{s=new pI(e,t)}catch(o){return null}return r.forEach(o=>{s.test(o)&&(!n||i.compare(o)===1)&&(n=o,i=new fI(n,t))}),n};Zg.exports=hI});var n_=A((cL,r_)=>{"use strict";var xu=qe(),mI=kt(),t_=ws(),yI=(r,e)=>{r=new mI(r,e);let t=new xu("0.0.0");if(r.test(t)||(t=new xu("0.0.0-0"),r.test(t)))return t;t=null;for(let n=0;n{let a=new xu(o.semver.version);switch(o.operator){case">":a.prerelease.length===0?a.patch++:a.prerelease.push(0),a.raw=a.format();case"":case">=":(!s||t_(a,s))&&(s=a);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${o.operator}`)}}),s&&(!t||t_(t,s))&&(t=s)}return t&&r.test(t)?t:null};r_.exports=yI});var s_=A((lL,i_)=>{"use strict";var gI=kt(),_I=(r,e)=>{try{return new gI(r,e).range||"*"}catch(t){return null}};i_.exports=_I});var pa=A((dL,l_)=>{"use strict";var bI=qe(),c_=vs(),{ANY:wI}=c_,vI=kt(),$I=Ss(),o_=ws(),a_=ca(),SI=da(),EI=la(),AI=(r,e,t,n)=>{r=new bI(r,n),e=new vI(e,n);let i,s,o,a,c;switch(t){case">":i=o_,s=SI,o=a_,a=">",c=">=";break;case"<":i=a_,s=EI,o=o_,a="<",c="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if($I(r,e,n))return!1;for(let l=0;l{p.semver===wI&&(p=new c_(">=0.0.0")),u=u||p,f=f||p,i(p.semver,u.semver,n)?u=p:o(p.semver,f.semver,n)&&(f=p)}),u.operator===a||u.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};l_.exports=AI});var u_=A((uL,d_)=>{"use strict";var xI=pa(),kI=(r,e,t)=>xI(r,e,">",t);d_.exports=kI});var p_=A((fL,f_)=>{"use strict";var PI=pa(),II=(r,e,t)=>PI(r,e,"<",t);f_.exports=II});var y_=A((pL,m_)=>{"use strict";var h_=kt(),OI=(r,e,t)=>(r=new h_(r,t),e=new h_(e,t),r.intersects(e,t));m_.exports=OI});var __=A((hL,g_)=>{"use strict";var RI=Ss(),TI=xt();g_.exports=(r,e,t)=>{let n=[],i=null,s=null,o=r.sort((d,u)=>TI(d,u,t));for(let d of o)RI(d,e,t)?(s=d,i||(i=d)):(s&&n.push([i,s]),s=null,i=null);i&&n.push([i,null]);let a=[];for(let[d,u]of n)d===u?a.push(d):!u&&d===o[0]?a.push("*"):u?d===o[0]?a.push(`<=${u}`):a.push(`${d} - ${u}`):a.push(`>=${d}`);let c=a.join(" || "),l=typeof e.raw=="string"?e.raw:String(e);return c.length{"use strict";var b_=kt(),Iu=vs(),{ANY:ku}=Iu,Pu=Ss(),Ou=xt(),MI=(r,e,t={})=>{if(r===e)return!0;r=new b_(r,t),e=new b_(e,t);let n=!1;e:for(let i of r.set){for(let s of e.set){let o=NI(i,s,t);if(n=n||o!==null,o)continue e}if(n)return!1}return!0},CI=[new Iu(">=0.0.0-0")],w_=[new Iu(">=0.0.0")],NI=(r,e,t)=>{if(r===e)return!0;if(r.length===1&&r[0].semver===ku){if(e.length===1&&e[0].semver===ku)return!0;t.includePrerelease?r=CI:r=w_}if(e.length===1&&e[0].semver===ku){if(t.includePrerelease)return!0;e=w_}let n=new Set,i,s;for(let p of r)p.operator===">"||p.operator===">="?i=v_(i,p,t):p.operator==="<"||p.operator==="<="?s=$_(s,p,t):n.add(p.semver);if(n.size>1)return null;let o;if(i&&s){if(o=Ou(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&&!Pu(p,String(i),t)||s&&!Pu(p,String(s),t))return null;for(let y of e)if(!Pu(p,String(y),t))return!1;return!0}let a,c,l,d,u=s&&!t.includePrerelease&&s.semver.prerelease.length?s.semver:!1,f=i&&!t.includePrerelease&&i.semver.prerelease.length?i.semver:!1;u&&u.prerelease.length===1&&s.operator==="<"&&u.prerelease[0]===0&&(u=!1);for(let p of e){if(d=d||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=v_(i,p,t),a===p&&a!==i)return!1}else if(i.operator===">="&&!p.test(i.semver))return!1}if(s){if(u&&p.semver.prerelease&&p.semver.prerelease.length&&p.semver.major===u.major&&p.semver.minor===u.minor&&p.semver.patch===u.patch&&(u=!1),p.operator==="<"||p.operator==="<="){if(c=$_(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&&d&&!i&&o!==0||f||u)},v_=(r,e,t)=>{if(!r)return e;let n=Ou(r.semver,e.semver,t);return n>0?r:n<0||e.operator===">"&&r.operator===">="?e:r},$_=(r,e,t)=>{if(!r)return e;let n=Ou(r.semver,e.semver,t);return n<0?r:n>0||e.operator==="<"&&r.operator==="<="?e:r};S_.exports=MI});var P_=A((yL,k_)=>{"use strict";var Ru=ci(),A_=ai(),LI=qe(),x_=hu(),jI=Gr(),DI=Yy(),qI=Qy(),FI=tg(),UI=ig(),VI=og(),BI=cg(),zI=dg(),HI=fg(),KI=xt(),WI=yg(),GI=_g(),JI=aa(),YI=$g(),XI=Eg(),QI=ws(),ZI=ca(),eO=gu(),tO=_u(),rO=la(),nO=da(),iO=bu(),sO=Mg(),oO=Ng(),aO=vs(),cO=kt(),lO=Ss(),dO=Yg(),uO=Qg(),fO=e_(),pO=n_(),hO=s_(),mO=pa(),yO=u_(),gO=p_(),_O=y_(),bO=__(),wO=E_();k_.exports={parse:jI,valid:DI,clean:qI,inc:FI,diff:UI,major:VI,minor:BI,patch:zI,prerelease:HI,compare:KI,rcompare:WI,compareLoose:GI,compareBuild:JI,sort:YI,rsort:XI,gt:QI,lt:ZI,eq:eO,neq:tO,gte:rO,lte:nO,cmp:iO,coerce:sO,truncate:oO,Comparator:aO,Range:cO,satisfies:lO,toComparators:dO,maxSatisfying:uO,minSatisfying:fO,minVersion:pO,validRange:hO,outside:mO,gtr:yO,ltr:gO,intersects:_O,simplifyRange:bO,subset:wO,SemVer:LI,re:Ru.re,src:Ru.src,tokens:Ru.t,SEMVER_SPEC_VERSION:A_.SEMVER_SPEC_VERSION,RELEASE_TYPES:A_.RELEASE_TYPES,compareIdentifiers:x_.compareIdentifiers,rcompareIdentifiers:x_.rcompareIdentifiers}});var As=A((CL,D_)=>{"use strict";var C_="[^\\\\/]",IO="(?=.)",N_="[^/]",Lu="(?:\\/|$)",L_="(?:^|\\/)",ju=`\\.{1,2}${Lu}`,OO="(?!\\.)",RO=`(?!${L_}${ju})`,TO=`(?!\\.{0,1}${Lu})`,MO=`(?!${ju})`,CO="[^.\\/]",NO=`${N_}*?`,LO="/",j_={DOT_LITERAL:"\\.",PLUS_LITERAL:"\\+",QMARK_LITERAL:"\\?",SLASH_LITERAL:"\\/",ONE_CHAR:IO,QMARK:N_,END_ANCHOR:Lu,DOTS_SLASH:ju,NO_DOT:OO,NO_DOTS:RO,NO_DOT_SLASH:TO,NO_DOTS_SLASH:MO,QMARK_NO_DOT:CO,STAR:NO,START_ANCHOR:L_,SEP:LO},jO={...j_,SLASH_LITERAL:"[\\\\/]",QMARK:C_,STAR:`${C_}*?`,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:"\\"},DO={__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"};D_.exports={DEFAULT_MAX_EXTGLOB_RECURSION:0,MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:DO,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?jO:j_}}});var xs=A(lt=>{"use strict";var{REGEX_BACKSLASH:qO,REGEX_REMOVE_BACKSLASH:FO,REGEX_SPECIAL_CHARS:UO,REGEX_SPECIAL_CHARS_GLOBAL:VO}=As();lt.isObject=r=>r!==null&&typeof r=="object"&&!Array.isArray(r);lt.hasRegexChars=r=>UO.test(r);lt.isRegexChar=r=>r.length===1&<.hasRegexChars(r);lt.escapeRegex=r=>r.replace(VO,"\\$1");lt.toPosixSlashes=r=>r.replace(qO,"/");lt.isWindows=()=>{if(typeof navigator!="undefined"&&navigator.platform){let r=navigator.platform.toLowerCase();return r==="win32"||r==="windows"}return typeof process!="undefined"&&process.platform?process.platform==="win32":!1};lt.removeBackslashes=r=>r.replace(FO,e=>e==="\\"?"":e);lt.escapeLast=(r,e,t)=>{let n=r.lastIndexOf(e,t);return n===-1?r:r[n-1]==="\\"?lt.escapeLast(r,e,n-1):`${r.slice(0,n)}\\${r.slice(n)}`};lt.removePrefix=(r,e={})=>{let t=r;return t.startsWith("./")&&(t=t.slice(2),e.prefix="./"),t};lt.wrapOutput=(r,e={},t={})=>{let n=t.contains?"":"^",i=t.contains?"":"$",s=`${n}(?:${r})${i}`;return e.negated===!0&&(s=`(?:^(?!${s}).*$)`),s};lt.basename=(r,{windows:e}={})=>{let t=r.split(e?/[\\/]/:"/"),n=t[t.length-1];return n===""?t[t.length-2]:n}});var K_=A((LL,H_)=>{"use strict";var q_=xs(),{CHAR_ASTERISK:Du,CHAR_AT:BO,CHAR_BACKWARD_SLASH:ks,CHAR_COMMA:zO,CHAR_DOT:qu,CHAR_EXCLAMATION_MARK:Fu,CHAR_FORWARD_SLASH:z_,CHAR_LEFT_CURLY_BRACE:Uu,CHAR_LEFT_PARENTHESES:Vu,CHAR_LEFT_SQUARE_BRACKET:HO,CHAR_PLUS:KO,CHAR_QUESTION_MARK:F_,CHAR_RIGHT_CURLY_BRACE:WO,CHAR_RIGHT_PARENTHESES:U_,CHAR_RIGHT_SQUARE_BRACKET:GO}=As(),V_=r=>r===z_||r===ks,B_=r=>{r.isPrefix!==!0&&(r.depth=r.isGlobstar?1/0:1)},JO=(r,e)=>{let t=e||{},n=r.length-1,i=t.parts===!0||t.scanToEnd===!0,s=[],o=[],a=[],c=r,l=-1,d=0,u=0,f=!1,p=!1,y=!1,h=!1,m=!1,g=!1,_=!1,w=!1,k=!1,v=!1,P=0,O,$,R={value:"",depth:0,isGlob:!1},S=()=>l>=n,V=()=>c.charCodeAt(l+1),B=()=>(O=$,c.charCodeAt(++l));for(;l0&&(E=c.slice(0,d),c=c.slice(d),u-=d),T&&y===!0&&u>0?(T=c.slice(0,u),x=c.slice(u)):y===!0?(T="",x=c):T=c,T&&T!==""&&T!=="/"&&T!==c&&V_(T.charCodeAt(T.length-1))&&(T=T.slice(0,-1)),t.unescape===!0&&(x&&(x=q_.removeBackslashes(x)),T&&_===!0&&(T=q_.removeBackslashes(T)));let de={prefix:E,input:r,start:d,base:T,glob:x,isBrace:f,isBracket:p,isGlob:y,isExtglob:h,isGlobstar:m,negated:w,negatedExtglob:k};if(t.tokens===!0&&(de.maxDepth=0,V_($)||o.push(R),de.tokens=o),t.parts===!0||t.tokens===!0){let Z;for(let U=0;U{"use strict";var Ps=As(),mt=xs(),{MAX_LENGTH:ga,POSIX_REGEX_SOURCE:YO,REGEX_NON_SPECIAL_CHARS:XO,REGEX_SPECIAL_CHARS_BACKREF:QO,REPLACEMENTS:W_}=Ps,ZO=(r,e)=>{if(typeof e.expandRange=="function")return e.expandRange(...r,e);r.sort();let t=`[${r.join("-")}]`;try{new RegExp(t)}catch(n){return r.map(i=>mt.escapeRegex(i)).join("..")}return t},li=(r,e)=>`Missing ${r}: "${e}" - use "\\\\${e}" to match literal characters`,G_=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},eR=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},zu=r=>{let e=r.trim(),t=!0;for(;t===!0;)t=!1,/^@\([^\\()[\]{}|]+\)$/.test(e)&&(e=e.slice(2,-1),t=!0);if(eR(e))return e.replace(/\\(.)/g,"$1")},tR=r=>{let e=r.map(zu).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}}}}},rR=r=>`${r.length===1?mt.escapeRegex(r[0]):`[${r.map(t=>mt.escapeRegex(t)).join("")}]`}*`,nR=r=>{let e=0,t=[];for(;eo.trim());if(i.length!==1)return;let s=zu(i[0]);if(!s||s.length!==1)return;t.push(s),e+=n.end+1}if(!(t.length<1))return t},iR=r=>{let e=0,t=r.trim(),n=Bu(t);for(;n;)e++,t=n.body.trim(),n=Bu(t);return e},sR=(r,e)=>{if(e.maxExtglobRecursion===!1)return{risky:!1};let t=typeof e.maxExtglobRecursion=="number"?e.maxExtglobRecursion:Ps.DEFAULT_MAX_EXTGLOB_RECURSION,n=G_(r).map(a=>a.trim());if(n.length>1&&(n.some(a=>a==="")||n.some(a=>/^[*?]+$/.test(a))||tR(n)))return{risky:!0};let i=[],s=!1,o=!0;for(let a of n){let c=nR(a);if(c){s=!0,i.push(...c);continue}let l=zu(a);if(l&&l.length===1){i.push(l);continue}if(o=!1,iR(a)>t)return{risky:!0}}return s?o?{risky:!0,safeOutput:rR([...new Set(i)])}:{risky:!0}:{risky:!1}},Hu=(r,e)=>{if(typeof r!="string")throw new TypeError("Expected a string");r=W_[r]||r;let t={...e},n=typeof t.maxLength=="number"?Math.min(ga,t.maxLength):ga,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=Ps.globChars(t.windows),l=Ps.extglobChars(c),{DOT_LITERAL:d,PLUS_LITERAL:u,SLASH_LITERAL:f,ONE_CHAR:p,DOTS_SLASH:y,NO_DOT:h,NO_DOT_SLASH:m,NO_DOTS_SLASH:g,QMARK:_,QMARK_NO_DOT:w,STAR:k,START_ANCHOR:v}=c,P=C=>`(${a}(?:(?!${v}${C.dot?y:d}).)*?)`,O=t.dot?"":h,$=t.dot?_:w,R=t.bash===!0?P(t):k;t.capture&&(R=`(${R})`),typeof t.noext=="boolean"&&(t.noextglob=t.noext);let S={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=mt.removePrefix(r,S),i=r.length;let V=[],B=[],T=[],E=s,x,de=()=>S.index===i-1,Z=S.peek=(C=1)=>r[S.index+C],U=S.advance=()=>r[++S.index]||"",fe=()=>r.slice(S.index+1),Ve=(C="",$e=0)=>{S.consumed+=C,S.index+=$e},Yt=C=>{S.output+=C.output!=null?C.output:C.value,Ve(C.value)},Lr=()=>{let C=1;for(;Z()==="!"&&(Z(2)!=="("||Z(3)==="?");)U(),S.start++,C++;return C%2===0?!1:(S.negated=!0,S.start++,!0)},ln=C=>{S[C]++,T.push(C)},jr=C=>{S[C]--,T.pop()},ee=C=>{if(E.type==="globstar"){let $e=S.braces>0&&(C.type==="comma"||C.type==="brace"),M=C.extglob===!0||V.length&&(C.type==="pipe"||C.type==="paren");C.type!=="slash"&&C.type!=="paren"&&!$e&&!M&&(S.output=S.output.slice(0,-E.output.length),E.type="star",E.value="*",E.output=R,S.output+=E.output)}if(V.length&&C.type!=="paren"&&(V[V.length-1].inner+=C.value),(C.value||C.output)&&Yt(C),E&&E.type==="text"&&C.type==="text"){E.output=(E.output||E.value)+C.value,E.value+=C.value;return}C.prev=E,o.push(C),E=C},go=(C,$e)=>{let M={...l[$e],conditions:1,inner:""};M.prev=E,M.parens=S.parens,M.output=S.output,M.startIndex=S.index,M.tokensIndex=o.length;let te=(t.capture?"(":"")+M.open;ln("parens"),ee({type:C,value:$e,output:S.output?"":p}),ee({type:"paren",extglob:!0,value:U(),output:te}),V.push(M)},U0=C=>{let $e=r.slice(C.startIndex,S.index+1),M=r.slice(C.startIndex+2,S.index),te=sR(M,t);if((C.type==="plus"||C.type==="star")&&te.risky){let he=te.safeOutput?(C.output?"":p)+(t.capture?`(${te.safeOutput})`:te.safeOutput):void 0,Xt=o[C.tokensIndex];Xt.type="text",Xt.value=$e,Xt.output=he||mt.escapeRegex($e);for(let Qt=C.tokensIndex+1;Qt1&&C.inner.includes("/")&&(he=P(t)),(he!==R||de()||/^\)+$/.test(fe()))&&(ye=C.close=`)$))${he}`),C.inner.includes("*")&&(Oe=fe())&&/^\.[^\\/.]+$/.test(Oe)){let Xt=Hu(Oe,{...e,fastpaths:!1}).output;ye=C.close=`)${Xt})${he})`}C.prev.type==="bos"&&(S.negatedExtglob=!0)}ee({type:"paren",extglob:!0,value:x,output:ye}),jr("parens")};if(t.fastpaths!==!1&&!/(^[*!]|[/()[\]{}"])/.test(r)){let C=!1,$e=r.replace(QO,(M,te,ye,Oe,he,Xt)=>Oe==="\\"?(C=!0,M):Oe==="?"?te?te+Oe+(he?_.repeat(he.length):""):Xt===0?$+(he?_.repeat(he.length):""):_.repeat(ye.length):Oe==="."?d.repeat(ye.length):Oe==="*"?te?te+Oe+(he?R:""):R:te?M:`\\${M}`);return C===!0&&(t.unescape===!0?$e=$e.replace(/\\/g,""):$e=$e.replace(/\\+/g,M=>M.length%2===0?"\\\\":M?"\\":"")),$e===r&&t.contains===!0?(S.output=r,S):(S.output=mt.wrapOutput($e,S,e),S)}for(;!de();){if(x=U(),x==="\0")continue;if(x==="\\"){let M=Z();if(M==="/"&&t.bash!==!0||M==="."||M===";")continue;if(!M){x+="\\",ee({type:"text",value:x});continue}let te=/^\\+/.exec(fe()),ye=0;if(te&&te[0].length>2&&(ye=te[0].length,S.index+=ye,ye%2!==0&&(x+="\\")),t.unescape===!0?x=U():x+=U(),S.brackets===0){ee({type:"text",value:x});continue}}if(S.brackets>0&&(x!=="]"||E.value==="["||E.value==="[^")){if(t.posix!==!1&&x===":"){let M=E.value.slice(1);if(M.includes("[")&&(E.posix=!0,M.includes(":"))){let te=E.value.lastIndexOf("["),ye=E.value.slice(0,te),Oe=E.value.slice(te+2),he=YO[Oe];if(he){E.value=ye+he,S.backtrack=!0,U(),!s.output&&o.indexOf(E)===1&&(s.output=p);continue}}}(x==="["&&Z()!==":"||x==="-"&&Z()==="]")&&(x=`\\${x}`),x==="]"&&(E.value==="["||E.value==="[^")&&(x=`\\${x}`),t.posix===!0&&x==="!"&&E.value==="["&&(x="^"),E.value+=x,Yt({value:x});continue}if(S.quotes===1&&x!=='"'){x=mt.escapeRegex(x),E.value+=x,Yt({value:x});continue}if(x==='"'){S.quotes=S.quotes===1?0:1,t.keepQuotes===!0&&ee({type:"text",value:x});continue}if(x==="("){ln("parens"),ee({type:"paren",value:x});continue}if(x===")"){if(S.parens===0&&t.strictBrackets===!0)throw new SyntaxError(li("opening","("));let M=V[V.length-1];if(M&&S.parens===M.parens+1){U0(V.pop());continue}ee({type:"paren",value:x,output:S.parens?")":"\\)"}),jr("parens");continue}if(x==="["){if(t.nobracket===!0||!fe().includes("]")){if(t.nobracket!==!0&&t.strictBrackets===!0)throw new SyntaxError(li("closing","]"));x=`\\${x}`}else ln("brackets");ee({type:"bracket",value:x});continue}if(x==="]"){if(t.nobracket===!0||E&&E.type==="bracket"&&E.value.length===1){ee({type:"text",value:x,output:`\\${x}`});continue}if(S.brackets===0){if(t.strictBrackets===!0)throw new SyntaxError(li("opening","["));ee({type:"text",value:x,output:`\\${x}`});continue}jr("brackets");let M=E.value.slice(1);if(E.posix!==!0&&M[0]==="^"&&!M.includes("/")&&(x=`/${x}`),E.value+=x,Yt({value:x}),t.literalBrackets===!1||mt.hasRegexChars(M))continue;let te=mt.escapeRegex(E.value);if(S.output=S.output.slice(0,-E.value.length),t.literalBrackets===!0){S.output+=te,E.value=te;continue}E.value=`(${a}${te}|${E.value})`,S.output+=E.value;continue}if(x==="{"&&t.nobrace!==!0){ln("braces");let M={type:"brace",value:x,output:"(",outputIndex:S.output.length,tokensIndex:S.tokens.length};B.push(M),ee(M);continue}if(x==="}"){let M=B[B.length-1];if(t.nobrace===!0||!M){ee({type:"text",value:x,output:x});continue}let te=")";if(M.dots===!0){let ye=o.slice(),Oe=[];for(let he=ye.length-1;he>=0&&(o.pop(),ye[he].type!=="brace");he--)ye[he].type!=="dots"&&Oe.unshift(ye[he].value);te=ZO(Oe,t),S.backtrack=!0}if(M.comma!==!0&&M.dots!==!0){let ye=S.output.slice(0,M.outputIndex),Oe=S.tokens.slice(M.tokensIndex);M.value=M.output="\\{",x=te="\\}",S.output=ye;for(let he of Oe)S.output+=he.output||he.value}ee({type:"brace",value:x,output:te}),jr("braces"),B.pop();continue}if(x==="|"){V.length>0&&V[V.length-1].conditions++,ee({type:"text",value:x});continue}if(x===","){let M=x,te=B[B.length-1];te&&T[T.length-1]==="braces"&&(te.comma=!0,M="|"),ee({type:"comma",value:x,output:M});continue}if(x==="/"){if(E.type==="dot"&&S.index===S.start+1){S.start=S.index+1,S.consumed="",S.output="",o.pop(),E=s;continue}ee({type:"slash",value:x,output:f});continue}if(x==="."){if(S.braces>0&&E.type==="dot"){E.value==="."&&(E.output=d);let M=B[B.length-1];E.type="dots",E.output+=x,E.value+=x,M.dots=!0;continue}if(S.braces+S.parens===0&&E.type!=="bos"&&E.type!=="slash"){ee({type:"text",value:x,output:d});continue}ee({type:"dot",value:x,output:d});continue}if(x==="?"){if(!(E&&E.value==="(")&&t.noextglob!==!0&&Z()==="("&&Z(2)!=="?"){go("qmark",x);continue}if(E&&E.type==="paren"){let te=Z(),ye=x;(E.value==="("&&!/[!=<:]/.test(te)||te==="<"&&!/<([!=]|\w+>)/.test(fe()))&&(ye=`\\${x}`),ee({type:"text",value:x,output:ye});continue}if(t.dot!==!0&&(E.type==="slash"||E.type==="bos")){ee({type:"qmark",value:x,output:w});continue}ee({type:"qmark",value:x,output:_});continue}if(x==="!"){if(t.noextglob!==!0&&Z()==="("&&(Z(2)!=="?"||!/[!=<:]/.test(Z(3)))){go("negate",x);continue}if(t.nonegate!==!0&&S.index===0){Lr();continue}}if(x==="+"){if(t.noextglob!==!0&&Z()==="("&&Z(2)!=="?"){go("plus",x);continue}if(E&&E.value==="("||t.regex===!1){ee({type:"plus",value:x,output:u});continue}if(E&&(E.type==="bracket"||E.type==="paren"||E.type==="brace")||S.parens>0){ee({type:"plus",value:x});continue}ee({type:"plus",value:u});continue}if(x==="@"){if(t.noextglob!==!0&&Z()==="("&&Z(2)!=="?"){ee({type:"at",extglob:!0,value:x,output:""});continue}ee({type:"text",value:x});continue}if(x!=="*"){(x==="$"||x==="^")&&(x=`\\${x}`);let M=XO.exec(fe());M&&(x+=M[0],S.index+=M[0].length),ee({type:"text",value:x});continue}if(E&&(E.type==="globstar"||E.star===!0)){E.type="star",E.star=!0,E.value+=x,E.output=R,S.backtrack=!0,S.globstar=!0,Ve(x);continue}let C=fe();if(t.noextglob!==!0&&/^\([^?]/.test(C)){go("star",x);continue}if(E.type==="star"){if(t.noglobstar===!0){Ve(x);continue}let M=E.prev,te=M.prev,ye=M.type==="slash"||M.type==="bos",Oe=te&&(te.type==="star"||te.type==="globstar");if(t.bash===!0&&(!ye||C[0]&&C[0]!=="/")){ee({type:"star",value:x,output:""});continue}let he=S.braces>0&&(M.type==="comma"||M.type==="brace"),Xt=V.length&&(M.type==="pipe"||M.type==="paren");if(!ye&&M.type!=="paren"&&!he&&!Xt){ee({type:"star",value:x,output:""});continue}for(;C.slice(0,3)==="/**";){let Qt=r[S.index+4];if(Qt&&Qt!=="/")break;C=C.slice(3),Ve("/**",3)}if(M.type==="bos"&&de()){E.type="globstar",E.value+=x,E.output=P(t),S.output=E.output,S.globstar=!0,Ve(x);continue}if(M.type==="slash"&&M.prev.type!=="bos"&&!Oe&&de()){S.output=S.output.slice(0,-(M.output+E.output).length),M.output=`(?:${M.output}`,E.type="globstar",E.output=P(t)+(t.strictSlashes?")":"|$)"),E.value+=x,S.globstar=!0,S.output+=M.output+E.output,Ve(x);continue}if(M.type==="slash"&&M.prev.type!=="bos"&&C[0]==="/"){let Qt=C[1]!==void 0?"|$":"";S.output=S.output.slice(0,-(M.output+E.output).length),M.output=`(?:${M.output}`,E.type="globstar",E.output=`${P(t)}${f}|${f}${Qt})`,E.value+=x,S.output+=M.output+E.output,S.globstar=!0,Ve(x+U()),ee({type:"slash",value:"/",output:""});continue}if(M.type==="bos"&&C[0]==="/"){E.type="globstar",E.value+=x,E.output=`(?:^|${f}|${P(t)}${f})`,S.output=E.output,S.globstar=!0,Ve(x+U()),ee({type:"slash",value:"/",output:""});continue}S.output=S.output.slice(0,-E.output.length),E.type="globstar",E.output=P(t),E.value+=x,S.output+=E.output,S.globstar=!0,Ve(x);continue}let $e={type:"star",value:x,output:R};if(t.bash===!0){$e.output=".*?",(E.type==="bos"||E.type==="slash")&&($e.output=O+$e.output),ee($e);continue}if(E&&(E.type==="bracket"||E.type==="paren")&&t.regex===!0){$e.output=x,ee($e);continue}(S.index===S.start||E.type==="slash"||E.type==="dot")&&(E.type==="dot"?(S.output+=m,E.output+=m):t.dot===!0?(S.output+=g,E.output+=g):(S.output+=O,E.output+=O),Z()!=="*"&&(S.output+=p,E.output+=p)),ee($e)}for(;S.brackets>0;){if(t.strictBrackets===!0)throw new SyntaxError(li("closing","]"));S.output=mt.escapeLast(S.output,"["),jr("brackets")}for(;S.parens>0;){if(t.strictBrackets===!0)throw new SyntaxError(li("closing",")"));S.output=mt.escapeLast(S.output,"("),jr("parens")}for(;S.braces>0;){if(t.strictBrackets===!0)throw new SyntaxError(li("closing","}"));S.output=mt.escapeLast(S.output,"{"),jr("braces")}if(t.strictSlashes!==!0&&(E.type==="star"||E.type==="bracket")&&ee({type:"maybe_slash",value:"",output:`${f}?`}),S.backtrack===!0){S.output="";for(let C of S.tokens)S.output+=C.output!=null?C.output:C.value,C.suffix&&(S.output+=C.suffix)}return S};Hu.fastpaths=(r,e)=>{let t={...e},n=typeof t.maxLength=="number"?Math.min(ga,t.maxLength):ga,i=r.length;if(i>n)throw new SyntaxError(`Input length: ${i}, exceeds maximum allowed length: ${n}`);r=W_[r]||r;let{DOT_LITERAL:s,SLASH_LITERAL:o,ONE_CHAR:a,DOTS_SLASH:c,NO_DOT:l,NO_DOTS:d,NO_DOTS_SLASH:u,STAR:f,START_ANCHOR:p}=Ps.globChars(t.windows),y=t.dot?d:l,h=t.dot?u:l,m=t.capture?"":"?:",g={negated:!1,prefix:""},_=t.bash===!0?".*?":f;t.capture&&(_=`(${_})`);let w=O=>O.noglobstar===!0?_:`(${m}(?:(?!${p}${O.dot?c:s}).)*?)`,k=O=>{switch(O){case"*":return`${y}${a}${_}`;case".*":return`${s}${a}${_}`;case"*.*":return`${y}${_}${s}${a}${_}`;case"*/*":return`${y}${_}${o}${a}${h}${_}`;case"**":return y+w(t);case"**/*":return`(?:${y}${w(t)}${o})?${h}${a}${_}`;case"**/*.*":return`(?:${y}${w(t)}${o})?${h}${_}${s}${a}${_}`;case"**/.*":return`(?:${y}${w(t)}${o})?${s}${a}${_}`;default:{let $=/^(.*?)\.(\w+)$/.exec(O);if(!$)return;let R=k($[1]);return R?R+s+$[2]:void 0}}},v=mt.removePrefix(r,g),P=k(v);return P&&t.strictSlashes!==!0&&(P+=`${o}?`),P};J_.exports=Hu});var Z_=A((DL,Q_)=>{"use strict";var oR=K_(),Ku=Y_(),X_=xs(),aR=As(),cR=r=>r&&typeof r=="object"&&!Array.isArray(r),ke=(r,e,t=!1)=>{if(Array.isArray(r)){let d=r.map(f=>ke(f,e,t));return f=>{for(let p of d){let y=p(f);if(y)return y}return!1}}let n=cR(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?ke.compileRe(r,e):ke.makeRe(r,e,!1,!0),a=o.state;delete o.state;let c=()=>!1;if(i.ignore){let d={...e,ignore:null,onMatch:null,onResult:null};c=ke(i.ignore,d,t)}let l=(d,u=!1)=>{let{isMatch:f,match:p,output:y}=ke.test(d,o,e,{glob:r,posix:s}),h={glob:r,state:a,regex:o,posix:s,input:d,output:y,match:p,isMatch:f};return typeof i.onResult=="function"&&i.onResult(h),f===!1?(h.isMatch=!1,u?h:!1):c(d)?(typeof i.onIgnore=="function"&&i.onIgnore(h),h.isMatch=!1,u?h:!1):(typeof i.onMatch=="function"&&i.onMatch(h),u?h:!0)};return t&&(l.state=a),l};ke.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?X_.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=ke.matchBase(r,e,t,i):a=e.exec(c)),{isMatch:!!a,match:a,output:c}};ke.matchBase=(r,e,t,n=t&&t.windows)=>(e instanceof RegExp?e:ke.makeRe(e,t)).test(X_.basename(r,{windows:n}));ke.isMatch=(r,e,t)=>ke(e,t)(r);ke.parse=(r,e)=>Array.isArray(r)?r.map(t=>ke.parse(t,e)):Ku(r,{...e,fastpaths:!1});ke.scan=(r,e)=>oR(r,e);ke.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=ke.toRegex(a,e);return n===!0&&(c.state=r),c};ke.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=Ku.fastpaths(r,e)),i.output||(i=Ku(r,e)),ke.compileRe(i,e,t,n)};ke.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/$^/}};ke.constants=aR;Q_.exports=ke});var Wu=A((qL,rb)=>{"use strict";var eb=Z_(),lR=xs();function tb(r,e,t=!1){return e&&(e.windows===null||e.windows===void 0)&&(e={...e,windows:lR.isWindows()}),eb(r,e,t)}Object.assign(tb,eb);rb.exports=tb});var b,Ee=vp(()=>{b=class extends Error{constructor(t,n){super(n);I(this,"code");this.code=t}}});async function S0(r,e,t,n){if(r!=null&&r.batch){if(r.batch.plan.fingerprint!==e.fingerprint)throw new b("mirror_recovery_required","A different prepared sync batch must recover before this plan can apply.");return r}let i=r?structuredClone(r):HM(e.replica_id,e.scope_epoch,e.mode,e.selective_sync);return i.scope_epoch=e.scope_epoch,i.selective_sync=e.selective_sync,i.batch={phase:"prepared",plan:e,next_action:0,receipts:[],payloads:t,checkpoint_before:{generation:e.checkpoint_generation,cursor:e.base_cursor},checkpoint_after:{generation:e.checkpoint_generation+1,cursor:e.authority_cursor}},await n.write(i),i}async function E0(r,e){let t=nt(r);t.phase!=="effects_complete"&&(t.phase="applying",delete t.failure,await Tc(r,{type:"phase",plan_fingerprint:t.plan.fingerprint,phase:"applying"},e))}async function A0(r,e,t){let n=nt(r),i=n.plan.actions[n.next_action];if(!i||i.action_id!==e.action_id)throw new b("invalid_mirror_state","The durable sync receipt does not match the next prepared action.");let s={type:"receipt",plan_fingerprint:n.plan.fingerprint,receipt:structuredClone(e),delta:zM(r,i)};n.receipts.push(structuredClone(e)),n.next_action+=1,await Tc(r,s,t)}async function x0(r,e){let t=nt(r),n=t.plan.actions[t.next_action];if(!n||n.command!=="advance_checkpoint")throw new b("invalid_mirror_state","Sync effects cannot complete before the checkpoint action is next.");t.phase="effects_complete",await Tc(r,{type:"effects_complete",plan_fingerprint:t.plan.fingerprint},e)}async function Rc(r,e,t,n){let i=nt(r);i.phase=e,i.failure=t,await Tc(r,{type:"phase",plan_fingerprint:i.plan.fingerprint,phase:e,failure:t},n)}async function Tc(r,e,t){t.appendJournal?await t.appendJournal(e):await t.write(r)}function zM(r,e){var s,o,a,c;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]:io((s=r.planned_conflicts)==null?void 0:s[t])},local_bindings:{[t]:io((o=r.local_bindings)==null?void 0:o[t])}};return n==="record"?i.records={[t]:io(r.records[t])}:n==="resource"?i.resources={[t]:io((a=r.resources)==null?void 0:a[t])}:i.files={[t]:io((c=r.files)==null?void 0:c[t])},i}function io(r){return r===void 0?null:structuredClone(r)}function nt(r){if(!r.batch)throw new b("invalid_mirror_state","The mirror has no prepared sync batch.");return r.batch}async function k0(r,e){var n;let t=nt(r);if(t.phase!=="blocked"||((n=t.failure)==null?void 0:n.code)!=="sync_plan_stale")throw new b("mirror_recovery_required","Only a stale batch at a durable action boundary can be abandoned.");delete r.batch,await e.write(r)}function HM(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 Mc=vp(()=>{Ee()});var MC={};G0(MC,{default:()=>zc});module.exports=J0(MC);var L=require("obsidian");var N=class extends Error{constructor(t,n,i){super(n);I(this,"code");I(this,"details");this.code=t,this.details=i,this.name="InteropError"}toPortableError(t){return{code:this.code,message:this.message,...this.details===void 0?{}:{details:this.details},...t===void 0?{}:{retryable:t}}}},Ui=class extends Error{constructor(t,n){super(n.message);I(this,"status");I(this,"error");this.status=t,this.error=n,this.name="ActionHandlerError"}};var Ty=dn(Qd(),1),My=dn(cu(),1);var lu={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 fk=My.default;function Cy(){return Object.fromEntries(Object.entries(lu).map(([r,e])=>[r,structuredClone(e)]))}function du(){let r=new Ty.Ajv2020({allErrors:!0,strict:!1,validateFormats:!0});fk(r);let e=Cy();r.addSchema(e.profile);for(let[t,n]of Object.entries(e))t!=="profile"&&r.addSchema(n);return r}function br(r,e){let t=String(lu[e].$id),n=r.getSchema(t);if(!n)throw new Error(`Canonical interoperability schema is unavailable: ${e}`);return n}function Wr(r){return(r!=null?r:[]).map(e=>{var t;return`${e.instancePath||"/"} ${(t=e.message)!=null?t:e.keyword}`}).join("; ")}function ir(r,e){if(!("value"in r))throw new N("contract_digest_conflict",`${e} must be resolved to an inline JSON Schema before runtime registration.`);return structuredClone(r.value)}function Ny(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=ir(r.record_schema,"record_schema"),r.binding_schema&&(e.binding_schema=ir(r.binding_schema,"binding_schema"));break;case"event":e.data_schema=ir(r.data_schema,"data_schema"),r.source_schema&&(e.source_schema=ir(r.source_schema,"source_schema"));break;case"action":e.input_schema=ir(r.input_schema,"input_schema"),r.output_schema&&(e.output_schema=ir(r.output_schema,"output_schema")),r.error_schema&&(e.error_schema=ir(r.error_schema,"error_schema")),r.provider_schema&&(e.provider_schema=ir(r.provider_schema,"provider_schema")),r.behavior&&(e.behavior=structuredClone(r.behavior));break}return e}async function ea(r){return oi(Ny(r))}async function oi(r){return`sha256:${await pk(uu(r))}`}function Ly(r,e){return{data:si(r,e.data_schema,`${e.id} data_schema`),...e.source_schema?{source:si(r,e.source_schema,`${e.id} source_schema`)}:{}}}function jy(r,e){return{input:si(r,e.input_schema,`${e.id} input_schema`),...e.output_schema?{output:si(r,e.output_schema,`${e.id} output_schema`)}:{},...e.error_schema?{error:si(r,e.error_schema,`${e.id} error_schema`)}:{},...e.provider_schema?{provider:si(r,e.provider_schema,`${e.id} provider_schema`)}:{}}}function ta(r,e,t,n){if(!(!r||r(e)))throw new N(t,`${n} failed JSON Schema validation: ${Wr(r.errors)}`)}function si(r,e,t){try{return r.compile(ir(e,t))}catch(n){throw new N("contract_digest_conflict",`${t} could not be compiled: ${n instanceof Error?n.message:String(n)}`)}}function uu(r){return r===null||typeof r!="object"?JSON.stringify(r):Array.isArray(r)?`[${r.map(uu).join(",")}]`:`{${Object.entries(r).filter(([,t])=>t!==void 0).sort(([t],[n])=>tn?1:0).map(([t,n])=>`${JSON.stringify(t)}:${uu(n)}`).join(",")}}`}async function pk(r){let e=new TextEncoder().encode(r),t=await globalThis.crypto.subtle.digest("SHA-256",e);return[...new Uint8Array(t)].map(n=>n.toString(16).padStart(2,"0")).join("")}var vr=dn(P_(),1);var Tu={delivery:["ephemeral"],ordering:["none"],cancellation:!0,deadlines:!0,provider_discovery:!0,request_deduplication:!0,cross_process_identity:!1},vO=new Set(["specversion","id","source","type","time","subject","datacontenttype","dataschema","data","mdbaseprofile","mdbasecontractversion","mdbasecontractdigest","mdbaseapplication","mdbaseimplementation","mdbaseimplementationversion","mdbaseinstanceid","correlationid","causationid"]),Es=class{constructor(e={}){I(this,"options");I(this,"profileVersion","0.1");I(this,"transport");I(this,"ajv",du());I(this,"contractValidator",br(this.ajv,"contract"));I(this,"eventValidator",br(this.ajv,"event"));I(this,"actionRequestValidator",br(this.ajv,"actionRequest"));I(this,"actionInvocationValidator",br(this.ajv,"actionInvocation"));I(this,"actionOutcomeValidator",br(this.ajv,"actionOutcome"));I(this,"eventSourceDeclarationValidator",br(this.ajv,"eventSourceDeclaration"));I(this,"actionProviderDeclarationValidator",br(this.ajv,"actionProviderDeclaration"));I(this,"contracts",new Map);I(this,"clients",new Map);I(this,"eventSources",new Map);I(this,"actionProviders",new Map);I(this,"subscriptions",new Map);I(this,"activeActions",new Map);I(this,"completedActions",new Map);I(this,"admissionLocks",new Map);I(this,"recentEvents",new Map);I(this,"authorize");I(this,"now");I(this,"idFactory");I(this,"recentEventLimit");I(this,"completedRequestLimit");I(this,"nextSequence",0);I(this,"disposed",!1);var t,n,i,s,o,a,c,l,d,u;this.options=e,this.authorize=(t=e.authorize)!=null?t:(()=>!1),this.now=(n=e.now)!=null?n:(()=>new Date),this.idFactory=(i=e.idFactory)!=null?i:(f=>{var y;this.nextSequence+=1;let p=typeof((y=globalThis.crypto)==null?void 0:y.randomUUID)=="function"?globalThis.crypto.randomUUID():`${this.now().getTime().toString(36)}-${this.nextSequence.toString(36)}`;return`${f}_${p}`}),this.recentEventLimit=Math.max(1,(s=e.recentEventLimit)!=null?s:1e3),this.completedRequestLimit=Math.max(1,(o=e.completedRequestLimit)!=null?o:1e3),this.transport={...Tu,...structuredClone((a=e.transport)!=null?a:{}),delivery:[...(l=(c=e.transport)==null?void 0:c.delivery)!=null?l:Tu.delivery],ordering:[...(u=(d=e.transport)==null?void 0:d.ordering)!=null?u:Tu.ordering]}}connect(e){this.assertActive(),$O(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){var l;let n=this.requireClient(e);if(t.contracts.length===0)throw new N("request_rejected","An event-source declaration must include a contract.");let i=`${e}:${t.declaration_id}`;if(this.eventSources.has(i))throw new N("request_rejected",`Event-source declaration ${t.declaration_id} is already registered.`);let s=new Map;for(let d of t.contracts){let u=await this.prepareEventContract(d.contract),f=I_(d.requirement,u.reference);if(O_(f,u.reference),await this.assertAuthorized({operation:"register_event_source",principal:n.identity,contract:u.reference}),u.sourceValidator&&!u.sourceValidator((l=d.binding)!=null?l:{}))throw new N("request_rejected",`${u.reference.id} source binding is invalid: ${Wr(u.sourceValidator.errors)}`);let p=ha(u.reference);if(s.has(p))throw new N("contract_digest_conflict",`Event contract ${p} is repeated by one declaration.`);s.set(p,{contract:u,requirement:f,...d.binding===void 0?{}:{binding:structuredClone(d.binding)},...d.ordering===void 0?{}:{ordering:[...d.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:d,requirement:u,binding:f,ordering:p})=>({requirement:structuredClone(u),resolved:structuredClone(d.reference),...f===void 0?{}:{binding:f},...p===void 0?{}:{ordering:p}}))},a={...o,declaration_digest:await oi(o)};Jr(this.eventSourceDeclarationValidator,a,"request_rejected","Event-source declaration"),this.commitContracts([...s.values()].map(({contract:d})=>d)),this.eventSources.set(i,{id:i,clientId:e,declaration:structuredClone(a),contracts:new Map([...s.entries()].map(([d,u])=>[d,{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){var y,h,m,g;let n=this.requireClient(e),i=ha(t.contract),s=[...n.sources].map(_=>this.eventSources.get(_)).find(_=>_==null?void 0:_.contracts.has(i));if(!s)throw new N("unknown_contract",`This client has not registered event contract ${t.contract.id} ${t.contract.version}.`);let o=(y=s.contracts.get(i))==null?void 0:y.contract;if(!o)throw new N("unknown_contract",`Event contract ${i} is unavailable.`);if(t.contract.digest&&t.contract.digest!==o.reference.digest)throw new N("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}}),Mu(t.data,"invalid_event_data",`Event ${o.reference.id} data`),ta(o.dataValidator,t.data,"invalid_event_data",`Event ${o.reference.id} data`);let a=(h=t.extensions)!=null?h:{};for(let _ of Object.keys(a))if(vO.has(_))throw new N("request_rejected",`Event extension ${_} is reserved.`);let c={...structuredClone(a),specversion:"1.0",id:(m=t.id)!=null?m:this.idFactory("evt"),source:SO(n.identity),type:o.reference.id,time:(g=t.time)!=null?g:this.now().toISOString(),...t.subject===void 0?{}:{subject:t.subject},datacontenttype:"application/json",dataschema:M_(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}};Jr(this.eventValidator,c,"invalid_event_data","Event envelope"),Cu(this.transport,c),EO(c,o.reference);let l=`${c.source}\0${c.id}`,d=this.recentEvents.get(l);if(d){if(JSON.stringify(d)!==JSON.stringify(c))throw new N("contract_digest_conflict",`Event ${c.source} ${c.id} was reused with different content.`);return{event:structuredClone(d),deliveries:0,duplicate:!0}}this.recentEvents.set(l,structuredClone(c)),T_(this.recentEvents,this.recentEventLimit);let u=[...this.subscriptions.values()].filter(({subscription:_})=>ma(_.contract,o.reference)),f=await Promise.allSettled(u.map(async _=>await this.isAuthorized({operation:"subscribe_event",principal:_.principal,contract:o.reference,...c.subject===void 0?{}:{subject:c.subject}})?(await _.handler(structuredClone(c)),!0):!1)),p=0;for(let _ of f)_.status==="fulfilled"&&_.value?p+=1:_.status==="rejected"&&this.report({severity:"error",code:"event_consumer_failed",message:`An event consumer failed while handling ${c.type}.`,contract:o.reference,cause:_.reason});return{event:structuredClone(c),deliveries:p,duplicate:!1}}async subscribeEvents(e,t,n){let i=this.requireClient(e);Nu(t.contract),kO(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){var u,f,p,y,h,m,g;let n=this.requireClient(e);if(t.handlers.length===0)throw new N("request_rejected","An action-provider declaration must include a handler.");let i=`${e}:${t.declaration_id}`;if(this.actionProviders.has(i))throw new N("request_rejected",`Action-provider declaration ${t.declaration_id} is already registered.`);let s=[],o=new Set;for(let _ of t.handlers){if(o.has(_.handler_id))throw new N("request_rejected",`Handler ${_.handler_id} is repeated.`);o.add(_.handler_id);let w=await this.prepareActionContract(_.contract),k=I_(_.requirement,w.reference);if(O_(k,w.reference),await this.assertAuthorized({operation:"register_action_provider",principal:n.identity,contract:w.reference,provider:n.identity}),w.providerValidator&&!w.providerValidator((u=_.binding)!=null?u:{}))throw new N("request_rejected",`${w.reference.id} provider binding is invalid: ${Wr(w.providerValidator.errors)}`);let v=(p=(f=_.contract.behavior)==null?void 0:f.idempotency)!=null?p:"none";if(((y=_.idempotency)==null?void 0:y.mode)==="request"&&v==="none")throw new N("request_rejected",`${w.reference.id} does not permit request deduplication.`);if(v==="required"&&((h=_.idempotency)==null?void 0:h.mode)!=="request")throw new N("request_rejected",`${w.reference.id} requires a provider with request deduplication.`);let P=(g=(m=_.contract.behavior)==null?void 0:m.cancellation)!=null?g:"none";if(_.cancellation==="cooperative"&&P!=="cooperative")throw new N("request_rejected",`${w.reference.id} does not declare cooperative cancellation.`);s.push({contract:w,declaration:{handler_id:_.handler_id,requirement:k,resolved:structuredClone(w.reference),..._.binding===void 0?{}:{binding:structuredClone(_.binding)},..._.idempotency===void 0?{}:{idempotency:structuredClone(_.idempotency)},..._.cancellation===void 0?{}:{cancellation:_.cancellation},..._.max_concurrency===void 0?{}:{max_concurrency:_.max_concurrency}},handler:_.handler})}let a={kind:"mdbase.action-provider",profile_version:"0.1",declaration_id:t.declaration_id,provider:structuredClone(n.identity),handlers:s.map(({declaration:_})=>structuredClone(_))},c={...a,declaration_digest:await oi(a)};Jr(this.actionProviderDeclarationValidator,c,"request_rejected","Action-provider declaration"),this.commitContracts(s.map(({contract:_})=>_));let l=s.map(({contract:_,declaration:w,handler:k})=>({registrationId:i,clientId:e,declaration:structuredClone(c),handlerDeclaration:structuredClone(w),contract:_,handler:k,active:0}));this.actionProviders.set(i,{id:i,clientId:e,declaration:structuredClone(c),handlers:l}),n.providers.add(i);let d=!0;return{declaration:structuredClone(c),dispose:()=>{d&&(d=!1,this.removeActionProvider(i))}}}async invokeAction(e,t){var a,c,l,d,u,f,p,y,h,m,g,_;let n=this.requireClient(e);Nu(t.contract);let i=(a=t.request_id)!=null?a:this.idFactory("req");this.cleanCompletedActions(),Mu(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:(c=t.created_at)!=null?c:this.now().toISOString(),...t.correlation_id===void 0?{}:{correlation_id:t.correlation_id},...t.causation_id===void 0?{}:{causation_id:t.causation_id},...t.subject===void 0?{}:{subject:t.subject},...t.idempotency_key===void 0?{}:{idempotency_key:t.idempotency_key},...t.deadline===void 0?{}:{deadline:t.deadline},...t.requested_provider===void 0?{}:{requested_provider:structuredClone(t.requested_provider)},input:structuredClone(t.input)};Jr(this.actionRequestValidator,s,"request_rejected","Action request"),Cu(this.transport,s);let o=await this.acquireAdmission(i);try{let w=await oi(AO(s)),k=this.activeActions.get(i);if(k){if(R_(e,i,w,k),((l=k.handler.handlerDeclaration.idempotency)==null?void 0:l.mode)!=="request")throw new N("request_rejected",`Action request ${i} is already active without deduplication.`);return structuredClone(await k.promise)}let v=this.completedActions.get(i);if(v){if(R_(e,i,w,v),!v.reusable)throw new N("request_rejected",`Action request ${i} was already completed without deduplication.`);return structuredClone(v.outcome)}if(s.deadline&&new Date(s.deadline).getTime()<=this.now().getTime())throw new N("deadline_exceeded",`Action request ${i} passed its deadline before admission.`);if(s.deadline&&!this.transport.deadlines)throw new N("unsupported_transport_capability","The active transport cannot enforce action deadlines.");let P=this.resolveActionCandidates(s.contract,s.requested_provider);P.length===0&&this.throwResolutionFailure(s.contract,s.requested_provider);let O=[];for(let U of P)await this.isAuthorized({operation:"invoke_action",principal:n.identity,contract:U.contract.reference,provider:U.declaration.provider,...s.subject===void 0?{}:{subject:s.subject}})&&O.push(U);if(O.length===0)throw new N("unauthorized",`No authorized provider can execute ${s.contract.id}.`);if(O.length>1)throw new N("ambiguous_provider",`Action ${s.contract.id} has ${O.length} eligible providers; select one explicitly.`);let $=O[0];if($.handlerDeclaration.max_concurrency!==void 0&&$.active>=$.handlerDeclaration.max_concurrency)throw new N("request_rejected",`Provider ${$.declaration.provider.implementation} is at capacity.`);if(((u=(d=$.contract.artifact.behavior)==null?void 0:d.idempotency)!=null?u:"none")==="required"&&!s.idempotency_key)throw new N("request_rejected",`${$.contract.reference.id} requires an idempotency key.`);ta($.contract.inputValidator,s.input,"invalid_action_input",`Action ${$.contract.reference.id} input`);let S={operation:"invoke_action",principal:n.identity,contract:$.contract.reference,provider:$.declaration.provider,...s.subject===void 0?{}:{subject:s.subject}},V=await((p=(f=this.options).authorizationContext)==null?void 0:p.call(f,S)),B={kind:"mdbase.action.invocation",profile_version:"0.1",invocation_id:this.idFactory("inv"),attempt_id:this.idFactory("attempt"),request_id:i,contract:structuredClone($.contract.reference),caller:structuredClone(n.identity),provider:structuredClone($.declaration.provider),provider_declaration_digest:$.declaration.declaration_digest,handler_id:$.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},...V===void 0?{}:{authorization_context:V},input:structuredClone(s.input)};Jr(this.actionInvocationValidator,B,"request_rejected","Action invocation"),await((h=(y=this.options).onInvocation)==null?void 0:h.call(y,structuredClone(B)));let T=new AbortController,E;if(B.deadline){let U=Math.max(0,new Date(B.deadline).getTime()-this.now().getTime());E=setTimeout(()=>T.abort(new N("deadline_exceeded",`Action request ${i} exceeded its deadline.`)),U)}$.active+=1;let x=this.executeAction($,B,T).finally(()=>{E!==void 0&&clearTimeout(E),$.active=Math.max(0,$.active-1),this.activeActions.delete(i)});this.activeActions.set(i,{clientId:e,requestId:i,requestDigest:w,handler:$,invocation:B,controller:T,promise:x}),o();let de=await x,Z=(g=(m=$.handlerDeclaration.idempotency)==null?void 0:m.retention_seconds)!=null?g:300;return this.completedActions.set(i,{clientId:e,requestDigest:w,outcome:structuredClone(de),reusable:((_=$.handlerDeclaration.idempotency)==null?void 0:_.mode)==="request",expiresAt:this.now().getTime()+Z*1e3}),T_(this.completedActions,this.completedRequestLimit),structuredClone(de)}finally{o()}}async executeAction(e,t,n){var i;try{let s=await e.handler(structuredClone(t.input),{invocation:structuredClone(t),signal:n.signal});if(n.signal.aborted){let a=n.signal.reason;return a instanceof N&&a.code==="deadline_exceeded"?this.failureOutcome(t,"failed",a.toPortableError()):this.failureOutcome(t,"cancelled",{code:"cancelled",message:`Action request ${t.request_id} was cancelled.`})}Mu(s,"invalid_action_output",`Action ${e.contract.reference.id} output`),ta(e.contract.outputValidator,s,"invalid_action_output",`Action ${e.contract.reference.id} output`);let o={kind:"mdbase.action.outcome",profile_version:"0.1",outcome_id:this.idFactory("outcome"),request_id:t.request_id,invocation_id:t.invocation_id,attempt_id:t.attempt_id,contract:structuredClone(t.contract),provider:structuredClone(t.provider),provider_declaration_digest:t.provider_declaration_digest,status:"succeeded",completed_at:this.now().toISOString(),output:structuredClone(s)};return Jr(this.actionOutcomeValidator,o,"invalid_action_output","Action outcome"),Cu(this.transport,o),o}catch(s){if(s instanceof Ui)return e.contract.errorValidator&&!e.contract.errorValidator((i=s.error.details)!=null?i:{})?this.failureOutcome(t,"failed",{code:"handler_failure",message:`Provider returned invalid declared error details: ${Wr(e.contract.errorValidator.errors)}`}):this.failureOutcome(t,s.status,s.error);if(s instanceof N)return this.failureOutcome(t,s.code==="cancelled"?"cancelled":s.code==="outcome_indeterminate"?"outcome_indeterminate":"failed",s.toPortableError());if(n.signal.aborted||PO(s)){let o=n.signal.reason;return o instanceof N&&o.code==="deadline_exceeded"?this.failureOutcome(t,"failed",o.toPortableError()):this.failureOutcome(t,"cancelled",{code:"cancelled",message:`Action request ${t.request_id} was cancelled.`})}return this.report({severity:"error",code:"action_handler_failed",message:`Provider ${t.provider.implementation} failed ${t.contract.id}.`,principal:t.provider,contract:t.contract,cause:s}),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 Jr(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 N("unauthorized",`Action request ${t} belongs to another caller.`);return a?structuredClone(a.outcome):null}if(o.clientId!==e)throw new N("unauthorized",`Action request ${t} belongs to another caller.`);if(await this.assertAuthorized({operation:"cancel_action",principal:i.identity,contract:o.invocation.contract,provider:o.invocation.provider,...o.invocation.subject===void 0?{}:{subject:o.invocation.subject}}),!this.transport.cancellation)throw new N("unsupported_transport_capability","The active transport cannot deliver cancellation.");if(o.handler.handlerDeclaration.cancellation!=="cooperative")throw new N("cancellation_unsupported",`Provider ${o.invocation.provider.implementation} does not support cancellation.`);return o.controller.abort(new N("cancelled",(n==null?void 0:n.trim())||`Action request ${t} was cancelled.`)),structuredClone(await o.promise)}resolveActionCandidates(e,t){let n=[...this.actionProviders.values()].flatMap(({handlers:s})=>s).filter(({contract:s,declaration:o})=>ma(e,s.reference)&&xO(t,o.provider)),i=(0,vr.maxSatisfying)([...new Set(n.map(({contract:s})=>s.reference.version))],e.version,{includePrerelease:!0});return i?n.filter(({contract:s})=>s.reference.version===i).sort((s,o)=>{var a,c;return s.declaration.provider.application.localeCompare(o.declaration.provider.application)||s.declaration.provider.implementation.localeCompare(o.declaration.provider.implementation)||((a=s.declaration.provider.instance_id)!=null?a:"").localeCompare((c=o.declaration.provider.instance_id)!=null?c:"")||s.handlerDeclaration.handler_id.localeCompare(o.handlerDeclaration.handler_id)}):[]}throwResolutionFailure(e,t){let n=[...this.contracts.values()].filter(i=>i.artifact.contract_type==="action"&&i.reference.id===e.id);throw n.length===0?new N("unknown_contract",`Action contract ${e.id} is unknown.`):n.some(({reference:i})=>ma(e,i))?t?new N("requested_provider_unavailable",`The requested provider is unavailable for ${e.id}.`):new N("no_provider",`No provider is registered for ${e.id}.`):new N("unsupported_contract_version",`No ${e.id} artifact satisfies ${e.version}.`)}async prepareEventContract(e){if(this.assertContractArtifact(e),e.contract_type!=="event")throw new N("unknown_contract",`${e.id} is not an event contract.`);let t={id:e.id,version:e.version,digest:await ea(e)};this.assertNoContractConflict(t);let n=Ly(this.ajv,e);return{artifact:structuredClone(e),reference:t,dataValidator:n.data,...n.source===void 0?{}:{sourceValidator:n.source}}}async prepareActionContract(e){if(this.assertContractArtifact(e),e.contract_type!=="action")throw new N("unknown_contract",`${e.id} is not an action contract.`);let t={id:e.id,version:e.version,digest:await ea(e)};this.assertNoContractConflict(t);let n=jy(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(Jr(this.contractValidator,e,"contract_digest_conflict",`Contract ${e.id||""}`),!(0,vr.valid)(e.version))throw new N("unsupported_contract_version",`${e.id} version must be exact SemVer.`)}assertNoContractConflict(e){let t=this.contracts.get(ha(e));if(t&&t.reference.digest!==e.digest)throw new N("contract_digest_conflict",`Contract ${e.id} ${e.version} conflicts with the registered artifact.`)}commitContracts(e){var n;let t=new Map;for(let i of e){let s=ha(i.reference),o=(n=t.get(s))!=null?n:this.contracts.get(s);if(o&&o.reference.digest!==i.reference.digest)throw new N("contract_digest_conflict",`Contract ${i.reference.id} ${i.reference.version} conflicts within the registration.`);t.set(s,i)}for(let[i,s]of t)this.contracts.has(i)||this.contracts.set(i,s)}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 N("cancelled","The caller unloaded.")),i.handler.clientId===e&&i.handler.handlerDeclaration.cancellation==="cooperative"&&i.controller.abort(new N("cancelled","The provider unloaded."));this.clients.delete(e),t||this.assertActive()}}removeEventSource(e){var n;let t=this.eventSources.get(e);t&&(this.eventSources.delete(e),(n=this.clients.get(t.clientId))==null||n.sources.delete(e))}removeActionProvider(e){var n;let t=this.actionProviders.get(e);if(t){this.actionProviders.delete(e),(n=this.clients.get(t.clientId))==null||n.providers.delete(e);for(let i of this.activeActions.values())i.handler.registrationId===e&&i.handler.handlerDeclaration.cancellation==="cooperative"&&i.controller.abort(new N("cancelled","The provider unloaded."))}}removeSubscription(e){var n;let t=this.subscriptions.get(e);t&&(this.subscriptions.delete(e),(n=this.clients.get(t.clientId))==null||n.subscriptions.delete(e))}requireClient(e){this.assertActive();let t=this.clients.get(e);if(!t||t.disposed)throw new N("transport_unavailable","Interop client is disposed.");return t}assertActive(){if(this.disposed)throw new N("transport_unavailable","Interop bridge is disposed.")}async assertAuthorized(e){if(!await this.isAuthorized(e))throw new N("unauthorized",`${e.operation} is not authorized.`)}async isAuthorized(e){try{return await this.authorize(structuredClone(e))}catch(t){return this.report({severity:"error",code:"authorization_failed",message:`Authorization failed for ${e.operation}.`,principal:e.principal,cause:t}),!1}}cleanCompletedActions(){let e=this.now().getTime();for(let[t,n]of this.completedActions)n.expiresAt<=e&&this.completedActions.delete(t)}async acquireAdmission(e){var a;let t=(a=this.admissionLocks.get(e))!=null?a:Promise.resolve(),n,i=new Promise(c=>{n=c}),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){var t,n;(n=(t=this.options).onDiagnostic)==null||n.call(t,structuredClone(e))}};function Jr(r,e,t,n){if(!r(e))throw new N(t,`${n} is invalid: ${Wr(r.errors)}`)}function $O(r){for(let[e,t]of Object.entries(r))if(t!==void 0&&(typeof t!="string"||t.length===0||!/^[A-Za-z0-9][A-Za-z0-9._:@/-]*$/u.test(t)))throw new N("request_rejected",`Implementation identity ${e} is invalid.`);if(!(0,vr.valid)(r.version))throw new N("request_rejected","Implementation identity version must be exact SemVer.")}function Nu(r){if(!/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)+$/u.test(r.id))throw new N("unknown_contract",`Contract ID ${r.id} is invalid.`);if(!(0,vr.validRange)(r.version,{includePrerelease:!0}))throw new N("unsupported_contract_version",`Contract requirement ${r.version} is not a SemVer range.`);if(r.digest&&!/^sha256:[0-9a-f]{64}$/u.test(r.digest))throw new N("contract_digest_conflict","Contract digest is invalid.")}function I_(r,e){let t=r!=null?r:{id:e.id,version:e.version,digest:e.digest};return Nu(t),structuredClone(t)}function O_(r,e){if(!ma(r,e))throw new N("unsupported_contract_version",`${e.id} ${e.version} does not satisfy its implementation requirement.`)}function ma(r,e){return r.id===e.id&&(0,vr.satisfies)(e.version,r.version,{includePrerelease:!0})&&(!r.digest||r.digest===e.digest)}function ha(r){return`${r.id}@${r.version}`}function M_(r){return`urn:mdbase:contract:${r.id}:${r.version}:${r.digest}`}function SO(r){return`urn:mdbase:app:${[r.application,r.implementation,...r.instance_id?[r.instance_id]:[]].map(encodeURIComponent).join(":")}`}function EO(r,e){if(r.type!==e.id||r.mdbasecontractversion!==e.version||r.mdbasecontractdigest!==e.digest||r.dataschema!==M_(e))throw new N("contract_digest_conflict","Event contract evidence is inconsistent.")}function AO(r){let{created_at:e,...t}=r;return t}function R_(r,e,t,n){if(n.clientId!==r)throw new N("unauthorized",`Action request ${e} belongs to another caller.`);if(n.requestDigest!==t)throw new N("request_rejected",`Action request ${e} was reused with different content.`)}function Mu(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 N(e,`${t}${o} must be a finite JSON number.`)}if(typeof s!="object")throw new N(e,`${t}${o} is not a JSON value.`);if(n.has(s))throw new N(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 N(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 Cu(r,e){if(r.max_payload_bytes===void 0)return;let t=JSON.stringify(e),n=new TextEncoder().encode(t).byteLength;if(n>r.max_payload_bytes)throw new N("unsupported_transport_capability",`The portable envelope is ${n} bytes; the active transport allows ${r.max_payload_bytes}.`)}function xO(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 kO(r,e){var t,n;if(e){if((t=e.delivery)!=null&&t.some(i=>!r.delivery.includes(i)))throw new N("unsupported_transport_capability","The active transport lacks a required delivery capability.");if((n=e.ordering)!=null&&n.some(i=>!r.ordering.includes(i)))throw new N("unsupported_transport_capability","The active transport lacks a required ordering capability.");for(let i of["cancellation","deadlines","provider_discovery","request_deduplication","cross_process_identity"])if(e[i]===!0&&r[i]!==!0)throw new N("unsupported_transport_capability",`The active transport lacks ${i}.`);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 PO(r){return r instanceof Error&&r.name==="AbortError"}var ya=class{constructor(e,t){this.app=e;this.profileVersion="0.1";this.bridge=new Es({authorize:()=>t(),transport:{delivery:["ephemeral"],ordering:["none"],cancellation:!0,deadlines:!0,provider_discovery:!0,request_deduplication:!0,cross_process_identity:!1},onDiagnostic:n=>{var s;(n.severity==="error"?console.error:console.warn)(`[mdbase/interop] ${n.code}: ${n.message}`,(s=n.cause)!=null?s:"")}}),this.transport=this.bridge.describe().transport}connect(e){var s,o;let t=(s=e.manifest)==null?void 0:s.id,n=(o=e.manifest)==null?void 0:o.version;if(!t||!n)throw new Error("Only a loaded Obsidian plugin with manifest identity can connect to mdbase interop.");let 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()}};var me=require("obsidian"),ib=dn(Qd(),1),sb=dn(cu(),1),Xu=dn(Wu(),1),wa=class extends Error{constructor(t,n){super(n);this.code=t;this.name="MdbasePathError"}},jt={spec_version:"0.3.0",name:"My mdbase collection",description:"Typed markdown collection",settings:{types_folder:"_types",explicit_type_keys:["type","types"],default_strict:!1,include_subfolders:!0,exclude:["_types",".obsidian",".git","node_modules",".trash",".mdbase"]}},Is=null;function dR(){return Is||(Is=new ib.Ajv2020({allErrors:!0,strict:!1,allowUnionTypes:!0}),(0,sb.default)(Is),Is)}function re(r){return!!r&&typeof r=="object"&&!Array.isArray(r)}function Ze(r){return JSON.parse(JSON.stringify(r))}function uR(r){if(r===!0)return!0;if(r===!1)return!1;if(r==="warn")return"warn"}function Gu(r){return Array.isArray(r)?`[${r.map(e=>Gu(e)).join(",")}]`:re(r)?`{${Object.keys(r).sort().map(t=>`${JSON.stringify(t)}:${Gu(r[t])}`).join(",")}}`:JSON.stringify(r)}function fR(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 pR(r){let e=new Map,t=new Set,n=i=>{var l,d,u,f;let s=e.get(i);if(s)return s;let o=r.get(i);if(!o)return null;if(t.has(i)){let p={...o,fields:Ze(o.fields)};return e.set(i,p),p}t.add(i);let a=o.extends?n(o.extends):null;t.delete(i);let c={...o,fields:a?{...Ze(a.fields),...Ze(o.fields)}:Ze(o.fields),display_name_key:(l=o.display_name_key)!=null?l:a==null?void 0:a.display_name_key,path_pattern:(d=o.path_pattern)!=null?d:a==null?void 0:a.path_pattern,filename_pattern:(u=o.filename_pattern)!=null?u:a==null?void 0:a.filename_pattern,strict:o.strict!==void 0?o.strict:a==null?void 0:a.strict,match:(f=o.match)!=null?f:a==null?void 0:a.match};return e.set(i,c),c};for(let i of r.keys())n(i);return e}function ob(r){let e=(0,me.normalizePath)(r),t=e.lastIndexOf("/");return t>=0?e.slice(0,t):""}function ab(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 cb(r){return/^[a-z][a-z0-9+.-]*:\/\//i.test(r)}function lb(r,e,t){var c;let n=ab(t);if(!n||cb(n))return null;let i=new Set,s=(0,me.normalizePath)(n);i.add(s),s.endsWith(".md")||i.add(`${s}.md`);let o=ob(e);if(o){let l=(0,me.normalizePath)(`${o}/${n}`);i.add(l),l.endsWith(".md")||i.add(`${l}.md`)}for(let l of i){let d=r.getAbstractFileByPath(l);if(d instanceof me.TFile)return d}let a=n.replace(/\.md$/i,"");return(c=r.getMarkdownFiles().find(l=>l.basename===a))!=null?c:null}function hR(r,e,t){return cb(ab(t))||lb(r,e,t)!==null}function It(r){let e=r.match(/^---[ \t]*\r?\n([\s\S]*?)^---[ \t]*(?:\r?\n|$)/m);if(!e)return{hasFrontmatter:!1,frontmatter:{},body:r};try{let t=e[1],n=(0,me.parseYaml)(t);return n==null&&t.trim()!==""?{hasFrontmatter:!0,frontmatter:{},body:r.slice(e[0].length),error:"Frontmatter must be a YAML object"}:n!=null&&!re(n)?{hasFrontmatter:!0,frontmatter:{},body:r.slice(e[0].length),error:"Frontmatter must be a YAML object"}:{hasFrontmatter:!0,frontmatter:n!=null?n:{},body:r.slice(e[0].length)}}catch(t){return{hasFrontmatter:!0,frontmatter:{},body:r.slice(e[0].length),error:t instanceof Error?t.message:String(t)}}}function yt(r,e=""){if(Object.keys(r).length===0)return e;let t=(0,me.stringifyYaml)(r).trimEnd(),n=e.replace(/^\n+/,"");return`--- ${t} --- -${n}`}async function ci(r){let e=r.getAbstractFileByPath("mdbase.yaml");if(!(e instanceof ge.TFile))return null;try{let t=await r.cachedRead(e),n=(0,ge.parseYaml)(t);if(!re(n))return null;let i=re(n.settings)?n.settings:{},s=re(n.runtime)?n.runtime:void 0;return{spec_version:typeof n.spec_version=="string"?n.spec_version:Ut.spec_version,name:typeof n.name=="string"?n.name:Ut.name,description:typeof n.description=="string"?n.description:Ut.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:Ut.settings.types_folder,explicit_type_keys:Array.isArray(i.explicit_type_keys)?i.explicit_type_keys.filter(o=>typeof o=="string"):[...Ut.settings.explicit_type_keys],default_strict:typeof i.default_strict=="boolean"?i.default_strict:Ut.settings.default_strict,include_subfolders:typeof i.include_subfolders=="boolean"?i.include_subfolders:Ut.settings.include_subfolders,exclude:Array.isArray(i.exclude)?i.exclude.filter(o=>typeof o=="string"):[...Ut.settings.exclude]}}}catch(t){return null}}async function Bb(r){var c;let e=[];if(!(r.getAbstractFileByPath("mdbase.yaml")instanceof ge.TFile)){let l=(0,ge.stringifyYaml)(Ut).trimEnd()+` -`;await r.create("mdbase.yaml",l),e.push("mdbase.yaml")}let n=(c=await ci(r))!=null?c:Ut,i=n.settings.types_folder;await r.adapter.exists(i)||(await r.createFolder(i),e.push(i));let o=(0,ge.normalizePath)(`${i}/note.md`);if(!await r.adapter.exists(o)){let l=HO("note",void 0,n.spec_version);await r.create(o,l),e.push(o)}return{created:e}}function zb(r,e){let t=re(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=it(t.enum)):n==="array"?(i.type="list",i.items=zb(t.items,!1)):n==="object"?(i.type="object",i.fields=$n(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=it(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 $n(r){let e=re(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,zb(i,t.has(n))]))}function Hb(r,e){var c,l,u,d;let t={...it(e)},n=(c=r.type)!=null?c:"string",i=()=>{delete t.properties,delete t.required,delete t.additionalProperties},s=()=>{delete t.items};if(n==="enum")delete t.type,t.enum=it((l=r.values)!=null?l:[]),delete t.format,i(),s();else if(n==="list")t.type="array",delete t.enum,delete t.format,i(),t.items=Hb((u=r.items)!=null?u:{type:"any"},re(t.items)?t.items:{});else if(n==="object"){t.type="object",delete t.enum,delete t.format,s();let f=ju((d=r.fields)!=null?d:{},re(t)?t:{},!1);t.properties=f.properties,f.required?t.required=f.required:delete t.required}else n==="link"?(t.type="string",delete t.enum,delete t.format,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=it(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 ju(r,e={},t=!1){let n=re(e.properties)?e.properties:{},i=Object.create(null),s=[];for(let[a,c]of Object.entries(r))i[a]=Hb(c,re(n[a])?n[a]:{}),c.required===!0&&s.push(a);let o={...it(e),type:"object",properties:i,additionalProperties:!t};return s.length>0?o.required=s:delete o.required,o}function AO(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(re(t)&&i in t)t=t[i];else return}return t}async function kO(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=jb(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,ge.normalizePath)(o.join("/")),c=r.getAbstractFileByPath(a);if(!(c instanceof ge.TFile))return null;try{let l=JSON.parse(await r.cachedRead(c)),u=AO(l,i);return re(u)?u:null}catch(l){return null}}async function Kb(r,e){var i,s,o,a;let t=new Map,n=`${(0,ge.normalizePath)(e.settings.types_folder)}/`;for(let c of r.getMarkdownFiles()){if(!c.path.startsWith(n))continue;let l=await r.cachedRead(c),u=Ct(l);if(!u.hasFrontmatter||u.error)continue;let d=u.frontmatter;if(e.spec_version.startsWith("0.3.")){if(d.kind!=="mdbase.type"||typeof d.name!="string"||!re(d.schema))continue;let m=d.schema,h=re(m.value)?m.value:null;if(!h&&typeof m.ref=="string"&&(h=await kO(r,c.path,m.ref)),!h)continue;let y=re(d.collection)?it(d.collection):void 0,b=$n(h);for(let g of(i=y==null?void 0:y.unique)!=null?i:[])typeof g.field=="string"&&b[g.field]&&(b[g.field].unique=!0);for(let[g,_]of Object.entries((s=y==null?void 0:y.links)!=null?s:{}))b[g]&&(b[g].target=_.target_type,b[g].validate_exists=_.validate_exists);t.set(d.name,{name:d.name,version:typeof d.version=="number"?d.version:void 0,description:typeof d.description=="string"?d.description:void 0,display_name_key:(o=y==null?void 0:y.display)==null?void 0:o.name_field,path_pattern:(a=y==null?void 0:y.path)==null?void 0:a.pattern,strict:h.additionalProperties===!1,match:re(d.match)?d.match:void 0,fields:b,filePath:c.path,specProfile:"v0.3",schema:it(h),collection:y,originalFrontmatter:it(d)});continue}if(!re(d.fields))continue;let f=typeof d.name=="string"&&d.name.trim().length>0?d.name.trim():c.basename,p={};for(let[m,h]of Object.entries(d.fields))re(h)&&(p[m]=h);t.set(f,{name:f,extends:typeof d.extends=="string"?d.extends:void 0,display_name_key:typeof d.display_name_key=="string"?d.display_name_key:void 0,path_pattern:typeof d.path_pattern=="string"?d.path_pattern:void 0,filename_pattern:typeof d.filename_pattern=="string"?d.filename_pattern:void 0,strict:vO(d.strict),match:re(d.match)?d.match:void 0,fields:p,filePath:c.path,specProfile:"v0.2",originalFrontmatter:it(d)})}return SO(t)}function xO(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 Fu(r,e){return r.replace(/\{([^}]+)\}/g,(t,n)=>{let i=e[n];return i==null?"":Array.isArray(i)?i.join("-"):String(i)})}function As(r){let e=r.replace(/\\/g,"/");if(!e||e.startsWith("/")||/^[A-Za-z]:\//.test(e)||e.includes("\0"))throw new ma("invalid_path",`Invalid collection-relative path: ${r}`);let t=e.split("/");if(t.includes(".."))throw new ma("path_traversal",`Path escapes the collection root: ${r}`);return(0,ge.normalizePath)(t.filter(n=>n&&n!==".").join("/"))}function PO(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 IO(r,e){var t;if(r.path_pattern){let n=(0,ge.normalizePath)(Fu(r.path_pattern,e));if(n.endsWith(".md")){let i=n.lastIndexOf("/");return i>=0?n.slice(0,i):""}return n.replace(/\/+$/,"")}return(t=r.match)!=null&&t.path_glob?PO(r.match.path_glob):""}function OO(r,e){var o,a;let t=(o=r.display_name_key)!=null?o:"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 c=(0,ge.normalizePath)(Fu(r.filename_pattern,e)),u=((a=c.split("/").pop())!=null?a:c).replace(/\.md$/i,"").trim();if(u.length>0)return`${Lb(u)}.md`}return`${Lb(s)}.md`}function ai(r){return Array.isArray(r)?`[${r.map(ai).join(",")}]`:re(r)?`{${Object.keys(r).sort().map(e=>`${JSON.stringify(e)}:${ai(r[e])}`).join(",")}}`:JSON.stringify(r)}function TO(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(!re(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 pa(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 RO(r,e,t,n){let i=(s,o)=>ai(s)===ai(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 pa(r.value,t,(s,o)=>s>o);case"gte":return pa(r.value,t,(s,o)=>s>=o);case"lt":return pa(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"&&r.value.startsWith(String(t));case"endsWith":case"ends_with":return typeof r.value=="string"&&r.value.endsWith(String(t));case"matches":try{return r.value!=null&&new RegExp(String(t).replace(/\\\\/g,"\\")).test(String(r.value))}catch(s){return!1}default:return!1}}function ha(r,e,t){if("and"in r)return Array.isArray(r.and)&&r.and.every(n=>re(n)&&ha(n,e,t));if("or"in r)return Array.isArray(r.or)&&r.or.some(n=>re(n)&&ha(n,e,t));if("not"in r)return re(r.not)&&!ha(r.not,e,t);for(let[n,i]of Object.entries(r)){let s=TO(e,n);if(!re(i)){if(!s.present||ai(s.value)!==ai(i))return!1;continue}for(let[o,a]of Object.entries(i))if(!RO(s,o,a,t))return!1}return!0}function li(r,e,t,n){let i=xO(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"&&((0,qu.default)(c.path_glob,{dot:!0})(r)||(l=!1)),l&&Array.isArray(c.fields_present)){for(let u of c.fields_present)if(!(u in e)){l=!1;break}}l&&re(c.where)&&(l=ha(c.where,e,t.spec_version)),l&&typeof c.where=="string"&&(l=!1),l&&s.push(o)}return s}function Wb(r){return r==null||typeof r=="string"&&r.trim().length===0}function CO(r){return/^\d{4}-\d{2}-\d{2}$/.test(r)}function MO(r){return/^\d{2}:\d{2}(:\d{2})?$/.test(r)}function NO(r){return typeof r=="string"||Array.isArray(r)?r.length:null}function Me(r,e,t,n,i,s){r.push({path:e,code:n,message:i,severity:t,field:s})}function Rt(r,e,t,n,i){typeof r=="number"&&(typeof e.min=="number"&&r= ${e.min}`,t),typeof e.max=="number"&&r>e.max&&Me(i,n,"error","above_max",`Field '${t}' must be <= ${e.max}`,t));let s=NO(r);if(s!=null&&(typeof e.min_length=="number"&&s= ${e.min_length}`,t),typeof e.max_length=="number"&&s>e.max_length&&Me(i,n,"error","above_max_length",`Field '${t}' length must be <= ${e.max_length}`,t)),typeof e.pattern=="string"&&typeof r=="string")try{new RegExp(e.pattern).test(r)||Me(i,n,"error","pattern_mismatch",`Field '${t}' must match pattern /${e.pattern}/`,t)}catch(o){Me(i,n,"warn","invalid_pattern",`Field '${t}' has invalid regex pattern: ${o instanceof Error?o.message:String(o)}`,t)}}function Lu(r,e,t,n,i,s){var c;let o=(c=e.type)!=null?c:"any";if(r==null)return;e.deprecated===!0&&Me(i,n,"warn","deprecated_field",`Field '${t}' is marked deprecated`,t);let a=l=>{Me(i,n,"error","invalid_type",`Field '${t}' expected ${l}`,t)};switch(o){case"any":Rt(r,e,t,n,i);return;case"string":if(typeof r!="string"){a("a string");return}Rt(r,e,t,n,i);return;case"integer":if(typeof r!="number"||!Number.isInteger(r)){a("an integer");return}Rt(r,e,t,n,i);return;case"number":if(typeof r!="number"||Number.isNaN(r)){a("a number");return}Rt(r,e,t,n,i);return;case"boolean":typeof r!="boolean"&&a("a boolean");return;case"date":if(typeof r!="string"||!CO(r)){a("a date (YYYY-MM-DD)");return}Rt(r,e,t,n,i);return;case"datetime":if(typeof r!="string"||Number.isNaN(Date.parse(r))){a("a datetime string");return}Rt(r,e,t,n,i);return;case"time":if(typeof r!="string"||!MO(r)){a("a time string (HH:MM)");return}Rt(r,e,t,n,i);return;case"enum":{let l=Array.isArray(e.values)?e.values:[];if(!l.includes(r)){Me(i,n,"error","invalid_enum",`Field '${t}' must be one of: ${l.map(u=>String(u)).join(", ")}`,t);return}Rt(r,e,t,n,i);return}case"list":{if(!Array.isArray(r)){a("a list");return}Rt(r,e,t,n,i),e.items&&r.forEach((l,u)=>{Lu(l,e.items,`${t}[${u}]`,n,i,s)});return}case"object":{if(!re(r)){a("an object");return}if(e.fields&&re(e.fields))for(let[l,u]of Object.entries(e.fields)){if(!re(u))continue;let d=u,f=`${t}.${l}`,p=r[l];if(d.required&&Wb(p)){Me(i,n,"error","missing_required",`Missing required field '${f}'`,f);continue}Lu(p,d,f,n,i,s)}return}case"link":{if(typeof r!="string"&&!re(r)){a("a link string");return}if(e.validate_exists===!0&&s){let l=typeof r=="string"?r:typeof r.path=="string"?r.path:typeof r.file=="string"?r.file:"";(!l||!EO(s,n,l))&&Me(i,n,"error","missing_link_target",`Field '${t}' references a missing note`,t)}return}case"tags":if(typeof r=="string"){Rt(r,e,t,n,i);return}if(Array.isArray(r)&&r.every(l=>typeof l=="string")){Rt(r,e,t,n,i);return}a("a tag string or list of strings");return;default:Rt(r,e,t,n,i);return}}function LO(r){return r.replace(/^\//,"").split("/").filter(Boolean).map(t=>t.replace(/~1/g,"/").replace(/~0/g,"~")).join(".")||void 0}function DO(r){return r.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase()}function qO(r,e,t){var c;let n=r.params,i=LO(r.instancePath),s=typeof n.missingProperty=="string"?n.missingProperty:typeof n.additionalProperty=="string"?n.additionalProperty:void 0,o=i&&s?`${i}.${s}`:s!=null?s:i,a=r.keyword==="format"?"format_invalid":`schema_${DO(r.keyword)}`;return{path:e,code:a,message:`JSON Schema ${r.keyword} failed for type '${t}': ${(c=r.message)!=null?c:"invalid value"}`,severity:"error",field:o,type:t,schema_location:`embedded://type/schema#${r.schemaPath}`,details:{instance_path:r.instancePath,schema_path:r.schemaPath}}}function Du(r){if(Array.isArray(r)){for(let e of r){let t=Du(e);if(t)return t}return null}if(!re(r))return null;if(typeof r.$ref=="string"&&!r.$ref.startsWith("#"))return r.$ref;for(let e of Object.values(r)){let t=Du(e);if(t)return t}return null}function jO(r,e,t,n){var s;if(!t.schema)return;let i=Du(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 o=wO().compile(t.schema);if(o(e))return;for(let a of(s=o.errors)!=null?s:[])n.push(qO(a,r,t.name))}catch(o){n.push({path:r,code:"invalid_embedded_schema",message:o instanceof Error?o.message:String(o),severity:"error",type:t.name})}}async function FO(r,e,t,n,i,s,o){var a,c;for(let[l,u]of Object.entries((c=(a=n.collection)==null?void 0:a.links)!=null?c:{})){let d=t[l],f=Array.isArray(d)?d:[d];for(let p of f){if(p==null||typeof p!="string")continue;let m=Ub(r,e,p);if(!m&&u.validate_exists===!0){Me(o,e,"error","link_not_found",`Field '${l}' references a missing note`,l);continue}if(m&&u.target_type&&u.target_type!=="any"){let h=Ct(await r.cachedRead(m));li(m.path,h.frontmatter,i,s).includes(u.target_type)||Me(o,e,"error","link_wrong_type",`Field '${l}' must reference type '${u.target_type}'`,l)}}}}function VO(r,e,t,n,i){if(t.specProfile==="v0.3"){jO(r,e,t,n);return}for(let[s,o]of Object.entries(t.fields)){if(!re(o))continue;let a=o,c=e[s];if(a.required&&Wb(c)){Me(n,r,"error","missing_required",`Missing required field '${s}' for type '${t.name}'`,s);continue}Lu(c,a,s,r,n,i)}}function UO(r){let e=new Set;for(let t of r)for(let n of Object.keys(t.fields))e.add(n);return e}function BO(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 ks(r,e){let t=(0,ge.normalizePath)(r),n=(0,ge.normalizePath)(e.settings.types_folder);if(t.startsWith(`${n}/`)||t===n||!e.settings.include_subfolders&&t.includes("/"))return!0;for(let i of e.settings.exclude)if((0,qu.default)(i,{dot:!0,matchBase:!i.includes("/")})(t)||!i.includes("*")&&!i.includes("?")&&!i.includes("/")&&t.startsWith(`${i}/`))return!0;return!1}async function Vu(r,e,t,n){if(ks(e.path,t))return[];let i=[],s=await r.cachedRead(e),o=Ct(s);if(o.error)return Me(i,e.path,"error","invalid_frontmatter",o.error),i;let a=o.frontmatter,c=li(e.path,a,t,n);if(c.length===0)return Me(i,e.path,"warn","no_matching_type","No type could be resolved for this file"),i;let l=c.map(d=>n.get(d)).filter(d=>!!d);if(l.length===0)return Me(i,e.path,"error","unknown_type",`Resolved types are not defined: ${c.join(", ")}`),i;for(let d of l)VO(e.path,a,d,i,r),d.specProfile==="v0.3"&&await FO(r,e.path,a,d,t,n,i);let u=t.spec_version.startsWith("0.3.")?!1:BO(l,t);if(u!==!1){let d=UO(l),f=new Set(t.settings.explicit_type_keys),p=u===!0?"error":"warn";for(let m of Object.keys(a))d.has(m)||f.has(m)||Me(i,e.path,p,"unknown_field",`Unknown field '${m}' in strict mode`,m)}return i}async function zO(r,e,t){var s,o;let n=new Map;for(let a of r.getMarkdownFiles()){if(ks(a.path,e))continue;let c=await r.cachedRead(a),l=Ct(c);if(l.error)continue;let d=li(a.path,l.frontmatter,e,t).map(f=>t.get(f)).filter(f=>!!f);for(let f of d)for(let[p,m]of Object.entries(f.fields)){if(!re(m)||m.unique!==!0)continue;let y=l.frontmatter[p];if(y==null)continue;let b=Nu(y),g=`${f.name}::${p}::${b}`,_=(s=n.get(g))!=null?s:[];_.push({path:a.path,typeName:f.name,fieldName:p,value:y,fingerprint:b}),n.set(g,_)}}let i=[];for(let a of n.values())if(!(a.length<=1))for(let c of a){let l=a.filter(u=>u.path!==c.path).map(u=>u.path).join(", ");Me(i,c.path,"error",((o=t.get(c.typeName))==null?void 0:o.specProfile)==="v0.3"?"duplicate_value":"duplicate_unique",`Field '${c.fieldName}' must be unique for type '${c.typeName}'. Duplicate found in: ${l}`,c.fieldName)}return i}async function Gb(r,e,t){let n=[];for(let s of r.getMarkdownFiles()){if(ks(s.path,e))continue;let o=await Vu(r,s,e,t);n.push(...o)}let i=await zO(r,e,t);return n.push(...i),n}function HO(r,e,t=Ut.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()}),`${wt(i,`# ${r} +${n}`}async function ui(r){let e=r.getAbstractFileByPath("mdbase.yaml");if(!(e instanceof me.TFile))return null;try{let t=await r.cachedRead(e),n=(0,me.parseYaml)(t);if(!re(n))return null;let i=re(n.settings)?n.settings:{},s=re(n.runtime)?n.runtime:void 0;return{spec_version:typeof n.spec_version=="string"?n.spec_version:jt.spec_version,name:typeof n.name=="string"?n.name:jt.name,description:typeof n.description=="string"?n.description:jt.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:jt.settings.types_folder,explicit_type_keys:Array.isArray(i.explicit_type_keys)?i.explicit_type_keys.filter(o=>typeof o=="string"):[...jt.settings.explicit_type_keys],default_strict:typeof i.default_strict=="boolean"?i.default_strict:jt.settings.default_strict,include_subfolders:typeof i.include_subfolders=="boolean"?i.include_subfolders:jt.settings.include_subfolders,exclude:Array.isArray(i.exclude)?i.exclude.filter(o=>typeof o=="string"):[...jt.settings.exclude]}}}catch(t){return null}}async function db(r){var c;let e=[];if(!(r.getAbstractFileByPath("mdbase.yaml")instanceof me.TFile)){let l=(0,me.stringifyYaml)(jt).trimEnd()+` +`;await r.create("mdbase.yaml",l),e.push("mdbase.yaml")}let n=(c=await ui(r))!=null?c:jt,i=n.settings.types_folder;await r.adapter.exists(i)||(await r.createFolder(i),e.push(i));let o=(0,me.normalizePath)(`${i}/note.md`);if(!await r.adapter.exists(o)){let l=NR("note",void 0,n.spec_version);await r.create(o,l),e.push(o)}return{created:e}}function ub(r,e){let t=re(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=Ze(t.enum)):n==="array"?(i.type="list",i.items=ub(t.items,!1)):n==="object"?(i.type="object",i.fields=Sn(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=Ze(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 Sn(r){let e=re(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,ub(i,t.has(n))]))}function fb(r,e){var c,l,d,u;let t={...Ze(e)},n=(c=r.type)!=null?c:"string",i=()=>{delete t.properties,delete t.required,delete t.additionalProperties},s=()=>{delete t.items};if(n==="enum")delete t.type,t.enum=Ze((l=r.values)!=null?l:[]),delete t.format,i(),s();else if(n==="list")t.type="array",delete t.enum,delete t.format,i(),t.items=fb((d=r.items)!=null?d:{type:"any"},re(t.items)?t.items:{});else if(n==="object"){t.type="object",delete t.enum,delete t.format,s();let f=Qu((u=r.fields)!=null?u:{},re(t)?t:{},!1);t.properties=f.properties,f.required?t.required=f.required:delete t.required}else n==="link"?(t.type="string",delete t.enum,delete t.format,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=Ze(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 Qu(r,e={},t=!1){let n=re(e.properties)?e.properties:{},i=Object.create(null),s=[];for(let[a,c]of Object.entries(r))i[a]=fb(c,re(n[a])?n[a]:{}),c.required===!0&&s.push(a);let o={...Ze(e),type:"object",properties:i,additionalProperties:!t};return s.length>0?o.required=s:delete o.required,o}function mR(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(re(t)&&i in t)t=t[i];else return}return t}async function yR(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=ob(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,me.normalizePath)(o.join("/")),c=r.getAbstractFileByPath(a);if(!(c instanceof me.TFile))return null;try{let l=JSON.parse(await r.cachedRead(c)),d=mR(l,i);return re(d)?d:null}catch(l){return null}}async function pb(r,e){var i,s,o,a;let t=new Map,n=`${(0,me.normalizePath)(e.settings.types_folder)}/`;for(let c of r.getMarkdownFiles()){if(!c.path.startsWith(n))continue;let l=await r.cachedRead(c),d=It(l);if(!d.hasFrontmatter||d.error)continue;let u=d.frontmatter;if(e.spec_version.startsWith("0.3.")){if(u.kind!=="mdbase.type"||typeof u.name!="string"||!re(u.schema))continue;let y=u.schema,h=re(y.value)?y.value:null;if(!h&&typeof y.ref=="string"&&(h=await yR(r,c.path,y.ref)),!h)continue;let m=re(u.collection)?Ze(u.collection):void 0,g=Sn(h);for(let _ of(i=m==null?void 0:m.unique)!=null?i:[])typeof _.field=="string"&&g[_.field]&&(g[_.field].unique=!0);for(let[_,w]of Object.entries((s=m==null?void 0:m.links)!=null?s:{}))g[_]&&(g[_].target=w.target_type,g[_].validate_exists=w.validate_exists);t.set(u.name,{name:u.name,version:typeof u.version=="number"?u.version:void 0,description:typeof u.description=="string"?u.description:void 0,display_name_key:(o=m==null?void 0:m.display)==null?void 0:o.name_field,path_pattern:(a=m==null?void 0:m.path)==null?void 0:a.pattern,strict:h.additionalProperties===!1,match:re(u.match)?u.match:void 0,fields:g,filePath:c.path,specProfile:"v0.3",schema:Ze(h),collection:m,originalFrontmatter:Ze(u)});continue}if(!re(u.fields))continue;let f=typeof u.name=="string"&&u.name.trim().length>0?u.name.trim():c.basename,p={};for(let[y,h]of Object.entries(u.fields))re(h)&&(p[y]=h);t.set(f,{name:f,extends:typeof u.extends=="string"?u.extends:void 0,display_name_key:typeof u.display_name_key=="string"?u.display_name_key:void 0,path_pattern:typeof u.path_pattern=="string"?u.path_pattern:void 0,filename_pattern:typeof u.filename_pattern=="string"?u.filename_pattern:void 0,strict:uR(u.strict),match:re(u.match)?u.match:void 0,fields:p,filePath:c.path,specProfile:"v0.2",originalFrontmatter:Ze(u)})}return pR(t)}function gR(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 Zu(r,e){return r.replace(/\{([^}]+)\}/g,(t,n)=>{let i=e[n];return i==null?"":Array.isArray(i)?i.join("-"):String(i)})}function Os(r){let e=r.replace(/\\/g,"/");if(!e||e.startsWith("/")||/^[A-Za-z]:\//.test(e)||e.includes("\0"))throw new wa("invalid_path",`Invalid collection-relative path: ${r}`);let t=e.split("/");if(t.includes(".."))throw new wa("path_traversal",`Path escapes the collection root: ${r}`);return(0,me.normalizePath)(t.filter(n=>n&&n!==".").join("/"))}function _R(r){let e=r.search(/[\*\?\[]/),n=(e===-1?r:r.slice(0,e)).replace(/\/+$/,"");if(n.endsWith(".md")){let i=n.lastIndexOf("/");return i>=0?n.slice(0,i):""}return n}function bR(r,e){var t;if(r.path_pattern){let n=(0,me.normalizePath)(Zu(r.path_pattern,e));if(n.endsWith(".md")){let i=n.lastIndexOf("/");return i>=0?n.slice(0,i):""}return n.replace(/\/+$/,"")}return(t=r.match)!=null&&t.path_glob?_R(r.match.path_glob):""}function wR(r,e){var o,a;let t=(o=r.display_name_key)!=null?o:"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 c=(0,me.normalizePath)(Zu(r.filename_pattern,e)),d=((a=c.split("/").pop())!=null?a:c).replace(/\.md$/i,"").trim();if(d.length>0)return`${nb(d)}.md`}return`${nb(s)}.md`}function di(r){return Array.isArray(r)?`[${r.map(di).join(",")}]`:re(r)?`{${Object.keys(r).sort().map(e=>`${JSON.stringify(e)}:${di(r[e])}`).join(",")}}`:JSON.stringify(r)}function vR(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(!re(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 _a(r,e,t){return(typeof r=="number"&&typeof e=="number"&&Number.isFinite(r)&&Number.isFinite(e)||typeof r=="string"&&typeof e=="string")&&t(r,e)}function $R(r,e,t,n){let i=(s,o)=>di(s)===di(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 _a(r.value,t,(s,o)=>s>o);case"gte":return _a(r.value,t,(s,o)=>s>=o);case"lt":return _a(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"&&r.value.startsWith(String(t));case"endsWith":case"ends_with":return typeof r.value=="string"&&r.value.endsWith(String(t));case"matches":try{return r.value!=null&&new RegExp(String(t).replace(/\\\\/g,"\\")).test(String(r.value))}catch(s){return!1}default:return!1}}function ba(r,e,t){if("and"in r)return Array.isArray(r.and)&&r.and.every(n=>re(n)&&ba(n,e,t));if("or"in r)return Array.isArray(r.or)&&r.or.some(n=>re(n)&&ba(n,e,t));if("not"in r)return re(r.not)&&!ba(r.not,e,t);for(let[n,i]of Object.entries(r)){let s=vR(e,n);if(!re(i)){if(!s.present||di(s.value)!==di(i))return!1;continue}for(let[o,a]of Object.entries(i))if(!$R(s,o,a,t))return!1}return!0}function fi(r,e,t,n){let i=gR(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"&&((0,Xu.default)(c.path_glob,{dot:!0})(r)||(l=!1)),l&&Array.isArray(c.fields_present)){for(let d of c.fields_present)if(!(d in e)){l=!1;break}}l&&re(c.where)&&(l=ba(c.where,e,t.spec_version)),l&&typeof c.where=="string"&&(l=!1),l&&s.push(o)}return s}function hb(r){return r==null||typeof r=="string"&&r.trim().length===0}function SR(r){return/^\d{4}-\d{2}-\d{2}$/.test(r)}function ER(r){return/^\d{2}:\d{2}(:\d{2})?$/.test(r)}function AR(r){return typeof r=="string"||Array.isArray(r)?r.length:null}function Te(r,e,t,n,i,s){r.push({path:e,code:n,message:i,severity:t,field:s})}function Pt(r,e,t,n,i){typeof r=="number"&&(typeof e.min=="number"&&r= ${e.min}`,t),typeof e.max=="number"&&r>e.max&&Te(i,n,"error","above_max",`Field '${t}' must be <= ${e.max}`,t));let s=AR(r);if(s!=null&&(typeof e.min_length=="number"&&s= ${e.min_length}`,t),typeof e.max_length=="number"&&s>e.max_length&&Te(i,n,"error","above_max_length",`Field '${t}' length must be <= ${e.max_length}`,t)),typeof e.pattern=="string"&&typeof r=="string")try{new RegExp(e.pattern).test(r)||Te(i,n,"error","pattern_mismatch",`Field '${t}' must match pattern /${e.pattern}/`,t)}catch(o){Te(i,n,"warn","invalid_pattern",`Field '${t}' has invalid regex pattern: ${o instanceof Error?o.message:String(o)}`,t)}}function Ju(r,e,t,n,i,s){var c;let o=(c=e.type)!=null?c:"any";if(r==null)return;e.deprecated===!0&&Te(i,n,"warn","deprecated_field",`Field '${t}' is marked deprecated`,t);let a=l=>{Te(i,n,"error","invalid_type",`Field '${t}' expected ${l}`,t)};switch(o){case"any":Pt(r,e,t,n,i);return;case"string":if(typeof r!="string"){a("a string");return}Pt(r,e,t,n,i);return;case"integer":if(typeof r!="number"||!Number.isInteger(r)){a("an integer");return}Pt(r,e,t,n,i);return;case"number":if(typeof r!="number"||Number.isNaN(r)){a("a number");return}Pt(r,e,t,n,i);return;case"boolean":typeof r!="boolean"&&a("a boolean");return;case"date":if(typeof r!="string"||!SR(r)){a("a date (YYYY-MM-DD)");return}Pt(r,e,t,n,i);return;case"datetime":if(typeof r!="string"||Number.isNaN(Date.parse(r))){a("a datetime string");return}Pt(r,e,t,n,i);return;case"time":if(typeof r!="string"||!ER(r)){a("a time string (HH:MM)");return}Pt(r,e,t,n,i);return;case"enum":{let l=Array.isArray(e.values)?e.values:[];if(!l.includes(r)){Te(i,n,"error","invalid_enum",`Field '${t}' must be one of: ${l.map(d=>String(d)).join(", ")}`,t);return}Pt(r,e,t,n,i);return}case"list":{if(!Array.isArray(r)){a("a list");return}Pt(r,e,t,n,i),e.items&&r.forEach((l,d)=>{Ju(l,e.items,`${t}[${d}]`,n,i,s)});return}case"object":{if(!re(r)){a("an object");return}if(e.fields&&re(e.fields))for(let[l,d]of Object.entries(e.fields)){if(!re(d))continue;let u=d,f=`${t}.${l}`,p=r[l];if(u.required&&hb(p)){Te(i,n,"error","missing_required",`Missing required field '${f}'`,f);continue}Ju(p,u,f,n,i,s)}return}case"link":{if(typeof r!="string"&&!re(r)){a("a link string");return}if(e.validate_exists===!0&&s){let l=typeof r=="string"?r:typeof r.path=="string"?r.path:typeof r.file=="string"?r.file:"";(!l||!hR(s,n,l))&&Te(i,n,"error","missing_link_target",`Field '${t}' references a missing note`,t)}return}case"tags":if(typeof r=="string"){Pt(r,e,t,n,i);return}if(Array.isArray(r)&&r.every(l=>typeof l=="string")){Pt(r,e,t,n,i);return}a("a tag string or list of strings");return;default:Pt(r,e,t,n,i);return}}function xR(r){return r.replace(/^\//,"").split("/").filter(Boolean).map(t=>t.replace(/~1/g,"/").replace(/~0/g,"~")).join(".")||void 0}function kR(r){return r.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase()}function PR(r,e,t){var c;let n=r.params,i=xR(r.instancePath),s=typeof n.missingProperty=="string"?n.missingProperty:typeof n.additionalProperty=="string"?n.additionalProperty:void 0,o=i&&s?`${i}.${s}`:s!=null?s:i,a=r.keyword==="format"?"format_invalid":`schema_${kR(r.keyword)}`;return{path:e,code:a,message:`JSON Schema ${r.keyword} failed for type '${t}': ${(c=r.message)!=null?c:"invalid value"}`,severity:"error",field:o,type:t,schema_location:`embedded://type/schema#${r.schemaPath}`,details:{instance_path:r.instancePath,schema_path:r.schemaPath}}}function Yu(r){if(Array.isArray(r)){for(let e of r){let t=Yu(e);if(t)return t}return null}if(!re(r))return null;if(typeof r.$ref=="string"&&!r.$ref.startsWith("#"))return r.$ref;for(let e of Object.values(r)){let t=Yu(e);if(t)return t}return null}function IR(r,e,t,n){var s;if(!t.schema)return;let i=Yu(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 o=dR().compile(t.schema);if(o(e))return;for(let a of(s=o.errors)!=null?s:[])n.push(PR(a,r,t.name))}catch(o){n.push({path:r,code:"invalid_embedded_schema",message:o instanceof Error?o.message:String(o),severity:"error",type:t.name})}}async function OR(r,e,t,n,i,s,o){var a,c;for(let[l,d]of Object.entries((c=(a=n.collection)==null?void 0:a.links)!=null?c:{})){let u=t[l],f=Array.isArray(u)?u:[u];for(let p of f){if(p==null||typeof p!="string")continue;let y=lb(r,e,p);if(!y&&d.validate_exists===!0){Te(o,e,"error","link_not_found",`Field '${l}' references a missing note`,l);continue}if(y&&d.target_type&&d.target_type!=="any"){let h=It(await r.cachedRead(y));fi(y.path,h.frontmatter,i,s).includes(d.target_type)||Te(o,e,"error","link_wrong_type",`Field '${l}' must reference type '${d.target_type}'`,l)}}}}function RR(r,e,t,n,i){if(t.specProfile==="v0.3"){IR(r,e,t,n);return}for(let[s,o]of Object.entries(t.fields)){if(!re(o))continue;let a=o,c=e[s];if(a.required&&hb(c)){Te(n,r,"error","missing_required",`Missing required field '${s}' for type '${t.name}'`,s);continue}Ju(c,a,s,r,n,i)}}function TR(r){let e=new Set;for(let t of r)for(let n of Object.keys(t.fields))e.add(n);return e}function MR(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 Rs(r,e){let t=(0,me.normalizePath)(r),n=(0,me.normalizePath)(e.settings.types_folder);if(t.startsWith(`${n}/`)||t===n||!e.settings.include_subfolders&&t.includes("/"))return!0;for(let i of e.settings.exclude)if((0,Xu.default)(i,{dot:!0,matchBase:!i.includes("/")})(t)||!i.includes("*")&&!i.includes("?")&&!i.includes("/")&&t.startsWith(`${i}/`))return!0;return!1}async function ef(r,e,t,n){if(Rs(e.path,t))return[];let i=[],s=await r.cachedRead(e),o=It(s);if(o.error)return Te(i,e.path,"error","invalid_frontmatter",o.error),i;let a=o.frontmatter,c=fi(e.path,a,t,n);if(c.length===0)return Te(i,e.path,"warn","no_matching_type","No type could be resolved for this file"),i;let l=c.map(u=>n.get(u)).filter(u=>!!u);if(l.length===0)return Te(i,e.path,"error","unknown_type",`Resolved types are not defined: ${c.join(", ")}`),i;for(let u of l)RR(e.path,a,u,i,r),u.specProfile==="v0.3"&&await OR(r,e.path,a,u,t,n,i);let d=t.spec_version.startsWith("0.3.")?!1:MR(l,t);if(d!==!1){let u=TR(l),f=new Set(t.settings.explicit_type_keys),p=d===!0?"error":"warn";for(let y of Object.keys(a))u.has(y)||f.has(y)||Te(i,e.path,p,"unknown_field",`Unknown field '${y}' in strict mode`,y)}return i}async function CR(r,e,t){var s,o;let n=new Map;for(let a of r.getMarkdownFiles()){if(Rs(a.path,e))continue;let c=await r.cachedRead(a),l=It(c);if(l.error)continue;let u=fi(a.path,l.frontmatter,e,t).map(f=>t.get(f)).filter(f=>!!f);for(let f of u)for(let[p,y]of Object.entries(f.fields)){if(!re(y)||y.unique!==!0)continue;let m=l.frontmatter[p];if(m==null)continue;let g=Gu(m),_=`${f.name}::${p}::${g}`,w=(s=n.get(_))!=null?s:[];w.push({path:a.path,typeName:f.name,fieldName:p,value:m,fingerprint:g}),n.set(_,w)}}let i=[];for(let a of n.values())if(!(a.length<=1))for(let c of a){let l=a.filter(d=>d.path!==c.path).map(d=>d.path).join(", ");Te(i,c.path,"error",((o=t.get(c.typeName))==null?void 0:o.specProfile)==="v0.3"?"duplicate_value":"duplicate_unique",`Field '${c.fieldName}' must be unique for type '${c.typeName}'. Duplicate found in: ${l}`,c.fieldName)}return i}async function mb(r,e,t){let n=[];for(let s of r.getMarkdownFiles()){if(Rs(s.path,e))continue;let o=await ef(r,s,e,t);n.push(...o)}let i=await CR(r,e,t);return n.push(...i),n}function NR(r,e,t=jt.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()}),`${yt(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()}),`${wt(n,`# ${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()}),`${yt(n,`# ${r} Type definition for ${r}.`)} -`}function Jb(r,e){var i;let t={},n=(i=e.settings.explicit_type_keys[0])!=null?i:"type";t[n]=n==="types"?[r.name]:r.name;for(let[s,o]of Object.entries(r.fields)){if(!re(o))continue;let a=o;a.default!==void 0&&(t[s]=it(a.default))}return t}function Yb(r,e){let t=[];for(let[n,i]of Object.entries(r.fields)){if(!re(i))continue;let s=i;s.computed||s.required&&e[n]===void 0&&t.push([n,s])}return t}function Uu(r,e){var i;let t=r.trim();switch((i=e.type)!=null?i:"string"){case"string":case"date":case"datetime":case"time":case"link":case"enum":case"any":return t;case"integer":{let s=Number.parseInt(t,10);if(!Number.isInteger(s))throw new Error("Expected integer input");return s}case"number":{let s=Number.parseFloat(t);if(Number.isNaN(s))throw new Error("Expected numeric input");return s}case"boolean":{let s=t.toLowerCase();if(["true","1","yes","y"].includes(s))return!0;if(["false","0","no","n"].includes(s))return!1;throw new Error("Expected boolean input: true/false")}case"list":{let s=t.split(",").map(o=>o.trim()).filter(o=>o.length>0);return e.items?s.map(o=>Uu(o,e.items)):s}case"object":{let s=(0,ge.parseYaml)(t);if(!re(s))throw new Error("Expected YAML object value");return s}case"tags":return t.split(",").map(s=>s.trim()).filter(s=>s.length>0);default:return t}}function Lb(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 Xb(r,e){let t=(0,ge.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 KO(r,e){if(!r.path_pattern||r.path_pattern.trim().length===0)return null;let t=(0,ge.normalizePath)(Fu(r.path_pattern,e));return t.endsWith(".md")?t:null}async function Qb(r,e,t){var u;let n=KO(e,t),i=IO(e,t),s=n?(u=n.split("/").pop())!=null?u:n:OO(e,t),o=As(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;let l=a.lastIndexOf("/");return l>0&&await Xb(r,a.slice(0,l)),a}async function Zb(r,e,t,n=""){let i=As(e),s=i.lastIndexOf("/");if(s>0&&await Xb(r,i.slice(0,s)),await r.adapter.exists(i))throw new Error(`File already exists: ${i}`);let o=`${wt(t,n)} -`;return r.create(i,o)}function ya(r){return $O(r)}var ae=require("obsidian"),Uw=ln(Mu(),1);var ga=Symbol.for("yaml.alias"),ba=Symbol.for("yaml.document"),Bt=Symbol.for("yaml.map"),Bu=Symbol.for("yaml.pair"),vt=Symbol.for("yaml.scalar"),Ar=Symbol.for("yaml.seq"),st=Symbol.for("yaml.node.type"),zt=r=>!!r&&typeof r=="object"&&r[st]===ga,Ht=r=>!!r&&typeof r=="object"&&r[st]===ba,Kt=r=>!!r&&typeof r=="object"&&r[st]===Bt,ne=r=>!!r&&typeof r=="object"&&r[st]===Bu,J=r=>!!r&&typeof r=="object"&&r[st]===vt,Wt=r=>!!r&&typeof r=="object"&&r[st]===Ar;function pe(r){if(r&&typeof r=="object")switch(r[st]){case Bt:case Ar:return!0}return!1}function se(r){if(r&&typeof r=="object")switch(r[st]){case ga:case Bt:case vt:case Ar:return!0}return!1}var _a=r=>(J(r)||pe(r))&&!!r.anchor;var ht=Symbol("break visit"),e_=Symbol("skip children"),fr=Symbol("remove node");function pr(r,e){let t=t_(e);Ht(r)?di(null,r.contents,t,Object.freeze([r]))===fr&&(r.contents=null):di(null,r,t,Object.freeze([]))}pr.BREAK=ht;pr.SKIP=e_;pr.REMOVE=fr;function di(r,e,t,n){let i=r_(r,e,t,n);if(se(i)||ne(i))return n_(r,n,i),di(r,i,t,n);if(typeof i!="symbol"){if(pe(e)){n=Object.freeze(n.concat(e));for(let s=0;sr.replace(/[!,[\]{}]/g,e=>WO[e]),hr=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+GO(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&&se(e.contents)){let s={};pr(e.contents,(o,a)=>{se(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(` -`)}};hr.defaultYaml={explicit:!1,version:"1.2"};hr.defaultTags={"!!":"tag:yaml.org,2002:"};function va(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 zu(r){let e=new Set;return pr(r,{Value(t,n){n.anchor&&e.add(n.anchor)}}),e}function Hu(r,e){for(let t=1;;++t){let n=`${r}${t}`;if(!e.has(n))return n}}function i_(r,e){let t=[],n=new Map,i=null;return{onAnchor:s=>{t.push(s),i!=null||(i=zu(r));let o=Hu(e,i);return i.add(o),o},setAnchors:()=>{for(let s of t){let o=n.get(s);if(typeof o=="object"&&o.anchor&&(J(o.node)||pe(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 Yr(r,e,t,n){if(n&&typeof n=="object")if(Array.isArray(n))for(let i=0,s=n.length;iNe(n,String(i),t));if(r&&typeof r.toJSON=="function"){if(!t||!_a(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!=null&&t.keep)?Number(r):r}var Xr=class{constructor(e){Object.defineProperty(this,st,{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(!Ht(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=Ne(this,"",o);if(typeof i=="function")for(let{count:c,res:l}of o.anchors.values())i(l,c);return typeof s=="function"?Yr(s,{"":a},"",a):a}};var kr=class extends Xr{constructor(e){super(ga),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,t){if((t==null?void 0:t.maxAliasCount)===0)throw new ReferenceError("Alias resolution is disabled");let n;t!=null&&t.aliasResolveCache?n=t.aliasResolveCache:(n=[],pr(e,{Node:(s,o)=>{(zt(o)||_a(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)}return i}toJSON(e,t){if(!t)return{source:this.source};let{anchors:n,doc:i,maxAliasCount:s}=t,o=this.resolve(i,t);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let a=n.get(o);if(a||(Ne(o,null,t),a=n.get(o)),(a==null?void 0:a.res)===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(s>=0&&(a.count+=1,a.aliasCount===0&&(a.aliasCount=$a(i,o,n)),a.count*a.aliasCount>s)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return a.res}toString(e,t,n){let i=`*${this.source}`;if(e){if(va(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 $a(r,e,t){if(zt(e)){let n=e.resolve(r),i=t&&n&&t.get(n);return i?i.count*i.aliasCount:0}else if(pe(e)){let n=0;for(let i of e.items){let s=$a(r,i,t);s>n&&(n=s)}return n}else if(ne(e)){let n=$a(r,e.key,t),i=$a(r,e.value,t);return Math.max(n,i)}return 1}var Sa=r=>!r||typeof r!="function"&&typeof r!="object",V=class extends Xr{constructor(e){super(vt),this.value=e}toJSON(e,t){return t!=null&&t.keep?this.value:Ne(this.value,e,t)}toString(){return String(this.value)}};V.BLOCK_FOLDED="BLOCK_FOLDED";V.BLOCK_LITERAL="BLOCK_LITERAL";V.PLAIN="PLAIN";V.QUOTE_DOUBLE="QUOTE_DOUBLE";V.QUOTE_SINGLE="QUOTE_SINGLE";var JO="tag:yaml.org,2002:";function YO(r,e,t){var n;if(e){let i=t.filter(o=>o.tag===e),s=(n=i.find(o=>!o.format))!=null?n:i[0];if(!s)throw new Error(`Tag ${e} not found`);return s}return t.find(i=>{var s;return((s=i.identify)==null?void 0:s.call(i,r))&&!i.format})}function xr(r,e,t){var d,f,p,m;if(Ht(r)&&(r=r.contents),se(r))return r;if(ne(r)){let h=(f=(d=t.schema[Bt]).createNode)==null?void 0:f.call(d,t.schema,null,t);return h.items.push(r),h}(r instanceof String||r instanceof Number||r instanceof Boolean||typeof BigInt!="undefined"&&r instanceof BigInt)&&(r=r.valueOf());let{aliasDuplicateObjects:n,onAnchor:i,onTagObj:s,schema:o,sourceObjects:a}=t,c;if(n&&r&&typeof r=="object"){if(c=a.get(r),c)return(p=c.anchor)!=null||(c.anchor=i(r)),new kr(c.anchor);c={anchor:null,node:null},a.set(r,c)}e!=null&&e.startsWith("!!")&&(e=JO+e.slice(2));let l=YO(r,e,o.tags);if(!l){if(r&&typeof r.toJSON=="function"&&(r=r.toJSON()),!r||typeof r!="object"){let h=new V(r);return c&&(c.node=h),h}l=r instanceof Map?o[Bt]:Symbol.iterator in Object(r)?o[Ar]:o[Bt]}s&&(s(l),delete t.onTagObj);let u=l!=null&&l.createNode?l.createNode(t.schema,r,t):typeof((m=l==null?void 0:l.nodeClass)==null?void 0:m.from)=="function"?l.nodeClass.from(t.schema,r,t):new V(r);return e?u.tag=e:l.default||(u.tag=l.tag),c&&(c.node=u),u}function xs(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 xr(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 pi=r=>r==null||typeof r=="object"&&!!r[Symbol.iterator]().next().done,fi=class extends Xr{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=>se(n)||ne(n)?n.clone(e):n),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(pi(e))this.add(t);else{let[n,...i]=e,s=this.get(n,!0);if(pe(s))s.addIn(i,t);else if(s===void 0&&this.schema)this.set(n,xs(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(pe(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&&J(s)?s.value:s:pe(s)?s.getIn(i,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!ne(t))return!1;let n=t.value;return n==null||e&&J(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 pe(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(pe(s))s.setIn(i,t);else if(s===void 0&&this.schema)this.set(n,xs(this.schema,i,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${i}`)}}};var s_=r=>r.replace(/^(?!$)(?: $)?/gm,"#");function Mt(r,e){return/^\n+$/.test(r)?r.substring(1):e?r.replace(/^(?! *$)/gm,e):r}var mr=(r,e,t)=>r.endsWith(` -`)?Mt(t,e):t.includes(` +`}function yb(r,e){var i;let t={},n=(i=e.settings.explicit_type_keys[0])!=null?i:"type";t[n]=n==="types"?[r.name]:r.name;for(let[s,o]of Object.entries(r.fields)){if(!re(o))continue;let a=o;a.default!==void 0&&(t[s]=Ze(a.default))}return t}function gb(r,e){let t=[];for(let[n,i]of Object.entries(r.fields)){if(!re(i))continue;let s=i;s.computed||s.required&&e[n]===void 0&&t.push([n,s])}return t}function tf(r,e){var i;let t=r.trim();switch((i=e.type)!=null?i:"string"){case"string":case"date":case"datetime":case"time":case"link":case"enum":case"any":return t;case"integer":{let s=Number.parseInt(t,10);if(!Number.isInteger(s))throw new Error("Expected integer input");return s}case"number":{let s=Number.parseFloat(t);if(Number.isNaN(s))throw new Error("Expected numeric input");return s}case"boolean":{let s=t.toLowerCase();if(["true","1","yes","y"].includes(s))return!0;if(["false","0","no","n"].includes(s))return!1;throw new Error("Expected boolean input: true/false")}case"list":{let s=t.split(",").map(o=>o.trim()).filter(o=>o.length>0);return e.items?s.map(o=>tf(o,e.items)):s}case"object":{let s=(0,me.parseYaml)(t);if(!re(s))throw new Error("Expected YAML object value");return s}case"tags":return t.split(",").map(s=>s.trim()).filter(s=>s.length>0);default:return t}}function nb(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 _b(r,e){let t=(0,me.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 LR(r,e){if(!r.path_pattern||r.path_pattern.trim().length===0)return null;let t=(0,me.normalizePath)(Zu(r.path_pattern,e));return t.endsWith(".md")?t:null}async function bb(r,e,t){var d;let n=LR(e,t),i=bR(e,t),s=n?(d=n.split("/").pop())!=null?d:n:wR(e,t),o=Os(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;let l=a.lastIndexOf("/");return l>0&&await _b(r,a.slice(0,l)),a}async function wb(r,e,t,n=""){let i=Os(e),s=i.lastIndexOf("/");if(s>0&&await _b(r,i.slice(0,s)),await r.adapter.exists(i))throw new Error(`File already exists: ${i}`);let o=`${yt(t,n)} +`;return r.create(i,o)}function va(r){return fR(r)}var oe=require("obsidian"),R0=dn(Wu(),1);var $a=Symbol.for("yaml.alias"),Sa=Symbol.for("yaml.document"),Dt=Symbol.for("yaml.map"),rf=Symbol.for("yaml.pair"),gt=Symbol.for("yaml.scalar"),$r=Symbol.for("yaml.seq"),et=Symbol.for("yaml.node.type"),qt=r=>!!r&&typeof r=="object"&&r[et]===$a,or=r=>!!r&&typeof r=="object"&&r[et]===Sa,Ft=r=>!!r&&typeof r=="object"&&r[et]===Dt,ne=r=>!!r&&typeof r=="object"&&r[et]===rf,G=r=>!!r&&typeof r=="object"&&r[et]===gt,Ut=r=>!!r&&typeof r=="object"&&r[et]===$r;function le(r){if(r&&typeof r=="object")switch(r[et]){case Dt:case $r:return!0}return!1}function se(r){if(r&&typeof r=="object")switch(r[et]){case $a:case Dt:case gt:case $r:return!0}return!1}var Ea=r=>(G(r)||le(r))&&!!r.anchor;var dt=Symbol("break visit"),vb=Symbol("skip children"),ar=Symbol("remove node");function cr(r,e){let t=$b(e);or(r)?pi(null,r.contents,t,Object.freeze([r]))===ar&&(r.contents=null):pi(null,r,t,Object.freeze([]))}cr.BREAK=dt;cr.SKIP=vb;cr.REMOVE=ar;function pi(r,e,t,n){let i=Sb(r,e,t,n);if(se(i)||ne(i))return Eb(r,n,i),pi(r,i,t,n);if(typeof i!="symbol"){if(le(e)){n=Object.freeze(n.concat(e));for(let s=0;sr.replace(/[!,[\]{}]/g,e=>jR[e]),lr=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+DR(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&&se(e.contents)){let s={};cr(e.contents,(o,a)=>{se(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(` +`)}};lr.defaultYaml={explicit:!1,version:"1.2"};lr.defaultTags={"!!":"tag:yaml.org,2002:"};function xa(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 nf(r){let e=new Set;return cr(r,{Value(t,n){n.anchor&&e.add(n.anchor)}}),e}function sf(r,e){for(let t=1;;++t){let n=`${r}${t}`;if(!e.has(n))return n}}function Ab(r,e){let t=[],n=new Map,i=null;return{onAnchor:s=>{t.push(s),i!=null||(i=nf(r));let o=sf(e,i);return i.add(o),o},setAnchors:()=>{for(let s of t){let o=n.get(s);if(typeof o=="object"&&o.anchor&&(G(o.node)||le(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 Yr(r,e,t,n){if(n&&typeof n=="object")if(Array.isArray(n))for(let i=0,s=n.length;iMe(n,String(i),t));if(r&&typeof r.toJSON=="function"){if(!t||!Ea(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!=null&&t.keep)?Number(r):r}var Xr=class{constructor(e){Object.defineProperty(this,et,{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(!or(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=Me(this,"",o);if(typeof i=="function")for(let{count:c,res:l}of o.anchors.values())i(l,c);return typeof s=="function"?Yr(s,{"":a},"",a):a}};var Sr=class extends Xr{constructor(e){super($a),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,t){if((t==null?void 0:t.maxAliasCount)===0)throw new ReferenceError("Alias resolution is disabled");let n;t!=null&&t.aliasResolveCache?n=t.aliasResolveCache:(n=[],cr(e,{Node:(s,o)=>{(qt(o)||Ea(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)}return i}toJSON(e,t){if(!t)return{source:this.source};let{anchors:n,doc:i,maxAliasCount:s}=t,o=this.resolve(i,t);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let a=n.get(o);if(a||(Me(o,null,t),a=n.get(o)),(a==null?void 0:a.res)===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(s>=0&&(a.count+=1,a.aliasCount===0&&(a.aliasCount=ka(i,o,n)),a.count*a.aliasCount>s)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return a.res}toString(e,t,n){let i=`*${this.source}`;if(e){if(xa(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 ka(r,e,t){if(qt(e)){let n=e.resolve(r),i=t&&n&&t.get(n);return i?i.count*i.aliasCount:0}else if(le(e)){let n=0;for(let i of e.items){let s=ka(r,i,t);s>n&&(n=s)}return n}else if(ne(e)){let n=ka(r,e.key,t),i=ka(r,e.value,t);return Math.max(n,i)}return 1}var Pa=r=>!r||typeof r!="function"&&typeof r!="object",q=class extends Xr{constructor(e){super(gt),this.value=e}toJSON(e,t){return t!=null&&t.keep?this.value:Me(this.value,e,t)}toString(){return String(this.value)}};q.BLOCK_FOLDED="BLOCK_FOLDED";q.BLOCK_LITERAL="BLOCK_LITERAL";q.PLAIN="PLAIN";q.QUOTE_DOUBLE="QUOTE_DOUBLE";q.QUOTE_SINGLE="QUOTE_SINGLE";var qR="tag:yaml.org,2002:";function FR(r,e,t){var n;if(e){let i=t.filter(o=>o.tag===e),s=(n=i.find(o=>!o.format))!=null?n:i[0];if(!s)throw new Error(`Tag ${e} not found`);return s}return t.find(i=>{var s;return((s=i.identify)==null?void 0:s.call(i,r))&&!i.format})}function Er(r,e,t){var u,f,p,y;if(or(r)&&(r=r.contents),se(r))return r;if(ne(r)){let h=(f=(u=t.schema[Dt]).createNode)==null?void 0:f.call(u,t.schema,null,t);return h.items.push(r),h}(r instanceof String||r instanceof Number||r instanceof Boolean||typeof BigInt!="undefined"&&r instanceof BigInt)&&(r=r.valueOf());let{aliasDuplicateObjects:n,onAnchor:i,onTagObj:s,schema:o,sourceObjects:a}=t,c;if(n&&r&&typeof r=="object"){if(c=a.get(r),c)return(p=c.anchor)!=null||(c.anchor=i(r)),new Sr(c.anchor);c={anchor:null,node:null},a.set(r,c)}e!=null&&e.startsWith("!!")&&(e=qR+e.slice(2));let l=FR(r,e,o.tags);if(!l){if(r&&typeof r.toJSON=="function"&&(r=r.toJSON()),!r||typeof r!="object"){let h=new q(r);return c&&(c.node=h),h}l=r instanceof Map?o[Dt]:Symbol.iterator in Object(r)?o[$r]:o[Dt]}s&&(s(l),delete t.onTagObj);let d=l!=null&&l.createNode?l.createNode(t.schema,r,t):typeof((y=l==null?void 0:l.nodeClass)==null?void 0:y.from)=="function"?l.nodeClass.from(t.schema,r,t):new q(r);return e?d.tag=e:l.default||(d.tag=l.tag),c&&(c.node=d),d}function Ts(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 Er(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 yi=r=>r==null||typeof r=="object"&&!!r[Symbol.iterator]().next().done,mi=class extends Xr{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=>se(n)||ne(n)?n.clone(e):n),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(yi(e))this.add(t);else{let[n,...i]=e,s=this.get(n,!0);if(le(s))s.addIn(i,t);else if(s===void 0&&this.schema)this.set(n,Ts(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(le(i))return i.deleteIn(n);throw new Error(`Expected YAML collection at ${t}. Remaining path: ${n}`)}getIn(e,t){let[n,...i]=e,s=this.get(n,!0);return i.length===0?!t&&G(s)?s.value:s:le(s)?s.getIn(i,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!ne(t))return!1;let n=t.value;return n==null||e&&G(n)&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn(e){let[t,...n]=e;if(n.length===0)return this.has(t);let i=this.get(t,!0);return le(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(le(s))s.setIn(i,t);else if(s===void 0&&this.schema)this.set(n,Ts(this.schema,i,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${i}`)}}};var xb=r=>r.replace(/^(?!$)(?: $)?/gm,"#");function Ot(r,e){return/^\n+$/.test(r)?r.substring(1):e?r.replace(/^(?! *$)/gm,e):r}var dr=(r,e,t)=>r.endsWith(` +`)?Ot(t,e):t.includes(` `)?` -`+Mt(t,e):(r.endsWith(" ")?"":" ")+t;var Ku="flow",Ea="block",Ps="quoted";function Is(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,m=!1,h=-1,y=-1,b=-1;t===Ea&&(h=o_(r,h,e.length),h!==-1&&(d=h+c));for(let _;_=r[h+=1];){if(t===Ps&&_==="\\"){switch(y=h,r[h+1]){case"x":h+=3;break;case"u":h+=5;break;case"U":h+=9;break;default:h+=1}b=h}if(_===` -`)t===Ea&&(h=o_(r,h,e.length)),d=h+e.length+c,f=void 0;else{if(_===" "&&p&&p!==" "&&p!==` +`+Ot(t,e):(r.endsWith(" ")?"":" ")+t;var of="flow",Ia="block",Ms="quoted";function Cs(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):u=i-n);let f,p,y=!1,h=-1,m=-1,g=-1;t===Ia&&(h=kb(r,h,e.length),h!==-1&&(u=h+c));for(let w;w=r[h+=1];){if(t===Ms&&w==="\\"){switch(m=h,r[h+1]){case"x":h+=3;break;case"u":h+=5;break;case"U":h+=9;break;default:h+=1}g=h}if(w===` +`)t===Ia&&(h=kb(r,h,e.length)),u=h+e.length+c,f=void 0;else{if(w===" "&&p&&p!==" "&&p!==` `&&p!==" "){let k=r[h+1];k&&k!==" "&&k!==` -`&&k!==" "&&(f=h)}if(h>=d)if(f)l.push(f),d=f+c,f=void 0;else if(t===Ps){for(;p===" "||p===" ";)p=_,_=r[h+=1],m=!0;let k=h>b+1?h-2:y-1;if(u[k])return r;l.push(k),u[k]=!0,d=k+c,f=void 0}else m=!0}p=_}if(m&&a&&a(),l.length===0)return r;o&&o();let g=r.slice(0,l[0]);for(let _=0;_({indentAtStart:e?r.indent.length:r.indentAtStart,lineWidth:r.options.lineWidth,minContentWidth:r.options.minContentWidth}),xa=r=>/^(%|---|\.\.\.)/m.test(r);function XO(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 Os(r,e){let t=JSON.stringify(r);if(e.options.doubleQuotedAsJSON)return t;let{implicitKey:n}=e,i=e.options.doubleQuotedMinMultiLineLength,s=e.indent||(xa(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=u)if(f)l.push(f),u=f+c,f=void 0;else if(t===Ms){for(;p===" "||p===" ";)p=w,w=r[h+=1],y=!0;let k=h>g+1?h-2:m-1;if(d[k])return r;l.push(k),d[k]=!0,u=k+c,f=void 0}else y=!0}p=w}if(y&&a&&a(),l.length===0)return r;o&&o();let _=r.slice(0,l[0]);for(let w=0;w({indentAtStart:e?r.indent.length:r.indentAtStart,lineWidth:r.options.lineWidth,minContentWidth:r.options.minContentWidth}),Ta=r=>/^(%|---|\.\.\.)/m.test(r);function UR(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 Ns(r,e){let t=JSON.stringify(r);if(e.options.doubleQuotedAsJSON)return t;let{implicitKey:n}=e,i=e.options.doubleQuotedMinMultiLineLength,s=e.indent||(Ta(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 d=t.substr(c+2,4);switch(d){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:d.substr(0,2)==="00"?o+="\\x"+d.substr(2):o+=t.substr(c,6)}c+=5,a=c+1}break;case"n":if(n||t[c+2]==='"'||t.length -`;let d,f;for(f=t.length;f>0;--f){let v=t[f-1];if(v!==` -`&&v!==" "&&v!==" ")break}let p=t.substring(f),m=p.indexOf(` -`);m===-1?d="-":t===p||m!==p.length-1?(d="+",s&&s()):d="",p&&(t=t.slice(0,-p.length),p[p.length-1]===` -`&&(p=p.slice(0,-1)),p=p.replace(Gu,`$&${l}`));let h=!1,y,b=-1;for(y=0;y{E=!0});let w=Is(`${g}${v}${p}`,l,Ea,O);if(!E)return`>${k} -${l}${w}`}return t=t.replace(/\n+/g,`$&${l}`),`|${k} -${l}${g}${t}${p}`}function QO(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 hi(s,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(s))return a||u||!s.includes(` -`)?hi(s,e):Aa(r,e,t,n);if(!a&&!u&&i!==V.PLAIN&&s.includes(` -`))return Aa(r,e,t,n);if(xa(s)){if(c==="")return e.forceBlockIndent=!0,Aa(r,e,t,n);if(a&&c===l)return hi(s,e)}let d=s.replace(/\n+/g,`$& -${c}`);if(o){let f=h=>{var y;return h.default&&h.tag!=="tag:yaml.org,2002:str"&&((y=h.test)==null?void 0:y.test(d))},{compat:p,tags:m}=e.doc.schema;if(m.some(f)||p!=null&&p.some(f))return hi(s,e)}return a?d:Is(d,c,Ku,ka(e,!1))}function Sn(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!==V.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=V.QUOTE_DOUBLE);let c=u=>{switch(u){case V.BLOCK_FOLDED:case V.BLOCK_LITERAL:return i||s?hi(o.value,e):Aa(o,e,t,n);case V.QUOTE_DOUBLE:return Os(o.value,e);case V.QUOTE_SINGLE:return Wu(o.value,e);case V.PLAIN:return QO(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 Pa(r,e){let t=Object.assign({blockQuote:!0,commentString:s_,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 ZO(r,e){var i,s,o,a;if(e.tag){let c=r.filter(l=>l.tag===e.tag);if(c.length>0)return(i=c.find(l=>l.format===e.format))!=null?i:c[0]}let t,n;if(J(e)){n=e.value;let c=r.filter(l=>{var u;return(u=l.identify)==null?void 0:u.call(l,n)});if(c.length>1){let l=c.filter(u=>u.test);l.length>0&&(c=l)}t=(s=c.find(l=>l.format===e.format))!=null?s:c.find(l=>!l.format)}else n=e,t=r.find(c=>c.nodeClass&&n instanceof c.nodeClass);if(!t){let c=(a=(o=n==null?void 0:n.constructor)==null?void 0:o.name)!=null?a:n===null?"null":typeof n;throw new Error(`Tag not resolved for ${c} value`)}return t}function eT(r,e,{anchors:t,doc:n}){var a;if(!n.directives)return"";let i=[],s=(J(r)||pe(r))&&r.anchor;s&&va(s)&&(t.add(s),i.push(`&${s}`));let o=(a=r.tag)!=null?a:e.default?null:e.tag;return o&&i.push(n.directives.tagString(o)),i.join(" ")}function Pr(r,e,t,n){var c,l;if(ne(r))return r.toString(e,t,n);if(zt(r)){if(e.doc.directives)return r.toString(e);if((c=e.resolvedAliases)!=null&&c.has(r))throw new TypeError("Cannot stringify circular structure without alias nodes");e.resolvedAliases?e.resolvedAliases.add(r):e.resolvedAliases=new Set([r]),r=r.resolve(e.doc)}let i,s=se(r)?r:e.doc.createNode(r,{onTagObj:u=>i=u});i!=null||(i=ZO(e.doc.schema.tags,s));let o=eT(s,i,e);o.length>0&&(e.indentAtStart=((l=e.indentAtStart)!=null?l:0)+o.length+1);let a=typeof i.stringify=="function"?i.stringify(s,e,t,n):J(s)?Sn(s,e,t,n):s.toString(e,t,n);return o?J(s)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o} -${e.indent}${a}`:a}function a_({key:r,value:e},t,n,i){var O,w;let{allNullValues:s,doc:o,indent:a,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:d}}=t,f=se(r)&&r.comment||null;if(d){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(pe(r)||!se(r)&&typeof r=="object"){let x="With simple keys, collection cannot be used as a key value";throw new Error(x)}}let p=!d&&(!r||f&&e==null&&!t.inFlow||pe(r)||(J(r)?r.type===V.BLOCK_FOLDED||r.type===V.BLOCK_LITERAL:typeof r=="object"));t=Object.assign({},t,{allNullValues:!1,implicitKey:!p&&(d||!s),indent:a+c});let m=!1,h=!1,y=Pr(r,t,()=>m=!0,()=>h=!0);if(!p&&!t.inFlow&&y.length>1024){if(d)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");p=!0}if(t.inFlow){if(s||e==null)return m&&n&&n(),y===""?"?":p?`? ${y}`:y}else if(s&&!d||e==null&&p)return y=`? ${y}`,f&&!m?y+=mr(y,t.indent,l(f)):h&&i&&i(),y;m&&(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 b,g,_;se(e)?(b=!!e.spaceBefore,g=e.commentBefore,_=e.comment):(b=!1,g=null,_=null,e&&typeof e=="object"&&(e=o.createNode(e))),t.implicitKey=!1,!p&&!f&&J(e)&&(t.indentAtStart=y.length+1),h=!1,!u&&c.length>=2&&!t.inFlow&&!p&&Wt(e)&&!e.flow&&!e.tag&&!e.anchor&&(t.indent=t.indent.substring(2));let k=!1,v=Pr(e,t,()=>k=!0,()=>h=!0),E=" ";if(f||b||g){if(E=b?` -`:"",g){let x=l(g);E+=` -${Mt(x,t.indent)}`}v===""&&!t.inFlow?E===` -`&&_&&(E=` +`;let u,f;for(f=t.length;f>0;--f){let v=t[f-1];if(v!==` +`&&v!==" "&&v!==" ")break}let p=t.substring(f),y=p.indexOf(` +`);y===-1?u="-":t===p||y!==p.length-1?(u="+",s&&s()):u="",p&&(t=t.slice(0,-p.length),p[p.length-1]===` +`&&(p=p.slice(0,-1)),p=p.replace(cf,`$&${l}`));let h=!1,m,g=-1;for(m=0;m{P=!0});let $=Cs(`${_}${v}${p}`,l,Ia,O);if(!P)return`>${k} +${l}${$}`}return t=t.replace(/\n+/g,`$&${l}`),`|${k} +${l}${_}${t}${p}`}function VR(r,e,t,n){let{type:i,value:s}=r,{actualString:o,implicitKey:a,indent:c,indentStep:l,inFlow:d}=e;if(a&&s.includes(` +`)||d&&/[[\]{},]/.test(s))return gi(s,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(s))return a||d||!s.includes(` +`)?gi(s,e):Oa(r,e,t,n);if(!a&&!d&&i!==q.PLAIN&&s.includes(` +`))return Oa(r,e,t,n);if(Ta(s)){if(c==="")return e.forceBlockIndent=!0,Oa(r,e,t,n);if(a&&c===l)return gi(s,e)}let u=s.replace(/\n+/g,`$& +${c}`);if(o){let f=h=>{var m;return h.default&&h.tag!=="tag:yaml.org,2002:str"&&((m=h.test)==null?void 0:m.test(u))},{compat:p,tags:y}=e.doc.schema;if(y.some(f)||p!=null&&p.some(f))return gi(s,e)}return a?u:Cs(u,c,of,Ra(e,!1))}function En(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!==q.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=q.QUOTE_DOUBLE);let c=d=>{switch(d){case q.BLOCK_FOLDED:case q.BLOCK_LITERAL:return i||s?gi(o.value,e):Oa(o,e,t,n);case q.QUOTE_DOUBLE:return Ns(o.value,e);case q.QUOTE_SINGLE:return af(o.value,e);case q.PLAIN:return VR(o,e,t,n);default:return null}},l=c(a);if(l===null){let{defaultKeyType:d,defaultStringType:u}=e.options,f=i&&d||u;if(l=c(f),l===null)throw new Error(`Unsupported default string type ${f}`)}return l}function Ma(r,e){let t=Object.assign({blockQuote:!0,commentString:xb,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 BR(r,e){var i,s,o,a;if(e.tag){let c=r.filter(l=>l.tag===e.tag);if(c.length>0)return(i=c.find(l=>l.format===e.format))!=null?i:c[0]}let t,n;if(G(e)){n=e.value;let c=r.filter(l=>{var d;return(d=l.identify)==null?void 0:d.call(l,n)});if(c.length>1){let l=c.filter(d=>d.test);l.length>0&&(c=l)}t=(s=c.find(l=>l.format===e.format))!=null?s:c.find(l=>!l.format)}else n=e,t=r.find(c=>c.nodeClass&&n instanceof c.nodeClass);if(!t){let c=(a=(o=n==null?void 0:n.constructor)==null?void 0:o.name)!=null?a:n===null?"null":typeof n;throw new Error(`Tag not resolved for ${c} value`)}return t}function zR(r,e,{anchors:t,doc:n}){var a;if(!n.directives)return"";let i=[],s=(G(r)||le(r))&&r.anchor;s&&xa(s)&&(t.add(s),i.push(`&${s}`));let o=(a=r.tag)!=null?a:e.default?null:e.tag;return o&&i.push(n.directives.tagString(o)),i.join(" ")}function Ar(r,e,t,n){var c,l;if(ne(r))return r.toString(e,t,n);if(qt(r)){if(e.doc.directives)return r.toString(e);if((c=e.resolvedAliases)!=null&&c.has(r))throw new TypeError("Cannot stringify circular structure without alias nodes");e.resolvedAliases?e.resolvedAliases.add(r):e.resolvedAliases=new Set([r]),r=r.resolve(e.doc)}let i,s=se(r)?r:e.doc.createNode(r,{onTagObj:d=>i=d});i!=null||(i=BR(e.doc.schema.tags,s));let o=zR(s,i,e);o.length>0&&(e.indentAtStart=((l=e.indentAtStart)!=null?l:0)+o.length+1);let a=typeof i.stringify=="function"?i.stringify(s,e,t,n):G(s)?En(s,e,t,n):s.toString(e,t,n);return o?G(s)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o} +${e.indent}${a}`:a}function Pb({key:r,value:e},t,n,i){var O,$;let{allNullValues:s,doc:o,indent:a,indentStep:c,options:{commentString:l,indentSeq:d,simpleKeys:u}}=t,f=se(r)&&r.comment||null;if(u){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(le(r)||!se(r)&&typeof r=="object"){let R="With simple keys, collection cannot be used as a key value";throw new Error(R)}}let p=!u&&(!r||f&&e==null&&!t.inFlow||le(r)||(G(r)?r.type===q.BLOCK_FOLDED||r.type===q.BLOCK_LITERAL:typeof r=="object"));t=Object.assign({},t,{allNullValues:!1,implicitKey:!p&&(u||!s),indent:a+c});let y=!1,h=!1,m=Ar(r,t,()=>y=!0,()=>h=!0);if(!p&&!t.inFlow&&m.length>1024){if(u)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 y&&n&&n(),m===""?"?":p?`? ${m}`:m}else if(s&&!u||e==null&&p)return m=`? ${m}`,f&&!y?m+=dr(m,t.indent,l(f)):h&&i&&i(),m;y&&(f=null),p?(f&&(m+=dr(m,t.indent,l(f))),m=`? ${m} +${a}:`):(m=`${m}:`,f&&(m+=dr(m,t.indent,l(f))));let g,_,w;se(e)?(g=!!e.spaceBefore,_=e.commentBefore,w=e.comment):(g=!1,_=null,w=null,e&&typeof e=="object"&&(e=o.createNode(e))),t.implicitKey=!1,!p&&!f&&G(e)&&(t.indentAtStart=m.length+1),h=!1,!d&&c.length>=2&&!t.inFlow&&!p&&Ut(e)&&!e.flow&&!e.tag&&!e.anchor&&(t.indent=t.indent.substring(2));let k=!1,v=Ar(e,t,()=>k=!0,()=>h=!0),P=" ";if(f||g||_){if(P=g?` +`:"",_){let R=l(_);P+=` +${Ot(R,t.indent)}`}v===""&&!t.inFlow?P===` +`&&w&&(P=` -`):E+=` -${t.indent}`}else if(!p&&pe(e)){let x=v[0],$=v.indexOf(` -`),L=$!==-1,F=(w=(O=t.inFlow)!=null?O:e.flow)!=null?w:e.items.length===0;if(L||!F){let z=!1;if(L&&(x==="&"||x==="!")){let P=v.indexOf(" ");x==="&"&&P!==-1&&P<$&&v[P+1]==="!"&&(P=v.indexOf(" ",P+1)),(P===-1||$r===Oa||typeof r=="symbol"&&r.description===Oa,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new V(Symbol(Oa)),{addToJSMap:Yu}),stringify:()=>Oa},c_=(r,e)=>(Gt.identify(e)||J(e)&&(!e.type||e.type===V.PLAIN)&&Gt.identify(e.value))&&(r==null?void 0:r.doc.schema.tags.some(t=>t.tag===Gt.tag&&t.default));function Yu(r,e,t){let n=l_(r,t);if(Wt(n))for(let i of n.items)Ju(r,e,i);else if(Array.isArray(n))for(let i of n)Ju(r,e,i);else Ju(r,e,n)}function Ju(r,e,t){let n=l_(r,t);if(!Kt(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 l_(r,e){return r&&zt(e)?e.resolve(r.doc,r):e}function Ta(r,e,{key:t,value:n}){if(se(t)&&t.addToJSMap)t.addToJSMap(r,e,n);else if(c_(r,t))Yu(r,e,n);else{let i=Ne(t,"",r);if(e instanceof Map)e.set(i,Ne(n,i,r));else if(e instanceof Set)e.add(i);else{let s=tT(t,i,r),o=Ne(n,s,r);s in e?Object.defineProperty(e,s,{value:o,writable:!0,enumerable:!0,configurable:!0}):e[s]=o}}return e}function tT(r,e,t){if(e===null)return"";if(typeof e!="object")return String(e);if(se(r)&&(t!=null&&t.doc)){let n=Pa(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)+'..."'),Ia(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 mi(r,e,t){let n=xr(r,void 0,t),i=xr(e,void 0,t);return new Ee(n,i)}var Ee=class r{constructor(e,t=null){Object.defineProperty(this,st,{value:Bu}),this.key=e,this.value=t}clone(e){let{key:t,value:n}=this;return se(t)&&(t=t.clone(e)),se(n)&&(n=n.clone(e)),new r(t,n)}toJSON(e,t){let n=t!=null&&t.mapAsMap?new Map:{};return Ta(t,n,this)}toString(e,t,n){return e!=null&&e.doc?a_(this,e,t,n):JSON.stringify(this)}};function Ca(r,e,t){var s;return(((s=e.inFlow)!=null?s:r.flow)?nT:rT)(r,e,t)}function rT({comment:r,items:e},t,{blockItemPrefix:n,flowChars:i,itemIndent:s,onChompKeep:o,onComment:a}){let{indent:c,options:{commentString:l}}=t,u=Object.assign({},t,{indent:s,type:null}),d=!1,f=[];for(let m=0;my=null,()=>d=!0);y&&(b+=mr(b,s,l(y))),d&&y&&(d=!1),f.push(n+b)}let p;if(f.length===0)p=i.start+i.end;else{p=f[0];for(let m=1;mr===Na||typeof r=="symbol"&&r.description===Na,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new q(Symbol(Na)),{addToJSMap:df}),stringify:()=>Na},Ib=(r,e)=>(Vt.identify(e)||G(e)&&(!e.type||e.type===q.PLAIN)&&Vt.identify(e.value))&&(r==null?void 0:r.doc.schema.tags.some(t=>t.tag===Vt.tag&&t.default));function df(r,e,t){let n=Ob(r,t);if(Ut(n))for(let i of n.items)lf(r,e,i);else if(Array.isArray(n))for(let i of n)lf(r,e,i);else lf(r,e,n)}function lf(r,e,t){let n=Ob(r,t);if(!Ft(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 Ob(r,e){return r&&qt(e)?e.resolve(r.doc,r):e}function La(r,e,{key:t,value:n}){if(se(t)&&t.addToJSMap)t.addToJSMap(r,e,n);else if(Ib(r,t))df(r,e,n);else{let i=Me(t,"",r);if(e instanceof Map)e.set(i,Me(n,i,r));else if(e instanceof Set)e.add(i);else{let s=HR(t,i,r),o=Me(n,s,r);s in e?Object.defineProperty(e,s,{value:o,writable:!0,enumerable:!0,configurable:!0}):e[s]=o}}return e}function HR(r,e,t){if(e===null)return"";if(typeof e!="object")return String(e);if(se(r)&&(t!=null&&t.doc)){let n=Ma(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)+'..."'),Ca(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 _i(r,e,t){let n=Er(r,void 0,t),i=Er(e,void 0,t);return new Se(n,i)}var Se=class r{constructor(e,t=null){Object.defineProperty(this,et,{value:rf}),this.key=e,this.value=t}clone(e){let{key:t,value:n}=this;return se(t)&&(t=t.clone(e)),se(n)&&(n=n.clone(e)),new r(t,n)}toJSON(e,t){let n=t!=null&&t.mapAsMap?new Map:{};return La(t,n,this)}toString(e,t,n){return e!=null&&e.doc?Pb(this,e,t,n):JSON.stringify(this)}};function Da(r,e,t){var s;return(((s=e.inFlow)!=null?s:r.flow)?WR:KR)(r,e,t)}function KR({comment:r,items:e},t,{blockItemPrefix:n,flowChars:i,itemIndent:s,onChompKeep:o,onComment:a}){let{indent:c,options:{commentString:l}}=t,d=Object.assign({},t,{indent:s,type:null}),u=!1,f=[];for(let y=0;ym=null,()=>u=!0);m&&(g+=dr(g,s,l(m))),u&&m&&(u=!1),f.push(n+g)}let p;if(f.length===0)p=i.start+i.end;else{p=f[0];for(let y=1;yy=null);l||(l=d.length>u||b.includes(` -`)),m0&&(l||(l=d.reduce((g,_)=>g+_.length+2,2)+(b.length+2)>e.options.lineWidth)),l&&(b+=",")),y&&(b+=mr(b,n,a(y))),d.push(b),u=d.length}let{start:f,end:p}=t;if(d.length===0)return f+p;if(!l){let m=d.reduce((h,y)=>h+y.length+2,2);l=e.options.lineWidth>0&&m>e.options.lineWidth}if(l){let m=f;for(let h of d)m+=h?` +`+Ot(l(r),c),a&&a()):u&&o&&o(),p}function WR({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,d=0,u=[];for(let y=0;ym=null);l||(l=u.length>d||g.includes(` +`)),y0&&(l||(l=u.reduce((_,w)=>_+w.length+2,2)+(g.length+2)>e.options.lineWidth)),l&&(g+=",")),m&&(g+=dr(g,n,a(m))),u.push(g),d=u.length}let{start:f,end:p}=t;if(u.length===0)return f+p;if(!l){let y=u.reduce((h,m)=>h+m.length+2,2);l=e.options.lineWidth>0&&y>e.options.lineWidth}if(l){let y=f;for(let h of u)y+=h?` ${s}${i}${h}`:` -`;return`${m} -${i}${p}`}else return`${f}${o}${d.join(" ")}${o}${p}`}function Ra({indent:r,options:{commentString:e}},t,n,i){if(n&&i&&(n=n.replace(/^\n+/,"")),n){let s=Mt(e(n),r);t.push(s.trimStart())}}function Qr(r,e){let t=J(e)?e.value:e;for(let n of r)if(ne(n)&&(n.key===e||n.key===t||J(n.key)&&n.key.value===t))return n}var Ie=class extends fi{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(Bt,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(mi(c,l,n))};if(t instanceof Map)for(let[c,l]of t)a(c,l);else if(t&&typeof t=="object")for(let c of Object.keys(t))a(c,t[c]);return typeof e.sortMapEntries=="function"&&o.items.sort(e.sortMapEntries),o}add(e,t){var o;let n;ne(e)?n=e:!e||typeof e!="object"||!("key"in e)?n=new Ee(e,e==null?void 0:e.value):n=new Ee(e.key,e.value);let i=Qr(this.items,n.key),s=(o=this.schema)==null?void 0:o.sortMapEntries;if(i){if(!t)throw new Error(`Key ${n.key} already set`);J(i.value)&&Sa(n.value)?i.value.value=n.value:i.value=n.value}else if(s){let a=this.items.findIndex(c=>s(n,c)<0);a===-1?this.items.push(n):this.items.splice(a,0,n)}else this.items.push(n)}delete(e){let t=Qr(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){var s;let n=Qr(this.items,e),i=n==null?void 0:n.value;return(s=!t&&J(i)?i.value:i)!=null?s:void 0}has(e){return!!Qr(this.items,e)}set(e,t){this.add(new Ee(e,t),!0)}toJSON(e,t,n){let i=n?new n:t!=null&&t.mapAsMap?new Map:{};t!=null&&t.onCreate&&t.onCreate(i);for(let s of this.items)Ta(t,i,s);return i}toString(e,t,n){if(!e)return JSON.stringify(this);for(let i of this.items)if(!ne(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})),Ca(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:n,onComment:t})}};var Jt={collection:"map",default:!0,nodeClass:Ie,tag:"tag:yaml.org,2002:map",resolve(r,e){return Kt(r)||e("Expected a mapping for this tag"),r},createNode:(r,e,t)=>Ie.from(r,e,t)};var Ge=class extends fi{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(Ar,e),this.items=[]}add(e){this.items.push(e)}delete(e){let t=Ma(e);return typeof t!="number"?!1:this.items.splice(t,1).length>0}get(e,t){let n=Ma(e);if(typeof n!="number")return;let i=this.items[n];return!t&&J(i)?i.value:i}has(e){let t=Ma(e);return typeof t=="number"&&t=0?e:null}var Yt={collection:"seq",default:!0,nodeClass:Ge,tag:"tag:yaml.org,2002:seq",resolve(r,e){return Wt(r)||e("Expected a sequence for this tag"),r},createNode:(r,e,t)=>Ge.from(r,e,t)};var Zr={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),Sn(r,e,t,n)}};var En={identify:r=>r==null,createNode:()=>new V(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new V(null),stringify:({source:r},e)=>typeof r=="string"&&En.test.test(r)?r:e.options.nullStr};var Ts={identify:r=>typeof r=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:r=>new V(r[0]==="t"||r[0]==="T"),stringify({source:r,value:e},t){if(r&&Ts.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 Je({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 Na={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:Je},La={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():Je(r)}},Da={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 V(parseFloat(r)),t=r.indexOf(".");return t!==-1&&r[r.length-1]==="0"&&(e.minFractionDigits=r.length-t-1),e},stringify:Je};var qa=r=>typeof r=="bigint"||Number.isInteger(r),Xu=(r,e,t,{intAsBigInt:n})=>n?BigInt(r):parseInt(r.substring(e),t);function d_(r,e,t){let{value:n}=r;return qa(n)&&n>=0?t+n.toString(e):Je(r)}var ja={identify:r=>qa(r)&&r>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(r,e,t)=>Xu(r,2,8,t),stringify:r=>d_(r,8,"0o")},Fa={identify:qa,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(r,e,t)=>Xu(r,0,10,t),stringify:Je},Va={identify:r=>qa(r)&&r>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(r,e,t)=>Xu(r,2,16,t),stringify:r=>d_(r,16,"0x")};var u_=[Jt,Yt,Zr,En,Ts,ja,Fa,Va,Na,La,Da];function f_(r){return typeof r=="bigint"||Number.isInteger(r)}var Ua=({value:r})=>JSON.stringify(r),iT=[{identify:r=>typeof r=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:r=>r,stringify:Ua},{identify:r=>r==null,createNode:()=>new V(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Ua},{identify:r=>typeof r=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:r=>r==="true",stringify:Ua},{identify:f_,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})=>f_(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:Ua}],sT={default:!0,tag:"",test:/^/,resolve(r,e){return e(`Unresolved plain scalar ${JSON.stringify(r)}`),r}},p_=[Jt,Yt].concat(iT,sT);var Rs={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 s=i.items[0]||new Ee(new V(null));if(i.commentBefore&&(s.key.commentBefore=s.key.commentBefore?`${i.commentBefore} +`;return`${y} +${i}${p}`}else return`${f}${o}${u.join(" ")}${o}${p}`}function ja({indent:r,options:{commentString:e}},t,n,i){if(n&&i&&(n=n.replace(/^\n+/,"")),n){let s=Ot(e(n),r);t.push(s.trimStart())}}function Qr(r,e){let t=G(e)?e.value:e;for(let n of r)if(ne(n)&&(n.key===e||n.key===t||G(n.key)&&n.key.value===t))return n}var Pe=class extends mi{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(Dt,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(_i(c,l,n))};if(t instanceof Map)for(let[c,l]of t)a(c,l);else if(t&&typeof t=="object")for(let c of Object.keys(t))a(c,t[c]);return typeof e.sortMapEntries=="function"&&o.items.sort(e.sortMapEntries),o}add(e,t){var o;let n;ne(e)?n=e:!e||typeof e!="object"||!("key"in e)?n=new Se(e,e==null?void 0:e.value):n=new Se(e.key,e.value);let i=Qr(this.items,n.key),s=(o=this.schema)==null?void 0:o.sortMapEntries;if(i){if(!t)throw new Error(`Key ${n.key} already set`);G(i.value)&&Pa(n.value)?i.value.value=n.value:i.value=n.value}else if(s){let a=this.items.findIndex(c=>s(n,c)<0);a===-1?this.items.push(n):this.items.splice(a,0,n)}else this.items.push(n)}delete(e){let t=Qr(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){var s;let n=Qr(this.items,e),i=n==null?void 0:n.value;return(s=!t&&G(i)?i.value:i)!=null?s:void 0}has(e){return!!Qr(this.items,e)}set(e,t){this.add(new Se(e,t),!0)}toJSON(e,t,n){let i=n?new n:t!=null&&t.mapAsMap?new Map:{};t!=null&&t.onCreate&&t.onCreate(i);for(let s of this.items)La(t,i,s);return i}toString(e,t,n){if(!e)return JSON.stringify(this);for(let i of this.items)if(!ne(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})),Da(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:n,onComment:t})}};var Bt={collection:"map",default:!0,nodeClass:Pe,tag:"tag:yaml.org,2002:map",resolve(r,e){return Ft(r)||e("Expected a mapping for this tag"),r},createNode:(r,e,t)=>Pe.from(r,e,t)};var Ke=class extends mi{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super($r,e),this.items=[]}add(e){this.items.push(e)}delete(e){let t=qa(e);return typeof t!="number"?!1:this.items.splice(t,1).length>0}get(e,t){let n=qa(e);if(typeof n!="number")return;let i=this.items[n];return!t&&G(i)?i.value:i}has(e){let t=qa(e);return typeof t=="number"&&t=0?e:null}var zt={collection:"seq",default:!0,nodeClass:Ke,tag:"tag:yaml.org,2002:seq",resolve(r,e){return Ut(r)||e("Expected a sequence for this tag"),r},createNode:(r,e,t)=>Ke.from(r,e,t)};var Zr={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),En(r,e,t,n)}};var An={identify:r=>r==null,createNode:()=>new q(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new q(null),stringify:({source:r},e)=>typeof r=="string"&&An.test.test(r)?r:e.options.nullStr};var Ls={identify:r=>typeof r=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:r=>new q(r[0]==="t"||r[0]==="T"),stringify({source:r,value:e},t){if(r&&Ls.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 We({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 Fa={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:We},Ua={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():We(r)}},Va={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 q(parseFloat(r)),t=r.indexOf(".");return t!==-1&&r[r.length-1]==="0"&&(e.minFractionDigits=r.length-t-1),e},stringify:We};var Ba=r=>typeof r=="bigint"||Number.isInteger(r),uf=(r,e,t,{intAsBigInt:n})=>n?BigInt(r):parseInt(r.substring(e),t);function Rb(r,e,t){let{value:n}=r;return Ba(n)&&n>=0?t+n.toString(e):We(r)}var za={identify:r=>Ba(r)&&r>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(r,e,t)=>uf(r,2,8,t),stringify:r=>Rb(r,8,"0o")},Ha={identify:Ba,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(r,e,t)=>uf(r,0,10,t),stringify:We},Ka={identify:r=>Ba(r)&&r>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(r,e,t)=>uf(r,2,16,t),stringify:r=>Rb(r,16,"0x")};var Tb=[Bt,zt,Zr,An,Ls,za,Ha,Ka,Fa,Ua,Va];function Mb(r){return typeof r=="bigint"||Number.isInteger(r)}var Wa=({value:r})=>JSON.stringify(r),GR=[{identify:r=>typeof r=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:r=>r,stringify:Wa},{identify:r=>r==null,createNode:()=>new q(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Wa},{identify:r=>typeof r=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:r=>r==="true",stringify:Wa},{identify:Mb,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})=>Mb(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:Wa}],JR={default:!0,tag:"",test:/^/,resolve(r,e){return e(`Unresolved plain scalar ${JSON.stringify(r)}`),r}},Cb=[Bt,zt].concat(GR,JR);var js={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 s=i.items[0]||new Se(new q(null));if(i.commentBefore&&(s.key.commentBefore=s.key.commentBefore?`${i.commentBefore} ${s.key.commentBefore}`:i.commentBefore),i.comment){let o=(t=s.value)!=null?t:s.key;o.comment=o.comment?`${i.comment} -${o.comment}`:i.comment}i=s}r.items[n]=ne(i)?i:new Ee(i)}}else e("Expected a sequence for this tag");return r}function Zu(r,e,t){let{replacer:n}=t,i=new Ge(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(mi(a,c,t))}return i}var Cs={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Qu,createNode:Zu};var yi=class r extends Ge{constructor(){super(),this.add=Ie.prototype.add.bind(this),this.delete=Ie.prototype.delete.bind(this),this.get=Ie.prototype.get.bind(this),this.has=Ie.prototype.has.bind(this),this.set=Ie.prototype.set.bind(this),this.tag=r.tag}toJSON(e,t){if(!t)return super.toJSON(e);let n=new Map;t!=null&&t.onCreate&&t.onCreate(n);for(let i of this.items){let s,o;if(ne(i)?(s=Ne(i.key,"",t),o=Ne(i.value,s,t)):s=Ne(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=Zu(e,t,n),s=new this;return s.items=i.items,s}};yi.tag="tag:yaml.org,2002:omap";var Ms={collection:"seq",identify:r=>r instanceof Map,nodeClass:yi,default:!1,tag:"tag:yaml.org,2002:omap",resolve(r,e){let t=Qu(r,e),n=[];for(let{key:i}of t.items)J(i)&&(n.includes(i.value)?e(`Ordered maps must not include duplicate keys: ${i.value}`):n.push(i.value));return Object.assign(new yi,t)},createNode:(r,e,t)=>yi.from(r,e,t)};function h_({value:r,source:e},t){return e&&(r?ef:tf).test.test(e)?e:r?t.options.trueStr:t.options.falseStr}var ef={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 V(!0),stringify:h_},tf={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 V(!1),stringify:h_};var m_={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:Je},y_={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():Je(r)}},g_={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 V(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:Je};var Ns=r=>typeof r=="bigint"||Number.isInteger(r);function Ba(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 rf(r,e,t){let{value:n}=r;if(Ns(n)){let i=n.toString(e);return n<0?"-"+t+i.substr(1):t+i}return Je(r)}var b_={identify:Ns,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(r,e,t)=>Ba(r,2,2,t),stringify:r=>rf(r,2,"0b")},__={identify:Ns,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(r,e,t)=>Ba(r,1,8,t),stringify:r=>rf(r,8,"0")},w_={identify:Ns,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(r,e,t)=>Ba(r,0,10,t),stringify:Je},v_={identify:Ns,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(r,e,t)=>Ba(r,2,16,t),stringify:r=>rf(r,16,"0x")};var gi=class r extends Ie{constructor(e){super(e),this.tag=r.tag}add(e){let t;ne(e)?t=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?t=new Ee(e.key,null):t=new Ee(e,null),Qr(this.items,t.key)||this.items.push(t)}get(e,t){let n=Qr(this.items,e);return!t&&ne(n)?J(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=Qr(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new Ee(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(mi(o,null,n));return s}};gi.tag="tag:yaml.org,2002:set";var Ls={collection:"map",identify:r=>r instanceof Set,nodeClass:gi,default:!1,tag:"tag:yaml.org,2002:set",createNode:(r,e,t)=>gi.from(r,e,t),resolve(r,e){if(Kt(r)){if(r.hasAllNullValues(!0))return Object.assign(new gi,r);e("Set items must all have null values")}else e("Expected a mapping for this tag");return r}};function nf(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 $_(r){let{value:e}=r,t=o=>o;if(typeof e=="bigint")t=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return Je(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 za={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})=>nf(r,t),stringify:$_},Ha={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=>nf(r,!1),stringify:$_},bi={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(bi.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=nf(u,!1);Math.abs(d)<30&&(d*=60),l-=6e4*d}return new Date(l)},stringify:({value:r})=>{var e;return(e=r==null?void 0:r.toISOString().replace(/(T00:00:00)?\.000Z$/,""))!=null?e:""}};var sf=[Jt,Yt,Zr,En,ef,tf,b_,__,w_,v_,m_,y_,g_,Rs,Gt,Ms,Cs,Ls,za,Ha,bi];var S_=new Map([["core",u_],["failsafe",[Jt,Yt,Zr]],["json",p_],["yaml11",sf],["yaml-1.1",sf]]),E_={binary:Rs,bool:Ts,float:Da,floatExp:La,floatNaN:Na,floatTime:Ha,int:Fa,intHex:Va,intOct:ja,intTime:za,map:Jt,merge:Gt,null:En,omap:Ms,pairs:Cs,seq:Yt,set:Ls,timestamp:bi},A_={"tag:yaml.org,2002:binary":Rs,"tag:yaml.org,2002:merge":Gt,"tag:yaml.org,2002:omap":Ms,"tag:yaml.org,2002:pairs":Cs,"tag:yaml.org,2002:set":Ls,"tag:yaml.org,2002:timestamp":bi};function Ka(r,e,t){let n=S_.get(e);if(n&&!r)return t&&!n.includes(Gt)?n.concat(Gt):n.slice();let i=n;if(!i)if(Array.isArray(r))i=[];else{let s=Array.from(S_.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(Gt)),i.reduce((s,o)=>{let a=typeof o=="string"?E_[o]:o;if(!a){let c=JSON.stringify(o),l=Object.keys(E_).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 oT=(r,e)=>r.keye.key?1:0,Ds=class r{constructor({compat:e,customTags:t,merge:n,resolveKnownTags:i,schema:s,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?Ka(e,"compat"):e?Ka(null,e):null,this.name=typeof s=="string"&&s||"core",this.knownTags=i?A_:{},this.tags=Ka(t,this.name,n),this.toStringOptions=a!=null?a:null,Object.defineProperty(this,Bt,{value:Jt}),Object.defineProperty(this,vt,{value:Zr}),Object.defineProperty(this,Ar,{value:Yt}),this.sortMapEntries=typeof o=="function"?o:o===!0?oT:null}clone(){let e=Object.create(r.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};function k_(r,e){var c;let t=[],n=e.directives===!0;if(e.directives!==!1&&r.directives){let l=r.directives.toString(r);l?(t.push(l),n=!0):r.directives.docStart&&(n=!0)}n&&t.push("---");let i=Pa(r,e),{commentString:s}=i.options;if(r.commentBefore){t.length!==1&&t.unshift("");let l=s(r.commentBefore);t.unshift(Mt(l,""))}let o=!1,a=null;if(r.contents){if(se(r.contents)){if(r.contents.spaceBefore&&n&&t.push(""),r.contents.commentBefore){let d=s(r.contents.commentBefore);t.push(Mt(d,""))}i.forceBlockIndent=!!r.comment,a=r.contents.comment}let l=a?void 0:()=>o=!0,u=Pr(r.contents,i,()=>a=null,l);a&&(u+=mr(u,"",s(a))),(u[0]==="|"||u[0]===">")&&t[t.length-1]==="---"?t[t.length-1]=`--- ${u}`:t.push(u)}else t.push(Pr(r.contents,i));if((c=r.directives)!=null&&c.docEnd)if(r.comment){let l=s(r.comment);l.includes(` -`)?(t.push("..."),t.push(Mt(l,""))):t.push(`... ${l}`)}else t.push("...");else{let l=r.comment;l&&o&&(l=l.replace(/^\n+/,"")),l&&((!o||a)&&t[t.length-1]!==""&&t.push(""),t.push(Mt(s(l),"")))}return t.join(` +${o.comment}`:i.comment}i=s}r.items[n]=ne(i)?i:new Se(i)}}else e("Expected a sequence for this tag");return r}function pf(r,e,t){let{replacer:n}=t,i=new Ke(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(_i(a,c,t))}return i}var Ds={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:ff,createNode:pf};var bi=class r extends Ke{constructor(){super(),this.add=Pe.prototype.add.bind(this),this.delete=Pe.prototype.delete.bind(this),this.get=Pe.prototype.get.bind(this),this.has=Pe.prototype.has.bind(this),this.set=Pe.prototype.set.bind(this),this.tag=r.tag}toJSON(e,t){if(!t)return super.toJSON(e);let n=new Map;t!=null&&t.onCreate&&t.onCreate(n);for(let i of this.items){let s,o;if(ne(i)?(s=Me(i.key,"",t),o=Me(i.value,s,t)):s=Me(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=pf(e,t,n),s=new this;return s.items=i.items,s}};bi.tag="tag:yaml.org,2002:omap";var qs={collection:"seq",identify:r=>r instanceof Map,nodeClass:bi,default:!1,tag:"tag:yaml.org,2002:omap",resolve(r,e){let t=ff(r,e),n=[];for(let{key:i}of t.items)G(i)&&(n.includes(i.value)?e(`Ordered maps must not include duplicate keys: ${i.value}`):n.push(i.value));return Object.assign(new bi,t)},createNode:(r,e,t)=>bi.from(r,e,t)};function Nb({value:r,source:e},t){return e&&(r?hf:mf).test.test(e)?e:r?t.options.trueStr:t.options.falseStr}var hf={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 q(!0),stringify:Nb},mf={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 q(!1),stringify:Nb};var Lb={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:We},jb={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():We(r)}},Db={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 q(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:We};var Fs=r=>typeof r=="bigint"||Number.isInteger(r);function Ga(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 yf(r,e,t){let{value:n}=r;if(Fs(n)){let i=n.toString(e);return n<0?"-"+t+i.substr(1):t+i}return We(r)}var qb={identify:Fs,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(r,e,t)=>Ga(r,2,2,t),stringify:r=>yf(r,2,"0b")},Fb={identify:Fs,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(r,e,t)=>Ga(r,1,8,t),stringify:r=>yf(r,8,"0")},Ub={identify:Fs,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(r,e,t)=>Ga(r,0,10,t),stringify:We},Vb={identify:Fs,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(r,e,t)=>Ga(r,2,16,t),stringify:r=>yf(r,16,"0x")};var wi=class r extends Pe{constructor(e){super(e),this.tag=r.tag}add(e){let t;ne(e)?t=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?t=new Se(e.key,null):t=new Se(e,null),Qr(this.items,t.key)||this.items.push(t)}get(e,t){let n=Qr(this.items,e);return!t&&ne(n)?G(n.key)?n.key.value:n.key:n}set(e,t){if(typeof t!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof t}`);let n=Qr(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new Se(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(_i(o,null,n));return s}};wi.tag="tag:yaml.org,2002:set";var Us={collection:"map",identify:r=>r instanceof Set,nodeClass:wi,default:!1,tag:"tag:yaml.org,2002:set",createNode:(r,e,t)=>wi.from(r,e,t),resolve(r,e){if(Ft(r)){if(r.hasAllNullValues(!0))return Object.assign(new wi,r);e("Set items must all have null values")}else e("Expected a mapping for this tag");return r}};function gf(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 Bb(r){let{value:e}=r,t=o=>o;if(typeof e=="bigint")t=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return We(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 Ja={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})=>gf(r,t),stringify:Bb},Ya={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=>gf(r,!1),stringify:Bb},vi={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(vi.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),d=e[8];if(d&&d!=="Z"){let u=gf(d,!1);Math.abs(u)<30&&(u*=60),l-=6e4*u}return new Date(l)},stringify:({value:r})=>{var e;return(e=r==null?void 0:r.toISOString().replace(/(T00:00:00)?\.000Z$/,""))!=null?e:""}};var _f=[Bt,zt,Zr,An,hf,mf,qb,Fb,Ub,Vb,Lb,jb,Db,js,Vt,qs,Ds,Us,Ja,Ya,vi];var zb=new Map([["core",Tb],["failsafe",[Bt,zt,Zr]],["json",Cb],["yaml11",_f],["yaml-1.1",_f]]),Hb={binary:js,bool:Ls,float:Va,floatExp:Ua,floatNaN:Fa,floatTime:Ya,int:Ha,intHex:Ka,intOct:za,intTime:Ja,map:Bt,merge:Vt,null:An,omap:qs,pairs:Ds,seq:zt,set:Us,timestamp:vi},Kb={"tag:yaml.org,2002:binary":js,"tag:yaml.org,2002:merge":Vt,"tag:yaml.org,2002:omap":qs,"tag:yaml.org,2002:pairs":Ds,"tag:yaml.org,2002:set":Us,"tag:yaml.org,2002:timestamp":vi};function Xa(r,e,t){let n=zb.get(e);if(n&&!r)return t&&!n.includes(Vt)?n.concat(Vt):n.slice();let i=n;if(!i)if(Array.isArray(r))i=[];else{let s=Array.from(zb.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(Vt)),i.reduce((s,o)=>{let a=typeof o=="string"?Hb[o]:o;if(!a){let c=JSON.stringify(o),l=Object.keys(Hb).map(d=>JSON.stringify(d)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return s.includes(a)||s.push(a),s},[])}var YR=(r,e)=>r.keye.key?1:0,Vs=class r{constructor({compat:e,customTags:t,merge:n,resolveKnownTags:i,schema:s,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?Xa(e,"compat"):e?Xa(null,e):null,this.name=typeof s=="string"&&s||"core",this.knownTags=i?Kb:{},this.tags=Xa(t,this.name,n),this.toStringOptions=a!=null?a:null,Object.defineProperty(this,Dt,{value:Bt}),Object.defineProperty(this,gt,{value:Zr}),Object.defineProperty(this,$r,{value:zt}),this.sortMapEntries=typeof o=="function"?o:o===!0?YR:null}clone(){let e=Object.create(r.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};function Wb(r,e){var c;let t=[],n=e.directives===!0;if(e.directives!==!1&&r.directives){let l=r.directives.toString(r);l?(t.push(l),n=!0):r.directives.docStart&&(n=!0)}n&&t.push("---");let i=Ma(r,e),{commentString:s}=i.options;if(r.commentBefore){t.length!==1&&t.unshift("");let l=s(r.commentBefore);t.unshift(Ot(l,""))}let o=!1,a=null;if(r.contents){if(se(r.contents)){if(r.contents.spaceBefore&&n&&t.push(""),r.contents.commentBefore){let u=s(r.contents.commentBefore);t.push(Ot(u,""))}i.forceBlockIndent=!!r.comment,a=r.contents.comment}let l=a?void 0:()=>o=!0,d=Ar(r.contents,i,()=>a=null,l);a&&(d+=dr(d,"",s(a))),(d[0]==="|"||d[0]===">")&&t[t.length-1]==="---"?t[t.length-1]=`--- ${d}`:t.push(d)}else t.push(Ar(r.contents,i));if((c=r.directives)!=null&&c.docEnd)if(r.comment){let l=s(r.comment);l.includes(` +`)?(t.push("..."),t.push(Ot(l,""))):t.push(`... ${l}`)}else t.push("...");else{let l=r.comment;l&&o&&(l=l.replace(/^\n+/,"")),l&&((!o||a)&&t[t.length-1]!==""&&t.push(""),t.push(Ot(s(l),"")))}return t.join(` `)+` -`}var Ir=class r{constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,st,{value:ba});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!=null&&n._directives?(this.directives=n._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new hr({version:o}),this.setSchema(o,n),this.contents=e===void 0?null:this.createNode(e,i,n)}clone(){let e=Object.create(r.prototype,{[st]:{value:ba}});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=se(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){_i(this.contents)&&this.contents.add(e)}addIn(e,t){_i(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){let n=zu(this);e.anchor=!t||n.has(t)?Hu(t||"a",n):t}return new kr(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=g=>typeof g=="number"||g instanceof String||g instanceof Number,b=t.filter(y).map(String);b.length>0&&(t=t.concat(b)),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!=null?n:{},{onAnchor:d,setAnchors:f,sourceObjects:p}=i_(this,o||"a"),m={aliasDuplicateObjects:s!=null?s:!0,keepUndefined:c!=null?c:!1,onAnchor:d,onTagObj:l,replacer:i,schema:this.schema,sourceObjects:p},h=xr(e,u,m);return a&&pe(h)&&(h.flow=!0),f(),h}createPair(e,t,n={}){let i=this.createNode(e,null,n),s=this.createNode(t,null,n);return new Ee(i,s)}delete(e){return _i(this.contents)?this.contents.delete(e):!1}deleteIn(e){return pi(e)?this.contents==null?!1:(this.contents=null,!0):_i(this.contents)?this.contents.deleteIn(e):!1}get(e,t){return pe(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return pi(e)?!t&&J(this.contents)?this.contents.value:this.contents:pe(this.contents)?this.contents.getIn(e,t):void 0}has(e){return pe(this.contents)?this.contents.has(e):!1}hasIn(e){return pi(e)?this.contents!==void 0:pe(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=xs(this.schema,[e],t):_i(this.contents)&&this.contents.set(e,t)}setIn(e,t){pi(e)?this.contents=t:this.contents==null?this.contents=xs(this.schema,Array.from(e),t):_i(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 hr({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 hr({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 Ds(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=Ne(this.contents,t!=null?t:"",a);if(typeof s=="function")for(let{count:l,res:u}of a.anchors.values())s(u,l);return typeof o=="function"?Yr(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 k_(this,e)}};function _i(r){if(pe(r))return!0;throw new Error("Expected a YAML collection as document contents")}var qs=class extends Error{constructor(e,t,n,i){super(),this.name=e,this.code=n,this.message=i,this.pos=t}},Xt=class extends qs{constructor(e,t,n){super("YAMLParseError",e,t,n)}},js=class extends qs{constructor(e,t,n){super("YAMLWarning",e,t,n)}},of=(r,e)=>t=>{if(t.pos[0]===-1)return;t.linePos=t.pos.map(a=>e.linePos(a));let{line:n,col:i}=t.linePos[0];t.message+=` at line ${n}, column ${i}`;let s=i-1,o=r.substring(e.lineStarts[n-1],e.lineStarts[n]).replace(/[\n\r]+$/,"");if(s>=60&&o.length>80){let a=Math.min(s-39,o.length-79);o="\u2026"+o.substring(a),s-=a-1}if(o.length>80&&(o=o.substring(0,79)+"\u2026"),n>1&&/^ *$/.test(o.substring(0,s))){let a=r.substring(e.lineStarts[n-2],e.lineStarts[n-1]);a.length>80&&(a=a.substring(0,79)+`\u2026 +`}var en=class r{constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,et,{value:Sa});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!=null&&n._directives?(this.directives=n._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new lr({version:o}),this.setSchema(o,n),this.contents=e===void 0?null:this.createNode(e,i,n)}clone(){let e=Object.create(r.prototype,{[et]:{value:Sa}});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=se(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){$i(this.contents)&&this.contents.add(e)}addIn(e,t){$i(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){let n=nf(this);e.anchor=!t||n.has(t)?sf(t||"a",n):t}return new Sr(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 m=_=>typeof _=="number"||_ instanceof String||_ instanceof Number,g=t.filter(m).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:d}=n!=null?n:{},{onAnchor:u,setAnchors:f,sourceObjects:p}=Ab(this,o||"a"),y={aliasDuplicateObjects:s!=null?s:!0,keepUndefined:c!=null?c:!1,onAnchor:u,onTagObj:l,replacer:i,schema:this.schema,sourceObjects:p},h=Er(e,d,y);return a&&le(h)&&(h.flow=!0),f(),h}createPair(e,t,n={}){let i=this.createNode(e,null,n),s=this.createNode(t,null,n);return new Se(i,s)}delete(e){return $i(this.contents)?this.contents.delete(e):!1}deleteIn(e){return yi(e)?this.contents==null?!1:(this.contents=null,!0):$i(this.contents)?this.contents.deleteIn(e):!1}get(e,t){return le(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return yi(e)?!t&&G(this.contents)?this.contents.value:this.contents:le(this.contents)?this.contents.getIn(e,t):void 0}has(e){return le(this.contents)?this.contents.has(e):!1}hasIn(e){return yi(e)?this.contents!==void 0:le(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=Ts(this.schema,[e],t):$i(this.contents)&&this.contents.set(e,t)}setIn(e,t){yi(e)?this.contents=t:this.contents==null?this.contents=Ts(this.schema,Array.from(e),t):$i(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 lr({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 lr({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 Vs(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=Me(this.contents,t!=null?t:"",a);if(typeof s=="function")for(let{count:l,res:d}of a.anchors.values())s(d,l);return typeof o=="function"?Yr(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 Wb(this,e)}};function $i(r){if(le(r))return!0;throw new Error("Expected a YAML collection as document contents")}var Bs=class extends Error{constructor(e,t,n,i){super(),this.name=e,this.code=n,this.message=i,this.pos=t}},Ht=class extends Bs{constructor(e,t,n){super("YAMLParseError",e,t,n)}},zs=class extends Bs{constructor(e,t,n){super("YAMLWarning",e,t,n)}},bf=(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==null?void 0:c.line)===n&&c.col>i&&(a=Math.max(1,Math.min(c.col-i,80-s)));let l=" ".repeat(s)+"^".repeat(a);t.message+=`: ${o} ${l} -`}};function yr(r,{flow:e,indicator:t,next:n,offset:i,onError:s,parentIndent:o,startOnNewline:a}){let c=!1,l=a,u=a,d="",f="",p=!1,m=!1,h=null,y=null,b=null,g=null,_=null,k=null,v=null;for(let w of r)switch(m&&(w.type!=="space"&&w.type!=="newline"&&w.type!=="comma"&&s(w.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),m=!1),h&&(l&&w.type!=="comment"&&w.type!=="newline"&&s(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),h=null),w.type){case"space":!e&&(t!=="doc-start"||(n==null?void 0:n.type)!=="flow-collection")&&w.source.includes(" ")&&(h=w),u=!0;break;case"comment":{u||s(w,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let x=w.source.substring(1)||" ";d?d+=f+x:d=x,f="",l=!1;break}case"newline":l?d?d+=w.source:(!k||t!=="seq-item-ind")&&(c=!0):f+=w.source,l=!0,p=!0,(y||b)&&(g=w),u=!0;break;case"anchor":y&&s(w,"MULTIPLE_ANCHORS","A node can have at most one anchor"),w.source.endsWith(":")&&s(w.offset+w.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),y=w,v!=null||(v=w.offset),l=!1,u=!1,m=!0;break;case"tag":{b&&s(w,"MULTIPLE_TAGS","A node can have at most one tag"),b=w,v!=null||(v=w.offset),l=!1,u=!1,m=!0;break}case t:(y||b)&&s(w,"BAD_PROP_ORDER",`Anchors and tags must be after the ${w.source} indicator`),k&&s(w,"UNEXPECTED_TOKEN",`Unexpected ${w.source} in ${e!=null?e:"collection"}`),k=w,l=t==="seq-item-ind"||t==="explicit-key-ind",u=!1;break;case"comma":if(e){_&&s(w,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),_=w,l=!1,u=!1;break}default:s(w,"UNEXPECTED_TOKEN",`Unexpected ${w.type} token`),l=!1,u=!1}let E=r[r.length-1],O=E?E.offset+E.source.length:i;return m&&n&&n.type!=="space"&&n.type!=="newline"&&n.type!=="comma"&&(n.type!=="scalar"||n.source!=="")&&s(n.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),h&&(l&&h.indent<=o||(n==null?void 0:n.type)==="block-map"||(n==null?void 0:n.type)==="block-seq")&&s(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:_,found:k,spaceBefore:c,comment:d,hasNewline:p,anchor:y,tag:b,newlineAfterProp:g,end:O,start:v!=null?v:O}}function en(r){if(!r)return null;switch(r.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(r.source.includes(` -`))return!0;if(r.end){for(let e of r.end)if(e.type==="newline")return!0}return!1;case"flow-collection":for(let e of r.items){for(let t of e.start)if(t.type==="newline")return!0;if(e.sep){for(let t of e.sep)if(t.type==="newline")return!0}if(en(e.key)||en(e.value))return!0}return!1;default:return!0}}function Fs(r,e,t){if((e==null?void 0:e.type)==="flow-collection"){let n=e.end[0];n.indent===r&&(n.source==="]"||n.source==="}")&&en(e)&&t(n,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}function Wa(r,e,t){let{uniqueKeys:n}=r.options;if(n===!1)return!1;let i=typeof n=="function"?n:(s,o)=>s===o||J(s)&&J(o)&&s.value===o.value;return e.some(s=>i(s.key,t))}var x_="All mapping items must start at the same column";function P_({composeNode:r,composeEmptyNode:e},t,n,i,s){var u,d;let o=(u=s==null?void 0:s.nodeClass)!=null?u:Ie,a=new o(t.schema);t.atRoot&&(t.atRoot=!1);let c=n.offset,l=null;for(let f of n.items){let{start:p,key:m,sep:h,value:y}=f,b=yr(p,{indicator:"explicit-key-ind",next:m!=null?m:h==null?void 0:h[0],offset:c,onError:i,parentIndent:n.indent,startOnNewline:!0}),g=!b.found;if(g){if(m&&(m.type==="block-seq"?i(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in m&&m.indent!==n.indent&&i(c,"BAD_INDENT",x_)),!b.anchor&&!b.tag&&!h){l=b.end,b.comment&&(a.comment?a.comment+=` -`+b.comment:a.comment=b.comment);continue}(b.newlineAfterProp||en(m))&&i(m!=null?m:p[p.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else((d=b.found)==null?void 0:d.indent)!==n.indent&&i(c,"BAD_INDENT",x_);t.atKey=!0;let _=b.end,k=m?r(t,m,b,i):e(t,_,p,null,b,i);t.schema.compat&&Fs(n.indent,m,i),t.atKey=!1,Wa(t,a.items,k)&&i(_,"DUPLICATE_KEY","Map keys must be unique");let v=yr(h!=null?h:[],{indicator:"map-value-ind",next:y,offset:k.range[2],onError:i,parentIndent:n.indent,startOnNewline:!m||m.type==="block-scalar"});if(c=v.end,v.found){g&&((y==null?void 0:y.type)==="block-map"&&!v.hasNewline&&i(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),t.options.strict&&b.startr&&(r.type==="block-map"||r.type==="block-seq");function O_({composeNode:r,composeEmptyNode:e},t,n,i,s){var y,b,g;let o=n.start.source==="{",a=o?"flow map":"flow sequence",c=(y=s==null?void 0:s.nodeClass)!=null?y:o?Ie:Ge,l=new c(t.schema);l.flow=!0;let u=t.atRoot;u&&(t.atRoot=!1),t.atKey&&(t.atKey=!1);let d=n.offset+n.start.source.length;for(let _=0;_0){let _=gr(m,h,t.options.strict,i);_.comment&&(l.comment?l.comment+=` -`+_.comment:l.comment=_.comment),l.range=[n.offset,h,_.offset]}else l.range=[n.offset,h,h];return l}function lf(r,e,t,n,i,s){let o=t.type==="block-map"?P_(r,e,t,n,s):t.type==="block-seq"?I_(r,e,t,n,s):O_(r,e,t,n,s),a=o.constructor;return i==="!"||i===a.tagName?(o.tag=a.tagName,o):(i&&(o.tag=i),o)}function T_(r,e,t,n,i){var f,p,m;let s=n.tag,o=s?e.directives.tagName(s.source,h=>i(s,"TAG_RESOLVE_FAILED",h)):null;if(t.type==="block-seq"){let{anchor:h,newlineAfterProp:y}=n,b=h&&s?h.offset>s.offset?h:s:h!=null?h:s;b&&(!y||y.offseth.tag===o&&h.collection===a);if(!c){let h=e.schema.knownTags[o];if((h==null?void 0:h.collection)===a)e.schema.tags.push(Object.assign({},h,{default:!1})),c=h;else return h?i(s,"BAD_COLLECTION_TYPE",`${h.tag} used for ${a} collection, but expects ${(f=h.collection)!=null?f:"scalar"}`,!0):i(s,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),lf(r,e,t,i,o)}let l=lf(r,e,t,i,o,c),u=(m=(p=c.resolve)==null?void 0:p.call(c,l,h=>i(s,"TAG_RESOLVE_FAILED",h),e.options))!=null?m:l,d=se(u)?u:new V(u);return d.range=l.range,d.tag=o,c!=null&&c.format&&(d.format=c.format),d}function df(r,e,t){let n=e.offset,i=aT(e,r.options.strict,t);if(!i)return{value:"",type:null,comment:"",range:[n,n,n]};let s=i.mode===">"?V.BLOCK_FOLDED:V.BLOCK_LITERAL,o=e.source?cT(e.source):[],a=o.length;for(let h=o.length-1;h>=0;--h){let y=o[h][1];if(y===""||y==="\r")a=h;else break}if(a===0){let h=i.chomp==="+"&&o.length>0?` -`.repeat(Math.max(1,o.length-1)):"",y=n+i.length;return e.source&&(y+=e.source.length),{value:h,type:s,comment:i.comment,range:[n,y,y]}}let c=e.indent+i.indent,l=e.offset+i.length,u=0;for(let h=0;hc&&(c=y.length);else{y.length=a;--h)o[h][0].length>c&&(a=h+1);let d="",f="",p=!1;for(let h=0;hc||b[0]===" "?(f===" "?f=` +`}};function ur(r,{flow:e,indicator:t,next:n,offset:i,onError:s,parentIndent:o,startOnNewline:a}){let c=!1,l=a,d=a,u="",f="",p=!1,y=!1,h=null,m=null,g=null,_=null,w=null,k=null,v=null;for(let $ of r)switch(y&&($.type!=="space"&&$.type!=="newline"&&$.type!=="comma"&&s($.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),y=!1),h&&(l&&$.type!=="comment"&&$.type!=="newline"&&s(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),h=null),$.type){case"space":!e&&(t!=="doc-start"||(n==null?void 0:n.type)!=="flow-collection")&&$.source.includes(" ")&&(h=$),d=!0;break;case"comment":{d||s($,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let R=$.source.substring(1)||" ";u?u+=f+R:u=R,f="",l=!1;break}case"newline":l?u?u+=$.source:(!k||t!=="seq-item-ind")&&(c=!0):f+=$.source,l=!0,p=!0,(m||g)&&(_=$),d=!0;break;case"anchor":m&&s($,"MULTIPLE_ANCHORS","A node can have at most one anchor"),$.source.endsWith(":")&&s($.offset+$.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),m=$,v!=null||(v=$.offset),l=!1,d=!1,y=!0;break;case"tag":{g&&s($,"MULTIPLE_TAGS","A node can have at most one tag"),g=$,v!=null||(v=$.offset),l=!1,d=!1,y=!0;break}case t:(m||g)&&s($,"BAD_PROP_ORDER",`Anchors and tags must be after the ${$.source} indicator`),k&&s($,"UNEXPECTED_TOKEN",`Unexpected ${$.source} in ${e!=null?e:"collection"}`),k=$,l=t==="seq-item-ind"||t==="explicit-key-ind",d=!1;break;case"comma":if(e){w&&s($,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),w=$,l=!1,d=!1;break}default:s($,"UNEXPECTED_TOKEN",`Unexpected ${$.type} token`),l=!1,d=!1}let P=r[r.length-1],O=P?P.offset+P.source.length:i;return y&&n&&n.type!=="space"&&n.type!=="newline"&&n.type!=="comma"&&(n.type!=="scalar"||n.source!=="")&&s(n.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),h&&(l&&h.indent<=o||(n==null?void 0:n.type)==="block-map"||(n==null?void 0:n.type)==="block-seq")&&s(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:w,found:k,spaceBefore:c,comment:u,hasNewline:p,anchor:m,tag:g,newlineAfterProp:_,end:O,start:v!=null?v:O}}function tn(r){if(!r)return null;switch(r.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(r.source.includes(` +`))return!0;if(r.end){for(let e of r.end)if(e.type==="newline")return!0}return!1;case"flow-collection":for(let e of r.items){for(let t of e.start)if(t.type==="newline")return!0;if(e.sep){for(let t of e.sep)if(t.type==="newline")return!0}if(tn(e.key)||tn(e.value))return!0}return!1;default:return!0}}function Hs(r,e,t){if((e==null?void 0:e.type)==="flow-collection"){let n=e.end[0];n.indent===r&&(n.source==="]"||n.source==="}")&&tn(e)&&t(n,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}function Qa(r,e,t){let{uniqueKeys:n}=r.options;if(n===!1)return!1;let i=typeof n=="function"?n:(s,o)=>s===o||G(s)&&G(o)&&s.value===o.value;return e.some(s=>i(s.key,t))}var Gb="All mapping items must start at the same column";function Jb({composeNode:r,composeEmptyNode:e},t,n,i,s){var d,u;let o=(d=s==null?void 0:s.nodeClass)!=null?d:Pe,a=new o(t.schema);t.atRoot&&(t.atRoot=!1);let c=n.offset,l=null;for(let f of n.items){let{start:p,key:y,sep:h,value:m}=f,g=ur(p,{indicator:"explicit-key-ind",next:y!=null?y:h==null?void 0:h[0],offset:c,onError:i,parentIndent:n.indent,startOnNewline:!0}),_=!g.found;if(_){if(y&&(y.type==="block-seq"?i(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in y&&y.indent!==n.indent&&i(c,"BAD_INDENT",Gb)),!g.anchor&&!g.tag&&!h){l=g.end,g.comment&&(a.comment?a.comment+=` +`+g.comment:a.comment=g.comment);continue}(g.newlineAfterProp||tn(y))&&i(y!=null?y:p[p.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else((u=g.found)==null?void 0:u.indent)!==n.indent&&i(c,"BAD_INDENT",Gb);t.atKey=!0;let w=g.end,k=y?r(t,y,g,i):e(t,w,p,null,g,i);t.schema.compat&&Hs(n.indent,y,i),t.atKey=!1,Qa(t,a.items,k)&&i(w,"DUPLICATE_KEY","Map keys must be unique");let v=ur(h!=null?h:[],{indicator:"map-value-ind",next:m,offset:k.range[2],onError:i,parentIndent:n.indent,startOnNewline:!y||y.type==="block-scalar"});if(c=v.end,v.found){_&&((m==null?void 0:m.type)==="block-map"&&!v.hasNewline&&i(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),t.options.strict&&g.startr&&(r.type==="block-map"||r.type==="block-seq");function Xb({composeNode:r,composeEmptyNode:e},t,n,i,s){var m,g,_;let o=n.start.source==="{",a=o?"flow map":"flow sequence",c=(m=s==null?void 0:s.nodeClass)!=null?m:o?Pe:Ke,l=new c(t.schema);l.flow=!0;let d=t.atRoot;d&&(t.atRoot=!1),t.atKey&&(t.atKey=!1);let u=n.offset+n.start.source.length;for(let w=0;w0){let w=fr(y,h,t.options.strict,i);w.comment&&(l.comment?l.comment+=` +`+w.comment:l.comment=w.comment),l.range=[n.offset,h,w.offset]}else l.range=[n.offset,h,h];return l}function $f(r,e,t,n,i,s){let o=t.type==="block-map"?Jb(r,e,t,n,s):t.type==="block-seq"?Yb(r,e,t,n,s):Xb(r,e,t,n,s),a=o.constructor;return i==="!"||i===a.tagName?(o.tag=a.tagName,o):(i&&(o.tag=i),o)}function Qb(r,e,t,n,i){var f,p,y;let s=n.tag,o=s?e.directives.tagName(s.source,h=>i(s,"TAG_RESOLVE_FAILED",h)):null;if(t.type==="block-seq"){let{anchor:h,newlineAfterProp:m}=n,g=h&&s?h.offset>s.offset?h:s:h!=null?h:s;g&&(!m||m.offseth.tag===o&&h.collection===a);if(!c){let h=e.schema.knownTags[o];if((h==null?void 0:h.collection)===a)e.schema.tags.push(Object.assign({},h,{default:!1})),c=h;else return h?i(s,"BAD_COLLECTION_TYPE",`${h.tag} used for ${a} collection, but expects ${(f=h.collection)!=null?f:"scalar"}`,!0):i(s,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),$f(r,e,t,i,o)}let l=$f(r,e,t,i,o,c),d=(y=(p=c.resolve)==null?void 0:p.call(c,l,h=>i(s,"TAG_RESOLVE_FAILED",h),e.options))!=null?y:l,u=se(d)?d:new q(d);return u.range=l.range,u.tag=o,c!=null&&c.format&&(u.format=c.format),u}function Sf(r,e,t){let n=e.offset,i=XR(e,r.options.strict,t);if(!i)return{value:"",type:null,comment:"",range:[n,n,n]};let s=i.mode===">"?q.BLOCK_FOLDED:q.BLOCK_LITERAL,o=e.source?QR(e.source):[],a=o.length;for(let h=o.length-1;h>=0;--h){let m=o[h][1];if(m===""||m==="\r")a=h;else break}if(a===0){let h=i.chomp==="+"&&o.length>0?` +`.repeat(Math.max(1,o.length-1)):"",m=n+i.length;return e.source&&(m+=e.source.length),{value:h,type:s,comment:i.comment,range:[n,m,m]}}let c=e.indent+i.indent,l=e.offset+i.length,d=0;for(let h=0;hc&&(c=m.length);else{m.length=a;--h)o[h][0].length>c&&(a=h+1);let u="",f="",p=!1;for(let h=0;hc||g[0]===" "?(f===" "?f=` `:!p&&f===` `&&(f=` -`),d+=f+y.slice(c)+b,f=` -`,p=!0):b===""?f===` -`?d+=` +`),u+=f+m.slice(c)+g,f=` +`,p=!0):g===""?f===` +`?u+=` `:f=` -`:(d+=f+b,f=" ",p=!1)}switch(i.chomp){case"-":break;case"+":for(let h=a;ht(n+f,p,m);switch(i){case"scalar":a=V.PLAIN,c=lT(s,l);break;case"single-quoted-scalar":a=V.QUOTE_SINGLE,c=dT(s,l);break;case"double-quoted-scalar":a=V.QUOTE_DOUBLE,c=uT(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=gr(o,u,e,t);return{value:c,type:a,comment:d.comment,range:[n,u,d.offset]}}function lT(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}`),R_(r)}function dT(r,e){return(r[r.length-1]!=="'"||r.length===1)&&e(r.length,"MISSING_CHAR","Missing closing 'quote"),R_(r.slice(1,-1)).replace(/''/g,"'")}function R_(r){var c;let e,t;try{e=new RegExp(`(.*?)(?t(n+f,p,y);switch(i){case"scalar":a=q.PLAIN,c=ZR(s,l);break;case"single-quoted-scalar":a=q.QUOTE_SINGLE,c=eT(s,l);break;case"double-quoted-scalar":a=q.QUOTE_DOUBLE,c=tT(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 d=n+s.length,u=fr(o,d,e,t);return{value:c,type:a,comment:u.comment,range:[n,d,u.offset]}}function ZR(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}`),Zb(r)}function eT(r,e){return(r[r.length-1]!=="'"||r.length===1)&&e(r.length,"MISSING_CHAR","Missing closing 'quote"),Zb(r.slice(1,-1)).replace(/''/g,"'")}function Zb(r){var c;let e,t;try{e=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 fT(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 rT(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 pT={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:` -`,r:"\r",t:" ",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function hT(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(a){let c=r.substr(e-2,t+2);return n(e-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${c}`),c}}function ff(r,e,t,n){let{value:i,type:s,comment:o,range:a}=e.type==="block-scalar"?df(r,e,n):uf(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[vt]:c?l=mT(r.schema,i,c,t,n):e.type==="scalar"?l=yT(r,i,e,n):l=r.schema[vt];let u;try{let d=l.resolve(i,f=>n(t!=null?t:e,"TAG_RESOLVE_FAILED",f),r.options);u=J(d)?d:new V(d)}catch(d){let f=d instanceof Error?d.message:String(d);n(t!=null?t:e,"TAG_RESOLVE_FAILED",f),u=new V(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 mT(r,e,t,n,i){var a;if(t==="!")return r[vt];let s=[];for(let c of r.tags)if(!c.collection&&c.tag===t)if(c.default&&c.test)s.push(c);else return c;for(let c of s)if((a=c.test)!=null&&a.test(e))return c;let o=r.knownTags[t];return o&&!o.collection?(r.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(i(n,"TAG_RESOLVE_FAILED",`Unresolved tag: ${t}`,t!=="tag:yaml.org,2002:str"),r[vt])}function yT({atKey:r,directives:e,schema:t},n,i,s){var a;let o=t.tags.find(c=>{var l;return(c.default===!0||r&&c.default==="key")&&((l=c.test)==null?void 0:l.test(n))})||t[vt];if(t.compat){let c=(a=t.compat.find(l=>{var u;return l.default&&((u=l.test)==null?void 0:u.test(n))}))!=null?a:t[vt];if(o.tag!==c.tag){let l=e.tagString(o.tag),u=e.tagString(c.tag),d=`Value may be parsed as either ${l} or ${u}`;s(i,"TAG_RESOLVE_FAILED",d,!0)}}return o}function C_(r,e,t){if(e){t!=null||(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==null?void 0:i.type)==="space";)r+=i.source.length,i=e[++n];break}}return r}var gT={composeNode:pf,composeEmptyNode:Ga};function pf(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=bT(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=ff(r,e,c,n),a&&(l.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=T_(gT,r,e,t,n),a&&(l.anchor=a.source.substring(1))}catch(d){let f=d instanceof Error?d.message:String(d);n(e,"RESOURCE_EXHAUSTION",f)}break;default:{let d=e.type==="error"?e.message:`Unsupported token (type: ${e.type})`;n(e,"UNEXPECTED_TOKEN",d),u=!1}}return l!=null||(l=Ga(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&&(!J(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&n(c!=null?c:e,"NON_STRING_KEY","With stringKeys, all keys must be strings"),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 Ga(r,e,t,n,{spaceBefore:i,comment:s,anchor:o,tag:a,end:c},l){let u={type:"scalar",offset:C_(e,t,n),indent:-1,source:""},d=ff(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 bT({options:r},{offset:e,source:t,end:n},i){let s=new kr(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=gr(n,o,r.strict,i);return s.range=[e,o,a.offset],a.comment&&(s.comment=a.comment),s}function M_(r,e,{offset:t,start:n,value:i,end:s},o){let a=Object.assign({_directives:e},r),c=new Ir(void 0,a),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=yr(n,{indicator:"doc-start",next:i!=null?i:s==null?void 0: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?pf(l,i,u,o):Ga(l,u.end,n,null,u,o);let d=c.contents.range[2],f=gr(s,d,!1,o);return f.comment&&(c.comment=f.comment),c.range=[t,d,f.offset],c}function Vs(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 N_(r){var i;let e="",t=!1,n=!1;for(let s=0;sn(t,"TAG_RESOLVE_FAILED",u)):null,l;r.options.stringKeys&&r.atKey?l=r.schema[gt]:c?l=sT(r.schema,i,c,t,n):e.type==="scalar"?l=oT(r,i,e,n):l=r.schema[gt];let d;try{let u=l.resolve(i,f=>n(t!=null?t:e,"TAG_RESOLVE_FAILED",f),r.options);d=G(u)?u:new q(u)}catch(u){let f=u instanceof Error?u.message:String(u);n(t!=null?t:e,"TAG_RESOLVE_FAILED",f),d=new q(i)}return d.range=a,d.source=i,s&&(d.type=s),c&&(d.tag=c),l.format&&(d.format=l.format),o&&(d.comment=o),d}function sT(r,e,t,n,i){var a;if(t==="!")return r[gt];let s=[];for(let c of r.tags)if(!c.collection&&c.tag===t)if(c.default&&c.test)s.push(c);else return c;for(let c of s)if((a=c.test)!=null&&a.test(e))return c;let o=r.knownTags[t];return o&&!o.collection?(r.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(i(n,"TAG_RESOLVE_FAILED",`Unresolved tag: ${t}`,t!=="tag:yaml.org,2002:str"),r[gt])}function oT({atKey:r,directives:e,schema:t},n,i,s){var a;let o=t.tags.find(c=>{var l;return(c.default===!0||r&&c.default==="key")&&((l=c.test)==null?void 0:l.test(n))})||t[gt];if(t.compat){let c=(a=t.compat.find(l=>{var d;return l.default&&((d=l.test)==null?void 0:d.test(n))}))!=null?a:t[gt];if(o.tag!==c.tag){let l=e.tagString(o.tag),d=e.tagString(c.tag),u=`Value may be parsed as either ${l} or ${d}`;s(i,"TAG_RESOLVE_FAILED",u,!0)}}return o}function ew(r,e,t){if(e){t!=null||(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==null?void 0:i.type)==="space";)r+=i.source.length,i=e[++n];break}}return r}var aT={composeNode:xf,composeEmptyNode:Za};function xf(r,e,t,n){let i=r.atKey,{spaceBefore:s,comment:o,anchor:a,tag:c}=t,l,d=!0;switch(e.type){case"alias":l=cT(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=Af(r,e,c,n),a&&(l.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=Qb(aT,r,e,t,n),a&&(l.anchor=a.source.substring(1))}catch(u){let f=u instanceof Error?u.message:String(u);n(e,"RESOURCE_EXHAUSTION",f)}break;default:{let u=e.type==="error"?e.message:`Unsupported token (type: ${e.type})`;n(e,"UNEXPECTED_TOKEN",u),d=!1}}return l!=null||(l=Za(r,e.offset,void 0,null,t,n)),a&&l.anchor===""&&n(a,"BAD_ALIAS","Anchor cannot be an empty string"),i&&r.options.stringKeys&&(!G(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&n(c!=null?c:e,"NON_STRING_KEY","With stringKeys, all keys must be strings"),s&&(l.spaceBefore=!0),o&&(e.type==="scalar"&&e.source===""?l.comment=o:l.commentBefore=o),r.options.keepSourceTokens&&d&&(l.srcToken=e),l}function Za(r,e,t,n,{spaceBefore:i,comment:s,anchor:o,tag:a,end:c},l){let d={type:"scalar",offset:ew(e,t,n),indent:-1,source:""},u=Af(r,d,a,l);return o&&(u.anchor=o.source.substring(1),u.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),i&&(u.spaceBefore=!0),s&&(u.comment=s,u.range[2]=c),u}function cT({options:r},{offset:e,source:t,end:n},i){let s=new Sr(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=fr(n,o,r.strict,i);return s.range=[e,o,a.offset],a.comment&&(s.comment=a.comment),s}function tw(r,e,{offset:t,start:n,value:i,end:s},o){let a=Object.assign({_directives:e},r),c=new en(void 0,a),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},d=ur(n,{indicator:"doc-start",next:i!=null?i:s==null?void 0:s[0],offset:t,onError:o,parentIndent:0,startOnNewline:!0});d.found&&(c.directives.docStart=!0,i&&(i.type==="block-map"||i.type==="block-seq")&&!d.hasNewline&&o(d.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=i?xf(l,i,d,o):Za(l,d.end,n,null,d,o);let u=c.contents.range[2],f=fr(s,u,!1,o);return f.comment&&(c.comment=f.comment),c.range=[t,u,f.offset],c}function Ks(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 rw(r){var i;let e="",t=!1,n=!1;for(let s=0;s{let o=Vs(t);s?this.warnings.push(new js(o,n,i)):this.errors.push(new Xt(o,n,i))},this.directives=new hr({version:e.version||"1.2"}),this.options=e}decorate(e,t){let{comment:n,afterEmptyLine:i}=N_(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(pe(s)&&!s.flow&&s.items.length>0){let o=s.items[0];ne(o)&&(o=o.key);let a=o.commentBefore;o.commentBefore=a?`${n} +`)+(o.substring(1)||" "),t=!0,n=!1;break;case"%":((i=r[s+1])==null?void 0:i[0])!=="#"&&(s+=1),t=!1;break;default:t||(n=!0),t=!1}}return{comment:e,afterEmptyLine:n}}var Ws=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(t,n,i,s)=>{let o=Ks(t);s?this.warnings.push(new zs(o,n,i)):this.errors.push(new Ht(o,n,i))},this.directives=new lr({version:e.version||"1.2"}),this.options=e}decorate(e,t){let{comment:n,afterEmptyLine:i}=rw(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(le(s)&&!s.flow&&s.items.length>0){let o=s.items[0];ne(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=Vs(e);s[0]+=t,this.onError(s,"BAD_DIRECTIVE",n,i)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{let t=M_(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 Xt(Vs(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 Xt(Vs(e),"UNEXPECTED_TOKEN",n));break}this.doc.directives.docEnd=!0;let t=gr(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 Xt(Vs(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 Ir(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 hf=Symbol("break visit"),_T=Symbol("skip children"),L_=Symbol("remove item");function An(r,e){"type"in r&&r.type==="document"&&(r={start:r.start,value:r.value}),D_(Object.freeze([]),r,e)}An.BREAK=hf;An.SKIP=_T;An.REMOVE=L_;An.itemAtPath=(r,e)=>{let t=r;for(let[n,i]of e){let s=t==null?void 0:t[n];if(s&&"items"in s)t=s.items[i];else return}return t};An.parentCollection=(r,e)=>{let t=An.itemAtPath(r,e.slice(0,-1)),n=e[e.length-1][0],i=t==null?void 0:t[n];if(i&&"items"in i)return i;throw new Error("Parent collection not found")};function D_(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 s=Ks(e);s[0]+=t,this.onError(s,"BAD_DIRECTIVE",n,i)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{let t=tw(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 Ht(Ks(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 Ht(Ks(e),"UNEXPECTED_TOKEN",n));break}this.doc.directives.docEnd=!0;let t=fr(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 Ht(Ks(e),"UNEXPECTED_TOKEN",`Unsupported token ${e.type}`))}}*end(e=!1,t=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){let n=Object.assign({_directives:this.directives},this.options),i=new en(void 0,n);this.atDirectives&&this.onError(t,"MISSING_CHAR","Missing directives-end indicator line"),i.range=[0,t,t],this.decorate(i,!1),yield i}}};var kf=Symbol("break visit"),lT=Symbol("skip children"),nw=Symbol("remove item");function xn(r,e){"type"in r&&r.type==="document"&&(r={start:r.start,value:r.value}),iw(Object.freeze([]),r,e)}xn.BREAK=kf;xn.SKIP=lT;xn.REMOVE=nw;xn.itemAtPath=(r,e)=>{let t=r;for(let[n,i]of e){let s=t==null?void 0:t[n];if(s&&"items"in s)t=s.items[i];else return}return t};xn.parentCollection=(r,e)=>{let t=xn.itemAtPath(r,e.slice(0,-1)),n=e[e.length-1][0],i=t==null?void 0:t[n];if(i&&"items"in i)return i;throw new Error("Parent collection not found")};function iw(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 Qt(r){switch(r){case void 0:case" ":case` -`:case"\r":case" ":return!0;default:return!1}}var j_=new Set("0123456789ABCDEFabcdef"),vT=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Ya=new Set(",[]{}"),$T=new Set(` ,[]{} -\r `),bf=r=>!r||$T.has(r),Bs=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,t=!1){var i;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=(i=this.next)!=null?i:"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===` +`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(r[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}function Kt(r){switch(r){case void 0:case" ":case` +`:case"\r":case" ":return!0;default:return!1}}var ow=new Set("0123456789ABCDEFabcdef"),uT=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),tc=new Set(",[]{}"),fT=new Set(` ,[]{} +\r `),Rf=r=>!r||fT.has(r),Gs=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,t=!1){var i;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=(i=this.next)!=null?i:"stream";for(;n&&(t||this.hasChars(1));)n=yield*this.parseNext(n)}atLineEnd(){let e=this.pos,t=this.buffer[e];for(;t===" "||t===" ";)t=this.buffer[++e];return!t||t==="#"||t===` `?!0:t==="\r"?this.buffer[e+1]===` `:!1}charAt(e){return this.buffer[this.pos+e]}continueScalar(e){let t=this.buffer[e];if(this.indentNext>0){let n=0;for(;t===" ";)t=this.buffer[++n+e];if(t==="\r"){let i=this.buffer[n+e+1];if(i===` `||!i&&!this.atEnd)return e+n+1}return t===` -`||n>=this.indentNext||!t&&!this.atEnd?e+n:-1}if(t==="-"||t==="."){let n=this.buffer.substr(e,3);if((n==="---"||n==="...")&&Qt(this.buffer[e+3]))return-1}return e}getLine(){let e=this.lineEndPos;return(typeof e!="number"||e!==-1&&ethis.indentValue&&!Qt(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[e,t]=this.peek(2);if(!t&&!this.atEnd)return this.setNext("block-start");if((e==="-"||e==="?"||e===":")&&Qt(t)){let n=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=n,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let e=this.getLine();if(e===null)return this.setNext("doc");let t=yield*this.pushIndicators();switch(e[t]){case"#":yield*this.pushCount(e.length-t);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(bf),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return t+=yield*this.parseBlockScalarHeader(),t+=yield*this.pushSpaces(!0),yield*this.pushCount(e.length-t),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let e,t,n=-1;do e=yield*this.pushNewline(),e>0?(t=yield*this.pushSpaces(!1),this.indentValue=n=t):t=0,t+=yield*this.pushSpaces(!0);while(e+t>0);let i=this.getLine();if(i===null)return this.setNext("flow");if((n!==-1&&n=this.indentNext||!t&&!this.atEnd?e+n:-1}if(t==="-"||t==="."){let n=this.buffer.substr(e,3);if((n==="---"||n==="...")&&Kt(this.buffer[e+3]))return-1}return e}getLine(){let e=this.lineEndPos;return(typeof e!="number"||e!==-1&&ethis.indentValue&&!Kt(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[e,t]=this.peek(2);if(!t&&!this.atEnd)return this.setNext("block-start");if((e==="-"||e==="?"||e===":")&&Kt(t)){let n=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=n,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let e=this.getLine();if(e===null)return this.setNext("doc");let t=yield*this.pushIndicators();switch(e[t]){case"#":yield*this.pushCount(e.length-t);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(Rf),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return t+=yield*this.parseBlockScalarHeader(),t+=yield*this.pushSpaces(!0),yield*this.pushCount(e.length-t),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let e,t,n=-1;do e=yield*this.pushNewline(),e>0?(t=yield*this.pushSpaces(!1),this.indentValue=n=t):t=0,t+=yield*this.pushSpaces(!0);while(e+t>0);let i=this.getLine();if(i===null)return this.setNext("flow");if((n!==-1&&n"0"&&t<="9")this.blockScalarIndent=Number(t)-1;else if(t!=="-")break}return yield*this.pushUntil(t=>Qt(t)||t==="#")}*parseBlockScalar(){let e=this.pos-1,t=0,n;e:for(let s=this.pos;n=this.buffer[s];++s)switch(n){case" ":t+=1;break;case` +`,s)}i!==-1&&(t=i-(n[i-1]==="\r"?2:1))}if(t===-1){if(!this.atEnd)return this.setNext("quoted-scalar");t=this.buffer.length}return yield*this.pushToIndex(t+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let e=this.pos;for(;;){let t=this.buffer[++e];if(t==="+")this.blockScalarKeep=!0;else if(t>"0"&&t<="9")this.blockScalarIndent=Number(t)-1;else if(t!=="-")break}return yield*this.pushUntil(t=>Kt(t)||t==="#")}*parseBlockScalar(){let e=this.pos-1,t=0,n;e:for(let s=this.pos;n=this.buffer[s];++s)switch(n){case" ":t+=1;break;case` `:e=s,t=0;break;case"\r":{let o=this.buffer[s+1];if(!o&&!this.atEnd)return this.setNext("block-scalar");if(o===` `)break}default:break e}if(!n&&!this.atEnd)return this.setNext("block-scalar");if(t>=this.indentNext){this.blockScalarIndent===-1?this.indentNext=t:this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let s=this.continueScalar(e+1);if(s===-1)break;e=this.buffer.indexOf(` `,s)}while(e!==-1);if(e===-1){if(!this.atEnd)return this.setNext("block-scalar");e=this.buffer.length}}let i=e+1;for(n=this.buffer[i];n===" ";)n=this.buffer[++i];if(n===" "){for(;n===" "||n===" "||n==="\r"||n===` `;)n=this.buffer[++i];e=i-1}else if(!this.blockScalarKeep)do{let s=e-1,o=this.buffer[s];o==="\r"&&(o=this.buffer[--s]);let a=s;for(;o===" ";)o=this.buffer[--s];if(o===` -`&&s>=this.pos&&s+1+t>a)e=s;else break}while(!0);return yield Ja,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(Qt(s)||e&&Ya.has(s))break;t=n}else if(Qt(i)){let s=this.buffer[n+1];if(i==="\r"&&(s===` +`&&s>=this.pos&&s+1+t>a)e=s;else break}while(!0);return yield ec,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(Kt(s)||e&&tc.has(s))break;t=n}else if(Kt(i)){let s=this.buffer[n+1];if(i==="\r"&&(s===` `?(n+=1,i=` -`,s=this.buffer[n+1]):t=n),s==="#"||e&&Ya.has(s))break;if(i===` -`){let o=this.continueScalar(n+1);if(o===-1)break;n=Math.max(n,o-2)}}else{if(e&&Ya.has(i))break;t=n}return!i&&!this.atEnd?this.setNext("plain-scalar"):(yield Ja,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(bf),e+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let t=this.flowLevel>0,n=this.charAt(1);if(Qt(n)||t&&Ya.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(;!Qt(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(vT.has(t))t=this.buffer[++e];else if(t==="%"&&j_.has(this.buffer[e+1])&&j_.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===` +`,s=this.buffer[n+1]):t=n),s==="#"||e&&tc.has(s))break;if(i===` +`){let o=this.continueScalar(n+1);if(o===-1)break;n=Math.max(n,o-2)}}else{if(e&&tc.has(i))break;t=n}return!i&&!this.atEnd?this.setNext("plain-scalar"):(yield ec,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(Rf),e+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let t=this.flowLevel>0,n=this.charAt(1);if(Kt(n)||t&&tc.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(;!Kt(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(uT.has(t))t=this.buffer[++e];else if(t==="%"&&ow.has(this.buffer[e+1])&&ow.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 zs=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(;((t=r[++e])==null?void 0:t.type)==="space";);return r.splice(e,r.length)}function Qa(r,e){if(e.length<1e5)Array.prototype.push.apply(r,e);else for(let t=0;t0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let e=this.peek(1);if(this.type==="doc-end"&&(e==null?void 0:e.type)!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!e)return yield*this.stream();switch(e.type){case"document":return yield*this.document(e);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(e);case"block-scalar":return yield*this.blockScalar(e);case"block-map":return yield*this.blockMap(e);case"block-seq":return yield*this.blockSequence(e);case"flow-collection":return yield*this.flowCollection(e);case"doc-end":return yield*this.documentEnd(e)}yield*this.pop()}peek(e){return this.stack[this.stack.length-e]}*pop(e){let t=e!=null?e:this.stack.pop();if(!t)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield t;else{let n=this.peek(1);switch(t.type==="block-scalar"?t.indent="indent"in n?n.indent:0:t.type==="flow-collection"&&n.type==="document"&&(t.indent=0),t.type==="flow-collection"&&V_(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&&F_(i.start)===-1&&(t.indent===0||i.start.every(s=>s.type!=="comment"||s.indent0&&(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 Js=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(;((t=r[++e])==null?void 0:t.type)==="space";);return r.splice(e,r.length)}function nc(r,e){if(e.length<1e5)Array.prototype.push.apply(r,e);else for(let t=0;t0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let e=this.peek(1);if(this.type==="doc-end"&&(e==null?void 0:e.type)!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!e)return yield*this.stream();switch(e.type){case"document":return yield*this.document(e);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(e);case"block-scalar":return yield*this.blockScalar(e);case"block-map":return yield*this.blockMap(e);case"block-seq":return yield*this.blockSequence(e);case"flow-collection":return yield*this.flowCollection(e);case"doc-end":return yield*this.documentEnd(e)}yield*this.pop()}peek(e){return this.stack[this.stack.length-e]}*pop(e){let t=e!=null?e:this.stack.pop();if(!t)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield t;else{let n=this.peek(1);switch(t.type==="block-scalar"?t.indent="indent"in n?n.indent:0:t.type==="flow-collection"&&n.type==="document"&&(t.indent=0),t.type==="flow-collection"&&cw(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&&aw(i.start)===-1&&(t.indent===0||i.start.every(s=>s.type!=="comment"||s.indent=e.indent){let i=!this.onKeyLine&&this.indent===e.indent,s=i&&(t.sep||t.explicitKey)&&this.type!=="seq-item-ind",o=[];if(s&&t.sep&&!t.value){let a=[];for(let c=0;ce.indent&&(a.length=0);break;default:a.length=0}}a.length>=2&&(o=t.sep.splice(a[1]))}switch(this.type){case"anchor":case"tag":s||t.value?(o.push(this.sourceToken),e.items.push({start:o}),this.onKeyLine=!0):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"explicit-key-ind":!t.sep&&!t.explicitKey?(t.start.push(this.sourceToken),t.explicitKey=!0):s||t.value?(o.push(this.sourceToken),e.items.push({start:o,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(t.explicitKey)if(t.sep)if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(tn(t.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]});else if(U_(t.key)&&!tn(t.sep,"newline")){let a=wi(t.start),c=t.key,l=t.sep;l.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:a,key:c,sep:l}]})}else o.length>0?t.sep=t.sep.concat(o,this.sourceToken):t.sep.push(this.sourceToken);else if(tn(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{let a=wi(t.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:a,key:null,sep:[this.sourceToken]}]})}else t.sep?t.value||s?e.items.push({start:o,key:null,sep:[this.sourceToken]}):tn(t.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let a=this.flowScalar(this.type);s||t.value?(e.items.push({start:o,key:a,sep:[]}),this.onKeyLine=!0):t.sep?this.stack.push(a):(Object.assign(t,{key:a,sep:[]}),this.onKeyLine=!0);return}default:{let a=this.startBlockValue(e);if(a){if(a.type==="block-seq"){if(!t.explicitKey&&t.sep&&!tn(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 i&&e.items.push({start:o});this.stack.push(a);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){var n;let t=e.items[e.items.length-1];switch(this.type){case"newline":if(t.value){let i="end"in t.value?t.value.end:void 0,s=Array.isArray(i)?i[i.length-1]:void 0;(s==null?void 0:s.type)==="comment"?i==null||i.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],s=(n=i==null?void 0:i.value)==null?void 0:n.end;if(Array.isArray(s)){Qa(s,t.start),s.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return;case"anchor":case"tag":if(t.value||this.indent<=e.indent)break;t.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==e.indent)break;t.value||tn(t.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return}if(this.indent>e.indent){let i=this.startBlockValue(e);if(i){this.stack.push(i);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let t=e.items[e.items.length-1];if(this.type==="flow-error-end"){let n;do yield*this.pop(),n=this.peek(1);while((n==null?void 0:n.type)==="flow-collection")}else if(e.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!t||t.sep?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return;case"map-value-ind":!t||t.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!t||t.value?e.items.push({start:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let 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=Xa(n),s=wi(i);V_(e);let o=e.end.splice(1,e.end.length);o.push(this.sourceToken);let a={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:s,key:e,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let t=this.source.indexOf(` +`,t)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){var n;let t=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,t.value){let i="end"in t.value?t.value.end:void 0,s=Array.isArray(i)?i[i.length-1]:void 0;(s==null?void 0:s.type)==="comment"?i==null||i.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else{if(this.atIndentedComment(t.start,e.indent)){let i=e.items[e.items.length-2],s=(n=i==null?void 0:i.value)==null?void 0:n.end;if(Array.isArray(s)){nc(s,t.start),s.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let i=!this.onKeyLine&&this.indent===e.indent,s=i&&(t.sep||t.explicitKey)&&this.type!=="seq-item-ind",o=[];if(s&&t.sep&&!t.value){let a=[];for(let c=0;ce.indent&&(a.length=0);break;default:a.length=0}}a.length>=2&&(o=t.sep.splice(a[1]))}switch(this.type){case"anchor":case"tag":s||t.value?(o.push(this.sourceToken),e.items.push({start:o}),this.onKeyLine=!0):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"explicit-key-ind":!t.sep&&!t.explicitKey?(t.start.push(this.sourceToken),t.explicitKey=!0):s||t.value?(o.push(this.sourceToken),e.items.push({start:o,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(t.explicitKey)if(t.sep)if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(rn(t.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]});else if(lw(t.key)&&!rn(t.sep,"newline")){let a=Si(t.start),c=t.key,l=t.sep;l.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:a,key:c,sep:l}]})}else o.length>0?t.sep=t.sep.concat(o,this.sourceToken):t.sep.push(this.sourceToken);else if(rn(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{let a=Si(t.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:a,key:null,sep:[this.sourceToken]}]})}else t.sep?t.value||s?e.items.push({start:o,key:null,sep:[this.sourceToken]}):rn(t.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let a=this.flowScalar(this.type);s||t.value?(e.items.push({start:o,key:a,sep:[]}),this.onKeyLine=!0):t.sep?this.stack.push(a):(Object.assign(t,{key:a,sep:[]}),this.onKeyLine=!0);return}default:{let a=this.startBlockValue(e);if(a){if(a.type==="block-seq"){if(!t.explicitKey&&t.sep&&!rn(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 i&&e.items.push({start:o});this.stack.push(a);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){var n;let t=e.items[e.items.length-1];switch(this.type){case"newline":if(t.value){let i="end"in t.value?t.value.end:void 0,s=Array.isArray(i)?i[i.length-1]:void 0;(s==null?void 0:s.type)==="comment"?i==null||i.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],s=(n=i==null?void 0:i.value)==null?void 0:n.end;if(Array.isArray(s)){nc(s,t.start),s.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return;case"anchor":case"tag":if(t.value||this.indent<=e.indent)break;t.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==e.indent)break;t.value||rn(t.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return}if(this.indent>e.indent){let i=this.startBlockValue(e);if(i){this.stack.push(i);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let t=e.items[e.items.length-1];if(this.type==="flow-error-end"){let n;do yield*this.pop(),n=this.peek(1);while((n==null?void 0:n.type)==="flow-collection")}else if(e.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!t||t.sep?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return;case"map-value-ind":!t||t.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!t||t.value?e.items.push({start:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let 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=rc(n),s=Si(i);cw(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=Xa(e),n=wi(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=Xa(e),n=wi(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 ST(r){let e=r.prettyErrors!==!1;return{lineCounter:r.lineCounter||e&&new zs||null,prettyErrors:e}}function B_(r,e={}){let{lineCounter:t,prettyErrors:n}=ST(e),i=new Hs(t==null?void 0:t.addNewLine),s=new Us(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 Xt(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&t&&(o.errors.forEach(of(r,t)),o.warnings.forEach(of(r,t))),o}function Ks(r,e,t){let n;typeof e=="function"?n=e:t===void 0&&e&&typeof e=="object"&&(t=e);let i=B_(r,t);if(!i)return null;if(i.warnings.forEach(s=>Ia(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))}function _f(r,e,t){var i;let n=null;if(typeof e=="function"||Array.isArray(e)?n=e:t===void 0&&e&&(t=e),typeof t=="string"&&(t=t.length),typeof t=="number"){let s=Math.round(t);t=s<1?void 0:s>8?{indent:8}:{indent:s}}if(r===void 0){let{keepUndefined:s}=(i=t!=null?t:e)!=null?i:{};if(!s)return}return Ht(r)&&!n?r.toString(t):new Ir(r,n,t).toString(t)}function AT(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in r&&r.BYTES_PER_ELEMENT===1}function Za(r,e,t=""){let n=AT(r),i=r==null?void 0:r.length,s=e!==void 0;if(!n||s&&i!==e){let o=t&&`"${t}" `,a=s?` of length ${e}`:"",c=n?`length=${i}`:`type=${typeof r}`,l=o+"expected Uint8Array"+a+", got "+c;throw n?new RangeError(l):new TypeError(l)}return r}function wf(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function z_(r,e){Za(r,void 0,"digestInto() output");let t=e.outputLen;if(r.length='+t)}function rn(...r){for(let e=0;e>>e}function tc(r,e){return r<>>32-e>>>0}var kT=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",xT=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function qe(r){if(Za(r),kT)return r.toHex();let e="";for(let t=0;tr(s).update(i).digest(),n=r(void 0);return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.canXOF=n.canXOF,t.create=i=>r(i),Object.assign(t,e),Object.freeze(t)}var H_=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function nc(r,e,t){return r&e^~r&t}function ic(r,e,t){return r&e^r&t^e&t}var vi=class{constructor(e,t,n,i){T(this,"blockLen");T(this,"outputLen");T(this,"canXOF",!1);T(this,"padOffset");T(this,"isLE");T(this,"buffer");T(this,"view");T(this,"finished",!1);T(this,"length",0);T(this,"pos",0);T(this,"destroyed",!1);this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=i,this.buffer=new Uint8Array(e),this.view=ec(this.buffer)}update(e){wf(this),Za(e);let{view:t,buffer:n,blockLen:i}=this,s=e.length;for(let o=0;oi-o&&(this.process(n,0),o=0);for(let d=o;du.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;d>>3,h=Zt(p,17)^Zt(p,19)^p>>>10;nn[d]=h+nn[d-7]+m+nn[d-16]|0}let{A:n,B:i,C:s,D:o,E:a,F:c,G:l,H:u}=this;for(let d=0;d<64;d++){let f=Zt(a,6)^Zt(a,11)^Zt(a,25),p=u+f+nc(a,c,l)+PT[d]+nn[d]|0,h=(Zt(n,2)^Zt(n,13)^Zt(n,22))+ic(n,i,s)|0;u=l,l=c,c=a,a=o+p|0,o=s,s=i,i=n,n=p+h|0}n=n+this.A|0,i=i+this.B|0,s=s+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(n,i,s,o,a,c,l,u)}roundClean(){rn(nn)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),rn(this.buffer)}},$f=class extends vf{constructor(){super(32);T(this,"A",Or[0]|0);T(this,"B",Or[1]|0);T(this,"C",Or[2]|0);T(this,"D",Or[3]|0);T(this,"E",Or[4]|0);T(this,"F",Or[5]|0);T(this,"G",Or[6]|0);T(this,"H",Or[7]|0)}};var Ye=rc(()=>new $f,H_(1));var S=class extends Error{constructor(t,n){super(n);T(this,"code");this.code=t}};var Tr=new TextEncoder,IT=new Set(["null","true","false"]);function OT(r){return qe(Ye(Tr.encode(r)))}function W_(r){return`sha256:${OT(r)}`}function kn(r){if(Object.keys(r.frontmatter).length===0)return r.body;let e=_f(r.frontmatter,{lineWidth:0}).trimEnd(),t=r.body?` -${r.body.replace(/^\n/,"")}`:"";return`--- -${e} ---- -${t}`}function G_(r,e){let t=0,n=!1;for(let s in e.frontmatter){if(!Object.prototype.hasOwnProperty.call(e.frontmatter,s))continue;if(!n&&(n=!0,t=mt(r,`--- -`,t),t<0))return!1;let o=e.frontmatter[s];if(!/^[A-Za-z_][A-Za-z0-9_-]*$/u.test(s))return null;let a=K_(o);if(a!==null){if(t=mt(r,s,t),t<0||(t=mt(r,": ",t),t<0)||(t=mt(r,a,t),t<0)||(t=mt(r,` -`,t),t<0))return!1;continue}if(!Array.isArray(o))return null;if(o.length===0){if(t=mt(r,s,t),t<0||(t=mt(r,`: [] -`,t),t<0))return!1;continue}if(t=mt(r,s,t),t<0||(t=mt(r,`: -`,t),t<0))return!1;for(let c of o){let l=K_(c);if(l===null)return null;if(t=mt(r," - ",t),t<0||(t=mt(r,l,t),t<0)||(t=mt(r,` -`,t),t<0))return!1}}if(!n)return r===e.body;if(t=mt(r,`--- +`,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=rc(e),n=Si(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=rc(e),n=Si(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 pT(r){let e=r.prettyErrors!==!1;return{lineCounter:r.lineCounter||e&&new Js||null,prettyErrors:e}}function dw(r,e={}){let{lineCounter:t,prettyErrors:n}=pT(e),i=new Ys(t==null?void 0:t.addNewLine),s=new Ws(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 Ht(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&t&&(o.errors.forEach(bf(r,t)),o.warnings.forEach(bf(r,t))),o}function Ei(r,e,t){let n;typeof e=="function"?n=e:t===void 0&&e&&typeof e=="object"&&(t=e);let i=dw(r,t);if(!i)return null;if(i.warnings.forEach(s=>Ca(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 yT=r=>r/2**32|0,gT=r=>r>>>0;function uw(r,e,t,n){let i=yT(t),s=gT(t);r.setUint32(e,n?s:i,n),r.setUint32(e+4,n?i:s,n)}function fw(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in r&&r.BYTES_PER_ELEMENT===1}var Tf=r=>r?`"${r}" `:"";function _T(r,e=""){if(typeof r!="number")throw new TypeError(Tf(e)+"expected number, got "+typeof r);if(!Number.isSafeInteger(r)||r<0)throw new RangeError(Tf(e)+"expected integer >= 0, got "+r);return r}function ic(r,e,t=""){if(fw(r)&&(e===void 0||r.length===e))return r;e!==void 0&&_T(e,"length");let n=fw(r),i=e!==void 0?` of length ${e}`:"",s=n?`length=${r.length}`:`type=${typeof r}`,o=Tf(t)+"expected Uint8Array"+i+", got "+s;throw n?new RangeError(o):new TypeError(o)}var pw=(r,e)=>{if(r===null||typeof r!="object"||Array.isArray(r))throw new TypeError((e==="object"?"":`"${e}" `)+"expected object, got type="+typeof r)};function Mf(r,e=!0){if(r.destroyed)throw new Error("hash was destroyed");if(e&&r.finished)throw new Error("digest() was already called")}function hw(r,e){ic(r,void 0,"output");let t=e.outputLen;if(!(r.length>=t))throw new RangeError('"output" expected length >= '+t)}function Ai(...r){for(let e=0;e>>e}function oc(r,e){return r<>>32-e>>>0}var bT=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",wT=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function Le(r){if(ic(r),bT)return r.toHex();let e="";for(let t=0;t{}),s}}var Pi=class{constructor(e,t,n){T(this,"pathPolicy");T(this,"digest");T(this,"recordIds",new Set);T(this,"physicalPaths",new Set);this.pathPolicy=e,this.digest=n;for(let i of t)this.physicalPaths.add(Ei(i.path))}validate(e){let t=e.document,n=e;if(bt(n.path,this.pathPolicy),this.recordIds.has(n.record_id))throw new S("invalid_snapshot",`Hosted snapshot repeats record identity ${n.record_id}.`);this.recordIds.add(n.record_id);let i=Ei(n.path);if(this.physicalPaths.has(i))throw new S("invalid_snapshot",`Hosted record path ${n.path} aliases another snapshot path on a supported filesystem.`);this.physicalPaths.add(i);let s=this.digest(t);if(n.revision.length!==7+s.length||!n.revision.startsWith("sha256:")||!n.revision.endsWith(s))throw new S("invalid_snapshot",`Hosted record ${n.path} does not match its declared revision.`);if(G_(t,n)!==!0&&t!==kn(n)){let a;try{a=Rr(t,n.path)}catch(c){throw new S("invalid_snapshot",`Hosted record ${n.path} is not valid Markdown.`)}if(!Vf(a.frontmatter,n.frontmatter)||!PR(a.body,n.body))throw new S("invalid_snapshot",`Hosted record ${n.path} does not match its declared document.`)}return{record:n,document:t,hash:s}}};function jw(r){if(!Object.prototype.hasOwnProperty.call(r,"document"))return r;let{document:e,...t}=r;return t}async function $c(r,e,t){let n,i=new Set;do{let s=await r.snapshot(e.snapshot_id,n);if(s.protocol_version!==1||s.snapshot_id!==e.snapshot_id||s.scope_epoch!==e.scope_epoch||s.cursor!==e.head)throw new S("invalid_snapshot","Authority snapshot boundary changed during download.");if(await t(s.records),n=s.next_page,n!==void 0&&i.has(n))throw new S("invalid_snapshot","Authority snapshot repeated a page cursor.");n!==void 0&&i.add(n)}while(n)}function PR(r,e){return r===e||r.startsWith(` +`)?e.body.slice(1):e.body;return t=ut(r,` +`,t),t>=0&&r.startsWith(i,t)&&t+i.length===r.length}function uc(r,e){var i;let t=r.match(/^---[ \t]*\r?\n([\s\S]*?)^---[ \t]*(?:\r?\n|$)([\s\S]*)$/m);if(!t)return{frontmatter:{},body:r};let n;try{n=Ei(t[1])}catch(s){return{frontmatter:{},body:r}}return n===null&&t[1].trim()===""&&(n={}),!n||typeof n!="object"||Array.isArray(n)?{frontmatter:{},body:r}:{frontmatter:n,body:(i=t[2])!=null?i:""}}function gw(r){return typeof r=="boolean"||r===null||typeof r=="number"&&Number.isSafeInteger(r)?String(r):typeof r!="string"||!/^[A-Za-z][A-Za-z0-9 _.-]*$/u.test(r)||r.length<=5&&ST.has(r.toLowerCase())?null:r}function ut(r,e,t){return r.startsWith(e,t)?t+e.length:-1}function fc(r){let e=Ge.create().update(xr.encode(`mdbase-authority-manifest-v2 +`));for(let t of[...r].sort((n,i)=>n.kind!==i.kind?n.kinde.type==="file_put"||e.type==="file_remove"))throw new b("file_sync_unsupported","This replica cannot materialize collection file changes yet. Upgrade it before continuing sync.")}function ww(r){xT([r])}Ee();Ee();var J=class extends b{constructor(t,n,i,s){super(t,n);I(this,"status");this.status=i,this.name="AuthorityAdoptionError",(s==null?void 0:s.cause)!==void 0&&(this.cause=s.cause)}},kr=class extends J{constructor(t,n){super("authority_adoption_outcome_unknown",t,void 0,n);I(this,"sourceMustRemainFenced",!0);this.name="AuthorityAdoptionOutcomeUnknownError"}};var ki=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function kn(r,e){if(!ki.test(r))throw new J("invalid_authority_adoption",`${e} must be a UUID.`);return r.toLowerCase()}var Xs=Uint32Array.from([1732584193,4023233417,2562383102,271733878,3285377520]),sn=new Uint32Array(80),jf=class extends xi{constructor(){super(64,20,8,!1);I(this,"A",Xs[0]|0);I(this,"B",Xs[1]|0);I(this,"C",Xs[2]|0);I(this,"D",Xs[3]|0);I(this,"E",Xs[4]|0)}get(){let{A:t,B:n,C:i,D:s,E:o}=this;return[t,n,i,s,o]}set(t,n,i,s,o){this.A=t|0,this.B=n|0,this.C=i|0,this.D=s|0,this.E=o|0}_cloneInto(t){return(t||(t=new this.constructor)).set(...this.get()),this._cloneIntoMeta(t)}process(t,n){for(let l=0;l<16;l++,n+=4)sn[l]=t.getUint32(n,!1);for(let l=16;l<80;l++)sn[l]=oc(sn[l-3]^sn[l-8]^sn[l-14]^sn[l-16],1);let{A:i,B:s,C:o,D:a,E:c}=this;for(let l=0;l<80;l++){let d,u;l<20?(d=cc(s,o,a),u=1518500249):l<40?(d=s^o^a,u=1859775393):l<60?(d=lc(s,o,a),u=2400959708):(d=s^o^a,u=3395469782);let f=oc(i,5)+d+c+u+sn[l]|0;c=a,a=o,o=oc(s,30),s=i,i=f}i=i+this.A|0,s=s+this.B|0,o=o+this.C|0,a=a+this.D|0,c=c+this.E|0,this.set(i,s,o,a,c)}roundClean(){Ai(sn)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0),Ai(this.buffer)}},hc=ac(()=>new jf);var kT=1e4,PT=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,IT=new TextEncoder;async function $w(r,e,t,n,i){var h,m,g;let s=RT(n,t.media_type);if(s.size!==t.size||await TT(s,i.signal)!==t.content_digest)throw new J("authority_adoption_file_changed",`File bytes no longer match the fenced snapshot for ${t.path}.`);let o=MT(e.import_id,t),a=await Df(r,`${e.files_url}/uploads`,e.access_token,{protocol_version:1,type:"open_authority_import_file_upload",transfer_id:o,file_id:t.file_id},i.signal);if(NT(a,o,t.size),a.strategy.kind!=="object_put"&&a.strategy.kind!=="object_multipart")throw ft("Connect returned an incompatible authority import file strategy.");let c=a.strategy.kind==="object_put"?Math.max(1,t.size):a.strategy.part_size,l=a.strategy.kind==="object_put"?1:Math.ceil(t.size/c);if(l>kT)throw ft("Authority import returned too many file parts.");let d=new Set(a.received),u=new Map(((h=a.uploaded_parts)!=null?h:[]).map(_=>[_.part_number-1,_]));if(a.received.length===l&&await vw(r,e,t,o,[...u.values()],i.signal))return;let f=Array(l);for(let[_,w]of u)f[_]=w;let p=[...d].reduce((_,w)=>_+Math.min(c,Math.max(0,t.size-w*c)),0);for(let _=0;__!==void 0);if(!await vw(r,e,t,o,y,i.signal))throw new J("authority_adoption_file_upload_incomplete",`Connect could not commit ${t.path}.`)}async function vw(r,e,t,n,i,s){try{let o=await Df(r,`${e.files_url}/uploads/${encodeURIComponent(n)}/commit`,e.access_token,{protocol_version:1,type:"commit_file_upload",transfer_id:n,...i.length>0?{parts:i}:{}},s);if(o.protocol_version!==1||o.type!=="file_upload_committed"||o.transfer_id!==n||!qT(o.file,t))throw ft("Connect returned an invalid authority import file receipt.");return!0}catch(o){if(i.length===0&&o instanceof J&&o.code==="file_upload_incomplete")return!1;throw o}}async function Df(r,e,t,n,i){let s;try{s=await r({url:e,method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/json"},body:n,...i?{signal:i}:{}})}catch(o){throw mc(i),new J("authority_adoption_unreachable","Connect could not be reached for collection adoption.")}if(s.status<200||s.status>=300)throw FT(s);return s.body}async function OT(r,e,t,n){jT(e.url);let i;try{i=await r({url:e.url,method:"PUT",headers:DT(e.headers),body:t,rawBody:!0,...n?{signal:n}:{}})}catch(s){throw mc(n),new J("authority_adoption_unreachable","Connect could not be reached for collection adoption.")}if(i.status<200||i.status>=300)throw new J("authority_adoption_object_upload_failed","Object storage rejected an authority import file part.",i.status);return i}function RT(r,e){if(r instanceof Blob)return r;if(r instanceof ArrayBuffer)return new Blob([r],{type:e});let t=new Uint8Array(r.buffer,r.byteOffset,r.byteLength).slice();return new Blob([t],{type:e})}async function TT(r,e){let t=Ge.create(),n=r.stream().getReader();try{for(;;){mc(e);let i=await n.read();if(i.done)break;t.update(i.value)}}finally{n.releaseLock()}return`sha256:${Le(t.digest())}`}function MT(r,e){let t=CT(r),n=IT.encode(`mdbase-authority-import-file-v1\0${e.file_id}\0${e.revision}\0${e.content_digest}`),i=hc(new Uint8Array([...t,...n])).slice(0,16);i[6]=i[6]&15|80,i[8]=i[8]&63|128;let s=Le(i);return`${s.slice(0,8)}-${s.slice(8,12)}-${s.slice(12,16)}-${s.slice(16,20)}-${s.slice(20)}`}function CT(r){if(!PT.test(r))throw ft("Authority import ID is invalid.");return Uint8Array.from(r.replaceAll("-","").match(/../g).map(e=>Number.parseInt(e,16)))}function NT(r,e,t){var a;let n=r==null?void 0:r.strategy;if((r==null?void 0:r.protocol_version)!==1||r.type!=="file_transfer"||r.transfer_id!==e||r.direction!=="upload"||r.protection!=="transport_tls"||r.total_size!==t||!Array.isArray(r.received)||!n||!["object_put","object_multipart"].includes(n.kind)||n.kind==="object_multipart"&&(!Number.isSafeInteger(n.part_size)||n.part_size<=0))throw ft("Connect returned an invalid authority import file session.");if(n.kind!=="object_put"&&n.kind!=="object_multipart")throw ft("Connect returned an invalid authority import file strategy.");let i=n.kind==="object_put"?Math.max(1,t):n.part_size,s=n.kind==="object_put"?1:Math.ceil(t/i);if(new Set(r.received).size!==r.received.length||r.received.some(c=>!Number.isSafeInteger(c)||c<0||c>=s))throw ft("Connect returned invalid authority import file progress.");let o=(a=r.uploaded_parts)!=null?a:[];if(!Array.isArray(o)||o.some((c,l)=>!Number.isSafeInteger(c==null?void 0:c.part_number)||c.part_number<1||c.part_number>s||typeof c.etag!="string"||c.etag.length===0||c.etag.length>255||l>0&&o[l-1].part_number>=c.part_number)||(n.kind==="object_multipart"?o.length!==r.received.length||o.some((c,l)=>c.part_number-1!==r.received[l]):o.length!==0))throw ft("Connect returned invalid authority import part receipts.")}function LT(r,e,t,n,i){if((r==null?void 0:r.protocol_version)!==1||r.type!=="file_part"||r.transfer_id!==e||r.part_index!==t||r.offset!==n||r.content_length!==i||r.method.toUpperCase()!=="PUT"||!Number.isFinite(Date.parse(r.expires_at))||!qf(r.headers))throw ft("Connect returned an invalid prepared authority import file part.")}function jT(r){let e;try{e=new URL(r)}catch(t){throw ft("Connect returned an invalid object storage URL.")}if(e.protocol!=="https:"&&!(e.protocol==="http:"&&["localhost","127.0.0.1","[::1]","::1"].includes(e.hostname))||e.username||e.password||e.hash)throw ft("Connect returned an unsafe object storage URL.")}function DT(r){let e={};for(let[t,n]of Object.entries(r)){if(["authorization","cookie","host","proxy-authorization"].includes(t.toLowerCase()))throw ft("Connect returned unsafe object storage headers.");if(/\r|\n/.test(t)||/\r|\n/.test(n))throw ft("Connect returned invalid object storage headers.");e[t]=n}return e}function qT(r,e){return r.file_id===e.file_id&&r.path===e.path&&r.revision===e.revision&&r.content_digest===e.content_digest&&r.size===e.size&&r.media_type===e.media_type&&r.media_class===e.media_class&&r.modified_at===e.modified_at}function FT(r){let e=qf(r.body)&&qf(r.body.error)?r.body.error:{};return new J(typeof e.code=="string"?e.code:"authority_adoption_request_failed",typeof e.message=="string"?e.message:`Collection adoption request failed with status ${r.status}.`,r.status)}function ft(r){return new J("invalid_authority_adoption_response",r)}function mc(r){if(r!=null&&r.aborted)throw new J("authority_adoption_cancelled","Collection adoption was cancelled.")}function qf(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}var Ff=1500,UT=250,VT=3e4,Pw=1440*60*1e3,Pr=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,yc=class{constructor(e={}){I(this,"request");I(this,"now");I(this,"wait");var t,n,i;this.request=(t=e.request)!=null?t:BT,this.now=(n=e.now)!=null?n:Date.now,this.wait=(i=e.wait)!=null?i:WT}async begin(e,t={}){Pn(t.signal);let n=Ir(e.controlUrl),i=e.mirrorName.trim();if(!i||i.length>200)throw new Je("invalid_mirror_name","Mirror name must contain between 1 and 200 characters.");if(!["read_only","read_write"].includes(e.mode))throw new Je("invalid_mirror_mode","Mirror mode must be read-only or read-write.");if(e.collectionId!==void 0&&!Pr.test(e.collectionId))throw new Je("invalid_collection_id","Collection ID must be a UUID.");let s;try{s=await this.request({url:`${n}/v1/mirror-pairing-requests`,method:"POST",headers:{"content-type":"application/json"},body:{mirror_name:i,mode:e.mode,...e.collectionId?{collection_id:e.collectionId}:{}},...t.signal?{signal:t.signal}:{}})}catch(c){throw Pn(t.signal),xw()}let o=Aw(s,201);if(!Pi(o)||!Pr.test(_t(o.pairing_id))||!Qs(o.pairing_secret)||!GT(o.expires_in)||Number(o.expires_in)*1e3>Pw)throw Gt("Connect returned an invalid mirror approval.");let a=Ow(n,_t(o.verification_uri),_t(o.pairing_id));return{controlUrl:n,pairingId:_t(o.pairing_id),refreshCredential:_t(o.pairing_secret),verificationUri:a,expiresAt:new Date(this.now()+Number(o.expires_in)*1e3).toISOString(),requested:{mirrorName:i,mode:e.mode,...e.collectionId?{collectionId:e.collectionId}:{}}}}async enroll(e,t){let n=await this.begin(e,t),{refreshCredential:i,...s}=n;return await t.onVerification(s),this.waitForApproval(n,t)}async waitForApproval(e,t={}){var o,a;zT(e,this.now());let n=kw(t.pollIntervalMs),i=Date.parse(e.expiresAt),s=0;for(;this.now()=500){let l=Uf(c);if(await this.retry(i,(a=c.retryAfterMs)!=null?a:n,t,s,{code:l.code,message:l.message})===null)break;continue}throw Uf(c)}throw new Je("mirror_enrollment_expired","Mirror approval expired before it was completed.")}async renew(e,t={}){HT(e),Pn(t.signal);let n;try{n=await this.request({url:Ew(e.controlUrl,e.enrollmentId,"renew"),method:"POST",headers:{authorization:`Bearer ${e.refreshCredential}`},...t.signal?{signal:t.signal}:{}})}catch(s){throw Pn(t.signal),xw()}let i={controlUrl:e.controlUrl,pairingId:e.enrollmentId,refreshCredential:e.refreshCredential,verificationUri:`${e.controlUrl}/mirror/${e.enrollmentId}`,expiresAt:new Date(this.now()+6e4).toISOString(),requested:{mirrorName:e.name,mode:e.mode,collectionId:e.collectionId}};return Sw(i,Aw(n,200),{replicaId:e.replicaId})}async retry(e,t,n,i,s){var l;let o=e-this.now();if(o<=0)return null;let a=Math.min(kw(t),o),c=new Date(this.now()+a).toISOString();return(l=n.onStatus)==null||l.call(n,{state:s?"retrying":"waiting_for_approval",attempt:i,expiresAt:new Date(e).toISOString(),retryAt:c,...s?{error:s}:{}}),await this.wait(a,n.signal),c}},Je=class extends b{constructor(t,n,i){super(t,n);I(this,"status");this.status=i,this.name="MirrorEnrollmentError"}};function Ir(r){let e;try{e=new URL(r)}catch(n){throw new Je("invalid_connect_url","Connect URL must be an absolute HTTPS origin.")}if(e.pathname!=="/"||e.search||e.hash||e.username||e.password)throw new Je("invalid_connect_url","Connect URL must be an origin without credentials, path, query, or fragment.");let t=["localhost","127.0.0.1","[::1]","::1"].includes(e.hostname);if(e.protocol!=="https:"&&!(e.protocol==="http:"&&t))throw new Je("invalid_connect_url","Connect URL must use HTTPS outside loopback development.");return e.origin}async function BT(r){let e=await fetch(r.url,{method:r.method,headers:r.headers,...r.body===void 0?{}:{body:JSON.stringify(r.body)},...r.signal?{signal:r.signal}:{}}),t=await e.json().catch(()=>null),n=e.headers.get("retry-after");return{status:e.status,body:t,...n===null?{}:{retryAfterMs:KT(n)}}}function Sw(r,e,t){if(!Pi(e)||e.status!=="paired"||!Pi(e.replica))throw Gt("Connect returned an invalid mirror enrollment.");let n=e.replica,i=_t(n.id),s=_t(n.collection_id),o=_t(n.name).trim(),a=n.mode,c=_t(e.token),l=_t(e.token_expires_at);if(!Pr.test(i)||!Pr.test(s)||!o||!["read_only","read_write"].includes(String(a))||!Qs(c)||!Tw(l))throw Gt("Connect returned invalid mirror credentials.");if(a!==r.requested.mode)throw Gt("Connect returned a mirror with a different access mode.");if(r.requested.collectionId&&s!==r.requested.collectionId)throw Gt("Connect returned a different collection.");if(t.mirrorName!==void 0&&o!==t.mirrorName)throw Gt("Connect returned a mirror with a different name.");if(t.replicaId!==void 0&&i!==t.replicaId)throw Gt("Connect returned a different mirror replica.");let d;try{d=Iw(_t(e.sync_url),s)}catch(u){throw Gt("Connect returned an invalid authority sync URL.")}return{controlUrl:Ir(r.controlUrl),syncUrl:d,collectionId:s,replicaId:i,mode:a,name:o,enrollmentId:r.pairingId,accessToken:c,refreshCredential:r.refreshCredential,accessTokenExpiresAt:l}}function zT(r,e){Ir(r.controlUrl);let t=Date.parse(r.expiresAt);if(!Pr.test(r.pairingId)||!Qs(r.refreshCredential)||!Number.isFinite(t)||t-e>Pw||!r.requested.mirrorName.trim()||r.requested.mirrorName.length>200||!["read_only","read_write"].includes(r.requested.mode)||r.requested.collectionId!==void 0&&!Pr.test(r.requested.collectionId))throw new Je("invalid_mirror_enrollment_session","Mirror enrollment session is invalid.");Ow(r.controlUrl,r.verificationUri,r.pairingId)}function HT(r){if(Ir(r.controlUrl),Iw(r.syncUrl,r.collectionId),!Pr.test(r.collectionId)||!Pr.test(r.replicaId)||!Pr.test(r.enrollmentId)||!Qs(r.accessToken)||!Qs(r.refreshCredential)||!Tw(r.accessTokenExpiresAt)||!r.name.trim()||r.name.length>200||!["read_only","read_write"].includes(r.mode))throw new Je("invalid_mirror_enrollment","Stored mirror enrollment is invalid.")}function Iw(r,e){let t=new URL(r),n=`/v1/authorities/${encodeURIComponent(e)}/sync`;if(!(t.protocol==="https:"||t.protocol==="http:"&&["localhost","127.0.0.1","[::1]","::1"].includes(t.hostname))||t.username||t.password||t.pathname.replace(/\/$/,"")!==n||t.search||t.hash)throw new Error("invalid sync URL");return`${t.origin}${n}`}function Ow(r,e,t){let n;try{n=new URL(e)}catch(s){throw Gt("Connect returned an invalid mirror verification URI.")}let i=new URL(`/mirror/${encodeURIComponent(t)}`,r);if(n.origin!==i.origin||n.pathname!==i.pathname||n.search||n.hash||n.username||n.password)throw Gt("Connect returned an untrusted mirror verification URI.");return n.href}function Ew(r,e,t){return`${Ir(r)}/v1/mirror-pairing-requests/${encodeURIComponent(e)}/${t}`}function Aw(r,e){if(r.status!==e)throw Uf(r);return r.body}function Uf(r){let e=Pi(r.body)&&Pi(r.body.error)?r.body.error:{};return new Je(_t(e.code)||"mirror_enrollment_request_failed",_t(e.message)||`Mirror enrollment request failed with status ${r.status}.`,r.status)}function Gt(r){return new Je("invalid_mirror_enrollment_response",r)}function Rw(r){return{code:"mirror_enrollment_unreachable",message:"Connect could not be reached for mirror enrollment."}}function xw(){let r=Rw(void 0);return new Je(r.code,r.message)}function kw(r=Ff){return Number.isFinite(r)?Math.min(VT,Math.max(UT,Math.round(r))):Ff}function KT(r){let e=Number(r);if(Number.isFinite(e)&&e>=0)return e*1e3;let t=Date.parse(r);return Number.isFinite(t)?Math.max(0,t-Date.now()):Ff}function WT(r,e){return Pn(e),new Promise((t,n)=>{let i=setTimeout(o,r),s=()=>{clearTimeout(i),e==null||e.removeEventListener("abort",s),n(new Je("mirror_enrollment_cancelled","Mirror enrollment was cancelled."))};function o(){e==null||e.removeEventListener("abort",s),t()}e==null||e.addEventListener("abort",s,{once:!0})})}function Pn(r){if(r!=null&&r.aborted)throw new Je("mirror_enrollment_cancelled","Mirror enrollment was cancelled.")}function Tw(r){let e=Date.parse(r);return Number.isFinite(e)}function GT(r){return typeof r=="number"&&Number.isSafeInteger(r)&&r>0}function Qs(r){return typeof r=="string"&&r.length>=16}function _t(r){return typeof r=="string"?r:""}function Pi(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}Ee();var JT=/(?:^|\/)(?:\.{1,2}|)(?:\/|$)/u,YT=/[\p{Cc}:?<>|*"]/u,XT=/[. ](?:\/|$)/u,QT=/(?:^|\/)(?:CON|PRN|AUX|NUL|COM[1-9¹²³]|LPT[1-9¹²³])(?:\.|\/|$)/iu;function Jt(r){if(!r||r.startsWith("/")||r.includes("\\")||JT.test(r)||YT.test(r)||XT.test(r)||QT.test(r))throw new b("invalid_path",`Mirror received an unsafe path: ${r}.`)}function bt(r){return Jt(r),Ii(r)}function Ii(r){return/^[\x20-\x7e]+$/u.test(r)?/[A-Z]/u.test(r)?r.toLowerCase():r:r.normalize("NFC").toLowerCase().normalize("NFC")}Ee();var Cw=new Set(["image","audio","video","pdf","other"]),Mw=["image","audio","video","pdf","other"],ZT=new Set([".mdbase",".git","node_modules","_contracts","_schemas","_types","_views"]),eM=/^(?:CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\.|$)/iu,tM=/^sha256:[0-9a-f]{64}$/u,rM=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,nM=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/u;function In(r){var s,o;let e={file_classes:[...(s=r==null?void 0:r.file_classes)!=null?s:[]],excluded_folders:[...(o=r==null?void 0:r.excluded_folders)!=null?o:[]]};if(e.excluded_folders.length>100)throw new b("invalid_file_materialization","Selective sync supports at most 100 excluded folders.");let t=new Set;for(let a of e.file_classes){if(!Cw.has(a)||t.has(a))throw new b("invalid_file_materialization","Selected file media classes must be valid and unique.");t.add(a)}let n=new Set,i=new Set;for(let a of e.excluded_folders){Lw(a,!0);let c=bt(a);if(n.has(a)||i.has(c))throw new b("invalid_file_materialization","Excluded folders must be unique on portable filesystems.");n.add(a),i.add(c)}return e.file_classes.sort((a,c)=>Mw.indexOf(a)-Mw.indexOf(c)),e.excluded_folders.sort((a,c)=>bt(a).localeCompare(bt(c))),e}function On(r,e){let t=bt(e);return!r.excluded_folders.some(n=>{let i=bt(n);return t===i||t.startsWith(`${i}/`)})}function _c(r,e){return r.file_classes.includes(e.media_class)&&On(r,e.path)}function Vf(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 Nw(r,e){return r.file_classes.includes(Vf(e))&&On(r,e)}function pt(r){if(Lw(r.path,!1),typeof r.file_id!="string"||!rM.test(r.file_id)||typeof r.revision!="string"||!r.revision||r.revision.length>255||!tM.test(r.content_digest)||!Number.isSafeInteger(r.size)||r.size<0||!Cw.has(r.media_class)||typeof r.modified_at!="string"||!nM.test(r.modified_at)||!Number.isFinite(Date.parse(r.modified_at))||r.media_type!==void 0&&(typeof r.media_type!="string"||!r.media_type||r.media_type.length>255))throw new b("invalid_snapshot",`Collection file ${r.path} has invalid metadata.`)}function Lw(r,e){if(Jt(r),r.length>1024)throw new b("invalid_file_path","Collection file paths cannot exceed 1024 characters.");if(r.split("/").some(i=>i.startsWith(".")||/[<>"|?*]/u.test(i)||eM.test(i)||ZT.has(i.toLowerCase()))||!e&&/\.md$/iu.test(r))throw new b("invalid_file_path",`Collection file path ${r} is hidden, reserved, or non-portable.`)}async function jw(r,e,t){let n,i=new Set;do{let s=await r.fileSnapshot(e.snapshot_id,n);if(s.protocol_version!==1||s.type!=="file_snapshot_page"||s.snapshot_id!==e.snapshot_id||s.scope_epoch!==e.scope_epoch||s.cursor!==e.head)throw new b("invalid_snapshot","Authority file snapshot boundary changed during download.");for(let o of s.files)pt(o);if(await t(s.files),n=s.next_page,n!==void 0&&i.has(n))throw new b("invalid_snapshot","Authority file snapshot repeated a page cursor.");n!==void 0&&i.add(n)}while(n)}function Or(r,e){return(r==null?void 0:r.size)===e.size&&r.content_digest===e.content_digest}async function*gc(r,e){let t=Ge.create(),n=0;for await(let i of r){if(!(i instanceof Uint8Array)||i.byteLength===0){if(i instanceof Uint8Array&&i.byteLength===0)continue;throw new b("file_integrity_failed","A file transport returned invalid bytes.")}if(n+=i.byteLength,!Number.isSafeInteger(n)||n>e.size)throw new b("file_integrity_failed",`Downloaded bytes for ${e.path} are oversized.`);t.update(i),yield i}if(n!==e.size||`sha256:${Le(t.digest())}`!==e.content_digest)throw new b("file_integrity_failed",`Downloaded bytes for ${e.path} failed integrity verification.`)}async function*Dw(r,e,t){let n=Ge.create(),i=0;for await(let s of r){if(!(s instanceof Uint8Array))throw new b("file_integrity_failed",`Local bytes for ${t} are invalid.`);if(s.byteLength!==0){if(i+=s.byteLength,!Number.isSafeInteger(i)||i>e.size)throw new b("pending_local_changed",`Local file ${t} changed while being staged.`);n.update(s),yield s}}if(i!==e.size||`sha256:${Le(n.digest())}`!==e.content_digest)throw new b("pending_local_changed",`Local file ${t} changed while being staged.`)}async function bc(r,e,t){if(pt(t),await e.has(t.content_digest))try{for await(let n of gc(e.read(t.content_digest),t));return}catch(n){await e.remove(t.content_digest)}try{await e.write(t.content_digest,gc(r.downloadFile(t),t))}catch(n){throw await e.remove(t.content_digest).catch(()=>{}),n}if(!await e.has(t.content_digest))throw new b("file_integrity_failed","The verified file blob was not persisted.")}var on=new TextEncoder;function Hf(r){var u,f,p,y,h;let e=kn(r.collectionId,"Collection ID"),t=(u=r.sourceHead)!=null?u:0;if(!Number.isSafeInteger(t)||t<0)throw new J("invalid_authority_snapshot","Source head must be a non-negative integer.");let n=new Set,i=r.resources.map(m=>{let g=wc(m.path);if(n.add(g)||Bf(g),!["configuration","lock","contract","schema","type","view"].includes(m.kind))throw new J("invalid_authority_snapshot",`Unsupported collection resource kind for ${g}.`);return{path:g,kind:m.kind,revision:qw(m.document),document:m.document}}).sort(sM);if(((f=i[0])==null?void 0:f.path)!=="mdbase.yaml"||i[0].kind!=="configuration"||i.filter(({kind:m})=>m==="configuration").length!==1)throw new J("invalid_authority_snapshot","A portable snapshot requires one mdbase.yaml configuration resource.");let s=r.records.map(m=>{let g=wc(m.path);return n.add(g)||Bf(g),{record_id:m.recordId?kn(m.recordId,`Record ID for ${g}`):Uw(e,g),path:g,document:m.document}}).sort((m,g)=>zf(m.path,g.path)),o=new Set,a=((p=r.files)!=null?p:[]).map(m=>{let g=wc(m.path);n.add(g)||Bf(g);let _=kn(m.file_id,`File ID for ${g}`);if(!o.add(_))throw new J("invalid_authority_snapshot",`Collection snapshot contains file ID more than once: ${_}`);return iM(m,g),{...m,file_id:_,path:g}}).sort((m,g)=>zf(m.path,g.path)),c=Fw(i.flatMap(({path:m,revision:g})=>[m,g])),l=Fw([...i.flatMap(({path:m,revision:g})=>["resource",m,g]),...s.flatMap(m=>["record",m.path,qw(m.document)]),...a.flatMap(m=>{var g;return["file",m.path,m.file_id,m.revision,m.content_digest,String(m.size),(g=m.media_type)!=null?g:"",m.media_class]})]),d=fc([...i.map(({path:m,document:g})=>({kind:"resource",path:m,identity:"",document_hash:Le(Ge(on.encode(g)))})),...s.map(m=>({kind:"record",path:m.path,identity:m.record_id,document_hash:Le(Ge(on.encode(m.document)))})),...a.map(m=>({kind:"file",path:m.path,identity:m.file_id,document_hash:pc(m)}))]);return{protocol_version:1,collection_id:e,source_head:t,source_revision:l,manifest_digest:d,resources:{revision:c,spec_version:r.specVersion,types:(y=r.types)!=null?y:[],contracts:(h=r.contracts)!=null?h:[],documents:i},records:s,files:a}}function iM(r,e){try{pt({...r,path:e})}catch(t){throw new J("invalid_authority_snapshot",`File descriptor is invalid for ${e}.`)}if(r.media_class!==Vf(e))throw new J("invalid_authority_snapshot",`File media class does not match its path for ${e}.`)}function Uw(r,e){let t=oM(kn(r,"Collection ID")),i=hc(new Uint8Array([...t,...on.encode(wc(e))])).slice(0,16);i[6]=i[6]&15|80,i[8]=i[8]&63|128;let s=Le(i);return`${s.slice(0,8)}-${s.slice(8,12)}-${s.slice(12,16)}-${s.slice(16,20)}-${s.slice(20)}`}function qw(r){return`sha256:${Le(Ge(on.encode(r)))}`}function Fw(r){let e=Ge.create();for(let t of r){let n=BigInt(on.encode(t).length),i=new Uint8Array(8);new DataView(i.buffer).setBigUint64(0,n),e.update(i),e.update(on.encode(t))}return`sha256:${Le(e.digest())}`}function sM(r,e){return r.kind==="configuration"&&e.kind!=="configuration"?-1:e.kind==="configuration"&&r.kind!=="configuration"?1:zf(r.path,e.path)}function zf(r,e){let t=on.encode(r),n=on.encode(e),i=Math.min(t.length,n.length);for(let s=0;s!t||t==="."||t===".."))throw new J("invalid_authority_snapshot",`Collection path is unsafe: ${r}`);return e}function Bf(r){throw new J("invalid_authority_snapshot",`Collection snapshot contains the path more than once: ${r}`)}function oM(r){return Uint8Array.from(r.replaceAll("-","").match(/../g).map(e=>Number.parseInt(e,16)))}var aM=/^sha256:[a-f0-9]{64}$/,cM=/^[a-f0-9]{64}$/,Wf=1500,Gf=1440*60*1e3,lM=200,Vw=8*1024*1024,dM=new TextEncoder,vc=class{constructor(e={}){I(this,"request");I(this,"now");I(this,"wait");var t,n,i;this.request=(t=e.request)!=null?t:hM,this.now=(n=e.now)!=null?n:Date.now,this.wait=(i=e.wait)!=null?i:pM}async begin(e,t={}){var f,p;Tn(t.signal);let n=Ir(e.controlUrl),i=kn(e.collectionId,"Collection ID"),s=Kf(e.displayName,"Collection name"),o=Kf(e.sourceName,"Source name"),a=(f=e.retainMirror)!=null?f:!0,c=a?Kf((p=e.mirrorName)!=null?p:o,"Mirror name"):void 0,l;try{l=await this.request({url:`${n}/v1/authority-adoptions`,method:"POST",headers:{"content-type":"application/json"},body:{collection_id:i,display_name:s,source_name:o,retain_mirror:a,...c?{mirror_name:c}:{}},...t.signal?{signal:t.signal}:{}})}catch(y){throw Tn(t.signal),Kw()}let d=fM(l,201);if(!Rr(d)||!ki.test(tt(d.adoption_id))||!Jf(d.adoption_secret)||!_M(d.expires_in)||Number(d.expires_in)*1e3>Gf)throw rt("Connect returned an invalid collection adoption request.");let u=Xw(n,tt(d.verification_uri),tt(d.adoption_id));return{controlUrl:n,adoptionId:tt(d.adoption_id),credential:tt(d.adoption_secret),verificationUri:u,expiresAt:new Date(this.now()+Number(d.expires_in)*1e3).toISOString(),requested:{collectionId:i,displayName:s,sourceName:o,retainMirror:a,...c?{mirrorName:c}:{}}}}async start(e,t){let n=await this.begin(e,t),{credential:i,...s}=n;return await t.onVerification(s),{session:n,prepared:await this.waitForApproval(n,t)}}async waitForApproval(e,t={}){var o,a;Oi(e,this.now());let n=Ww(t.pollIntervalMs),i=Date.parse(e.expiresAt),s=0;for(;this.now()=500){let l=Rn(c);if(!await this.retry(i,(a=c.retryAfterMs)!=null?a:n,s,t,{code:l.code,message:l.message}))break;continue}throw Rn(c)}throw new J("authority_adoption_expired","Collection adoption approval expired before upload began.")}async exchange(e,t={}){Oi(e,this.now(),!0);let n=await this.controlRequest(e,"exchange","POST",{},t.signal);if(n.status===202)throw new J("authority_adoption_pending","Collection adoption is still awaiting approval.",202);if(n.status!==200)throw Rn(n);return zw(e,n.body)}async uploadSnapshot(e,t,n,i={}){Oi(e,this.now(),!0),Jw(e,t),Bw(e,n);let s={protocol_version:1,collection_id:n.collection_id,source_head:n.source_head,source_revision:n.source_revision,manifest_digest:n.manifest_digest,resources:n.resources,record_count:n.records.length,file_count:n.files.length,files:n.files};await this.importRequest(t.import.manifest_url,"PUT",t.import.access_token,s,i.signal);let o=0,a=[],c=0;for(let l of n.records){let d=dM.encode(JSON.stringify(l)).length;if(d>Vw)throw new J("authority_adoption_record_too_large",`Record ${l.path} is too large to adopt.`);a.length>0&&(a.length===lM||c+d>Vw)&&(await this.uploadPage(t.import,o,a,i.signal),o+=1,a=[],c=0),a.push(l),c+=d}a.length>0&&await this.uploadPage(t.import,o,a,i.signal);for(let l of n.files){if(!i.fileSource)throw new J("authority_adoption_file_source_required",`File bytes are required to adopt ${l.path}.`);let d=await i.fileSource(l);await $w(this.request,t.import,l,d,i)}await this.importRequest(t.import.finalize_url,"POST",t.import.access_token,void 0,i.signal)}async complete(e,t,n={}){Oi(e,this.now(),!0),Bw(e,t);let i;try{i=await this.controlRequest(e,"complete","POST",{manifest_digest:t.manifest_digest,source_revision:t.source_revision,source_head:t.source_head},n.signal)}catch(a){throw Tn(n.signal),new kr("Connect could not confirm whether hosted authority activated.",{cause:a})}if(i.status>=500)throw new kr("Connect could not confirm whether hosted authority activated.");if(i.status!==200)throw Rn(i);let s=i.body;if(!Rr(s)||s.status!=="completed")throw rt("Connect returned an invalid adoption completion.");let o=Yw(e,s.adoption);if(o.state!=="completed"||o.manifest_digest!==t.manifest_digest||o.source_revision!==t.source_revision||o.final_head!==t.source_head)throw rt("Connect completed a different adoption snapshot.");return{status:"completed",adoption:o}}async cancel(e,t={}){Oi(e,this.now(),!0);let n=await this.controlRequest(e,void 0,"DELETE",void 0,t.signal);if(n.status!==200)throw Rn(n)}mirrorEnrollmentSession(e,t){var n;if(Oi(e,this.now(),!0),t.status!=="completed"||t.adoption.collection_id!==e.requested.collectionId)throw rt("Completed adoption does not belong to this session.");return e.requested.retainMirror?{controlUrl:e.controlUrl,pairingId:e.adoptionId,refreshCredential:e.credential,verificationUri:`${e.controlUrl}/mirror/${e.adoptionId}`,expiresAt:new Date(this.now()+Gf).toISOString(),requested:{mirrorName:(n=e.requested.mirrorName)!=null?n:e.requested.sourceName,mode:"read_write",collectionId:e.requested.collectionId}}:null}async uploadPage(e,t,n,i){let s={protocol_version:1,page:t,records:n};await this.importRequest(e.records_url,"PUT",e.access_token,s,i)}async importRequest(e,t,n,i,s){let o;try{o=await this.request({url:e,method:t,headers:{authorization:`Bearer ${n}`,...i===void 0?{}:{"content-type":"application/json"}},...i===void 0?{}:{body:i},...s?{signal:s}:{}})}catch(a){throw Tn(s),Kw()}if(o.status<200||o.status>=300)throw Rn(o)}controlRequest(e,t,n,i,s){return this.request({url:Hw(e,t),method:n,headers:{authorization:`Bearer ${e.credential}`,...i===void 0?{}:{"content-type":"application/json"}},...i===void 0?{}:{body:i},...s?{signal:s}:{}})}async retry(e,t,n,i,s){var l;let o=e-this.now();if(o<=0)return!1;let a=Math.min(Ww(t),o),c=new Date(this.now()+a).toISOString();return(l=i.onStatus)==null||l.call(i,{state:s?"retrying":"waiting_for_approval",attempt:n,expiresAt:new Date(e).toISOString(),retryAt:c,...s?{error:s}:{}}),await this.wait(a,i.signal),!0}};function Oi(r,e,t=!1){Ir(r.controlUrl);let n=Date.parse(r.expiresAt);if(!ki.test(r.adoptionId)||!Jf(r.credential)||!Number.isFinite(n)||n-e>Gf||!t&&n<=e||!ki.test(r.requested.collectionId)||!r.requested.displayName.trim()||!r.requested.sourceName.trim())throw new J("invalid_authority_adoption_session","Stored collection adoption state is invalid.");Xw(r.controlUrl,r.verificationUri,r.adoptionId)}function Jw(r,e){if(e.status!=="ready"||e.adoption.id!==r.adoptionId||e.adoption.collection_id!==r.requested.collectionId)throw rt("Prepared adoption does not belong to this session.");let t=e.import;if(!ki.test(t.import_id)||!Jf(t.access_token))throw rt("Connect returned an invalid authority import capability.");let n=[[t.manifest_url,"manifest"],[t.records_url,"records"],[t.files_url,"files"],[t.finalize_url,"finalize"]],i;for(let[s,o]of n){let a=uM(s,t.import_id,o);if(!a||i!==void 0&&a.origin!==i)throw rt("Connect returned an invalid authority import capability.");i=a.origin}}function Bw(r,e){var t;if(e.protocol_version!==1||e.collection_id!==r.requested.collectionId||!Number.isSafeInteger(e.source_head)||e.source_head<0||!aM.test(e.source_revision)||!cM.test(e.manifest_digest)||((t=e.resources.documents)==null?void 0:t.length)===0||!Array.isArray(e.files))throw new J("invalid_authority_snapshot","Authority snapshot does not belong to this adoption.")}function zw(r,e){if(!Rr(e)||!["ready","activating","completed"].includes(tt(e.status)))throw rt("Connect returned an invalid adoption exchange.");let t=Yw(r,e.adoption);if(e.status==="completed")return{status:"completed",adoption:t};if(e.status==="activating")return{status:"activating",adoption:t};if(!Rr(e.import)||!Rr(e.staged))throw rt("Connect omitted the authority import capability.");let n=e.import,i=e.staged,s={status:"ready",adoption:t,import:{import_id:tt(n.import_id),manifest_url:tt(n.manifest_url),records_url:tt(n.records_url),files_url:tt(n.files_url),finalize_url:tt(n.finalize_url),access_token:tt(n.access_token)},staged:{state:i.state,manifest_digest:Gw(i.manifest_digest),source_revision:Gw(i.source_revision),source_head:gM(i.source_head)}};if(Jw(r,s),!["receiving","uploaded"].includes(s.staged.state))throw rt("Connect returned an invalid staged import state.");return s}function Yw(r,e){if(!Rr(e))throw rt("Connect omitted collection adoption state.");let t=e;if(t.id!==r.adoptionId||t.collection_id!==r.requested.collectionId||!["requested","approved","prepared","activating","completed","cancelled","expired"].includes(t.state)||!Number.isSafeInteger(t.authority_epoch)||t.authority_epoch<2||!yM(t.expires_at))throw rt("Connect returned invalid collection adoption state.");return t}function uM(r,e,t){try{let n=new URL(r);return(n.protocol==="https:"||n.protocol==="http:"&&["localhost","127.0.0.1","[::1]","::1"].includes(n.hostname))&&!n.username&&!n.password&&!n.search&&!n.hash&&n.pathname===`/v1/authority-imports/${e}/${t}`?n:null}catch(n){return null}}function Xw(r,e,t){let n;try{n=new URL(e)}catch(s){throw rt("Connect returned an invalid adoption verification URI.")}let i=new URL(`/adopt/${encodeURIComponent(t)}`,r);if(n.origin!==i.origin||n.pathname!==i.pathname||n.search||n.hash||n.username||n.password)throw rt("Connect returned an untrusted adoption verification URI.");return n.href}function Hw(r,e){let t=e?`/${e}`:"";return`${Ir(r.controlUrl)}/v1/authority-adoptions/${encodeURIComponent(r.adoptionId)}${t}`}function Kf(r,e){let t=r.trim();if(!t||t.length>200)throw new J("invalid_authority_adoption",`${e} must contain between 1 and 200 characters.`);return t}function fM(r,e){if(r.status!==e)throw Rn(r);return r.body}function Rn(r){let e=Rr(r.body)&&Rr(r.body.error)?r.body.error:{};return new J(tt(e.code)||"authority_adoption_request_failed",tt(e.message)||`Collection adoption request failed with status ${r.status}.`,r.status)}function rt(r){return new J("invalid_authority_adoption_response",r)}function Qw(r){return{code:"authority_adoption_unreachable",message:"Connect could not be reached for collection adoption."}}function Kw(){let r=Qw(void 0);return new J(r.code,r.message)}function Ww(r=Wf){return Number.isFinite(r)?Math.min(3e4,Math.max(250,Math.round(r))):Wf}function pM(r,e){return Tn(e),new Promise((t,n)=>{let i=setTimeout(o,r),s=()=>{clearTimeout(i),e==null||e.removeEventListener("abort",s),n(new J("authority_adoption_cancelled","Collection adoption was cancelled."))};function o(){e==null||e.removeEventListener("abort",s),t()}e==null||e.addEventListener("abort",s,{once:!0})})}function Tn(r){if(r!=null&&r.aborted)throw new J("authority_adoption_cancelled","Collection adoption was cancelled.")}async function hM(r){let e=await fetch(r.url,{method:r.method,headers:r.headers,redirect:"error",...r.body===void 0?{}:{body:r.rawBody?r.body:JSON.stringify(r.body)},...r.signal?{signal:r.signal}:{}}),t=await e.json().catch(()=>({})),n=e.headers.get("retry-after");return{status:e.status,body:t,headers:Object.fromEntries(e.headers.entries()),...n?{retryAfterMs:mM(n)}:{}}}function mM(r){let e=Number(r);if(Number.isFinite(e)&&e>=0)return e*1e3;let t=Date.parse(r);return Number.isFinite(t)?Math.max(0,t-Date.now()):Wf}function yM(r){return Number.isFinite(Date.parse(r))}function Gw(r){return r===null?null:tt(r)}function gM(r){return r===null?null:typeof r=="number"&&Number.isSafeInteger(r)&&r>=0?r:Number.NaN}function _M(r){return typeof r=="number"&&Number.isSafeInteger(r)&&r>0}function Jf(r){return typeof r=="string"&&r.length>=16}function tt(r){return typeof r=="string"?r:""}function Rr(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}Ee();Ee();var bM=new TextEncoder,eo=Object.freeze({digest:r=>Le(Ge(bM.encode(r))),randomId:()=>{var r;if(typeof((r=globalThis.crypto)==null?void 0:r.randomUUID)!="function")throw new b("mirror_random_unavailable","This runtime must provide crypto.randomUUID() or a MirrorRuntime adapter.");return globalThis.crypto.randomUUID()},now:()=>new Date().toISOString()});var Zs=class{constructor(){I(this,"held",!1)}async runExclusive(e){if(this.held)throw new b("mirror_folder_in_use","Another mdbase mirror process is already using this folder.");this.held=!0;try{return await e()}finally{this.held=!1}}};function Zw(r,e,t){var i,s,o,a,c,l;if(r.engine_version!==3)throw new b("mirror_state_upgrade_required","Rebuild this prerelease mirror with the exact-document sync engine.");if(r.protocol_version!==1||r.replica_id!==e)throw new Error;if((i=r.resources)!=null||(r.resources={}),(s=r.generation)!=null||(r.generation=0),(o=r.files)!=null||(r.files={}),r.selective_sync=In(r.selective_sync),(a=r.planned_conflicts)!=null||(r.planned_conflicts={}),(c=r.local_bindings)!=null||(r.local_bindings={}),(l=r.mode)!=null||(r.mode="read_only"),r.mode!==t)throw new b("mirror_mode_mismatch",`Mirror metadata belongs to a ${r.mode.replace("_","-")} replica.`);let n=[];for(let[d,u]of Object.entries(r.records))if(n.push(bt(u.path)),u.record&&(u.record.record_id!==d||u.record.path!==u.path))throw new Error;for(let[d,u]of Object.entries(r.resources)){if(Jt(d),d!==u.path)throw new Error;n.push(bt(u.path))}for(let[d,u]of Object.entries(r.files)){if(pt(u.file),u.file.file_id!==d)throw new Error;n.push(bt(u.file.path))}n.sort();for(let d=1;dl.kind==="configuration"&&l.path==="mdbase.yaml");if(n.length!==1)throw new b("invalid_snapshot","Hosted snapshot requires exactly one canonical mdbase.yaml resource.");let i=r0(n[0].document,e),s=(c=s0(n[0].document).settings)!=null?c:{},o=Ri(s.types_folder,"_types"),a=Ri(s.contracts_folder,"_contracts");for(let l of r){let d=l.path.split(".").at(-1),u=l.path.split("/"),f=u.some(y=>y.startsWith(".")),p=!1;if(l.kind==="configuration")p=l.path==="mdbase.yaml";else if(l.kind==="lock")p=l.path==="mdbase.lock.yaml"&&$M(l.document);else if(l.kind==="type")p=Yf(l.path,o)&&d==="md"&&e0(l.document,l.path)==="mdbase.type";else if(l.kind==="contract")p=Yf(l.path,a)&&d==="md"&&e0(l.document,l.path)==="mdbase.contract";else if(l.kind==="schema"){let y=vM(l.document);p=!f&&d==="json"&&u.some(h=>h==="schemas"||h==="_schemas")&&y!==null}else l.kind==="view"&&(p=!f&&d==="base");if(!p)throw new b("invalid_snapshot",`Hosted resource ${l.path} is not valid for kind ${l.kind}.`)}return i}function t0(r){return{reservedFolders:new Set(["_types","_contracts","_types/_migrations",".mdbase"]),resourcePaths:r}}function r0(r,e){var s;let t=(s=s0(r).settings)!=null?s:{},n=Ri(t.types_folder,"_types");return{reservedFolders:new Set([n,Ri(t.contracts_folder,"_contracts"),Ri(t.migrations_folder,`${n}/_migrations`),Ri(t.cache_folder,".mdbase",!0)]),resourcePaths:e}}async function n0(r,e){if(r.length===0)return t0(new Set);let t=await e();if(t===null)throw new b("invalid_mirror_state","Mirror collection configuration is missing.");return r0(t,new Set(r))}function an(r,e){if(Jt(r),/(?:^|\/)\./u.test(r)||e.resourcePaths.has(r)||wM(r,e.reservedFolders)||!r.endsWith(".md"))throw new b("invalid_record_path",`Mirror record path ${r} is outside the configured record namespace.`)}function wM(r,e){for(let t of e)if(Yf(r,t))return!0;return!1}function i0(r,e){return r.filter(t=>{try{return an(t,e),!0}catch(n){return!1}})}function s0(r){let e;try{e=Ei(r)}catch(n){throw new b("invalid_snapshot","Hosted mdbase.yaml is not valid YAML.")}if(!e||typeof e!="object"||Array.isArray(e))throw new b("invalid_snapshot","Hosted mdbase.yaml requires an object document.");let t=e;if(typeof t.spec_version!="string")throw new b("invalid_snapshot","Hosted mdbase.yaml requires spec_version.");return t}function Ri(r,e,t=!1){let n=typeof r=="string"?r:e;if(Jt(n),!t&&n.split("/").some(i=>i.startsWith(".")))throw new b("invalid_snapshot",`Collection control folder ${n} must not be hidden.`);return n}function Yf(r,e){return r===e||r.startsWith(`${e}/`)}function vM(r){try{let e=JSON.parse(r);return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null}catch(e){return null}}function $M(r){try{let e=Ei(r);return e!==null&&typeof e=="object"&&!Array.isArray(e)&&e.kind==="mdbase.type-pack-lock"&&e.lock_version===1&&Array.isArray(e.packs)}catch(e){return!1}}function e0(r,e){try{return uc(r,e).frontmatter.kind}catch(t){return null}}Ee();function wt(r){return Ii(r)}function o0(r,e,t,n,i=[]){let s=wt(r);for(let o of t)if(wt(o)===s)throw new b("invalid_record_path",`Mirror record path ${r} aliases authority resource ${o} on a supported filesystem.`);for(let[o,a]of n)if((o!==e||a.path!==r)&&wt(a.path)===s)throw new b("invalid_record_path",`Mirror record paths ${a.path} and ${r} alias on a supported filesystem.`);for(let[,o]of i)if(wt(o.file.path)===s)throw new b("invalid_record_path",`Mirror record path ${r} aliases collection file ${o.file.path} on a supported filesystem.`)}function a0(r,e,t){var i,s;let n=wt(r);for(let o of Object.values((i=t.resources)!=null?i:{}))if(wt(o.path)===n)throw new b("invalid_file_path",`Collection file ${r} aliases authority resource ${o.path}.`);for(let o of Object.values(t.records))if(wt(o.path)===n)throw new b("invalid_file_path",`Collection file ${r} aliases record ${o.path}.`);for(let[o,a]of Object.entries((s=t.files)!=null?s:{}))if((o!==e||a.file.path!==r)&&wt(a.file.path)===n)throw new b("invalid_file_path",`Collection files ${a.file.path} and ${r} alias on a supported filesystem.`)}function to(r){let e=new Map;for(let t of r){let n=wt(t),i=e.get(n);if(i!==void 0&&i!==t)throw new b("invalid_record_path",`Mirror paths ${i} and ${t} alias on a supported filesystem.`);e.set(n,t)}}Ee();var Sc=class{constructor(e,t,n){I(this,"pathPolicy");I(this,"digest");I(this,"recordIds",new Set);I(this,"physicalPaths",new Set);this.pathPolicy=e,this.digest=n;for(let i of t)this.physicalPaths.add(Ii(i.path))}validate(e){let t=e.document,n=e;if(an(n.path,this.pathPolicy),this.recordIds.has(n.record_id))throw new b("invalid_snapshot",`Hosted snapshot repeats record identity ${n.record_id}.`);this.recordIds.add(n.record_id);let i=Ii(n.path);if(this.physicalPaths.has(i))throw new b("invalid_snapshot",`Hosted record path ${n.path} aliases another snapshot path on a supported filesystem.`);this.physicalPaths.add(i);let s=this.digest(t);if(n.revision.length!==7+s.length||!n.revision.startsWith("sha256:")||!n.revision.endsWith(s))throw new b("invalid_snapshot",`Hosted record ${n.path} does not match its declared revision.`);if(bw(t,n)!==!0){let a;try{a=uc(t,n.path)}catch(c){throw new b("invalid_snapshot",`Hosted record ${n.path} is not valid Markdown.`)}if(!Xf(a.frontmatter,n.frontmatter)||!SM(a.body,n.body))throw new b("invalid_snapshot",`Hosted record ${n.path} does not match its declared document.`)}return{record:n,document:t,hash:s}}};async function c0(r,e,t){let n,i=new Set;do{let s=await r.snapshot(e.snapshot_id,n);if(s.protocol_version!==1||s.snapshot_id!==e.snapshot_id||s.scope_epoch!==e.scope_epoch||s.cursor!==e.head)throw new b("invalid_snapshot","Authority snapshot boundary changed during download.");if(await t(s.records),n=s.next_page,n!==void 0&&i.has(n))throw new b("invalid_snapshot","Authority snapshot repeated a page cursor.");n!==void 0&&i.add(n)}while(n)}function SM(r,e){return r===e||r.startsWith(` `)&&r.slice(1)===e||e.startsWith(` -`)&&e.slice(1)===r}function Vf(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)=>Vf(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)&&Vf(s,n[i]))}var Sc=class{constructor(e,t,n,i){T(this,"fileSystem");T(this,"runtime");T(this,"mode");T(this,"blobStore");this.fileSystem=e,this.runtime=t,this.mode=n,this.blobStore=i}async recordPathPolicy(e){var t;return Iw(Object.keys((t=e.resources)!=null?t:{}),()=>this.fileSystem.read("mdbase.yaml"))}async put(e,t,n={}){var p,m,h,y;let{managedState:i=e,acceptedHash:s,preserveAcceptedDocument:o=!1,materialized:a,physicalPathPreflighted:c=!1}=n;bt(t.path,await this.recordPathPolicy(e)),a===void 0&&!c&&Tw(t.path,t.record_id,Object.keys((p=e.resources)!=null?p:{}),Object.entries(e.records),Object.entries((m=e.files)!=null?m:{}));let l=(h=a==null?void 0:a.document)!=null?h:kn(t),u=await this.fileSystem.read(t.path),d=i==null?void 0:i.records[t.record_id];if(u!==null&&u!==l){let b=this.runtime.digest(u);if(!(d!==void 0&&d.path===t.path&&b===d.hash)&&(s===void 0||b!==s))throw new Qe(t.record_id,t.path)}d&&d.path!==t.path&&await this.remove(i,t.record_id,d.path);let f=o&&typeof s=="string"&&u!==null&&this.runtime.digest(u)===s?s:null;f===null&&await this.fileSystem.write(t.path,l),e.records[t.record_id]={path:t.path,revision:t.revision,hash:(y=f!=null?f:a==null?void 0:a.hash)!=null?y:this.runtime.digest(l),...this.mode==="read_write"?{record:jw(t)}:{}}}async putFile(e,t,n=e){var p,m,h,y;if(St(t),!this.blobStore)throw new S("file_storage_unavailable","Selected collection files require a content-addressed blob store adapter.");Rw(t.path,t.file_id,e),(p=e.files)!=null||(e.files={});let i=(m=n.files)==null?void 0:m[t.file_id],s=await this.fileSystem.inspectBinary(t.path),o=ue(t.path),a=Object.values((h=n.files)!=null?h:{}).find(b=>ue(b.file.path)===o),c=[...Object.values((y=n.resources)!=null?y:{}),...Object.values(n.records)].find(b=>ue(b.path)===o),l=c?await this.fileSystem.read(t.path):null,u=(i==null?void 0:i.file.path)===t.path&&Oe(s,i.file),d=a!==void 0&&Oe(s,a.file),f=c!==void 0&&l!==null&&this.runtime.digest(l)===c.hash;if(s!==null&&!Oe(s,t)&&!u&&!d&&!f)throw new Qe(t.file_id,t.path);if(i&&i.file.path!==t.path){let b=await this.fileSystem.inspectBinary(i.file.path);if(b!==null&&!Oe(b,i.file))throw new Qe(t.file_id,i.file.path)}Oe(s,t)||await this.fileSystem.writeBinary(t.path,fc(this.blobStore.read(t.content_digest),t)),i&&i.file.path!==t.path&&await this.fileSystem.remove(i.file.path),e.files[t.file_id]={file:t}}async removeFile(e,t){var s;let n=(s=e.files)==null?void 0:s[t];if(!n)return;let i=await this.fileSystem.inspectBinary(n.file.path);if(i!==null&&!Oe(i,n.file))throw new Qe(t,n.file.path);i!==null&&await this.fileSystem.remove(n.file.path),delete e.files[t]}async remove(e,t,n){var a;let i=e.records[t],s=(a=i==null?void 0:i.path)!=null?a:n;bt(s,await this.recordPathPolicy(e));let o=await this.fileSystem.read(s);if(o!==null&&i&&this.runtime.digest(o)!==i.hash)throw new Qe(t,i.path);o!==null&&await this.fileSystem.remove(s),delete e.records[t]}async putResource(e,t,n){var o,a;let i=await this.fileSystem.read(t.path),s=(o=n==null?void 0:n.resources)==null?void 0:o[t.path];if(i!==null&&i!==t.document&&(!s||this.runtime.digest(i)!==s.hash))throw new Qe(`resource:${t.path}`,t.path);await this.fileSystem.write(t.path,t.document),(a=e.resources)!=null||(e.resources={}),e.resources[t.path]={path:t.path,revision:t.revision,hash:this.runtime.digest(t.document)}}async removeResource(e,t,n){let i=await this.fileSystem.read(t);if(i!==null&&this.runtime.digest(i)!==n.hash)throw new Qe(`resource:${t}`,t);i!==null&&await this.fileSystem.remove(t),e.resources&&delete e.resources[t]}};async function Fw(r){var d,f,p,m,h,y,b,g,_,k,v;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 S("promotion_incomplete_file_projection","Moving the source of truth requires every collection file class with no excluded folders.");if(((f=(d=e.pending)==null?void 0:d.length)!=null?f:0)>0||((m=(p=e.pending_files)==null?void 0:p.length)!=null?m:0)>0||Object.keys((h=e.conflicts)!=null?h:{}).length>0||Object.keys((y=e.file_conflicts)!=null?y:{}).length>0||Object.keys((b=e.local_issues)!=null?b:{}).length>0)throw new S("promotion_not_converged","Upload or resolve every local change before moving the source of truth.");await vc(e,i,n,s);let o=new Set(Object.keys((g=e.resources)!=null?g:{})),a=new Set(Object.values(e.records).map(E=>E.path)),c=(await n.listMarkdown(o)).filter(E=>!a.has(E));if(c.length>0)throw new S("promotion_unmanaged_files",`Synchronize unmanaged Markdown before promotion: ${c.join(", ")}.`);if(!n.listBinary)throw new S("promotion_file_scan_unavailable","Moving the source of truth requires binary file enumeration.");let l=new Set(Object.values((_=e.files)!=null?_:{}).map(E=>E.file.path)),u=(await n.listBinary(new Set([...o,...a]))).filter(E=>!l.has(E));if(u.length>0)throw new S("promotion_unmanaged_files",`Synchronize unmanaged files before moving the source of truth: ${u.join(", ")}.`);return{cursor:e.cursor,digest:ac([...Object.entries((k=e.resources)!=null?k:{}).map(([E,O])=>({kind:"resource",path:E,identity:"",document_hash:Sf(O.hash)})),...Object.entries(e.records).map(([E,O])=>({kind:"record",path:O.path,identity:E,document_hash:Sf(O.hash)})),...Object.values((v=e.files)!=null?v:{}).map(({file:E})=>({kind:"file",path:E.path,identity:E.file_id,document_hash:cc(E)}))])}}async function Ec(r,e,t){let n=await e.openSession();if(n.replica_id!==r||n.mode!==t)throw new S("invalid_mirror_session",`Filesystem mirror requires its own ${t.replace("_","-")} replica.`);return n}async function Vw(r,e){var L,F,z,P,I,ke,ce,de,Et,Ze,Lt,fo,cn;let{replicaId:t,transport:n,mode:i,fileSystem:s,runtime:o,materializer:a,blobStore:c,selectiveSync:l,reportProgress:u}=r,d=await Ec(t,n,i),f=(L=d.resources.documents)!=null?L:[],p=bc(f),m=new Pi(p,f,o.digest),h={protocol_version:1,replica_id:t,scope_epoch:d.scope_epoch,cursor:d.head,records:{},resources:{},files:{},selective_sync:l,mode:i,pending:[],pending_files:[],conflicts:{},file_conflicts:{},local_issues:{}},y=new Map,b=new Map;if(e){for(let U of Object.values((F=e.resources)!=null?F:{}))y.set(ue(U.path),U);for(let U of Object.values(e.records))y.set(ue(U.path),U);for(let U of Object.values((z=e.files)!=null?z:{}))b.set(ue(U.file.path),U.file)}let g=[];for(let U of f){let M=await s.read(U.path),te=e?y.get(ue(U.path)):void 0,et=e?b.get(ue(U.path)):void 0;if(te&&te.path!==U.path)throw new S("invalid_record_path",`Mirror paths ${te.path} and ${U.path} alias on a supported filesystem.`);M!==null&&M!==U.document&&(!te||o.digest(M)!==te.hash)&&(!et||!Oe(await s.inspectBinary(U.path),et))&&g.push(U.path)}let _=[],k=e?new Set:null;await $c(n,d,async U=>{for(let M of U){let te=m.validate(M),{document:et,record:R}=te;if(!tr(l,R.path))continue;let fe=await s.read(R.path),C=e?y.get(ue(R.path)):void 0,X=e?b.get(ue(R.path)):void 0;if(C&&C.path!==R.path)throw new S("invalid_record_path",`Mirror paths ${C.path} and ${R.path} alias on a supported filesystem.`);fe!==null&&fe!==et&&(!C||o.digest(fe)!==C.hash)&&(!X||!Oe(await s.inspectBinary(R.path),X))&&g.push(R.path),k==null||k.add(R.record_id),_.push(te)}});let v=[],E=new Set;await Js(n,d,async U=>{for(let M of U)if(on(l,M)){if(E.has(M.file_id))throw new S("invalid_snapshot",`Hosted snapshot repeats file identity ${M.file_id}.`);E.add(M.file_id),v.push(M)}}),rr([...f.map(U=>U.path),..._.map(({record:U})=>U.path),...v.map(U=>U.path)]);for(let U of v){let M=await s.inspectBinary(U.path),te=(P=e==null?void 0:e.files)==null?void 0:P[U.file_id],et=b.get(ue(U.path)),R=y.get(ue(U.path)),fe=R?await s.read(U.path):null;M!==null&&!Oe(M,U)&&(!te||te.file.path!==U.path||!Oe(M,te.file))&&(!et||!Oe(M,et))&&(!R||fe===null||o.digest(fe)!==R.hash)&&g.push(U.path)}if(e){for(let[M,te]of Object.entries(e.records)){if(k.has(M))continue;let et=await s.read(te.path);et!==null&&o.digest(et)!==te.hash&&g.push(te.path)}let U=new Set(f.map(M=>M.path));for(let M of Object.values((I=e.resources)!=null?I:{})){if(U.has(M.path))continue;let te=await s.read(M.path);te!==null&&o.digest(te)!==M.hash&&g.push(M.path)}for(let[M,te]of Object.entries((ke=e.files)!=null?ke:{})){if(E.has(M))continue;let et=await s.inspectBinary(te.file.path);et!==null&&!Oe(et,te.file)&&g.push(te.file.path)}}if(g.length)throw new wc([...new Set(g)].sort());if(v.length>0&&!c)throw new S("file_storage_unavailable","Selected collection files require a content-addressed blob store adapter.");let O=0;for(let U of v)await Ys(n,c,U),O+=1,u({phase:"downloading",completed:O,total:v.length,done:O===v.length});let w=f.length+_.length+v.length,x=0,$=()=>{x+=1,u({phase:"applying",completed:x,total:w,done:x===w})};for(let U of f)await a.putResource(h,U,e),$();for(let U of _)await a.put(h,U.record,{managedState:e,materialized:U}),$();for(let U of v)await a.putFile(h,U,e),$();if(e){let U=new Set([...Object.values((ce=h.resources)!=null?ce:{}).map(M=>ue(M.path)),...Object.values(h.records).map(M=>ue(M.path)),...Object.values((de=h.files)!=null?de:{}).map(M=>ue(M.file.path))]);for(let[M,te]of Object.entries(e.records))!h.records[M]&&!U.has(ue(te.path))&&await a.remove(e,M,te.path);for(let[M,te]of Object.entries((Et=e.resources)!=null?Et:{}))!((Ze=h.resources)!=null&&Ze[M])&&!U.has(ue(te.path))&&await a.removeResource(e,M,te);for(let M of Object.keys((Lt=e.files)!=null?Lt:{})){let te=(fo=e.files)==null?void 0:fo[M];te&&!((cn=h.files)!=null&&cn[M])&&!U.has(ue(te.file.path))&&await a.removeFile(e,M)}}return h.last_synced_at=o.now(),h}var Tn=class{constructor(e,t,n,i="read_only"){T(this,"replicaId");T(this,"transport");T(this,"mode");T(this,"stateStore");T(this,"fileSystem");T(this,"blobStore");T(this,"selectiveSync");T(this,"lease");T(this,"runtime");T(this,"materializer");T(this,"onProgress");var s,o;this.replicaId=e,this.transport=t,this.mode=i,this.stateStore=n.stateStore,this.fileSystem=n.fileSystem,this.blobStore=n.blobStore,this.selectiveSync=pc(n.selectiveSync),this.lease=(s=n.lease)!=null?s:new Xs,this.runtime=(o=n.runtime)!=null?o:Qs,this.materializer=new Sc(this.fileSystem,this.runtime,this.mode,this.blobStore),this.onProgress=n.onProgress}async sync(){await this.lease.runExclusive(async()=>{await this.syncUnlocked(),await this.pruneFileBlobs()})}async syncUnlocked(){var n,i,s,o,a,c,l,u;let e=await this.readState();if(!e){await this.rebuild(),this.mode==="read_write"&&await this.syncUnlocked();return}if(JSON.stringify(e.selective_sync)!==JSON.stringify(this.selectiveSync)){if(this.mode==="read_write"&&(((i=(n=e.pending)==null?void 0:n.length)!=null?i:0)>0||((o=(s=e.pending_files)==null?void 0:s.length)!=null?o:0)>0||Object.keys((a=e.conflicts)!=null?a:{}).length>0||Object.keys((c=e.file_conflicts)!=null?c:{}).length>0))throw new S("selective_sync_pending_changes","Upload pending Markdown changes before changing selective sync.");await this.rebuild(e);return}this.mode==="read_write"?(await this.flushPending(e),await this.flushPendingFiles(e),await this.captureLocalChanges(e),await this.flushPending(e),await this.flushPendingFiles(e)):await vc(e,await this.currentRecordPathPolicy(e),this.fileSystem,this.runtime.digest);let t=0;for(;;){let d=await this.transport.changes(e.cursor,200);if(d.scope_epoch!==e.scope_epoch||d.reset_required){await this.rebuild(e);return}for(let p of d.events)p.type==="file_put"&&St(p.file);let f=d.events.filter(p=>p.type==="remove"||p.type==="put"&&tr(this.selectiveSync,p.record.path));f.some(p=>p.type==="put")&&Cw(f,await this.currentRecordPathPolicy(e),e),this.preflightProjectedPaths(e,d.events);for(let p of d.events)if(p.type==="file_put"&&on(this.selectiveSync,p.file)){if(!this.blobStore)throw new S("file_storage_unavailable","Selected collection files require a content-addressed blob store adapter.");await Ys(this.transport,this.blobStore,p.file)}for(let p of d.events){if(p.type==="file_put"){on(this.selectiveSync,p.file)?await this.materializer.putFile(e,p.file):await this.materializer.removeFile(e,p.file.file_id),t+=1,this.reportProgress({phase:"applying",completed:t,total:null,done:!1});continue}if(p.type==="file_remove"){await this.materializer.removeFile(e,p.file_id),t+=1,this.reportProgress({phase:"applying",completed:t,total:null,done:!1});continue}let m=p.type==="put"?p.record.record_id:p.record_id,h=e.records[m],y=h==null?void 0:h.path;this.mode==="read_write"&&p.type==="put"&&(h==null?void 0:h.record)!==void 0&&h.path===p.record.path&&h.revision===p.record.revision||y&&((l=e.local_issues)!=null&&l[y])||((u=e.conflicts)!=null&&u[m]?Aw(e,p):p.type==="put"&&tr(this.selectiveSync,p.record.path)?await this.materializer.put(e,p.record,{physicalPathPreflighted:!0}):p.type==="put"?e.records[p.record.record_id]&&await this.materializer.remove(e,p.record.record_id,p.record.path):await this.materializer.remove(e,p.record_id,p.previous_path)),t+=1,this.reportProgress({phase:"applying",completed:t,total:null,done:!1})}if(e.cursor=d.cursor,!d.has_more){e.last_synced_at=this.runtime.now(),await this.writeState(e),t>0&&this.reportProgress({phase:"applying",completed:t,total:null,done:!0});return}await this.writeState(e)}}async status(){var a,c,l,u,d,f,p,m,h,y,b,g,_,k,v;let e=await this.readState();if(!e)return{state:"not_initialized",mode:this.mode,pending:0,pending_files:0,conflicts:[],file_conflicts:[],local_issues:[],cursor:null,last_synced_at:null};let t=[];for(let[E,O]of Object.entries((a=e.conflicts)!=null?a:{})){let w=e.records[E],x=(c=e.pending)==null?void 0:c.find($=>$.mutation.record_id===E);O.status==="conflicted"?t.push({record_id:E,path:(f=(d=(l=x==null?void 0:x.local_path)!=null?l:w==null?void 0:w.path)!=null?d:(u=O.conflict.current)==null?void 0:u.path)!=null?f:null,kind:"conflicted",message:"Local and remote changes need a decision."}):O.status==="rejected"&&t.push({record_id:E,path:(m=(p=x==null?void 0:x.local_path)!=null?p:w==null?void 0:w.path)!=null?m:null,kind:"rejected",message:O.error.message})}let n=Object.values((h=e.local_issues)!=null?h:{}).map(({path:E,code:O,message:w})=>({path:E,code:O,message:w})).sort((E,O)=>E.path.localeCompare(O.path)),i=(b=(y=e.pending)==null?void 0:y.length)!=null?b:0,s=(_=(g=e.pending_files)==null?void 0:g.length)!=null?_:0,o=Object.values((k=e.file_conflicts)!=null?k:{}).sort((E,O)=>E.path.localeCompare(O.path));return{state:t.length||o.length||n.length?"attention":i||s?"changes_waiting":"up_to_date",mode:this.mode,pending:i+s,pending_files:s,conflicts:t,file_conflicts:o,local_issues:n,cursor:e.cursor,last_synced_at:(v=e.last_synced_at)!=null?v:null}}async authorityPromotionManifest(){return this.lease.runExclusive(()=>this.authorityPromotionManifestUnlocked())}async authorityPromotionManifestUnlocked(){if(this.mode!=="read_write")throw new S("promotion_requires_writable_mirror","Only a two-way full collection mirror can become the local source of truth.");let e=await this.readState();if(!e)throw new S("promotion_not_initialized","Synchronize this folder before moving the source of truth.");return Fw({state:e,selectiveSync:this.selectiveSync,fileSystem:this.fileSystem,pathPolicy:await this.currentRecordPathPolicy(e),digest:this.runtime.digest})}async previewInitialization(){var y;if(await this.readState())return{already_initialized:!0,download_documents:0,upload_documents:0,unchanged_documents:0,download_files:0,upload_files:0,unchanged_files:0,collisions:[],local_issues:[]};let e=await Ec(this.replicaId,this.transport,this.mode),t=(y=e.resources.documents)!=null?y:[],n=bc(t),i=new Pi(n,t,this.runtime.digest),s=new Set,o=0,a=0,c=[],l=async(b,g)=>{s.add(b);let _=await this.fileSystem.read(b);_===null?o+=1:_===g?a+=1:c.push(b)};for(let b of t)await l(b.path,b.document);await $c(this.transport,e,async b=>{for(let g of b){let _=i.validate(g);tr(this.selectiveSync,_.record.path)&&await l(_.record.path,_.document)}});let u=0,d=0,f=0;await Js(this.transport,e,async b=>{for(let g of b){if(!on(this.selectiveSync,g))continue;s.add(g.path);let _=await this.fileSystem.inspectBinary(g.path);_===null?u+=1:Oe(_,g)?f+=1:c.push(g.path)}}),rr(s);let p=(await this.fileSystem.listMarkdown(new Set(t.map(b=>b.path)))).filter(b=>tr(this.selectiveSync,b)),m=[],h=0;if(this.mode==="read_write"){let b=_c(p,n);rr([...s,...b]);for(let g of b.filter(_=>!s.has(_))){let _=await this.fileSystem.read(g);if(_!==null)try{Rr(_,g),h+=1}catch(k){let v=sc(k,g);if(!v)throw k;m.push(v)}}if(this.fileSystem.listBinary){let g=new Set([...t.map(k=>k.path),...s]),_=(await this.fileSystem.listBinary(g)).filter(k=>hc(this.selectiveSync,k));for(let k of _)Ai(k,!1),s.has(k)||(d+=1);rr([...s,...b,..._])}}return{already_initialized:!1,download_documents:o,upload_documents:h,unchanged_documents:a,download_files:u,upload_files:d,unchanged_files:f,collisions:c,local_issues:m.sort((b,g)=>b.path.localeCompare(g.path))}}async rebuild(e){let t=await Vw({replicaId:this.replicaId,transport:this.transport,mode:this.mode,fileSystem:this.fileSystem,runtime:this.runtime,materializer:this.materializer,blobStore:this.blobStore,selectiveSync:this.selectiveSync,reportProgress:n=>this.reportProgress(n)},e);await this.writeState(t)}async resolveConflict(e,t){await this.lease.runExclusive(()=>this.resolveConflictUnlocked(e,t))}async resolveFileConflict(e,t){await this.lease.runExclusive(()=>this.resolveFileConflictUnlocked(e,t))}async resolveFileConflictUnlocked(e,t){var d,f,p,m;if(this.mode!=="read_write")throw new S("mirror_read_only","Receive-only mirrors do not contain writable file conflicts.");let n=await this.readState(),i=(d=n==null?void 0:n.file_conflicts)==null?void 0:d[e];if(!n||!i)throw new S("mirror_file_conflict_not_found","Writable file conflict was not found.");let s=((f=n.pending_files)!=null?f:[]).filter(h=>h.operation==="upload"&&!h.file_id?`new:${h.path}`===e:h.file_id===e);if(s.length!==1)throw new S("invalid_mirror_state","Writable file conflict has no unique pending mutation.");let o=s[0],a=await this.currentAuthorityFiles(),c=e.startsWith("new:")?void 0:a.find(h=>h.file_id===e),l=a.find(h=>ue(h.path)===ue(o.path)),u=c!=null?c:l;if(n.pending_files=n.pending_files.filter(h=>h!==o),t==="remote"){let h=new Set([o.path]);o.operation==="move"&&h.add(o.from_path);let y=o.operation==="upload"&&!o.file_id||(m=(p=n.files)==null?void 0:p[o.file_id])==null?void 0:m.file;y&&h.add(y.path);for(let b of h)await this.fileSystem.inspectBinary(b)!==null&&await this.fileSystem.remove(b);if(u&&on(this.selectiveSync,u)){if(!this.blobStore)throw new S("file_storage_unavailable","File conflict resolution requires a blob store.");await Ys(this.transport,this.blobStore,u),await this.materializer.putFile(n,u)}else y&&delete n.files[y.file_id]}else this.queueLocalFileResolution(n,o,c,l);delete n.file_conflicts[e],await this.writeState(n)}queueLocalFileResolution(e,t,n,i){if(n&&i&&n.file_id!==i.file_id)throw new S("file_resolution_ambiguous","The authority changed this file and another file now occupies the local destination.");let s=n!=null?n:i;if(s?e.files[s.file_id]={file:s}:(t.operation!=="upload"||t.file_id)&&delete e.files[t.file_id],t.operation==="delete"){if(!s)return;e.pending_files.push({operation:"delete",mutation_id:this.runtime.randomId(),file_id:s.file_id,path:s.path,base_revision:s.revision});return}if(t.operation==="move"){if(!s)throw new S("file_resolution_source_missing","The authority deleted this file; restore it as a new file to keep the local bytes.");e.pending_files.push({...t,mutation_id:this.runtime.randomId(),file_id:s.file_id,from_path:s.path,base_revision:s.revision});return}if(!s||s.path===t.path){e.pending_files.push({...t,transfer_id:this.runtime.randomId(),...s?{file_id:s.file_id,base_revision:s.revision}:{file_id:void 0,base_revision:void 0}});return}let o=this.runtime.randomId();e.pending_files.push({operation:"move",mutation_id:o,file_id:s.file_id,from_path:s.path,path:t.path,base_revision:s.revision,content_digest:s.content_digest,size:s.size},{...t,transfer_id:this.runtime.randomId(),file_id:s.file_id,base_revision:s.revision,after_mutation_id:o})}async currentAuthorityFiles(){let e=await Ec(this.replicaId,this.transport,this.mode),t=[];return await Js(this.transport,e,async n=>{t.push(...n)}),t}async resolveConflictUnlocked(e,t){var o,a,c,l,u;if(this.mode!=="read_write")throw new S("mirror_read_only","Receive-only mirrors do not contain writable conflicts.");let n=await this.readState(),i=(o=n==null?void 0:n.conflicts)==null?void 0:o[e];if(!n||!i)throw new S("mirror_conflict_not_found","Writable mirror conflict was not found.");let s=((a=n.pending)!=null?a:[]).filter(d=>d.mutation.record_id===e);if(t==="remote"){let d=i.status==="conflicted"?i.conflict.current:(c=n.records[e])==null?void 0:c.record;await this.installRemoteResolution(n,e,d,s),n.pending=((l=n.pending)!=null?l:[]).filter(f=>f.mutation.record_id!==e)}else if(i.status==="rejected")n.pending=((u=n.pending)!=null?u:[]).filter(d=>d.mutation.record_id!==e);else{if(i.status!=="conflicted")throw new S("invalid_mirror_state","Mirror conflict metadata is invalid.");let d=s.at(-1);if(!d)throw new S("conflict_mutation_missing","The local change for this sync issue is unavailable.");let f=i.conflict.current,p=await this.fileSystem.read(d.local_path),m=this.localResolutionMutations(n,e,d.local_path,p,f),h=n.pending.findIndex(y=>y.mutation.record_id===e);n.pending=n.pending.filter(y=>y.mutation.record_id!==e),n.pending.splice(h<0?n.pending.length:h,0,...m),f?n.records[e]={path:f.path,revision:f.revision,hash:this.runtime.digest(kn(f)),record:f}:delete n.records[e]}delete n.conflicts[e],await this.writeState(n)}async installRemoteResolution(e,t,n,i){let s=await this.currentRecordPathPolicy(e),o=new Set(i.map(c=>c.local_path));if(n){bt(n.path,s);for(let l of o)bt(l,s),l!==n.path&&await this.fileSystem.read(l)!==null&&await this.fileSystem.remove(l);let c=await this.fileSystem.read(n.path);await this.materializer.put(e,n,{managedState:e,acceptedHash:c===null?null:this.runtime.digest(c)});return}let a=e.records[t];a&&o.add(a.path);for(let c of o)bt(c,s),await this.fileSystem.read(c)!==null&&await this.fileSystem.remove(c);delete e.records[t]}localResolutionMutations(e,t,n,i,s){let o=[],a,c=(d,f)=>{let p=this.runtime.randomId();o.push({mutation:{...d,mutation_id:p,replica_id:this.replicaId,scope_epoch:e.scope_epoch,created_at:this.runtime.now(),...a?{causal_predecessor:a}:{}},local_path:n,local_hash:f}),a=p};if(i===null)return s&&c({operation:"delete",record_id:t,base_revision:s.revision,input:{}},null),o;let l=Rr(i,n),u=this.runtime.digest(i);return s?(i!==kn(s)&&c({operation:"update",record_id:t,base_revision:s.revision,input:{patch:oc(s.frontmatter,l.frontmatter),body:l.body}},u),n!==s.path&&c({operation:"rename",record_id:t,base_revision:s.revision,input:{path:n}},u),o):(c({operation:"create",record_id:t,input:{path:n,frontmatter:l.frontmatter,body:l.body}},u),o)}async captureLocalChanges(e){var a,c;let t=e.pending.length,n=e.pending_files.length,i=JSON.stringify((a=e.local_issues)!=null?a:{}),{pending:s,localIssues:o}=await Mw({replicaId:this.replicaId,state:e,pathPolicy:await this.currentRecordPathPolicy(e),fileSystem:this.fileSystem,runtime:this.runtime,pathSelected:l=>tr(this.selectiveSync,l)});e.local_issues=o,e.pending.push(...s),await Dw({state:e,fileSystem:this.fileSystem,blobStore:this.blobStore,selectiveSync:this.selectiveSync,runtime:this.runtime}),(e.pending.length!==t||e.pending_files.length!==n||JSON.stringify((c=e.local_issues)!=null?c:{})!==i)&&await this.writeState(e)}async flushPendingFiles(e){await qw(e,this.transport,this.blobStore,()=>this.writeState(e))}async flushPending(e){var a,c,l;let t=(a=e.pending)!=null?a:e.pending=[],n=0,i=0,s=t.filter(u=>{var d;return!((d=e.conflicts)!=null&&d[u.mutation.record_id])}).length,o=0;for(;n=qf&&(await this.writeState(e),i=0);continue}(l=e.conflicts)!=null||(e.conflicts={}),e.conflicts[u.mutation.record_id]=p,i+=1,i>=qf&&(await this.writeState(e),i=0),n+=1}i>0&&await this.writeState(e),s>0&&this.reportProgress({phase:"uploading",completed:o,total:s,done:!0})}async readState(){let e=await this.stateStore.read();if(e===null)return null;try{return Ew(e,this.replicaId,this.mode)}catch(t){throw t instanceof S?t:new S("invalid_mirror_state","Mirror metadata is corrupt or belongs to another replica.")}}async writeState(e){await this.stateStore.write(e)}async pruneFileBlobs(){var n,i;if(!this.blobStore)return;let e=await this.readState();if(!e)return;let t=new Set;for(let s of Object.values((n=e.files)!=null?n:{}))t.add(s.file.content_digest);for(let s of(i=e.pending_files)!=null?i:[])"content_digest"in s&&t.add(s.content_digest);await this.blobStore.prune(t)}reportProgress(e){var t;(t=this.onProgress)==null||t.call(this,e)}async currentRecordPathPolicy(e){return this.materializer.recordPathPolicy(e)}preflightProjectedPaths(e,t){var s,o;let n=new Map(Object.entries(e.records).map(([a,c])=>[a,c.path])),i=new Map(Object.entries((s=e.files)!=null?s:{}).map(([a,c])=>[a,c.file.path]));for(let a of t)a.type==="put"?tr(this.selectiveSync,a.record.path)?n.set(a.record.record_id,a.record.path):n.delete(a.record.record_id):a.type==="remove"?n.delete(a.record_id):a.type==="file_put"?on(this.selectiveSync,a.file)?i.set(a.file.file_id,a.file.path):i.delete(a.file.file_id):i.delete(a.file_id);rr([...Object.keys((o=e.resources)!=null?o:{}),...n.values(),...i.values()])}};var Zs=class extends Tn{constructor(e,t,n){super(e,t,n,"read_write")}};var eo=".mdbase/connect-role.json",to=".mdbase/authority-adoption.json",ro=".mdbase/authority-adoption-snapshot.json",IR="mdbase-obsidian-connect",Ii="mirrors",OR="mdbase-connect-access-",TR="mdbase-connect-refresh-",RR="mdbase-connect-adoption-",CR=300*1e3,Bf=[".git/",".obsidian/",".trash/",".mdbase/"],no=/^[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 Ac(r,e){if(e!=null)return e;if(!r.trim())return{};try{return JSON.parse(r)}catch(t){return{}}}function Bw(r){var i;let e=(i=r["retry-after"])!=null?i:r["Retry-After"];if(!e)return;let t=Number(e);if(Number.isFinite(t)&&t>=0)return t*1e3;let n=Date.parse(e);if(Number.isFinite(n))return Math.max(0,n-Date.now())}function MR(){return async r=>{var t,n;if((t=r.signal)!=null&&t.aborted)throw new DOMException("Enrollment cancelled.","AbortError");let e=await(0,ae.requestUrl)({url:r.url,method:r.method,headers:r.headers,body:r.body===void 0?void 0:JSON.stringify(r.body),contentType:r.body===void 0?void 0:"application/json",throw:!1});if((n=r.signal)!=null&&n.aborted)throw new DOMException("Enrollment cancelled.","AbortError");return{status:e.status,body:Ac(e.text,e.json),retryAfterMs:Bw(e.headers)}}}function NR(){return async r=>{var t,n;if((t=r.signal)!=null&&t.aborted)throw new DOMException("Collection adoption cancelled.","AbortError");let e=await(0,ae.requestUrl)({url:r.url,method:r.method,headers:r.headers,body:r.body===void 0?void 0:JSON.stringify(r.body),contentType:r.body===void 0?void 0:"application/json",throw:!1});if((n=r.signal)!=null&&n.aborted)throw new DOMException("Collection adoption cancelled.","AbortError");return{status:e.status,body:Ac(e.text,e.json),retryAfterMs:Bw(e.headers)}}}var zf=class{constructor(e,t){this.accessToken=t;let n;try{n=new URL(e)}catch(i){throw new S("invalid_sync_url","Sync URL must be an absolute authority endpoint.")}if(!(n.protocol==="https:"||n.protocol==="http:"&&["localhost","127.0.0.1","[::1]","::1"].includes(n.hostname))||n.username||n.password||n.search||n.hash||!/^\/v1\/authorities\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\/sync\/?$/i.test(n.pathname))throw new S("invalid_sync_url","Sync URL must identify one authority sync endpoint.");this.syncUrl=n.href.replace(/\/$/,""),this.filesUrl=this.syncUrl.replace(/\/sync$/,"/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){let t=crypto.randomUUID();try{let n=await this.fileRequest("POST","downloads",{protocol_version:1,type:"open_file_download",transfer_id:t,file_id:e.file_id,revision:e.revision}),i=ze(n.strategy)?n.strategy:{},s=i.part_size;if(n.protocol_version!==1||n.type!=="file_transfer"||n.transfer_id!==t||n.direction!=="download"||n.protection!=="transport_tls"||n.total_size!==e.size||i.kind!=="object_ranges"||!Number.isSafeInteger(s)||s<=0)throw new S("invalid_sync_response","The authority returned an incompatible file download session.");let o=Math.ceil(e.size/s);for(let a=0;a=300){let u=Ac(l.text,l.json),d=ze(u)&&ze(u.error)?u.error:{};throw new S(typeof d.code=="string"?d.code:"file_download_failed",typeof d.message=="string"?d.message:`File download failed (${l.status}).`)}if(l.arrayBuffer.byteLength!==c)throw new S("file_integrity_failed","The authority returned a file part with the wrong length.");yield new Uint8Array(l.arrayBuffer)}}finally{await this.fileRequest("DELETE",`transfers/${encodeURIComponent(t)}`).catch(()=>{})}}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)}request(e,t,n){return this.requestAt(this.syncUrl,e,t,n)}fileRequest(e,t,n){return this.requestAt(this.filesUrl,e,t,n)}async requestAt(e,t,n,i){let s=await(0,ae.requestUrl)({url:`${e}/${n}`,method:t,headers:{authorization:`Bearer ${this.accessToken}`},body:i===void 0?void 0:JSON.stringify(i),contentType:i===void 0?void 0:"application/json",throw:!1}),o=Ac(s.text,s.json);if(s.status<200||s.status>=300){let a=ze(o)&&ze(o.error)?o.error:{};throw new S(typeof a.code=="string"?a.code:"sync_failed",typeof a.message=="string"?a.message:`Sync request failed (${s.status}).`)}return o}};function Oi(r){let e=As(r);if(e===".mdbase"||Bf.some(t=>e.startsWith(t)))throw new S("unsafe_mirror_path",`The collection authority attempted to write a reserved path: ${e}`);return e}async function io(r,e){let t=(0,ae.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 ae.TFolder)){if(s)throw new S("mirror_path_collision",`A file blocks the mirror folder ${n}.`);await r.adapter.exists(n)||await r.createFolder(n)}}}var Hf=class{constructor(e){this.vault=e}async read(e){let t=Oi(e),n=this.vault.getAbstractFileByPath(t);if(n==null)return null;if(!(n instanceof ae.TFile))throw new S("mirror_path_collision",`Expected a file at ${t}.`);return this.vault.cachedRead(n)}async write(e,t){let n=Oi(e),i=n.lastIndexOf("/");i>=0&&await io(this.vault,n.slice(0,i));let s=this.vault.getAbstractFileByPath(n);if(s instanceof ae.TFolder)throw new S("mirror_path_collision",`A folder blocks the mirror file ${n}.`);s instanceof ae.TFile?await this.vault.modify(s,t):await this.vault.create(n,t)}async remove(e){let t=Oi(e),n=this.vault.getAbstractFileByPath(t);if(n!=null){if(!(n instanceof ae.TFile))throw new S("mirror_path_collision",`Expected a file at ${t}.`);await this.vault.delete(n,!0)}}async listMarkdown(e){return this.vault.getMarkdownFiles().map(t=>(0,ae.normalizePath)(t.path)).filter(t=>!e.has(t)).filter(t=>!Bf.some(n=>t.startsWith(n))).sort()}async inspectBinary(e){let t=Oi(e),n=this.vault.getAbstractFileByPath(t);if(n==null)return null;if(!(n instanceof ae.TFile))throw new S("mirror_path_collision",`Expected a file at ${t}.`);let i=await this.vault.readBinary(n),s=await crypto.subtle.digest("SHA-256",i),o=Array.from(new Uint8Array(s),a=>a.toString(16).padStart(2,"0")).join("");return{size:i.byteLength,content_digest:`sha256:${o}`}}async writeBinary(e,t){let n=Oi(e),i=[],s=0;for await(let u of t){if(!(u instanceof Uint8Array)||!Number.isSafeInteger(s+u.byteLength))throw new S("invalid_file_materialization","The binary file stream is invalid or too large.");i.push(u),s+=u.byteLength}let o=new Uint8Array(s),a=0;for(let u of i)o.set(u,a),a+=u.byteLength;let c=n.lastIndexOf("/");c>=0&&await io(this.vault,n.slice(0,c));let l=this.vault.getAbstractFileByPath(n);if(l instanceof ae.TFolder)throw new S("mirror_path_collision",`A folder blocks the mirror file ${n}.`);l instanceof ae.TFile?await this.vault.modifyBinary(l,o.buffer):await this.vault.createBinary(n,o.buffer)}async listBinary(e){return this.vault.getFiles().map(t=>(0,ae.normalizePath)(t.path)).filter(t=>!t.toLowerCase().endsWith(".md")).filter(t=>!e.has(t)).filter(t=>!Bf.some(n=>t.startsWith(n))).sort()}async readBinary(e){let t=Oi(e),n=this.vault.getAbstractFileByPath(t);if(n==null)return null;if(!(n instanceof ae.TFile))throw new S("mirror_path_collision",`Expected a file at ${t}.`);let i=new Uint8Array(await this.vault.readBinary(n));return(async function*(){yield i})()}},Kf=class{constructor(e){this.key=e;this.database=null}async read(){let e=await this.open();return new Promise((t,n)=>{let i=e.transaction(Ii,"readonly").objectStore(Ii).get(this.key);i.onsuccess=()=>{var s;return t((s=i.result)!=null?s:null)},i.onerror=()=>n(i.error)})}async write(e){let t=await this.open();await new Promise((n,i)=>{let s=t.transaction(Ii,"readwrite");s.objectStore(Ii).put(e,this.key),s.oncomplete=()=>n(),s.onerror=()=>i(s.error),s.onabort=()=>i(s.error)})}open(){var e;if(typeof indexedDB=="undefined")throw new S("storage_unavailable","IndexedDB is required for persistent mirror state.");return(e=this.database)!=null||(this.database=new Promise((t,n)=>{let i=indexedDB.open(IR,1);i.onupgradeneeded=()=>{i.result.objectStoreNames.contains(Ii)||i.result.createObjectStore(Ii)},i.onerror=()=>n(i.error),i.onsuccess=()=>t(i.result)})),this.database}},Ti=class Ti{constructor(e){this.key=e}async runExclusive(e){if(Ti.active.has(this.key))throw new S("mirror_busy","A mirror operation is already running for this vault.");Ti.active.add(this.key);try{return await e()}finally{Ti.active.delete(this.key)}}};Ti.active=new Set;var Wf=Ti,kc=class{constructor(e,t,n={}){this.app=e;this.settingsHost=t;this.options=n;this.progress=null;this.adoptionMarker=null;var i,s,o;this.fileSystem=(i=n.fileSystem)!=null?i:new Hf(e.vault),this.enrollmentClient=(s=n.enrollmentClient)!=null?s:new uc({request:MR()}),this.adoptionClient=(o=n.adoptionClient)!=null?o:new gc({request:NR()})}async initialize(){if(this.adoptionMarker=await this.readAdoptionMarker(),this.adoptionMarker&&this.settingsHost.getMirrorProfile())throw new S("authority_adoption_state_conflict","This vault contains both an authority-adoption checkpoint and a mirror profile.")}getProgress(){return this.progress?{...this.progress}:null}getAdoptionMarker(){return this.adoptionMarker?JSON.parse(JSON.stringify(this.adoptionMarker)):null}assertLocalAuthorityWritable(){if(this.adoptionMarker&&["fenced","activating","adopted"].includes(this.adoptionMarker.phase))throw new S("local_authority_fenced",this.adoptionMarker.phase==="adopted"?"Hosted mdbase is now authoritative. Finish reconnecting this vault as its mirror before editing.":"This local authority is frozen while its exact snapshot is adopted by hosted mdbase.")}async adoptLocalCollection(e,t){if(this.settingsHost.getMirrorProfile())throw new S("mirror_already_configured","This vault already mirrors a collection authority.");if(this.adoptionMarker)return this.resumeAdoption(t);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);return await this.storeAdoptionSecret(i),await this.writeAdoptionMarker({version:1,phase:"waiting_for_approval",session:Uf(i),manifest_digest:null,source_revision:null,source_head:null}),await t.onVerification(Uf(i)),this.runAdoptionWithRecovery(i,t)}async resumeAdoption(e={}){var s,o,a;let t=(s=this.adoptionMarker)!=null?s:await this.readAdoptionMarker();if(!t)throw new S("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 S("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((o=e.onVerification)==null?void 0:o.call(e,Uf(i))),this.runAdoptionWithRecovery(i,{...e,onVerification:(a=e.onVerification)!=null?a:(()=>{})})}async cancelAdoption(e){var i;let t=(i=this.adoptionMarker)!=null?i:await this.readAdoptionMarker();if(!t)return;if(["activating","adopted"].includes(t.phase))throw new S("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 S("authority_adoption_credentials_missing","The collection-adoption credential is missing from Obsidian's secret store.");await this.adoptionClient.cancel({...t.session,credential:n},{signal:e}),await this.clearAdoptionCheckpoint(t.session.adoptionId)}async enroll(e,t){let n=await this.assertCanBecomeMirror(e.collectionId),i=await this.enrollmentClient.enroll({...e,...n?{collectionId:n}:{}},t),s=await this.markMirror(i.collectionId);try{await this.persistEnrollment(i)}catch(o){if(s)try{await this.app.vault.adapter.remove(eo)}catch(a){throw new S("enrollment_recovery_required",`Enrollment settings could not be saved and the temporary role marker could not be removed: ${o instanceof Error?o.message:String(o)}`)}throw o}return this.requireProfile()}async preview(){return(await this.createMirror()).previewInitialization()}async status(){let e=this.settingsHost.getMirrorProfile();return e?(await this.assertMirror(e.collectionId),(await this.createMirror()).status()):null}async sync(e){let t=await this.createMirror(n=>{this.progress=n,e==null||e({...n})});try{return await t.sync(),t.status()}finally{this.progress=null}}async resolveConflict(e,t){let n=await this.createMirror();return await n.resolveConflict(e,t),n.status()}async runAdoption(e,t){let n=this.requireAdoptionMarker(e.adoptionId),i=null;if(n.phase==="adopted"){let s=await this.adoptionClient.exchange(e,t);if(s.status!=="completed")throw new S("authority_adoption_state_conflict","The local checkpoint says adoption completed, but Connect does not.");i=s}else if(n.phase==="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"&&await this.adoptionClient.uploadSnapshot(e,o,s,t),await this.updateAdoptionPhase("activating",s),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),o=await this.captureAuthoritySnapshot(e.requested.collectionId);await this.updateAdoptionPhase("uploading"),await this.adoptionClient.uploadSnapshot(e,s,o,t);let a=await this.captureAuthoritySnapshot(e.requested.collectionId);await this.writeAdoptionSnapshot(a),await this.updateAdoptionPhase("fenced",a);let c=await this.requirePreparedAdoption(e,t);await this.adoptionClient.uploadSnapshot(e,c,a,t),await this.updateAdoptionPhase("activating",a),i=await this.adoptionClient.complete(e,a,t)}return await this.updateAdoptionPhase("adopted"),this.finishRetainedMirror(e,i,t)}async runAdoptionWithRecovery(e,t){try{return await this.runAdoption(e,t)}catch(n){throw LR(n)?(await this.adoptionClient.cancel(e,{signal:t.signal}).catch(()=>{}),await this.clearAdoptionCheckpoint(e.adoptionId),new S(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 Cr("Hosted authority activation has already started. Resume using the saved fenced snapshot."):new S("authority_adoption_already_completed","Hosted authority has already adopted this collection.")}async finishRetainedMirror(e,t,n){var a,c;let i,s=this.adoptionClient.mirrorEnrollmentSession(e,t);if(!s)throw new S("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:l=>{var u;return(u=n.onStatus)==null?void 0:u.call(n,{...l,state:l.state})}})}catch(l){if((a=n.signal)!=null&&a.aborted)throw l;i=await this.enrollmentClient.enroll({controlUrl:e.controlUrl,collectionId:e.requested.collectionId,mirrorName:(c=e.requested.mirrorName)!=null?c:e.requested.sourceName,mode:"read_write"},{signal:n.signal,onVerification:n.onVerification})}let o=await this.markMirror(i.collectionId);try{await this.persistEnrollment(i)}catch(l){throw o&&await this.app.vault.adapter.remove(eo),l}return await this.clearAdoptionCheckpoint(e.adoptionId),this.requireProfile()}async captureAuthoritySnapshot(e){let t=await ci(this.app.vault);if(!t)throw new S("invalid_collection_configuration","A valid mdbase.yaml is required.");let n=await this.app.vault.adapter.read("mdbase.yaml"),i=(0,ae.parseYaml)(n),s=[{path:"mdbase.yaml",kind:"configuration",document:n}],o=`${(0,ae.normalizePath)(t.settings.types_folder)}/`,a=this.app.vault.getMarkdownFiles().filter(u=>(0,ae.normalizePath)(u.path).startsWith(o)).sort((u,d)=>u.path.localeCompare(d.path));for(let u of a)s.push({path:(0,ae.normalizePath)(u.path),kind:"type",document:await this.app.vault.cachedRead(u)});let c=DR(i);if(c.length){let u=c.map(f=>(0,Uw.default)(f,{dot:!0})),d=qR(this.app.vault).filter(f=>f.extension==="base").filter(f=>u.some(p=>p((0,ae.normalizePath)(f.path)))).sort((f,p)=>f.path.localeCompare(p.path));for(let f of d)s.push({path:(0,ae.normalizePath)(f.path),kind:"view",document:await this.app.vault.cachedRead(f)})}let l=[];for(let u of this.app.vault.getMarkdownFiles().sort((d,f)=>d.path.localeCompare(f.path))){let d=(0,ae.normalizePath)(u.path);if(ks(d,t))continue;let f=await this.app.vault.cachedRead(u);l.push({path:d,document:f})}return Cf({collectionId:e,sourceHead:0,specVersion:t.spec_version,resources:s,records:l})}async ensurePortableCollectionIdentity(){if(!await this.app.vault.adapter.exists("mdbase.yaml"))throw new S("collection_not_initialized","Initialize an mdbase collection before hosting it.");let e=await this.app.vault.adapter.read("mdbase.yaml"),t;try{t=(0,ae.parseYaml)(e)}catch(o){throw new S("invalid_collection_configuration","mdbase.yaml must contain valid YAML.")}if(!ze(t))throw new S("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},await this.app.vault.adapter.write("mdbase.yaml",(0,ae.stringifyYaml)(t))}else if(typeof n=="string"&&no.test(n))i=n;else throw new S("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}}async createMirror(e){var o,a,c,l,u,d,f,p,m;let t=this.requireProfile();await this.assertMirror(t.collectionId);let n=await this.freshAccessToken(t),i=(c=(a=(o=this.options).transportFactory)==null?void 0:a.call(o,t,n))!=null?c:new zf(t.syncUrl,n),s={stateStore:(d=(u=(l=this.options).stateStoreFactory)==null?void 0:u.call(l,t))!=null?d:new Kf(`${t.collectionId}:${t.replicaId}`),fileSystem:this.fileSystem,lease:(m=(p=(f=this.options).leaseFactory)==null?void 0:p.call(f,t))!=null?m:new Wf(`${t.collectionId}:${t.replicaId}`),onProgress:e};return t.mode==="read_write"?new Zs(t.replicaId,i,s):new Tn(t.replicaId,i,s)}requireProfile(){let e=this.settingsHost.getMirrorProfile();if(!e)throw new S("mirror_not_configured","This vault is not connected to a collection authority.");return e}accessSecretId(e){return`${OR}${e.toLowerCase()}`}refreshSecretId(e){return`${TR}${e.toLowerCase()}`}adoptionSecretId(e){return`${RR}${e.toLowerCase()}`}async storeAdoptionSecret(e){this.app.secretStorage.setSecret(this.adoptionSecretId(e.adoptionId),e.credential)}async persistEnrollment(e){this.app.secretStorage.setSecret(this.accessSecretId(e.collectionId),e.accessToken),this.app.secretStorage.setSecret(this.refreshSecretId(e.collectionId),e.refreshCredential),await this.settingsHost.saveMirrorProfile({version:1,syncUrl:e.syncUrl,controlUrl:e.controlUrl,collectionId:e.collectionId,replicaId:e.replicaId,mode:e.mode,name:e.name,enrollmentId:e.enrollmentId,accessTokenExpiresAt:e.accessTokenExpiresAt})}async freshAccessToken(e){let t=this.accessSecretId(e.collectionId),n=this.app.secretStorage.getSecret(t),i=Date.parse(e.accessTokenExpiresAt);if(n&&Number.isFinite(i)&&i-Date.now()>CR)return n;let s=this.app.secretStorage.getSecret(this.refreshSecretId(e.collectionId));if(!s)throw new S("mirror_credentials_missing","The mirror refresh credential is missing. Re-enroll this vault.");let o=await this.enrollmentClient.renew({controlUrl:e.controlUrl,syncUrl:e.syncUrl,collectionId:e.collectionId,replicaId:e.replicaId,mode:e.mode,name:e.name,enrollmentId:e.enrollmentId,accessToken:n!=null?n:"",refreshCredential:s,accessTokenExpiresAt:e.accessTokenExpiresAt});return await this.persistEnrollment(o),o.accessToken}async assertCanBecomeMirror(e){var o;let t=await this.readMarker(),n=await this.readPortableCollectionId();if(n&&!t)throw new S("local_authority_requires_transfer","This vault has a local Connect identity. Transfer authority explicitly before using it as a mirror.");if(n&&(t==null?void 0:t.collection_id)!==n)throw new S("mirror_identity_conflict","The vault identity and mirror role marker identify different collections.");let i=this.settingsHost.getMirrorProfile(),s=(o=i==null?void 0:i.collectionId)!=null?o:e;if(t&&s&&t.collection_id!==s)throw new S("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 S("existing_collection_requires_transfer","This vault already contains an mdbase collection. Connect an empty vault, or transfer collection authority explicitly.");return s!=null?s:t==null?void 0:t.collection_id}async readPortableCollectionId(){if(!await this.app.vault.adapter.exists("mdbase.yaml"))return null;let e;try{e=(0,ae.parseYaml)(await this.app.vault.adapter.read("mdbase.yaml"))}catch(i){throw new S("invalid_collection_configuration","mdbase.yaml must contain valid YAML.")}if(!ze(e))throw new S("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 S("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"||!no.test(n))throw new S("invalid_collection_configuration","x-mdbase-connect.collection_id must be a UUID string.");return n}async markMirror(e){let t=await this.readMarker();if(t){if(t.collection_id!==e)throw new S("mirror_identity_conflict","This vault already mirrors a different collection authority.");return!1}return await io(this.app.vault,".mdbase"),await this.app.vault.adapter.write(eo,`${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 S("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(eo))return null;let e;try{e=JSON.parse(await this.app.vault.adapter.read(eo))}catch(t){throw new S("invalid_mirror_marker","The mirror role marker is corrupt.")}if(!ze(e)||e.version!==1||e.role!=="mirror"||typeof e.collection_id!="string"||!no.test(e.collection_id))throw new S("invalid_mirror_marker","The mirror role marker is invalid.");return e}requireAdoptionMarker(e){if(!this.adoptionMarker||this.adoptionMarker.session.adoptionId!==e)throw new S("authority_adoption_state_conflict","The collection-adoption checkpoint does not match this approval.");return this.adoptionMarker}async updateAdoptionPhase(e,t){if(!this.adoptionMarker)throw new S("authority_adoption_not_found","Collection-adoption checkpoint is missing.");await this.writeAdoptionMarker({...this.adoptionMarker,phase:e,...t?{manifest_digest:t.manifest_digest,source_revision:t.source_revision,source_head:t.source_head}:{}})}async writeAdoptionMarker(e){await io(this.app.vault,".mdbase"),await this.app.vault.adapter.write(to,`${JSON.stringify(e,null,2)} -`),this.adoptionMarker=e}async readAdoptionMarker(){if(!await this.app.vault.adapter.exists(to))return null;let e;try{e=JSON.parse(await this.app.vault.adapter.read(to))}catch(t){throw new S("invalid_authority_adoption_checkpoint","The collection-adoption checkpoint is corrupt.")}if(!jR(e))throw new S("invalid_authority_adoption_checkpoint","The collection-adoption checkpoint is invalid.");return e}async writeAdoptionSnapshot(e){await io(this.app.vault,".mdbase"),await this.app.vault.adapter.write(ro,JSON.stringify(e))}async readAdoptionSnapshot(e){if(!await this.app.vault.adapter.exists(ro))throw new S("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(ro))}catch(n){throw new S("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 S("authority_adoption_snapshot_mismatch","The fenced authority snapshot does not match its durable checkpoint.");return t}async clearAdoptionCheckpoint(e){await this.app.vault.adapter.exists(to)&&await this.app.vault.adapter.remove(to),await this.app.vault.adapter.exists(ro)&&await this.app.vault.adapter.remove(ro),this.app.secretStorage.setSecret(this.adoptionSecretId(e),""),this.adoptionMarker=null}};function Uf(r){let{credential:e,...t}=r;return t}function LR(r){return r instanceof Y&&["authority_adoption_expired","authority_adoption_cancelled"].includes(r.code)}function DR(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 qR(r){var i;let e=(i=r.getFiles)==null?void 0:i.call(r);if(e)return e;let t=[],n=s=>{for(let o of s.children)o instanceof ae.TFile?t.push(o):o instanceof ae.TFolder&&n(o)};return n(r.getRoot()),t}function jR(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"&&no.test(e.adoptionId)&&typeof e.verificationUri=="string"&&typeof e.expiresAt=="string"&&ze(e.requested)&&typeof e.requested.collectionId=="string"&&no.test(e.requested.collectionId)&&typeof e.requested.displayName=="string"&&typeof e.requested.sourceName=="string"&&e.requested.retainMirror===!0&&(r.manifest_digest===null||typeof r.manifest_digest=="string")&&(r.source_revision===null||typeof r.source_revision=="string")&&(r.source_head===null||Number.isSafeInteger(r.source_head))}var ct=require("obsidian");var co="0.3.0",FR=new Set(["name","description","display_name_key","strict","path_pattern","filename_pattern","match","fields","extends"]),VR=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 Se(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function De(r){return r===void 0?r:JSON.parse(JSON.stringify(r))}function Dr(r){return Qs.digest(r)}function Rn(r){return Array.isArray(r)?`[${r.map(Rn).join(",")}]`:Se(r)?`{${Object.keys(r).sort().map(e=>`${JSON.stringify(e)}:${Rn(r[e])}`).join(",")}}`:JSON.stringify(r)}function Gf(r){if(Array.isArray(r))return r.map(Gf);if(!Se(r))return r;let e={};for(let[t,n]of Object.entries(r)){let i=Gf(n);i!=null&&(Array.isArray(i)&&i.length===0||Se(i)&&Object.keys(i).length===0||(e[t]=i))}return e}function Ri(r){return[...new Set(r)]}function UR(r){return Se(r.fields)?Object.values(r.fields).some(e=>Se(e)&&(typeof e.tn_role=="string"||Array.isArray(e.tn_completed_values))):!1}function Jf(r,e,t){let n=Se(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)?De(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=Jf(`${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(Se(n.fields)?n.fields:{})){let f=Jf(`${r}.${u}`,d,t);c[u]=f.schema,Object.assign(i,f.links),Object.assign(s,f.legacy),o.push(...f.unsupported),Se(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:Ri(l)}:{}};break}default:a={},o.push(`${r}.type`);break}t&&r==="title"&&(a.minLength=1,a.description="Short summary of the task."),typeof n.description=="string"&&(a.description=n.description),typeof n.min=="number"&&(n.type==="string"?a.minLength=n.min:n.type==="list"?a.minItems=n.min:a.minimum=n.min),typeof n.max=="number"&&(n.type==="string"?a.maxLength=n.max:n.type==="list"?a.maxItems=n.max:a.maximum=n.max),typeof n.min_length=="number"&&(a.minLength=n.min_length),typeof n.max_length=="number"&&(a.maxLength=n.max_length),typeof n.pattern=="string"&&(a.pattern=n.pattern),n.deprecated===!0&&(a.deprecated=!0),n.default!==void 0&&(a.default=De(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");(!VR.has(c)||(c==="tn_role"||c==="tn_completed_values")&&!u)&&(s[`${r}.${c}`]=De(l))}return{schema:a,links:i,legacy:s,unsupported:o}}function so(r,e,t,n){let i=Se(r[e])?r[e]:{},s=Se(i.set)?i.set:{};s[t]=n,i.set=s,r[e]=i}function BR(r,e,t){if(t==="now")so(r,"on_create",e,{now:!0});else if(t==="now_on_write")so(r,"on_update",e,{now:!0});else if(t==="uuid")so(r,"on_create",e,{uuid:!0});else if(t==="ulid")so(r,"on_create",e,{ulid:!0});else if(Se(t)&&t.transform==="slugify"&&typeof t.from=="string")so(r,"on_create",e,{slugify:t.from});else return!1;return!0}function zR(r){var t;let e=r.match(/^(.*\/)?\{title\}\.md$/);return e?{runtime:"tasknotes",template:"{{title}}",folder:((t=e[1])!=null?t:"").replace(/\/$/,""),generated_by:"tasknotes.filename.create"}:{runtime:"tasknotes",template:r,generated_by:"tasknotes.filename.create"}}function HR(r,e,t){var E;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"||!Se(t.fields))throw new Error(`${r} is not a v0.2 type with a name and fields.`);let n=UR(t),i=t.name.trim().toLowerCase(),s={type:{const:i}},o=[],a={},c={},l=[],u={},d={},f=[],p=[],m={},h={},y={};for(let[O,w]of Object.entries(t.fields)){let x=Se(w)?w:{},$=Jf(O,x,n);s[O]=$.schema,Object.assign(c,$.links),Object.assign(d,$.legacy),f.push(...$.unsupported),x.required===!0&&o.push(O),x.default!==void 0&&(a[O]=De(x.default)),x.unique===!0&&l.push({field:O,scope:"collection"}),x.generated!==void 0&&BR(u,O,x.generated)&&p.push(O),typeof x.tn_role=="string"&&(m[x.tn_role]=O),Array.isArray(x.tn_completed_values)&&(h.completed_values=De(x.tn_completed_values))}a.status!==void 0&&(h.default=De(a.status)),a.priority!==void 0&&(y.default=De(a.priority));let b=typeof t.display_name_key=="string"&&Object.prototype.hasOwnProperty.call(t.fields,t.display_name_key)?t.display_name_key:void 0,g={...b?{display:{name_field:b}}:{},read_defaults:a,links:c,unique:l};typeof t.path_pattern=="string"&&(g.path=n?zR(t.path_pattern):{pattern:t.path_pattern});let _={};for(let[O,w]of Object.entries(t))FR.has(O)||(_[O]=De(w));Object.keys(d).length&&(_.fields=d);let k=Gf({kind:"mdbase.type",name:i,version:1,description:typeof t.description=="string"?t.description:void 0,match:Se(t.match)?De(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:Ri(o)}:{}}},collection:g,lifecycle:u,...n?{"x-tasknotes":{contract:"tasknotes.task",version:1,field_roles:m,status:h,priority:y,archive:{tags_field:(E=m.tags)!=null?E:"tags",archived_tag:"archived"}}}:{},...Object.keys(_).length?{"x-legacy-v0.2":_}:{}}),v=[];t.extends!==void 0&&f.push("extends");for(let O of Ri(f).sort())v.push({path:r,code:"migration_lossy",message:`${O} cannot be expressed as canonical v0.3 write behavior and was retained as legacy metadata where possible.`,severity:"lossy"});return n&&v.push({path:r,code:"path_policy_runtime_owned",message:"TaskNotes filename behavior is recorded as TaskNotes runtime metadata.",severity:"warning"}),t.strict!==!0&&v.push({path:r,code:"additional_properties_true",message:"The migrated schema allows additional properties because the source type was not strict.",severity:"warning"}),typeof t.display_name_key=="string"&&!b&&v.push({path:r,code:"display_field_missing",message:`The display field '${t.display_name_key}' is not declared, so collection.display was omitted.`,severity:"warning"}),{target:k,summary:{path:r,name:i,fieldsConverted:Object.keys(t.fields).length,requiredFields:Ri(o),defaultsMoved:Object.keys(a),generatedFieldsMoved:Ri(p),linksMoved:Object.keys(c),taskNotes:n},diagnostics:v}}function KR(r){let e=De(r);e.spec_version=co;let t=Se(e.settings)?e.settings:{};if(e.settings=t,!Array.isArray(t.record_extensions)){let n=Array.isArray(t.extensions)?t.extensions.map(String).map(i=>i.replace(/^\./,"")):[];t.record_extensions=Ri(["md",...n])}return Array.isArray(t.explicit_type_keys)||(t.explicit_type_keys=["type","types"]),typeof t.include_subfolders!="boolean"&&(t.include_subfolders=!0),t.validation===void 0&&typeof t.default_validation=="string"&&(t.validation=t.default_validation),t.validation===void 0&&typeof e.default_validation=="string"&&(t.validation=e.default_validation),delete t.default_validation,delete t.extensions,delete e.default_validation,e}function zw(r,e){let t=Se(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 WR(r,e){var n,i;let t={};for(let[s,o]of Object.entries(Se(e.fields)?e.fields:{}))Se(o)&&(t[s]=De(o));return{name:typeof e.name=="string"?e.name:(i=(n=r.split("/").pop())==null?void 0:n.replace(/\.md$/,""))!=null?i:"type",fields:t,match:Se(e.match)?De(e.match):void 0,filePath:r,specProfile:"v0.2"}}function GR(r,e){var i,s;let t=Se(e.schema)?e.schema:{},n=Se(t.value)?t.value:{};return{name:typeof e.name=="string"?e.name:(s=(i=r.split("/").pop())==null?void 0:i.replace(/\.md$/,""))!=null?s:"type",fields:$n(n),match:Se(e.match)?De(e.match):void 0,collection:Se(e.collection)?De(e.collection):void 0,schema:De(n),filePath:r,specProfile:"v0.3"}}function JR(r,e,t){let n=De(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]=De(a.default))}return n}function YR(r,e,t){var i,s;let n=De(r);for(let o of e){let a=t.get(o);if(a)for(let[c,l]of Object.entries((s=(i=a.collection)==null?void 0:i.read_defaults)!=null?s:{}))c in n||(n[c]=De(l))}return n}async function XR(r,e){let t=(0,ct.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 ct.TFolder)){if(s)throw new Error(`A file blocks folder ${n}.`);await r.adapter.exists(n)||await r.createFolder(n)}}}async function xc(r,e,t){let n=(0,ct.normalizePath)(e),i=n.lastIndexOf("/");if(i>=0&&await XR(r,n.slice(0,i)),n.startsWith(".mdbase/")){await r.adapter.write(n,t);return}let s=r.getAbstractFileByPath(n);if(s instanceof ct.TFolder)throw new Error(`A folder blocks file ${n}.`);s instanceof ct.TFile?await r.modify(s,t):await r.create(n,t)}async function ao(r,e){let t=(0,ct.normalizePath)(e),n=r.getAbstractFileByPath(t);if(n instanceof ct.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 Hw(r){var k;let e=await ao(r,"mdbase.yaml"),t=(0,ct.parseYaml)(e);if(!Se(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===co?"This collection is already mdbase v0.3.":`Expected an mdbase v0.2.x collection, found ${JSON.stringify(n)}.`);let i=Se(t.settings)?t.settings:{},s=typeof i.types_folder=="string"?(0,ct.normalizePath)(i.types_folder):"_types",o=`${s}/`,a=[],c=[],l=[],u=KR(t),d=`${(0,ct.stringifyYaml)(u).trimEnd()} -`;a.push({path:"mdbase.yaml",sourceDigest:Dr(e),targetDigest:Dr(d),source:e,target:d});let f=new Map,p=new Map;for(let v of r.getMarkdownFiles().filter(E=>E.path.startsWith(o)).sort((E,O)=>E.path.localeCompare(O.path))){let E=await r.cachedRead(v),O=Ct(E);if(!O.hasFrontmatter||O.error)throw new Error(`Cannot migrate ${v.path}: ${(k=O.error)!=null?k:"frontmatter is missing"}.`);let w=HR(v.path,n,O.frontmatter),x=WR(v.path,O.frontmatter),$=GR(v.path,w.target);f.set(x.name,x),p.set($.name,$);let L=`${wt(w.target,O.body)} -`;a.push({path:v.path,sourceDigest:Dr(E),targetDigest:Dr(L),source:E,target:L}),c.push(w.summary),l.push(...w.diagnostics)}if(!c.length)throw new Error(`No v0.2 type files were found in ${s}.`);let m=0,h=0,y=zw(t,n),b=zw(u,co),g=r.getMarkdownFiles().filter(v=>!v.path.startsWith(o)).filter(v=>!v.path.startsWith(".mdbase/")).sort((v,E)=>v.path.localeCompare(E.path));for(let[v,E]of g.entries()){let O=Ct(await r.cachedRead(E));if(O.error){h+=1;continue}let w=li(E.path,O.frontmatter,y,f),x=li(E.path,O.frontmatter,b,p),$=JR(O.frontmatter,w,f),L=YR(O.frontmatter,x,p);(Rn(w.slice().sort())!==Rn(x.slice().sort())||Rn($)!==Rn(L))&&l.push({path:E.path,code:"effective_read_changed",message:"The proposed v0.3 types would change this record's resolved types or effective default values.",severity:"lossy"}),m+=1,v>0&&v%250===0&&await new Promise(F=>setTimeout(F,0))}let _=Dr(Rn({sourceVersion:n,operations:a.map(({path:v,sourceDigest:E,targetDigest:O})=>({path:v,sourceDigest:E,targetDigest:O})),diagnostics:l}));return{planVersion:1,analysisId:_,sourceVersion:n,targetVersion:co,createdAt:new Date().toISOString(),backupLocation:`.mdbase/migrations/v02-to-v03-${_.slice(0,12)}`,operations:a,typeSummaries:c,diagnostics:l,applicable:!l.some(v=>v.severity==="lossy"),recordFilesRewritten:0,recordsVerified:m,recordsSkipped:h}}async function oo(r,e,t){await xc(r,e,`${JSON.stringify(t,null,2)} -`)}async function Kw(r,e,t={}){if(e.planVersion!==1||e.targetVersion!==co)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 ao(r,s.path);if(Dr(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 xc(r,`${e.backupLocation}/files/${s.path}`,s.source);await oo(r,n,i),i.status="applying",await oo(r,n,i);try{for(let s of e.operations){let o=await ao(r,s.path);if(Dr(o)!==s.sourceDigest)throw new Error(`${s.path} changed during migration.`);i.written.push(s.path),await oo(r,n,i),await xc(r,s.path,s.target);let a=await ao(r,s.path);if(Dr(a)!==s.targetDigest)throw new Error(`${s.path} did not verify after write.`)}return i.status="applied",i.completed_at=new Date().toISOString(),await oo(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 xc(r,a,c.source),Dr(await ao(r,a))!==c.sourceDigest&&o.push(a)}catch(l){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 oo(r,n,i)}catch(a){}return{applied:!1,restored:o.length===0,manifestPath:n,written:[...i.written],error:i.error}}}var Pc=require("obsidian");function Te(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function br(r){return JSON.parse(JSON.stringify(r))}var QR=new Set(["file","formula","this"]);function ZR(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(QR.has(e.toLowerCase()))throw new Error(`Type name '${e}' is reserved.`);return e}function Yf(){return{specProfile:"v0.3",originalFrontmatter:{},name:"",description:"",extendsType:"",displayNameKey:"",strictMode:!1,pathPattern:"",filenamePattern:"",matchPathGlob:"",matchFieldsPresent:"",matchWhere:"",fields:[{name:"title",definition:{type:"string",required:!0}}],body:`# Type +`)&&e.slice(1)===r}function Xf(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)=>Xf(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)&&Xf(s,n[i]))}var Ti=class{constructor(e,t,n,i){I(this,"fileSystem");I(this,"runtime");I(this,"mode");I(this,"blobStore");this.fileSystem=e,this.runtime=t,this.mode=n,this.blobStore=i}async recordPathPolicy(e){var t;return n0(Object.keys((t=e.resources)!=null?t:{}),()=>this.fileSystem.read("mdbase.yaml"))}async put(e,t,n={}){var p,y,h,m;let{managedState:i=e,acceptedHash:s,materialized:o,inspectionPreflighted:a=!1}=n;a||an(t.path,await this.recordPathPolicy(e)),o===void 0&&!a&&o0(t.path,t.record_id,Object.keys((p=e.resources)!=null?p:{}),Object.entries(e.records),Object.entries((y=e.files)!=null?y:{}));let c=(h=o==null?void 0:o.document)!=null?h:dc(t),l=await this.fileSystem.read(t.path),d=i==null?void 0:i.records[t.record_id];if(l!==null&&l!==c){let g=this.runtime.digest(l);if(!(d!==void 0&&d.path===t.path&&g===d.hash)&&(s===void 0||g!==s))throw new ht(t.record_id,t.path)}d&&d.path!==t.path&&await this.remove(i,t.record_id,d.path);let u=this.runtime.digest(c);typeof s=="string"&&s===u&&l!==null&&this.runtime.digest(l)===u||await this.fileSystem.write(t.path,c),e.records[t.record_id]={path:t.path,revision:t.revision,hash:(m=o==null?void 0:o.hash)!=null?m:u,...this.mode==="read_write"?{record:t}:{}}}async putFile(e,t,n=e,i){var y,h,m,g;if(pt(t),!this.blobStore)throw new b("file_storage_unavailable","Selected collection files require a content-addressed blob store adapter.");a0(t.path,t.file_id,e),(y=e.files)!=null||(e.files={});let s=(h=n.files)==null?void 0:h[t.file_id],o=await this.fileSystem.inspectBinary(t.path),a=wt(t.path),c=Object.values((m=n.files)!=null?m:{}).find(_=>wt(_.file.path)===a),l=[...Object.values((g=n.resources)!=null?g:{}),...Object.values(n.records)].find(_=>wt(_.path)===a),d=l?await this.fileSystem.read(t.path):null,u=(s==null?void 0:s.file.path)===t.path&&Or(o,s.file),f=c!==void 0&&Or(o,c.file),p=l!==void 0&&d!==null&&this.runtime.digest(d)===l.hash;if(o!==null&&!Or(o,t)&&!u&&!f&&!p&&!(i!==void 0&&(o==null?void 0:o.size)===i.size&&o.content_digest===i.content_digest))throw new ht(t.file_id,t.path);if(s&&s.file.path!==t.path){let _=await this.fileSystem.inspectBinary(s.file.path);if(_!==null&&!Or(_,s.file))throw new ht(t.file_id,s.file.path)}Or(o,t)||await this.fileSystem.writeBinary(t.path,gc(this.blobStore.read(t.content_digest),t)),s&&s.file.path!==t.path&&await this.fileSystem.remove(s.file.path),e.files[t.file_id]={file:t}}async removeFile(e,t){var s;let n=(s=e.files)==null?void 0:s[t];if(!n)return;let i=await this.fileSystem.inspectBinary(n.file.path);if(i!==null&&!Or(i,n.file))throw new ht(t,n.file.path);i!==null&&await this.fileSystem.remove(n.file.path),delete e.files[t]}async remove(e,t,n,i={}){var c;let s=e.records[t],o=(c=s==null?void 0:s.path)!=null?c:n;i.inspectionPreflighted||an(o,await this.recordPathPolicy(e));let a=await this.fileSystem.read(o);if(a!==null&&s&&this.runtime.digest(a)!==s.hash)throw new ht(t,s.path);a!==null&&await this.fileSystem.remove(o),delete e.records[t]}async putResource(e,t,n){var o,a;let i=await this.fileSystem.read(t.path),s=(o=n==null?void 0:n.resources)==null?void 0:o[t.path];if(i!==null&&i!==t.document&&(!s||this.runtime.digest(i)!==s.hash))throw new ht(`resource:${t.path}`,t.path);await this.fileSystem.write(t.path,t.document),(a=e.resources)!=null||(e.resources={}),e.resources[t.path]={path:t.path,revision:t.revision,hash:this.runtime.digest(t.document)}}async removeResource(e,t,n){let i=await this.fileSystem.read(t);if(i!==null&&this.runtime.digest(i)!==n.hash)throw new ht(`resource:${t}`,t);i!==null&&await this.fileSystem.remove(t),e.resources&&delete e.resources[t]}};async function l0(r,e,t,n){var i,s;for(let o in r.records){if(!Object.hasOwn(r.records,o))continue;let a=r.records[o];an(a.path,e);let c=await t.read(a.path);if(c===null||n(c)!==a.hash)throw new ht(o,a.path)}for(let[o,a]of Object.entries((i=r.resources)!=null?i:{})){let c=await t.read(a.path);if(c===null||n(c)!==a.hash)throw new ht(`resource:${o}`,a.path)}for(let[o,a]of Object.entries((s=r.files)!=null?s:{})){let c=await t.inspectBinary(a.file.path);if(!Or(c,a.file))throw new ht(o,a.file.path)}}Ee();async function d0(r){var u,f,p,y,h;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 b("promotion_incomplete_file_projection","Moving the source of truth requires every collection file class with no excluded folders.");if(Object.keys((u=e.planned_conflicts)!=null?u:{}).length>0||e.batch!==void 0)throw new b("promotion_not_converged","Upload or resolve every local change before moving the source of truth.");await l0(e,i,n,s);let o=new Set(Object.keys((f=e.resources)!=null?f:{})),a=new Set(Object.values(e.records).map(m=>m.path)),c=(await n.listMarkdown(o)).filter(m=>!a.has(m));if(c.length>0)throw new b("promotion_unmanaged_files",`Synchronize unmanaged Markdown before promotion: ${c.join(", ")}.`);if(!n.listBinary)throw new b("promotion_file_scan_unavailable","Moving the source of truth requires binary file enumeration.");let l=new Set(Object.values((p=e.files)!=null?p:{}).map(m=>m.file.path)),d=(await n.listBinary(new Set([...o,...a]))).filter(m=>!l.has(m));if(d.length>0)throw new b("promotion_unmanaged_files",`Synchronize unmanaged files before moving the source of truth: ${d.join(", ")}.`);return{cursor:e.cursor,digest:fc([...Object.entries((y=e.resources)!=null?y:{}).map(([m,g])=>({kind:"resource",path:m,identity:"",document_hash:Lf(g.hash)})),...Object.entries(e.records).map(([m,g])=>({kind:"record",path:g.path,identity:m,document_hash:Lf(g.hash)})),...Object.values((h=e.files)!=null?h:{}).map(({file:m})=>({kind:"file",path:m.path,identity:m.file_id,document_hash:pc(m)}))])}}function cn(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+t.file_conflicts.length,issues:e.issues,...i?{failure:i}:{}}}function u0(r,e){return["planned","applying","cancelled","stale","blocked","failed"].includes(r.state)?r:r.conflicts.length>0||r.file_conflicts.length>0||r.local_issues.length>0||e.summary.blocking_issues>0||e.summary.conflicts>0?{...r,state:"attention"}:{...r,state:e.actions.some(t=>t.command!=="advance_checkpoint")?"changes_waiting":"up_to_date"}}function Tr(r,e){var a,c,l,d,u,f,p,y,h;if(!r)return{state:"not_initialized",mode:e,pending:0,pending_files:0,conflicts:[],file_conflicts:[],local_issues:[],cursor:null,last_synced_at:null};let t=[],n=[];for(let[m,g]of Object.entries((a=r.planned_conflicts)!=null?a:{})){if(g.entity==="file"){let k=g.local.state==="exact"?g.local.object.path:g.remote.state==="exact"?g.remote.object.path:"",v=n.findIndex(({file_id:P})=>P===m);v!==-1&&n.splice(v,1),n.push({file_id:m,path:k,code:"file_conflict",message:"Local and authority changes need a decision."});continue}let _=t.findIndex(({record_id:k})=>k===m);_!==-1&&t.splice(_,1);let w=g.local.state==="exact"?g.local.object.path:g.remote.state==="exact"?g.remote.object.path:null;t.push({record_id:m,path:w,kind:g.conflict_kind==="rejected"?"rejected":"conflicted",message:g.conflict_kind==="rejected"?"The authority rejected this local change.":"Local and authority changes need a decision."})}let i=[],s=r.batch?r.batch.plan.actions.slice(r.batch.next_action).filter(m=>m.command!=="advance_checkpoint").length:0,o=r.batch?r.batch.phase==="prepared"?"planned":r.batch.phase==="applying"||r.batch.phase==="effects_complete"?"applying":r.batch.phase==="cancelled"?"cancelled":((c=r.batch.failure)==null?void 0:c.code)==="sync_plan_stale"?"stale":"blocked":null;return{state:o!=null?o:t.length||n.length?"attention":"up_to_date",mode:e,pending:s,pending_files:r.batch?r.batch.plan.actions.slice(r.batch.next_action).filter(m=>m.command!=="advance_checkpoint"&&("target"in m&&m.target.entity==="file"||"source"in m&&m.source.entity==="file"||"entity"in m&&m.entity==="file")).length:0,conflicts:t,file_conflicts:n,local_issues:i,cursor:(d=(l=r.batch)==null?void 0:l.checkpoint_before.cursor)!=null?d:r.cursor,last_synced_at:(u=r.last_synced_at)!=null?u:null,generation:(f=r.generation)!=null?f:0,pending_checkpoint:(y=(p=r.batch)==null?void 0:p.checkpoint_after.cursor)!=null?y: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,...(h=r.batch)!=null&&h.failure?{failure:r.batch.failure}:{}}}Ee();Ee();async function EM(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 b("sync_protocol_incompatible",`Filesystem mirror requires exact-document v1 and its own ${t.replace("_","-")} replica.`);return n}async function Ec(r,e,t,n,i){var f;let s=await EM(r,e,t),o=(f=s.resources.documents)!=null?f:[],a=$c(o),c=new Sc(a,o,i.digest),l=[];await c0(e,s,async p=>{for(let y of p){let h=c.validate(y);On(n,h.record.path)&&l.push(h)}});let d=[],u=new Set;return await jw(e,s,async p=>{for(let y of p)if(_c(n,y)){if(u.has(y.file_id))throw new b("invalid_snapshot",`Hosted snapshot repeats file identity ${y.file_id}.`);u.add(y.file_id),d.push(y)}}),to([...o.map(p=>p.path),...l.map(({record:p})=>p.path),...d.map(p=>p.path)]),{session:s,resources:o,records:l,files:d}}var Ac="exact_document_plan_only_v1",xc="three_way_exact_document_v1",kc="portable_mirror_projection_v1";Ee();function Pc(r){return JSON.stringify(Qf(r))}function ro(r,e){return`sha256:${e(Pc(r))}`}function Qf(r){if(r===null||typeof r=="string"||typeof r=="boolean")return r;if(typeof r=="number"){if(!Number.isSafeInteger(r))throw new b("invalid_sync_plan","Sync plans contain only safe integer numeric values.");return r}if(Array.isArray(r))return r.map(Qf);if(typeof r=="object"){let e={};for(let t of Object.keys(r).sort()){let n=r[t];if(n===void 0)throw new b("invalid_sync_plan",`Sync plan field ${t} is undefined rather than an explicit state.`);e[t]=Qf(n)}return e}throw new b("invalid_sync_plan","Sync plans contain only canonical I-JSON values.")}function y0(r,e,t){let n=new Map(r.base.map(d=>[d.identity,d])),i=new Map(r.remote.map(d=>[d.identity,d])),s=new Map,o=new Map(r.local.map(d=>[d.object.path,d]));for(let d of r.local)!d.stable_identity||d.object.identity===""||(s.set(d.object.identity,d.object),o.delete(d.object.path));for(let[d,u]of n){let f=o.get(u.path);f&&(s.set(d,{...f.object,identity:d}),o.delete(u.path))}for(let[d,u]of i){if(s.has(d))continue;let f=o.get(u.path);f&&f.object.entity===u.entity&&(s.set(d,{...f.object,identity:d}),o.delete(u.path))}for(let[d,u]of n){if(s.has(d))continue;let f=[...o.values()].filter(y=>y.object.entity===u.entity&&y.object.payload_revision===u.payload_revision);if(f.length!==1)continue;let p=f[0];s.set(d,{...p.object,identity:d,revision:p.object.payload_revision===u.payload_revision?u.revision:p.object.revision}),o.delete(p.object.path)}for(let d of o.values()){let u=d.stable_identity?d.object.identity:CM(e,d.object,t);s.set(u,{...d.object,identity:u})}let a=new Set([...n.keys(),...s.keys(),...i.keys()]),c=new Map([...s.values()].map(d=>[d.path,d])),l=new Map([...i.values()].map(d=>[d.path,d]));return[...a].sort().map(d=>{var m,g,_,w,k;let u=n.get(d),f=s.get(d),p=i.get(d),y=(g=(m=p==null?void 0:p.path)!=null?m:f==null?void 0:f.path)!=null?g:u.path,h=(w=(_=f==null?void 0:f.path)!=null?_:p==null?void 0:p.path)!=null?w:u.path;return{entity:((k=f!=null?f:p)!=null?k:u).entity,identity:d,base:no(u),local:no(f),remote:no(p),local_target_owner:no(c.get(y)),remote_target_owner:no(l.get(h))}})}function g0(r,e){let t=[];for(let l of[...r.objects].sort(NM))RM(r,l,t);t=kM(t,r.objects,e),t=AM(t,r.objects);let n=t.map(l=>l.key);t.push({key:"checkpoint",depends_on_keys:n,command:"advance_checkpoint",reason:r.kind==="incremental"?"remote_change":r.kind,expected:r.boundary.checkpoint,next:{generation:r.boundary.checkpoint.generation+1,cursor:r.boundary.authority_cursor}});let i=new Map;for(let l of t){let{key:d,depends_on_keys:u,...f}=l;i.set(d,ro({action_scope:{replica_id:r.boundary.replica_id,scope_epoch:r.boundary.scope_epoch,generation:r.boundary.checkpoint.generation},key:d,...f},e))}let s=t.map(l=>{let{key:d,depends_on_keys:u,...f}=l,p={...f,action_id:i.get(d),depends_on:u.map(y=>i.get(y))};if((p.command==="put_remote"||p.command==="move_remote"||p.command==="delete_remote")&&(p.idempotency_key=p.action_id),p.command==="move_remote"){let y=u.find(h=>h===`${p.source.identity}:put-remote`);y&&(p.revision_from_dependency=i.get(y))}return p}),o=[...r.issues].sort(LM),a={uploads:s.filter(jM).length,downloads:s.filter(DM).length,conflicts:s.filter(l=>l.command==="record_conflict").length,blocking_issues:o.filter(l=>l.blocking).length},c={plan_version:1,engine_profile:Ac,protocol_profile:"exact_document_v1",planner_policy:xc,projection_policy:kc,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:s,issues:o,summary:a};return{...c,fingerprint:ro(c,e)}}function AM(r,e){var c;if(!r.some(l=>l.command==="move_remote"))return r;let t=[...r],n=new Set;for(let l of xM(t))for(let d of l){let u=t.find(f=>f.key===d);(u==null?void 0:u.command)==="move_remote"&&n.add(u.source.identity)}let i=tp(t),s=new Map(t.map(l=>[l.key,l])),o=!0;for(;o;){o=!1;for(let l of t){if(l.command!=="move_remote")continue;let d=l.expected_target_owner;if(d.state!=="exact"||d.object.identity===l.source.identity)continue;let u=s.get((c=i.get(pr(d.object)))!=null?c:""),f=u&&f0(u);(!u||f&&n.has(f))&&!n.has(l.source.identity)&&(n.add(l.source.identity),o=!0)}}if(n.size>0){t=t.filter(d=>{let u=f0(d);return!u||!n.has(u)||d.command!=="put_remote"&&d.command!=="move_remote"});let l=new Map(e.map(d=>[d.identity,d]));for(let d of[...n].sort()){let u=l.get(d);!u||u.entity==="resource"||t.push({key:`${d}:conflict`,depends_on_keys:[],command:"record_conflict",reason:"local_change",identity:d,entity:u.entity,local:u.local,remote:u.remote,conflict_kind:"path_occupied"})}}let a=tp(t);for(let l of t){if(l.command!=="move_remote")continue;let d=l.expected_target_owner;if(d.state!=="exact"||d.object.identity===l.source.identity)continue;let u=a.get(pr(d.object));!u||u===l.key||(l.depends_on_keys.includes(u)||l.depends_on_keys.push(u),l.expected_target_owner={state:"absent"})}return _0(t)}function xM(r){var s;let e=r.filter(o=>o.command==="move_remote"),t=new Map(e.map(o=>[o.key,o])),n=tp(r),i=new Map;for(let o of e){let a=[],c=new Map,l=o;for(;l;){let d=c.get(l.key);if(d!==void 0){let f=a.slice(d);i.set([...f].sort().join("\0"),f);break}c.set(l.key,a.length),a.push(l.key);let u=l.expected_target_owner;l=u.state==="exact"?t.get((s=n.get(pr(u.object)))!=null?s:""):void 0}}return[...i.values()]}function tp(r){let e=new Map;for(let t of r)t.command==="move_remote"?e.set(pr(t.source),t.key):t.command==="delete_remote"&&e.set(pr(t.target),t.key);return e}function f0(r){if(r.command==="move_remote")return r.source.identity;if(r.command==="put_remote"||r.command==="delete_remote")return r.target.identity}function kM(r,e,t){var u;if(!r.some(f=>f.command==="move_local"||f.command==="write_local"))return r;let n=[...r],i=new Set;for(let f of e)f.base.state==="exact"&&i.add(f.base.object.path),f.local.state==="exact"&&i.add(f.local.object.path),f.remote.state==="exact"&&i.add(f.remote.object.path);for(;;){let f=PM(n);if(!f)break;let p=[...f].sort()[0],y=n.findIndex(w=>w.key===p),h=n[y];if(!h||h.command!=="move_local")throw new Error("Planner invariant: local path cycle contains a non-move action.");let m=OM(h.source,h.target_path,i,t);i.add(m);let g={...h.source,path:m},_={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=g,h.expected_source_owner={state:"exact",object:g},h.depends_on_keys=[_.key],n.splice(y,0,_)}let s=rp(n),o=new Map(e.map(f=>[f.identity,f])),a=new Set,c=new Map(n.map(f=>[f.key,f])),l=!0;for(;l;){l=!1;for(let f of n){let p=p0(f),y=Ic(f);if((p==null?void 0:p.state)!=="exact"||p.object.identity===y)continue;let h=c.get((u=s.get(pr(p.object)))!=null?u:""),m=h&&Ic(h);(!h||m&&a.has(m))&&!a.has(y)&&(a.add(y),l=!0)}}if(a.size>0){n=n.filter(f=>!a.has(Ic(f))||f.command!=="move_local"&&f.command!=="write_local");for(let f of[...a].sort()){let p=o.get(f);!p||p.entity==="resource"||n.push({key:`${f}:conflict`,depends_on_keys:[],command:"record_conflict",reason:"remote_change",identity:f,entity:p.entity,local:p.local,remote:p.remote,conflict_kind:"path_occupied"})}}let d=rp(n);for(let f of n){let p=p0(f),y=Ic(f);if((p==null?void 0:p.state)!=="exact"||p.object.identity===y)continue;let h=d.get(pr(p.object));!h||h===f.key||(f.depends_on_keys.includes(h)||f.depends_on_keys.push(h),IM(f,{state:"absent"}))}return _0(n)}function PM(r){var i;let e=r.filter(s=>s.command==="move_local"),t=new Map(e.map(s=>[s.key,s])),n=rp(r);for(let s of e){let o=[],a=new Map,c=s;for(;c;){let l=a.get(c.key);if(l!==void 0)return o.slice(l);a.set(c.key,o.length),o.push(c.key);let d=c.expected_target_owner;c=d.state==="exact"?t.get((i=n.get(pr(d.object)))!=null?i:""):void 0}}}function rp(r){let e=new Map;for(let t of r)t.command==="move_local"?e.set(pr(t.source),t.key):t.command==="delete_local"&&e.set(pr(t.target),t.key);return e}function p0(r){if(r.command==="move_local")return r.expected_target_owner;if(r.command==="write_local")return r.expected_path_owner}function IM(r,e){r.command==="move_local"?r.expected_target_owner=e:r.command==="write_local"&&(r.expected_path_owner=e)}function Ic(r){return r.command==="move_local"?r.source.identity:r.command==="write_local"||r.command==="delete_local"?r.target.identity:""}function pr(r){return`${r.entity}\0${r.identity}\0${r.path}`}function OM(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 d=n(`${r.entity}\0${r.identity}\0${r.path}\0${e}\0${l}`),u=`${s}.mdbase-sync-stage-${d.slice(0,16)}${c}`;if(!t.has(u))return u}}function _0(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 RM(r,e,t){if(e.frozen_conflict){t.push({key:`${e.identity}:conflict`,depends_on_keys:[],command:"record_conflict",reason:"pending",identity:e.identity,entity:e.entity,...e.frozen_conflict});return}let n=!ep(e.local,e.base),i=!ep(e.remote,e.base);if(!(!n&&!i)){if(e.entity==="resource"){if(n)return;Zf(e,t);return}if(r.mode==="read_only"){n||Zf(e,t);return}if(n&&i){if(ep(e.local,e.remote))return;t.push(MM(e));return}n?TM(e,t):Zf(e,t)}}function Zf(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(h0(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(h0(r,t,i?[i]:[]))}function h0(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:Mr(r.local).revision,payload_revision:Mr(r.local).payload_revision,...Mr(r.local).size===void 0?{}:{size:Mr(r.local).size}}}:r.local,expected_path_owner:t.length>0?{state:"exact",object:{...e,revision:Mr(r.local).revision,payload_revision:Mr(r.local).payload_revision,...Mr(r.local).size===void 0?{}:{size:Mr(r.local).size}}}:r.local_target_owner}}function TM(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(m0(r,t,[]));return}let n=r.remote.object,i;if(t.revision!==n.revision){let s=m0(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 m0(r,e,t){return{key:`${r.identity}:put-remote`,depends_on_keys:t,command:"put_remote",reason:"local_change",target:e,payload_revision:Mr(r.local).payload_revision,expected_remote:r.remote,expected_local:r.local,idempotency_key:""}}function MM(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 Mr(r){if(r.state!=="exact")throw new Error("Planner invariant: expected exact object state.");return r.object}function no(r){return r?{state:"exact",object:r}:{state:"absent"}}function CM(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 ep(r,e){return Pc(r)===Pc(e)}function NM(r,e){return`${r.entity}\0${r.identity}`.localeCompare(`${e.entity}\0${e.identity}`)}function LM(r,e){var t,n;return`${(t=r.path)!=null?t:""}\0${r.code}\0${r.message}`.localeCompare(`${(n=e.path)!=null?n:""}\0${e.code}\0${e.message}`)}function jM(r){return r.command==="put_remote"||r.command==="move_remote"||r.command==="delete_remote"}function DM(r){return r.command==="write_local"||r.command==="move_local"||r.command==="delete_local"}var Oc=class{constructor(e,t,n,i,s,o,a,c,l){I(this,"replicaId");I(this,"transport");I(this,"mode");I(this,"fileSystem");I(this,"blobStore");I(this,"selectiveSync");I(this,"runtime");I(this,"readState");I(this,"currentRecordPathPolicy");this.replicaId=e,this.transport=t,this.mode=n,this.fileSystem=i,this.blobStore=s,this.selectiveSync=o,this.runtime=a,this.readState=c,this.currentRecordPathPolicy=l}async inspect(e){let t=e===void 0?await this.readState():e;if(!t)return this.inspectSnapshot("initial",null);if(t.batch)throw new b("mirror_recovery_required","The prepared sync batch must recover before a new inspection can be planned.");return JSON.stringify(t.selective_sync)!==JSON.stringify(this.selectiveSync)?this.inspectSnapshot("rebuild",t):this.inspectIncremental(t)}async inspectSnapshot(e,t){let n=await Ec(this.replicaId,this.transport,this.mode,this.selectiveSync,this.runtime),i=$c(n.resources),s=await this.inspectLocal(t,n.resources,i),o=new Map(n.records.map(({record:c})=>[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){var l,d;let t=new Map;for(let[u,f]of Object.entries(e.records))f.record&&t.set(u,f.record);let n=new Map(Object.entries((l=e.files)!=null?l:{}).map(([u,f])=>[u,f.file])),i=new Map(b0(e).map(u=>[UM(u),u])),s=e.cursor,o=e.cursor;for(;;){let u=s,f=await this.transport.changes(u,200);if(f.scope_epoch!==e.scope_epoch||f.cursorf.head||f.has_more&&f.cursor===u)throw new b("invalid_change_page","Authority returned an invalid change boundary.");if(f.reset_required)return this.inspectSnapshot("rebuild",e);for(let p of f.events){if(p.sequence<=o||p.sequence>f.cursor)throw new b("invalid_change_page","Authority change events are not strictly ordered.");o=p.sequence,this.applyRemoteObservation(i,t,n,p)}if(s=f.cursor,!f.has_more)break}let a=Object.values((d=e.resources)!=null?d:{}).map(u=>({path:u.path,kind:BM(u.path),revision:u.revision,document:""})),c=await this.inspectLocal(e,a,await this.currentRecordPathPolicy(e));return 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"){ww(i);let s=i.record.record_id;On(this.selectiveSync,i.record.path)?(e.set(`record:${s}`,w0(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"){pt(i.file);let s=i.file.file_id;_c(this.selectiveSync,i.file)?(e.set(`file:${s}`,ip(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){var y,h,m,g,_,w,k,v,P,O,$,R,S,V,B;let i=[],s=new Map,o=new Map,a=[],c=new Map(Object.entries((y=e==null?void 0:e.records)!=null?y:{}).map(([T,E])=>[E.path,[T,E]])),l=new Map(Object.entries((h=e==null?void 0:e.planned_conflicts)!=null?h:{}).filter(([,T])=>T.entity==="record"&&T.local.state==="exact").map(([T,E])=>[E.local.state==="exact"?E.local.object.path:"",T])),d=new Map(Object.entries((m=e==null?void 0:e.local_bindings)!=null?m:{}).filter(([,T])=>T.entity==="record").map(([T,E])=>[E.path,T])),u=new Set([...Object.keys((g=e==null?void 0:e.resources)!=null?g:{}),...t.map(T=>T.path)]);for(let T of u){let E=await this.fileSystem.read(T),x=(_=e==null?void 0:e.resources)==null?void 0:_[T];if(E===null)continue;let de=`sha256:${this.runtime.digest(E)}`;i.push({stable_identity:!0,object:Mi("resource",T,T,de)}),s.set(T,E);let Z=t.find(U=>U.path===T);!x&&Z&&Z.revision!==de?a.push({code:"local_collision",message:`${T} differs locally from the exact authority document.`,path:T,blocking:!0}):x&&x.revision!==de&&a.push({code:"mirror_diverged",message:`Authority-owned resource ${T} changed locally.`,path:T,blocking:!0})}let f=new Set(Object.values((w=e==null?void 0:e.records)!=null?w:{}).map(T=>T.path)),p=i0(await this.fileSystem.listMarkdown(u),n).filter(T=>On(this.selectiveSync,T)||f.has(T));for(let T of p){let E=await this.fileSystem.read(T);if(E===null)continue;let x=`sha256:${this.runtime.digest(E)}`,de=l.get(T),Z=d.get(T),U=(k=c.get(T))==null?void 0:k[0],fe=(P=(v=de!=null?de:Z)!=null?v:U)!=null?P:"";i.push({stable_identity:fe!=="",object:Mi("record",fe,T,x)}),s.set(T,E)}if(this.selectiveSync.file_classes.length>0){if(!this.fileSystem.listBinary)throw new b("file_storage_unavailable","Selected files require binary enumeration.");let T=new Set(Object.values((O=e==null?void 0:e.files)!=null?O:{}).map(U=>U.file.path)),E=new Map(Object.entries(($=e==null?void 0:e.files)!=null?$:{}).map(([U,fe])=>[fe.file.path,[U,fe]])),x=new Map(Object.entries((R=e==null?void 0:e.planned_conflicts)!=null?R:{}).filter(([,U])=>U.entity==="file"&&U.local.state==="exact").map(([U,fe])=>[fe.local.state==="exact"?fe.local.object.path:"",U])),de=new Map(Object.entries((S=e==null?void 0:e.local_bindings)!=null?S:{}).filter(([,U])=>U.entity==="file").map(([U,fe])=>[fe.path,U])),Z=(await this.fileSystem.listBinary(u)).filter(U=>Nw(this.selectiveSync,U)||T.has(U));for(let U of Z){let fe=await this.fileSystem.inspectBinary(U);if(!fe)continue;let Ve=x.get(U),Yt=de.get(U),Lr=E.get(U),ln=(B=(V=Ve!=null?Ve:Yt)!=null?V:Lr==null?void 0:Lr[0])!=null?B:"";i.push({stable_identity:ln!=="",object:{entity:"file",identity:ln,path:U,revision:Lr&&Lr[1].file.content_digest===fe.content_digest?Lr[1].file.revision:fe.content_digest,payload_revision:fe.content_digest,size:fe.size}}),o.set(U,fe)}}try{to([...u,...p,...o.keys()])}catch(T){let E=T instanceof Error?T:new Error(String(T));a.push({code:$0(T),message:E.message,blocking:!0})}return{observations:i,documents:s,binary:o,issues:a}}async finish(e){var u,f,p,y,h;let{prior:t,local:n}=e,i=(u=e.remoteRefs)!=null?u:[...e.remoteResources.map(FM),...[...e.remoteRecords.values()].map(w0),...[...e.remoteFiles.values()].map(ip)],s=y0({base:t?b0(t):[],local:n.observations,remote:i},`${this.replicaId}\0${e.scopeEpoch}\0${(f=t==null?void 0:t.generation)!=null?f:0}`,this.runtime.digest);for(let m of s){let g=(p=t==null?void 0:t.planned_conflicts)==null?void 0:p[m.identity];!g||g.entity!==m.entity||(m.frozen_conflict={local:g.local,remote:g.remote,conflict_kind:g.conflict_kind})}let o=[...n.issues];for(let m of s)(e.kind==="initial"||e.kind==="rebuild")&&m.base.state==="absent"&&m.local.state==="exact"&&m.remote.state==="exact"&&!v0(m.local,m.remote)&&o.push({code:"local_collision",message:`${m.remote.object.path} differs locally from the exact authority object.`,path:m.remote.object.path,blocking:!0}),m.remote.state==="exact"&&m.local_target_owner.state==="exact"&&m.remote.object.identity!==m.local_target_owner.object.identity&&o.push({code:"local_collision",message:`${m.remote.object.path} is owned by different local bytes.`,path:m.remote.object.path,blocking:!0});try{to([...i.map(m=>m.path),...n.observations.map(({object:m})=>m.path)])}catch(m){let g=m instanceof Error?m:new Error(String(m));o.push({code:$0(m),message:g.message,blocking:!0})}if(this.mode==="read_only"){for(let m of s)if(m.entity!=="resource"&&!v0(m.local,m.base)){let g=VM(m.local,m.base);if(o.some(_=>_.blocking&&_.path===g))continue;o.push({code:"mirror_diverged",message:`${g} changed in a receive-only mirror.`,path:g,blocking:!0})}}let a=ro(In(this.selectiveSync),this.runtime.digest),c={boundary:{engine_profile:Ac,protocol_profile:"exact_document_v1",planner_policy:xc,projection_policy:kc,replica_id:this.replicaId,scope_epoch:e.scopeEpoch,authority_cursor:e.authorityCursor,checkpoint:{generation:(y=t==null?void 0:t.generation)!=null?y:0,cursor:(h=t==null?void 0:t.cursor)!=null?h:null},selective_sync_fingerprint:a},mode:this.mode,kind:e.kind,selective_sync:In(this.selectiveSync),objects:s,issues:qM(o)},l=g0(c,this.runtime.digest),d=await this.bindPayloads(l,n,e.remoteRecords,e.remoteResources,e.remoteFiles);return{summary:c,plan:l,durable_payloads:d,prior:t,snapshot:e.snapshot,remote_records:e.remoteRecords,remote_files:e.remoteFiles}}async bindPayloads(e,t,n,i,s){let o={documents:{},records:{},resources:{},files:{},local_files:{},mutations:{}},a=new Map(i.map(c=>[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 d=t.binary.get(l);if(!d)throw Mn(c.action_id);await this.stageLocalBinary(l,d),o.local_files[c.action_id]={path:l,...d}}else{let d=t.documents.get(l);if(d===void 0||`sha256:${this.runtime.digest(d)}`!==c.payload_revision)throw Mn(c.action_id);o.documents[c.action_id]=d}c.target.entity==="record"&&(o.mutations[c.action_id]={operation:"put",mutation_id:np(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 Mn(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 Mn(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 Mn(c.action_id);await bc(this.transport,this.blobStore,l),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 Mn(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 Mn(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:np(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:np(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 b("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 b("sync_plan_stale",`${e} disappeared during inspection.`);await this.blobStore.write(t.content_digest,Dw(n,t,e))}};function qM(r){var t;let e=new Map;for(let n of r)e.set(`${n.code}\0${(t=n.path)!=null?t:""}\0${n.message}\0${n.blocking}`,n);return[...e.values()]}function b0(r){var e,t;return[...Object.entries((e=r.resources)!=null?e:{}).map(([n,i])=>Mi("resource",n,i.path,i.revision)),...Object.entries(r.records).map(([n,i])=>Mi("record",n,i.path,i.revision)),...Object.entries((t=r.files)!=null?t:{}).map(([n,i])=>ip({...i.file,file_id:n}))]}function w0(r){return Mi("record",r.record_id,r.path,r.revision)}function FM(r){return Mi("resource",r.path,r.path,r.revision)}function Mi(r,e,t,n){return{entity:r,identity:e,path:t,revision:n,payload_revision:n}}function ip(r){return{entity:"file",identity:r.file_id,path:r.path,revision:r.revision,payload_revision:r.content_digest,size:r.size}}function UM(r){return`${r.entity}:${r.identity}`}function v0(r,e){return JSON.stringify(r)===JSON.stringify(e)}function VM(r,e){return r.state==="exact"?r.object.path:e.state==="exact"?e.object.path:"mirror"}function Mn(r){return new b("sync_payload_incomplete",`Inspected action ${r} has no revision-bound payload.`)}function $0(r){return r&&typeof r=="object"&&"code"in r&&typeof r.code=="string"?r.code:"sync_inspection_failed"}function BM(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 np(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)}`}Ee();Mc();var Nc=class{constructor(e){I(this,"ports");I(this,"materializer");I(this,"ownersByPath",new Map);I(this,"pathsByOwner",new Map);this.ports=e,this.materializer=new Ti(e.fileSystem,e.runtime,e.mode,e.blobStore)}async execute(e,t){var s,o;let n=nt(e);this.indexPathOwners(e);let i=new Set(n.receipts.map(a=>a.action_id));for(await E0(e,this.ports.store);n.next_action!i.has(l));if(c){let l={code:"invalid_mirror_state",message:`Action ${a.action_id} is missing dependency ${c}.`,action_id:a.action_id};return await Rc(e,"blocked",l,this.ports.store),{status:"blocked",completed:n.next_action,failure:l}}try{let l=await this.dispatch(e,a);await A0(e,l,this.ports.store),i.add(l.action_id),(o=(s=this.ports).onProgress)==null||o.call(s,n.next_action,n.plan.actions.length-1)}catch(l){let d=GM(l,a.action_id);return await Rc(e,"blocked",d,this.ports.store),{status:d.code==="sync_plan_stale"?"stale":"blocked",completed:n.next_action,failure:d}}}throw new b("invalid_mirror_state","Prepared plan has no checkpoint action.")}async dispatch(e,t){var n,i;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":return(n=e.planned_conflicts)!=null||(e.planned_conflicts={}),e.planned_conflicts[t.identity]={entity:t.entity,local:t.local,remote:t.remote,conflict_kind:t.conflict_kind},(i=e.local_bindings)!=null||(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"advance_checkpoint":throw new b("invalid_mirror_state","The executor cannot dispatch checkpoint actions.")}}rebaseConflict(e,t){var s;let n=nt(e).payloads;if(t.entity==="record"){if(t.remote.state==="absent"){delete e.records[t.identity];return}let o=n.records[t.action_id];if(!o||o.revision!==t.remote.object.revision)throw hr(t);Cc(o,this.ports.runtime,o.revision),e.records[t.identity]={path:o.path,revision:o.revision,hash:t.local.state==="exact"?t.local.object.payload_revision.replace(/^sha256:/u,""):this.ports.runtime.digest(o.document),...this.ports.mode==="read_write"?{record:o}:{}};return}if((s=e.files)!=null||(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 hr(t);pt(i),e.files[t.identity]={file:i}}async writeLocal(e,t){let n=await this.ports.fileSystem.exists(t.target.path);(!n||!await this.matchesRef(t.target))&&(await this.assertLocal(t.expected_local),await this.assertPathOwner(t.target.path,t.expected_path_owner,n));let i=nt(e).payloads;if(t.target.entity==="record"){let o=i.records[t.action_id];if(!o||o.revision!==t.payload_revision)throw hr(t);return Cc(o,this.ports.runtime,t.payload_revision),await this.materializer.put(e,o,{inspectionPreflighted:!0}),this.installPathOwner(t.target),{action_id:t.action_id,status:"completed"}}if(t.target.entity==="resource"){let o=i.resources[t.action_id];if(!o||o.revision!==t.payload_revision||`sha256:${this.ports.runtime.digest(o.document)}`!==o.revision)throw hr(t);return await this.materializer.putResource(e,o,e),this.installPathOwner(t.target),{action_id:t.action_id,status:"completed"}}let s=i.files[t.action_id];if(!s||s.content_digest!==t.payload_revision)throw hr(t);return await this.materializer.putFile(e,s,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)),KM(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){var i;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 s=(i=e.resources)==null?void 0:i[t.target.identity];s?await this.materializer.removeResource(e,t.target.path,s):await this.ports.fileSystem.remove(t.target.path)}else await this.materializer.removeFile(e,t.target.identity);else WM(e,t.target);return this.removePathOwner(t.target),{action_id:t.action_id,status:"completed"}}async putRemote(e,t){var a,c;let n=nt(e).payloads;if(t.target.entity==="record"){let l=n.mutations[t.action_id],d=n.documents[t.action_id];if(!l||l.operation!=="put"||d===void 0)throw hr(t);if(`sha256:${this.ports.runtime.digest(d)}`!==t.payload_revision)throw new b("sync_plan_stale","Prepared local document payload no longer matches its revision.");let u=await this.ports.transport.mutate(l);return this.acceptRecordReceipt(e,t,u,d),sp(t.action_id,u)}if(t.target.entity==="resource")throw new b("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 hr(t);let s={protocol_version:1,type:"open_file_upload",transfer_id:ap(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(pt(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 op(t);return(a=e.files)!=null||(e.files={}),e.files[o.file.file_id]={file:o.file},(c=e.local_bindings)==null||delete c[t.target.identity],{action_id:t.action_id,status:"completed",file:o.file}}async moveRemote(e,t){var s,o,a;if(t.source.entity==="record"){let c=nt(e).payloads.mutations[t.action_id];if(!c||c.operation!=="move")throw hr(t);let l=await this.ports.transport.mutate(c);return this.acceptRecordReceipt(e,t,l),sp(t.action_id,l)}if(t.source.entity==="resource"||!this.ports.transport.moveFile)throw new b("invalid_sync_plan","This remote move command is unsupported.");let n={protocol_version:1,type:"move_file",mutation_id:ap(t.action_id),file_id:t.source.identity,if_revision:(s=this.dependencyFileRevision(e,t))!=null?s: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(pt(i.file),i.mutation_id!==n.mutation_id||i.file.file_id!==t.source.identity||i.file.path!==t.target_path)throw op(t);return(o=e.files)!=null||(e.files={}),e.files[t.source.identity]={file:i.file},(a=e.local_bindings)==null||delete a[t.source.identity],{action_id:t.action_id,status:"completed",file:i.file}}dependencyFileRevision(e,t){if(!t.revision_from_dependency)return;let n=nt(e).receipts.find(({action_id:i})=>i===t.revision_from_dependency);if(!(n!=null&&n.file)||n.file.file_id!==t.source.identity)throw new b("invalid_mirror_state",`Move ${t.action_id} is missing its dependency file receipt.`);return n.file.revision}async deleteRemote(e,t){var s,o;if(t.target.entity==="record"){let a=nt(e).payloads.mutations[t.action_id];if(!a||a.operation!=="delete")throw hr(t);let c=await this.ports.transport.mutate(a);return this.acceptRecordReceipt(e,t,c),sp(t.action_id,c)}if(t.target.entity==="resource"||!this.ports.transport.deleteFile)throw new b("invalid_sync_plan","This remote delete command is unsupported.");let n={protocol_version:1,type:"delete_file",mutation_id:ap(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 op(t);return(s=e.files)==null||delete s[t.target.identity],(o=e.local_bindings)==null||delete o[t.target.identity],{action_id:t.action_id,status:"completed"}}acceptRecordReceipt(e,t,n,i){var l,d,u,f;let o=("target"in t?t.target:t.source).identity;if(n.status==="applied"||n.status==="previously_applied"){if(n.record){Cc(n.record,this.ports.runtime,n.record.revision);let p=e.records[o];e.records[o]={path:n.record.path,revision:n.record.revision,hash:i===void 0?(l=p==null?void 0:p.hash)!=null?l: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];(d=e.local_bindings)==null||delete d[o];return}let a=n.status==="conflicted"?n.conflict.current:void 0;a&&Cc(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;(u=e.planned_conflicts)!=null||(e.planned_conflicts={}),e.planned_conflicts[o]={entity:"record",local:t.expected_local,remote:c,conflict_kind:n.status==="rejected"?"rejected":"both_changed"},(f=e.local_bindings)!=null||(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 new b("sync_plan_stale",`${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!=null?n:await this.pathExists(e)))throw new b("sync_plan_stale",`${e} is no longer vacant.`);return}if(!i||i.entity!==t.object.entity||i.identity!==t.object.identity)throw new b("sync_plan_stale",`${e} has a different path owner.`)}async matchesRef(e){if(e.entity==="file"){let n=await this.ports.fileSystem.inspectBinary(e.path);return n!==null&&n.content_digest===e.payload_revision&&(e.size===void 0||n.size===e.size)}let t=await this.ports.fileSystem.read(e.path);return t!==null&&`sha256:${this.ports.runtime.digest(t)}`===e.payload_revision}async pathExists(e){return this.ports.fileSystem.exists(e)}indexPathOwners(e){var t,n;this.ownersByPath.clear(),this.pathsByOwner.clear();for(let[i,s]of Object.entries(e.records))this.installPathOwner({entity:"record",identity:i,path:s.path,revision:s.revision,payload_revision:`sha256:${s.hash}`});for(let[i,s]of Object.entries((t=e.resources)!=null?t:{}))this.installPathOwner({entity:"resource",identity:i,path:s.path,revision:s.revision,payload_revision:`sha256:${s.hash}`});for(let[i,s]of Object.entries((n=e.files)!=null?n:{}))this.installPathOwner({entity:"file",identity:i,path:s.file.path,revision:s.file.revision,payload_revision:s.file.content_digest,size:s.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){var i;let t=`${e.entity}:${e.identity}`,n=(i=this.pathsByOwner.get(t))!=null?i:e.path;this.ownersByPath.delete(n),this.pathsByOwner.delete(t)}};function KM(r,e,t){var n,i;if(e.entity==="record"){let s=r.records[e.identity];s&&(s.path=t)}else if(e.entity==="resource"){let s=(n=r.resources)==null?void 0:n[e.identity];s&&(s.path=t)}else{let s=(i=r.files)==null?void 0:i[e.identity];s&&(s.file.path=t)}}function WM(r,e){var t,n;e.entity==="record"?delete r.records[e.identity]:e.entity==="resource"?(t=r.resources)==null||delete t[e.identity]:(n=r.files)==null||delete n[e.identity]}function Cc(r,e,t){let n=dc(r);if(r.revision!==t||`sha256:${e.digest(n)}`!==t)throw new b("invalid_sync_response","Record receipt does not match its exact document revision.")}function sp(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 hr(r){return new b("sync_payload_incomplete",`Prepared action ${r.action_id} has no exact payload capability.`)}function op(r){return new b("invalid_sync_response",`Authority receipt does not match prepared action ${r.action_id}.`)}function GM(r,e){let t=r instanceof Error?r:new Error(String(r));return{code:r&&typeof r=="object"&&"code"in r&&typeof r.code=="string"?r.code:"sync_action_failed",message:t.message,action_id:e}}function ap(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)}`}Ee();var jc=class{constructor(e,t){I(this,"fileSystem");I(this,"runtime");this.fileSystem=e,this.runtime=t}async validate(e,t){var n,i,s;if(((n=t==null?void 0:t.generation)!=null?n:0)!==e.checkpoint_generation||((i=t==null?void 0:t.cursor)!=null?i:null)!==e.base_cursor||((s=t==null?void 0:t.scope_epoch)!=null?s:e.scope_epoch)!==e.scope_epoch)throw Lc("The durable checkpoint changed after inspection.");for(let o of e.actions)o.depends_on.length===0&&await this.validateAction(o)}async validateAction(e){switch(e.command){case"write_local":await this.expected(e.expected_local),await this.expectedAt(e.target.path,e.expected_path_owner);return;case"delete_local":await this.expected(e.expected_local),await this.expectedAt(e.target.path,e.expected_path_owner);return;case"move_local":await this.expectedAt(e.source.path,e.expected_source_owner),await this.expectedAt(e.target_path,e.expected_target_owner);return;case"put_remote":case"move_remote":await this.expected(e.expected_local);return;case"delete_remote":await this.expectedAt(e.target.path,e.expected_local);return;case"record_conflict":await this.expected(e.local);return;case"advance_checkpoint":return}}async expectedAt(e,t){if(t.state==="absent"){if(await this.pathExists(e))throw Lc(`${e} is no longer vacant.`);return}if(t.object.path!==e||!await this.matches(t.object))throw Lc(`${e} no longer has the inspected owner and bytes.`)}async expected(e){if(e.state!=="absent"&&!await this.matches(e.object))throw Lc(`${e.object.path} no longer matches the inspected bytes.`)}async matches(e){if(e.entity==="file"){let n=await this.fileSystem.inspectBinary(e.path);return n!==null&&n.content_digest===e.payload_revision&&(e.size===void 0||n.size===e.size)}let t=await this.fileSystem.read(e.path);return t!==null&&`sha256:${this.runtime.digest(t)}`===e.payload_revision}async pathExists(e){return this.fileSystem.exists(e)}};function Lc(r){return new b("sync_plan_stale",r)}Mc();Ee();Mc();async function P0(r,e,t){var o;let n=nt(r);if(n.phase!=="effects_complete")throw new b("invalid_mirror_state","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 new b("invalid_mirror_state","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 new b("invalid_mirror_state","Prepared checkpoint boundary is inconsistent.");let s=n.plan.fingerprint;return r.generation=i.next.generation,r.cursor=(o=i.next.cursor)!=null?o:0,r.last_completed_plan=s,r.last_synced_at=e.now(),delete r.batch,await t.write(r),s}async function I0(r,e,t,n){var s,o,a;let[i]=e.actions;if(e.actions.length!==1||!i||i.command!=="advance_checkpoint"||i.expected.generation!==((s=r.generation)!=null?s:0)||i.expected.cursor!==r.cursor||i.next.generation!==((o=r.generation)!=null?o:0)+1||i.next.cursor!==e.authority_cursor||r.batch!==void 0)throw new b("invalid_mirror_state","Empty checkpoint plan is inconsistent.");return r.generation=i.next.generation,r.cursor=(a=i.next.cursor)!=null?a:0,r.last_completed_plan=e.fingerprint,r.last_synced_at=t.now(),await n.write(r),e.fingerprint}var Cn=class{constructor(e,t,n,i="read_only"){I(this,"replicaId");I(this,"transport");I(this,"mode");I(this,"stateStore");I(this,"fileSystem");I(this,"blobStore");I(this,"selectiveSync");I(this,"lease");I(this,"runtime");I(this,"materializer");I(this,"onProgress");var s,o;this.replicaId=e,this.transport=t,this.mode=i,this.stateStore=n.stateStore,this.fileSystem=n.fileSystem,this.blobStore=n.blobStore,this.selectiveSync=In(n.selectiveSync),this.lease=(s=n.lease)!=null?s:new Zs,this.runtime=(o=n.runtime)!=null?o:eo,this.materializer=new Ti(this.fileSystem,this.runtime,this.mode,this.blobStore),this.onProgress=n.onProgress}async sync(e={}){return this.lease.runExclusive(async()=>{var i,s;let t=await this.readState();if(((i=t==null?void 0:t.batch)==null?void 0:i.phase)==="blocked"&&((s=t.batch.failure)==null?void 0:s.code)==="sync_plan_stale"&&(await k0(t,this.journalStore()),t=await this.readState()),t!=null&&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()=>{var t,n;let e=await this.readState();return(n=(t=e==null?void 0:e.batch)==null?void 0:t.plan)!=null?n:(await this.inspectDetailed(e)).plan})}async apply(e,t={}){return this.lease.runExclusive(async()=>{let n=await this.readState();if(n!=null&&n.batch){if(n.batch.plan.fingerprint!==e.fingerprint)throw new b("mirror_recovery_required","A different prepared plan must recover before this plan can apply.");return this.executePrepared(n,t.signal)}let i=await this.inspectDetailed(n);return i.plan.fingerprint!==e.fingerprint?cn("stale",e,Tr(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){var s;let n=e.plan;if(n.issues.some(o=>o.blocking))return cn("attention",n,Tr(e.prior,this.mode),0);if(t!=null&&t.aborted)return cn("cancelled",n,Tr(e.prior,this.mode),0,{code:"sync_cancelled",message:"Sync cancelled before preparation."});try{await new jc(this.fileSystem,this.runtime).validate(n,e.prior)}catch(o){let a=o instanceof Error?o:new Error(String(o)),c=o&&typeof o=="object"&&"code"in o&&typeof o.code=="string"?o.code:"sync_revalidation_failed";return cn(c==="sync_plan_stale"?"stale":"failed",n,Tr(e.prior,this.mode),0,{code:c,message:a.message})}if(e.prior&&n.actions.length===1&&((s=n.actions[0])==null?void 0:s.command)==="advance_checkpoint")return await I0(e.prior,n,this.runtime,this.journalStore()),cn("applied",n,Tr(e.prior,this.mode),0);let i=await S0(e.prior,n,e.durable_payloads,this.journalStore());return this.executePrepared(i,t)}async executePrepared(e,t){let n=e.batch,i=await new Nc({transport:this.transport,fileSystem:this.fileSystem,blobStore:this.blobStore,runtime:this.runtime,mode:this.mode,store:this.journalStore(),onProgress:(c,l)=>{var d;return(d=this.onProgress)==null?void 0:d.call(this,{phase:"applying",completed:c,total:l,done:c===l})}}).execute(e,t);if(i.status!=="effects_complete"){let c=Tr(e,this.mode);return cn(i.status==="blocked"?"failed":i.status,n.plan,c,i.completed,i.failure)}let s=n.plan;await P0(e,this.runtime,this.journalStore()),await this.pruneFileBlobs();let o=Tr(e,this.mode),a=o.conflicts.length>0||o.file_conflicts.length>0||o.local_issues.length>0||s.summary.conflicts>0;return cn(a?"attention":"applied",s,o,i.completed)}inspectDetailed(e){return new Oc(this.replicaId,this.transport,this.mode,this.fileSystem,this.blobStore,this.selectiveSync,this.runtime,()=>this.readState(),t=>this.currentRecordPathPolicy(t)).inspect(e)}async status(){let e=await this.checkpointStatus();return e.state==="not_initialized"?e:u0(e,await this.inspect())}async checkpointStatus(){return this.lease.runExclusive(()=>this.checkpointStatusUnlocked())}async checkpointStatusUnlocked(){return Tr(await this.readState(),this.mode)}async authorityPromotionManifest(){return this.lease.runExclusive(async()=>{var i;if(this.mode!=="read_write")throw new b("promotion_requires_writable_mirror","Only a read-write mirror can prove an authority promotion source.");let e=await this.readState();if(!e)throw new b("mirror_not_initialized","Synchronize this mirror first.");if(e.batch||Object.keys((i=e.planned_conflicts)!=null?i:{}).length>0)throw new b("promotion_mirror_not_clean","Finish the prepared batch and resolve conflicts before promotion.");let t=await d0({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(s=>s.command!=="advance_checkpoint"))throw new b("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){await this.lease.runExclusive(()=>this.resolveConflictUnlocked(e,"record",t))}async resolveFileConflict(e,t){await this.lease.runExclusive(()=>this.resolveConflictUnlocked(e,"file",t))}async resolveConflictUnlocked(e,t,n){var o,a,c,l;if(this.mode!=="read_write")throw new b("mirror_read_only","Receive-only mirrors have no writable conflicts.");let i=await this.readState();if(!i||i.batch)throw new b("mirror_recovery_required","Finish sync recovery before resolving conflicts.");if(!((o=i.planned_conflicts)==null?void 0:o[e]))throw new b("mirror_conflict_not_found","Writable mirror conflict was not found.");if(n==="remote"){let d=await Ec(this.replicaId,this.transport,this.mode,this.selectiveSync,this.runtime);if(t==="record"){let u=(a=d.records.find(({record:f})=>f.record_id===e))==null?void 0:a.record;await this.installRemoteRecord(i,e,u)}else{let u=d.files.find(f=>f.file_id===e);await this.installRemoteFile(i,e,u)}}(c=i.planned_conflicts)==null||delete c[e],n==="remote"&&((l=i.local_bindings)==null||delete l[e]),await this.writeState(i)}async installRemoteRecord(e,t,n){var o,a,c,l;if(n){let d=(o=e.planned_conflicts)==null?void 0:o[t],u=await this.fileSystem.read(n.path),f=((a=e.records[t])==null?void 0:a.path)===n.path||(d==null?void 0:d.local.state)==="exact"&&d.local.object.path===n.path;await this.materializer.put(e,n,{inspectionPreflighted:!1,...f&&u!==null?{acceptedHash:this.runtime.digest(u)}:{}});return}let i=(c=e.planned_conflicts)==null?void 0:c[t],s=(i==null?void 0:i.local.state)==="exact"?i.local.object.path:(l=e.records[t])==null?void 0:l.path;s&&await this.fileSystem.read(s)!==null&&await this.fileSystem.remove(s),delete e.records[t]}async installRemoteFile(e,t,n){var o,a,c,l,d,u,f,p;if(n){if(!this.blobStore)throw new b("file_storage_unavailable","File resolution needs a blob store.");await bc(this.transport,this.blobStore,n);let y=(o=e.planned_conflicts)==null?void 0:o[t],h=(y==null?void 0:y.local.state)==="exact"?{content_digest:y.local.object.payload_revision,size:(a=y.local.object.size)!=null?a:0}:void 0,m=(l=(c=e.local_bindings)==null?void 0:c[t])==null?void 0:l.path;await this.materializer.putFile(e,n,e,h),m&&m!==n.path&&await this.fileSystem.remove(m);return}let i=(d=e.planned_conflicts)==null?void 0:d[t],s=(i==null?void 0:i.local.state)==="exact"?i.local.object.path:(f=(u=e.files)==null?void 0:u[t])==null?void 0:f.file.path;s&&await this.fileSystem.inspectBinary(s)!==null&&await this.fileSystem.remove(s),(p=e.files)==null||delete p[t]}async readState(){let e=await this.stateStore.read();if(e===null)return null;try{return Zw(e,this.replicaId,this.mode)}catch(t){throw t instanceof b?t:new b("invalid_mirror_state","Mirror metadata is corrupt or belongs to another replica.")}}writeState(e){return this.stateStore.write(e)}journalStore(){return{write:e=>this.writeState(e),...this.stateStore.appendJournal?{appendJournal:e=>this.stateStore.appendJournal(e)}:{}}}async pruneFileBlobs(){var n,i,s,o,a;if(!this.blobStore)return;let e=await this.readState();if(!e)return;let t=new Set;for(let c of Object.values((n=e.files)!=null?n:{}))t.add(c.file.content_digest);for(let c of Object.values((s=(i=e.batch)==null?void 0:i.payloads.files)!=null?s:{}))t.add(c.content_digest);for(let c of Object.values((a=(o=e.batch)==null?void 0:o.payloads.local_files)!=null?a:{}))t.add(c.content_digest);await this.blobStore.prune(t)}currentRecordPathPolicy(e){return this.materializer.recordPathPolicy(e)}};var so=class extends Cn{constructor(e,t,n){super(e,t,n,"read_write")}};function O0(r){let e=[...r.actions.flatMap(t=>t.command==="advance_checkpoint"?[]:[JM(t)]),...r.issues.map(t=>{var n;return{kind:"document",path:(n=t.path)!=null?n:"Sync engine",direction:"attention",action:"fix",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).map(t=>t.path),local_issues:r.issues.filter(t=>t.code==="invalid_frontmatter"&&t.path!==void 0).map(t=>({code:"invalid_frontmatter",message:t.message,path:t.path}))}}function JM(r){var c;if(r.command==="advance_checkpoint")throw new Error("Checkpoint actions are not preview entries.");if(r.command==="record_conflict"){let l=r.local.state==="exact"?r.local.object:r.remote.state==="exact"?r.remote.object:void 0;return{kind:r.entity==="file"?"file":"document",path:(c=l==null?void 0:l.path)!=null?c:r.identity,direction:"attention",action:"fix",detail:`Local and hosted ${r.entity} changes conflict (${r.conflict_kind.replace(/_/g," ")}).`,...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=r.command.split("_")[0],a=r.command.startsWith("move_")?` from ${t.path}`:"";return{kind:t.entity==="file"?"file":"document",path:n,direction:e?"download":"upload",action:s,detail:`${e?"Hosted":"Local"} ${t.entity} will ${o}${a}.`,...t.entity==="record"?{recordId:t.identity}:{},...t.entity==="file"?{fileId:t.identity}:{}}}var oo=".mdbase/connect-role.json",ao=".mdbase/authority-adoption.json",co=".mdbase/authority-adoption-snapshot.json",YM="mdbase-obsidian-connect-exact-v1",Ci="mirrors",XM="mdbase-connect-access-",QM="mdbase-connect-refresh-",ZM="mdbase-connect-adoption-",eC=300*1e3,lp=[".git/",".obsidian/",".trash/",".mdbase/"],lo=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Ue(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function Dc(r,e){if(e!=null)return e;if(!r.trim())return{};try{return JSON.parse(r)}catch(t){return{}}}function T0(r){var i;let e=(i=r["retry-after"])!=null?i:r["Retry-After"];if(!e)return;let t=Number(e);if(Number.isFinite(t)&&t>=0)return t*1e3;let n=Date.parse(e);if(Number.isFinite(n))return Math.max(0,n-Date.now())}function tC(){return async r=>{var t,n;if((t=r.signal)!=null&&t.aborted)throw new DOMException("Enrollment cancelled.","AbortError");let e=await(0,oe.requestUrl)({url:r.url,method:r.method,headers:r.headers,body:r.body===void 0?void 0:JSON.stringify(r.body),contentType:r.body===void 0?void 0:"application/json",throw:!1});if((n=r.signal)!=null&&n.aborted)throw new DOMException("Enrollment cancelled.","AbortError");return{status:e.status,body:Dc(e.text,e.json),retryAfterMs:T0(e.headers)}}}function rC(){return async r=>{var t,n;if((t=r.signal)!=null&&t.aborted)throw new DOMException("Collection adoption cancelled.","AbortError");let e=await(0,oe.requestUrl)({url:r.url,method:r.method,headers:r.headers,body:r.body===void 0?void 0:JSON.stringify(r.body),contentType:r.body===void 0?void 0:"application/json",throw:!1});if((n=r.signal)!=null&&n.aborted)throw new DOMException("Collection adoption cancelled.","AbortError");return{status:e.status,body:Dc(e.text,e.json),retryAfterMs:T0(e.headers)}}}var dp=class{constructor(e,t){this.accessToken=t;let n;try{n=new URL(e)}catch(i){throw new b("invalid_sync_url","Sync URL must be an absolute authority endpoint.")}if(!(n.protocol==="https:"||n.protocol==="http:"&&["localhost","127.0.0.1","[::1]","::1"].includes(n.hostname))||n.username||n.password||n.search||n.hash||!/^\/v1\/authorities\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\/sync\/?$/i.test(n.pathname))throw new b("invalid_sync_url","Sync URL must identify one authority sync endpoint.");this.syncUrl=n.href.replace(/\/$/,""),this.filesUrl=this.syncUrl.replace(/\/sync$/,"/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){let t=crypto.randomUUID();try{let n=await this.fileRequest("POST","downloads",{protocol_version:1,type:"open_file_download",transfer_id:t,file_id:e.file_id,revision:e.revision}),i=Ue(n.strategy)?n.strategy:{},s=i.part_size;if(n.protocol_version!==1||n.type!=="file_transfer"||n.transfer_id!==t||n.direction!=="download"||n.protection!=="transport_tls"||n.total_size!==e.size||i.kind!=="object_ranges"||!Number.isSafeInteger(s)||s<=0)throw new b("invalid_sync_response","The authority returned an incompatible file download session.");let o=Math.ceil(e.size/s);for(let a=0;a=300){let d=Dc(l.text,l.json),u=Ue(d)&&Ue(d.error)?d.error:{};throw new b(typeof u.code=="string"?u.code:"file_download_failed",typeof u.message=="string"?u.message:`File download failed (${l.status}).`)}if(l.arrayBuffer.byteLength!==c)throw new b("file_integrity_failed","The authority returned a file part with the wrong length.");yield new Uint8Array(l.arrayBuffer)}}finally{await this.fileRequest("DELETE",`transfers/${encodeURIComponent(t)}`).catch(()=>{})}}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)}request(e,t,n){return this.requestAt(this.syncUrl,e,t,n)}fileRequest(e,t,n){return this.requestAt(this.filesUrl,e,t,n)}async requestAt(e,t,n,i){let s=await(0,oe.requestUrl)({url:`${e}/${n}`,method:t,headers:{authorization:`Bearer ${this.accessToken}`},body:i===void 0?void 0:JSON.stringify(i),contentType:i===void 0?void 0:"application/json",throw:!1}),o=Dc(s.text,s.json);if(s.status<200||s.status>=300){let a=Ue(o)&&Ue(o.error)?o.error:{};throw new b(typeof a.code=="string"?a.code:"sync_failed",typeof a.message=="string"?a.message:`Sync request failed (${s.status}).`)}return o}};function Cr(r){let e=Os(r);if(e===".mdbase"||lp.some(t=>e.startsWith(t)))throw new b("unsafe_mirror_path",`The collection authority attempted to write a reserved path: ${e}`);return e}async function Li(r,e){let t=(0,oe.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 oe.TFolder)){if(s)throw new b("mirror_path_collision",`A file blocks the mirror folder ${n}.`);await r.adapter.exists(n)||await r.createFolder(n)}}}var up=class{constructor(e){this.vault=e}async exists(e){let t=Cr(e);return this.vault.getAbstractFileByPath(t)!==null||await this.vault.adapter.exists(t)}async read(e){let t=Cr(e),n=this.vault.getAbstractFileByPath(t);if(n==null)return null;if(!(n instanceof oe.TFile))throw new b("mirror_path_collision",`Expected a file at ${t}.`);return this.vault.cachedRead(n)}async write(e,t){let n=Cr(e),i=n.lastIndexOf("/");i>=0&&await Li(this.vault,n.slice(0,i));let s=this.vault.getAbstractFileByPath(n);if(s instanceof oe.TFolder)throw new b("mirror_path_collision",`A folder blocks the mirror file ${n}.`);s instanceof oe.TFile?await this.vault.modify(s,t):await this.vault.create(n,t)}async move(e,t){let n=Cr(e),i=Cr(t),s=i.lastIndexOf("/");s>=0&&await Li(this.vault,i.slice(0,s));let o=this.vault.getAbstractFileByPath(n);if(!(o instanceof oe.TFile))throw new b("mirror_path_collision",`Expected a file at ${n}.`);if(this.vault.getAbstractFileByPath(i)!==null||await this.vault.adapter.exists(i))throw new b("mirror_path_collision",`A file or folder blocks ${i}.`);await this.vault.rename(o,i)}async remove(e){let t=Cr(e),n=this.vault.getAbstractFileByPath(t);if(n!=null){if(!(n instanceof oe.TFile))throw new b("mirror_path_collision",`Expected a file at ${t}.`);await this.vault.delete(n,!0)}}async listMarkdown(e){return this.vault.getMarkdownFiles().map(t=>(0,oe.normalizePath)(t.path)).filter(t=>!e.has(t)).filter(t=>!lp.some(n=>t.startsWith(n))).sort()}async inspectBinary(e){let t=Cr(e),n=this.vault.getAbstractFileByPath(t);if(n==null)return null;if(!(n instanceof oe.TFile))throw new b("mirror_path_collision",`Expected a file at ${t}.`);let i=await this.vault.readBinary(n),s=await crypto.subtle.digest("SHA-256",i),o=Array.from(new Uint8Array(s),a=>a.toString(16).padStart(2,"0")).join("");return{size:i.byteLength,content_digest:`sha256:${o}`}}async writeBinary(e,t){let n=Cr(e),i=[],s=0;for await(let d of t){if(!(d instanceof Uint8Array)||!Number.isSafeInteger(s+d.byteLength))throw new b("invalid_file_materialization","The binary file stream is invalid or too large.");i.push(d),s+=d.byteLength}let o=new Uint8Array(s),a=0;for(let d of i)o.set(d,a),a+=d.byteLength;let c=n.lastIndexOf("/");c>=0&&await Li(this.vault,n.slice(0,c));let l=this.vault.getAbstractFileByPath(n);if(l instanceof oe.TFolder)throw new b("mirror_path_collision",`A folder blocks the mirror file ${n}.`);l instanceof oe.TFile?await this.vault.modifyBinary(l,o.buffer):await this.vault.createBinary(n,o.buffer)}async listBinary(e){return this.vault.getFiles().map(t=>(0,oe.normalizePath)(t.path)).filter(t=>!t.toLowerCase().endsWith(".md")).filter(t=>!e.has(t)).filter(t=>!lp.some(n=>t.startsWith(n))).sort()}async readBinary(e){let t=Cr(e),n=this.vault.getAbstractFileByPath(t);if(n==null)return null;if(!(n instanceof oe.TFile))throw new b("mirror_path_collision",`Expected a file at ${t}.`);let i=new Uint8Array(await this.vault.readBinary(n));return(async function*(){yield i})()}},fp=class{constructor(e){this.key=e;this.database=null}async read(){let e=await this.open();return new Promise((t,n)=>{let i=e.transaction(Ci,"readonly").objectStore(Ci).get(this.key);i.onsuccess=()=>{var s;return t((s=i.result)!=null?s:null)},i.onerror=()=>n(i.error)})}async write(e){let t=await this.open();await new Promise((n,i)=>{let s=t.transaction(Ci,"readwrite");s.objectStore(Ci).put(e,this.key),s.oncomplete=()=>n(),s.onerror=()=>i(s.error),s.onabort=()=>i(s.error)})}open(){var e;if(typeof indexedDB=="undefined")throw new b("storage_unavailable","IndexedDB is required for persistent mirror state.");return(e=this.database)!=null||(this.database=new Promise((t,n)=>{let i=indexedDB.open(YM,1);i.onupgradeneeded=()=>{i.result.objectStoreNames.contains(Ci)||i.result.createObjectStore(Ci)},i.onerror=()=>n(i.error),i.onsuccess=()=>t(i.result)})),this.database}},Ni=class Ni{constructor(e){this.key=e}async runExclusive(e){if(Ni.active.has(this.key))throw new b("mirror_busy","A mirror operation is already running for this vault.");Ni.active.add(this.key);try{return await e()}finally{Ni.active.delete(this.key)}}};Ni.active=new Set;var pp=Ni,qc=class{constructor(e,t,n={}){this.app=e;this.settingsHost=t;this.options=n;this.progress=null;this.syncAbort=null;this.adoptionMarker=null;var i,s,o;this.fileSystem=(i=n.fileSystem)!=null?i:new up(e.vault),this.enrollmentClient=(s=n.enrollmentClient)!=null?s:new yc({request:tC()}),this.adoptionClient=(o=n.adoptionClient)!=null?o:new vc({request:rC()})}async initialize(){if(this.adoptionMarker=await this.readAdoptionMarker(),this.adoptionMarker&&this.settingsHost.getMirrorProfile())throw new b("authority_adoption_state_conflict","This vault contains both an authority-adoption checkpoint and a mirror profile.")}getProgress(){return this.progress?{...this.progress}:null}cancelSync(){var e;(e=this.syncAbort)==null||e.abort()}getAdoptionMarker(){return this.adoptionMarker?JSON.parse(JSON.stringify(this.adoptionMarker)):null}assertLocalAuthorityWritable(){if(this.adoptionMarker&&["fenced","activating","adopted"].includes(this.adoptionMarker.phase))throw new b("local_authority_fenced",this.adoptionMarker.phase==="adopted"?"Hosted mdbase is now authoritative. Finish reconnecting this vault as its mirror before editing.":"This local authority is frozen while its exact snapshot is adopted by hosted mdbase.")}async adoptLocalCollection(e,t){if(this.settingsHost.getMirrorProfile())throw new b("mirror_already_configured","This vault already mirrors a collection authority.");if(this.adoptionMarker)return this.resumeAdoption(t);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);return await this.storeAdoptionSecret(i),await this.writeAdoptionMarker({version:1,phase:"waiting_for_approval",session:cp(i),manifest_digest:null,source_revision:null,source_head:null}),await t.onVerification(cp(i)),this.runAdoptionWithRecovery(i,t)}async resumeAdoption(e={}){var s,o,a;let t=(s=this.adoptionMarker)!=null?s:await this.readAdoptionMarker();if(!t)throw new b("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 b("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((o=e.onVerification)==null?void 0:o.call(e,cp(i))),this.runAdoptionWithRecovery(i,{...e,onVerification:(a=e.onVerification)!=null?a:(()=>{})})}async cancelAdoption(e){var i;let t=(i=this.adoptionMarker)!=null?i:await this.readAdoptionMarker();if(!t)return;if(["activating","adopted"].includes(t.phase))throw new b("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 b("authority_adoption_credentials_missing","The collection-adoption credential is missing from Obsidian's secret store.");await this.adoptionClient.cancel({...t.session,credential:n},{signal:e}),await this.clearAdoptionCheckpoint(t.session.adoptionId)}async enroll(e,t){let n=await this.assertCanBecomeMirror(e.collectionId),i=await this.enrollmentClient.enroll({...e,...n?{collectionId:n}:{}},t),s=await this.markMirror(i.collectionId);try{await this.persistEnrollment(i)}catch(o){if(s)try{await this.app.vault.adapter.remove(oo)}catch(a){throw new b("enrollment_recovery_required",`Enrollment settings could not be saved and the temporary role marker could not be removed: ${o instanceof Error?o.message:String(o)}`)}throw o}return this.requireProfile()}async preview(){let e=await this.createMirror();return O0(await e.inspect())}async status(){let e=this.settingsHost.getMirrorProfile();return e?(await this.assertMirror(e.collectionId),(await this.createMirror()).status()):null}async sync(e,t){if(this.syncAbort)throw new b("mirror_busy","Synchronization is already running for this vault.");let n=new AbortController;this.syncAbort=n;let i=await this.createMirror(s=>{this.progress=s,t==null||t({...s})});try{return await i.apply(e.plan,{signal:n.signal})}finally{this.progress=null,this.syncAbort=null}}async resolveConflict(e,t){let n=await this.createMirror();return await n.resolveConflict(e,t),n.status()}async runAdoption(e,t){let n=this.requireAdoptionMarker(e.adoptionId),i=null;if(n.phase==="adopted"){let s=await this.adoptionClient.exchange(e,t);if(s.status!=="completed")throw new b("authority_adoption_state_conflict","The local checkpoint says adoption completed, but Connect does not.");i=s}else if(n.phase==="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"&&await this.adoptionClient.uploadSnapshot(e,o,s,t),await this.updateAdoptionPhase("activating",s),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),o=await this.captureAuthoritySnapshot(e.requested.collectionId);await this.updateAdoptionPhase("uploading"),await this.adoptionClient.uploadSnapshot(e,s,o,t);let a=await this.captureAuthoritySnapshot(e.requested.collectionId);await this.writeAdoptionSnapshot(a),await this.updateAdoptionPhase("fenced",a);let c=await this.requirePreparedAdoption(e,t);await this.adoptionClient.uploadSnapshot(e,c,a,t),await this.updateAdoptionPhase("activating",a),i=await this.adoptionClient.complete(e,a,t)}return await this.updateAdoptionPhase("adopted"),this.finishRetainedMirror(e,i,t)}async runAdoptionWithRecovery(e,t){try{return await this.runAdoption(e,t)}catch(n){throw nC(n)?(await this.adoptionClient.cancel(e,{signal:t.signal}).catch(()=>{}),await this.clearAdoptionCheckpoint(e.adoptionId),new b(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 kr("Hosted authority activation has already started. Resume using the saved fenced snapshot."):new b("authority_adoption_already_completed","Hosted authority has already adopted this collection.")}async finishRetainedMirror(e,t,n){var a,c;let i,s=this.adoptionClient.mirrorEnrollmentSession(e,t);if(!s)throw new b("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:l=>{var d;return(d=n.onStatus)==null?void 0:d.call(n,{...l,state:l.state})}})}catch(l){if((a=n.signal)!=null&&a.aborted)throw l;i=await this.enrollmentClient.enroll({controlUrl:e.controlUrl,collectionId:e.requested.collectionId,mirrorName:(c=e.requested.mirrorName)!=null?c:e.requested.sourceName,mode:"read_write"},{signal:n.signal,onVerification:n.onVerification})}let o=await this.markMirror(i.collectionId);try{await this.persistEnrollment(i)}catch(l){throw o&&await this.app.vault.adapter.remove(oo),l}return await this.clearAdoptionCheckpoint(e.adoptionId),this.requireProfile()}async captureAuthoritySnapshot(e){let t=await ui(this.app.vault);if(!t)throw new b("invalid_collection_configuration","A valid mdbase.yaml is required.");let n=await this.app.vault.adapter.read("mdbase.yaml"),i=(0,oe.parseYaml)(n),s=[{path:"mdbase.yaml",kind:"configuration",document:n}],o=`${(0,oe.normalizePath)(t.settings.types_folder)}/`,a=this.app.vault.getMarkdownFiles().filter(d=>(0,oe.normalizePath)(d.path).startsWith(o)).sort((d,u)=>d.path.localeCompare(u.path));for(let d of a)s.push({path:(0,oe.normalizePath)(d.path),kind:"type",document:await this.app.vault.cachedRead(d)});let c=iC(i);if(c.length){let d=c.map(f=>(0,R0.default)(f,{dot:!0})),u=sC(this.app.vault).filter(f=>f.extension==="base").filter(f=>d.some(p=>p((0,oe.normalizePath)(f.path)))).sort((f,p)=>f.path.localeCompare(p.path));for(let f of u)s.push({path:(0,oe.normalizePath)(f.path),kind:"view",document:await this.app.vault.cachedRead(f)})}let l=[];for(let d of this.app.vault.getMarkdownFiles().sort((u,f)=>u.path.localeCompare(f.path))){let u=(0,oe.normalizePath)(d.path);if(Rs(u,t))continue;let f=await this.app.vault.cachedRead(d);l.push({path:u,document:f})}return Hf({collectionId:e,sourceHead:0,specVersion:t.spec_version,resources:s,records:l})}async ensurePortableCollectionIdentity(){if(!await this.app.vault.adapter.exists("mdbase.yaml"))throw new b("collection_not_initialized","Initialize an mdbase collection before hosting it.");let e=await this.app.vault.adapter.read("mdbase.yaml"),t;try{t=(0,oe.parseYaml)(e)}catch(o){throw new b("invalid_collection_configuration","mdbase.yaml must contain valid YAML.")}if(!Ue(t))throw new b("invalid_collection_configuration","mdbase.yaml must contain a YAML mapping.");let n=Ue(t["x-mdbase-connect"])?t["x-mdbase-connect"].collection_id:void 0,i;if(n===void 0){i=crypto.randomUUID();let o=Ue(t["x-mdbase-connect"])?t["x-mdbase-connect"]:{};t["x-mdbase-connect"]={...o,collection_id:i},await this.app.vault.adapter.write("mdbase.yaml",(0,oe.stringifyYaml)(t))}else if(typeof n=="string"&&lo.test(n))i=n;else throw new b("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}}async createMirror(e){var o,a,c,l,d,u,f,p,y;let t=this.requireProfile();await this.assertMirror(t.collectionId);let n=await this.freshAccessToken(t),i=(c=(a=(o=this.options).transportFactory)==null?void 0:a.call(o,t,n))!=null?c:new dp(t.syncUrl,n),s={stateStore:(u=(d=(l=this.options).stateStoreFactory)==null?void 0:d.call(l,t))!=null?u:new fp(`${t.collectionId}:${t.replicaId}`),fileSystem:this.fileSystem,lease:(y=(p=(f=this.options).leaseFactory)==null?void 0:p.call(f,t))!=null?y:new pp(`${t.collectionId}:${t.replicaId}`),onProgress:e};return t.mode==="read_write"?new so(t.replicaId,i,s):new Cn(t.replicaId,i,s)}requireProfile(){let e=this.settingsHost.getMirrorProfile();if(!e)throw new b("mirror_not_configured","This vault is not connected to a collection authority.");return e}accessSecretId(e){return`${XM}${e.toLowerCase()}`}refreshSecretId(e){return`${QM}${e.toLowerCase()}`}adoptionSecretId(e){return`${ZM}${e.toLowerCase()}`}async storeAdoptionSecret(e){this.app.secretStorage.setSecret(this.adoptionSecretId(e.adoptionId),e.credential)}async persistEnrollment(e){this.app.secretStorage.setSecret(this.accessSecretId(e.collectionId),e.accessToken),this.app.secretStorage.setSecret(this.refreshSecretId(e.collectionId),e.refreshCredential),await this.settingsHost.saveMirrorProfile({version:1,syncUrl:e.syncUrl,controlUrl:e.controlUrl,collectionId:e.collectionId,replicaId:e.replicaId,mode:e.mode,name:e.name,enrollmentId:e.enrollmentId,accessTokenExpiresAt:e.accessTokenExpiresAt})}async freshAccessToken(e){let t=this.accessSecretId(e.collectionId),n=this.app.secretStorage.getSecret(t),i=Date.parse(e.accessTokenExpiresAt);if(n&&Number.isFinite(i)&&i-Date.now()>eC)return n;let s=this.app.secretStorage.getSecret(this.refreshSecretId(e.collectionId));if(!s)throw new b("mirror_credentials_missing","The mirror refresh credential is missing. Re-enroll this vault.");let o=await this.enrollmentClient.renew({controlUrl:e.controlUrl,syncUrl:e.syncUrl,collectionId:e.collectionId,replicaId:e.replicaId,mode:e.mode,name:e.name,enrollmentId:e.enrollmentId,accessToken:n!=null?n:"",refreshCredential:s,accessTokenExpiresAt:e.accessTokenExpiresAt});return await this.persistEnrollment(o),o.accessToken}async assertCanBecomeMirror(e){var o;let t=await this.readMarker(),n=await this.readPortableCollectionId();if(n&&!t)throw new b("local_authority_requires_transfer","This vault has a local Connect identity. Transfer authority explicitly before using it as a mirror.");if(n&&(t==null?void 0:t.collection_id)!==n)throw new b("mirror_identity_conflict","The vault identity and mirror role marker identify different collections.");let i=this.settingsHost.getMirrorProfile(),s=(o=i==null?void 0:i.collectionId)!=null?o:e;if(t&&s&&t.collection_id!==s)throw new b("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 b("existing_collection_requires_transfer","This vault already contains an mdbase collection. Connect an empty vault, or transfer collection authority explicitly.");return s!=null?s:t==null?void 0:t.collection_id}async readPortableCollectionId(){if(!await this.app.vault.adapter.exists("mdbase.yaml"))return null;let e;try{e=(0,oe.parseYaml)(await this.app.vault.adapter.read("mdbase.yaml"))}catch(i){throw new b("invalid_collection_configuration","mdbase.yaml must contain valid YAML.")}if(!Ue(e))throw new b("invalid_collection_configuration","mdbase.yaml must contain a YAML mapping.");let t=e["x-mdbase-connect"];if(t===void 0)return null;if(!Ue(t))throw new b("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"||!lo.test(n))throw new b("invalid_collection_configuration","x-mdbase-connect.collection_id must be a UUID string.");return n}async markMirror(e){let t=await this.readMarker();if(t){if(t.collection_id!==e)throw new b("mirror_identity_conflict","This vault already mirrors a different collection authority.");return!1}return await Li(this.app.vault,".mdbase"),await this.app.vault.adapter.write(oo,`${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 b("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(oo))return null;let e;try{e=JSON.parse(await this.app.vault.adapter.read(oo))}catch(t){throw new b("invalid_mirror_marker","The mirror role marker is corrupt.")}if(!Ue(e)||e.version!==1||e.role!=="mirror"||typeof e.collection_id!="string"||!lo.test(e.collection_id))throw new b("invalid_mirror_marker","The mirror role marker is invalid.");return e}requireAdoptionMarker(e){if(!this.adoptionMarker||this.adoptionMarker.session.adoptionId!==e)throw new b("authority_adoption_state_conflict","The collection-adoption checkpoint does not match this approval.");return this.adoptionMarker}async updateAdoptionPhase(e,t){if(!this.adoptionMarker)throw new b("authority_adoption_not_found","Collection-adoption checkpoint is missing.");await this.writeAdoptionMarker({...this.adoptionMarker,phase:e,...t?{manifest_digest:t.manifest_digest,source_revision:t.source_revision,source_head:t.source_head}:{}})}async writeAdoptionMarker(e){await Li(this.app.vault,".mdbase"),await this.app.vault.adapter.write(ao,`${JSON.stringify(e,null,2)} +`),this.adoptionMarker=e}async readAdoptionMarker(){if(!await this.app.vault.adapter.exists(ao))return null;let e;try{e=JSON.parse(await this.app.vault.adapter.read(ao))}catch(t){throw new b("invalid_authority_adoption_checkpoint","The collection-adoption checkpoint is corrupt.")}if(!oC(e))throw new b("invalid_authority_adoption_checkpoint","The collection-adoption checkpoint is invalid.");return e}async writeAdoptionSnapshot(e){await Li(this.app.vault,".mdbase"),await this.app.vault.adapter.write(co,JSON.stringify(e))}async readAdoptionSnapshot(e){if(!await this.app.vault.adapter.exists(co))throw new b("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(co))}catch(n){throw new b("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 b("authority_adoption_snapshot_mismatch","The fenced authority snapshot does not match its durable checkpoint.");return t}async clearAdoptionCheckpoint(e){await this.app.vault.adapter.exists(ao)&&await this.app.vault.adapter.remove(ao),await this.app.vault.adapter.exists(co)&&await this.app.vault.adapter.remove(co),this.app.secretStorage.setSecret(this.adoptionSecretId(e),""),this.adoptionMarker=null}};function cp(r){let{credential:e,...t}=r;return t}function nC(r){return r instanceof J&&["authority_adoption_expired","authority_adoption_cancelled"].includes(r.code)}function iC(r){if(!Ue(r))return[];let e=r["x-obsidian"];return!Ue(e)||!Ue(e.bases)||!Array.isArray(e.bases.include)?[]:e.bases.include.filter(t=>typeof t=="string")}function sC(r){var i;let e=(i=r.getFiles)==null?void 0:i.call(r);if(e)return e;let t=[],n=s=>{for(let o of s.children)o instanceof oe.TFile?t.push(o):o instanceof oe.TFolder&&n(o)};return n(r.getRoot()),t}function oC(r){if(!Ue(r)||r.version!==1||!["waiting_for_approval","uploading","fenced","activating","adopted"].includes(String(r.phase))||!Ue(r.session))return!1;let e=r.session;return typeof e.controlUrl=="string"&&typeof e.adoptionId=="string"&&lo.test(e.adoptionId)&&typeof e.verificationUri=="string"&&typeof e.expiresAt=="string"&&Ue(e.requested)&&typeof e.requested.collectionId=="string"&&lo.test(e.requested.collectionId)&&typeof e.requested.displayName=="string"&&typeof e.requested.sourceName=="string"&&e.requested.retainMirror===!0&&(r.manifest_digest===null||typeof r.manifest_digest=="string")&&(r.source_revision===null||typeof r.source_revision=="string")&&(r.source_head===null||Number.isSafeInteger(r.source_head))}var it=require("obsidian");var ho="0.3.0",aC=new Set(["name","description","display_name_key","strict","path_pattern","filename_pattern","match","fields","extends"]),cC=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 ve(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function Ce(r){return r===void 0?r:JSON.parse(JSON.stringify(r))}function Nr(r){return eo.digest(r)}function Nn(r){return Array.isArray(r)?`[${r.map(Nn).join(",")}]`:ve(r)?`{${Object.keys(r).sort().map(e=>`${JSON.stringify(e)}:${Nn(r[e])}`).join(",")}}`:JSON.stringify(r)}function hp(r){if(Array.isArray(r))return r.map(hp);if(!ve(r))return r;let e={};for(let[t,n]of Object.entries(r)){let i=hp(n);i!=null&&(Array.isArray(i)&&i.length===0||ve(i)&&Object.keys(i).length===0||(e[t]=i))}return e}function ji(r){return[...new Set(r)]}function lC(r){return ve(r.fields)?Object.values(r.fields).some(e=>ve(e)&&(typeof e.tn_role=="string"||Array.isArray(e.tn_completed_values))):!1}function mp(r,e,t){let n=ve(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)?Ce(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=mp(`${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[d,u]of Object.entries(ve(n.fields)?n.fields:{})){let f=mp(`${r}.${d}`,u,t);c[d]=f.schema,Object.assign(i,f.links),Object.assign(s,f.legacy),o.push(...f.unsupported),ve(u)&&u.required===!0&&l.push(d)}t&&r==="blockedBy[]"&&l.push("uid"),a={type:"object",additionalProperties:Object.keys(c).length===0,properties:c,...l.length?{required:ji(l)}:{}};break}default:a={},o.push(`${r}.type`);break}t&&r==="title"&&(a.minLength=1,a.description="Short summary of the task."),typeof n.description=="string"&&(a.description=n.description),typeof n.min=="number"&&(n.type==="string"?a.minLength=n.min:n.type==="list"?a.minItems=n.min:a.minimum=n.min),typeof n.max=="number"&&(n.type==="string"?a.maxLength=n.max:n.type==="list"?a.maxItems=n.max:a.maximum=n.max),typeof n.min_length=="number"&&(a.minLength=n.min_length),typeof n.max_length=="number"&&(a.maxLength=n.max_length),typeof n.pattern=="string"&&(a.pattern=n.pattern),n.deprecated===!0&&(a.deprecated=!0),n.default!==void 0&&(a.default=Ce(n.default)),n.computed!==void 0&&o.push(`${r}.computed`);for(let[c,l]of Object.entries(n)){let d=t&&(c==="tn_role"||c==="tn_completed_values");(!cC.has(c)||(c==="tn_role"||c==="tn_completed_values")&&!d)&&(s[`${r}.${c}`]=Ce(l))}return{schema:a,links:i,legacy:s,unsupported:o}}function uo(r,e,t,n){let i=ve(r[e])?r[e]:{},s=ve(i.set)?i.set:{};s[t]=n,i.set=s,r[e]=i}function dC(r,e,t){if(t==="now")uo(r,"on_create",e,{now:!0});else if(t==="now_on_write")uo(r,"on_update",e,{now:!0});else if(t==="uuid")uo(r,"on_create",e,{uuid:!0});else if(t==="ulid")uo(r,"on_create",e,{ulid:!0});else if(ve(t)&&t.transform==="slugify"&&typeof t.from=="string")uo(r,"on_create",e,{slugify:t.from});else return!1;return!0}function uC(r){var t;let e=r.match(/^(.*\/)?\{title\}\.md$/);return e?{runtime:"tasknotes",template:"{{title}}",folder:((t=e[1])!=null?t:"").replace(/\/$/,""),generated_by:"tasknotes.filename.create"}:{runtime:"tasknotes",template:r,generated_by:"tasknotes.filename.create"}}function fC(r,e,t){var P;if(t.kind==="mdbase.type"||t.schema!==void 0)throw new Error(`${r} already looks like a v0.3 type.`);if(typeof t.name!="string"||!ve(t.fields))throw new Error(`${r} is not a v0.2 type with a name and fields.`);let n=lC(t),i=t.name.trim().toLowerCase(),s={type:{const:i}},o=[],a={},c={},l=[],d={},u={},f=[],p=[],y={},h={},m={};for(let[O,$]of Object.entries(t.fields)){let R=ve($)?$:{},S=mp(O,R,n);s[O]=S.schema,Object.assign(c,S.links),Object.assign(u,S.legacy),f.push(...S.unsupported),R.required===!0&&o.push(O),R.default!==void 0&&(a[O]=Ce(R.default)),R.unique===!0&&l.push({field:O,scope:"collection"}),R.generated!==void 0&&dC(d,O,R.generated)&&p.push(O),typeof R.tn_role=="string"&&(y[R.tn_role]=O),Array.isArray(R.tn_completed_values)&&(h.completed_values=Ce(R.tn_completed_values))}a.status!==void 0&&(h.default=Ce(a.status)),a.priority!==void 0&&(m.default=Ce(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,_={...g?{display:{name_field:g}}:{},read_defaults:a,links:c,unique:l};typeof t.path_pattern=="string"&&(_.path=n?uC(t.path_pattern):{pattern:t.path_pattern});let w={};for(let[O,$]of Object.entries(t))aC.has(O)||(w[O]=Ce($));Object.keys(u).length&&(w.fields=u);let k=hp({kind:"mdbase.type",name:i,version:1,description:typeof t.description=="string"?t.description:void 0,match:ve(t.match)?Ce(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:ji(o)}:{}}},collection:_,lifecycle:d,...n?{"x-tasknotes":{contract:"tasknotes.task",version:1,field_roles:y,status:h,priority:m,archive:{tags_field:(P=y.tags)!=null?P:"tags",archived_tag:"archived"}}}:{},...Object.keys(w).length?{"x-legacy-v0.2":w}:{}}),v=[];t.extends!==void 0&&f.push("extends");for(let O of ji(f).sort())v.push({path:r,code:"migration_lossy",message:`${O} cannot be expressed as canonical v0.3 write behavior and was retained as legacy metadata where possible.`,severity:"lossy"});return n&&v.push({path:r,code:"path_policy_runtime_owned",message:"TaskNotes filename behavior is recorded as TaskNotes runtime metadata.",severity:"warning"}),t.strict!==!0&&v.push({path:r,code:"additional_properties_true",message:"The migrated schema allows additional properties because the source type was not strict.",severity:"warning"}),typeof t.display_name_key=="string"&&!g&&v.push({path:r,code:"display_field_missing",message:`The display field '${t.display_name_key}' is not declared, so collection.display was omitted.`,severity:"warning"}),{target:k,summary:{path:r,name:i,fieldsConverted:Object.keys(t.fields).length,requiredFields:ji(o),defaultsMoved:Object.keys(a),generatedFieldsMoved:ji(p),linksMoved:Object.keys(c),taskNotes:n},diagnostics:v}}function pC(r){let e=Ce(r);e.spec_version=ho;let t=ve(e.settings)?e.settings:{};if(e.settings=t,!Array.isArray(t.record_extensions)){let n=Array.isArray(t.extensions)?t.extensions.map(String).map(i=>i.replace(/^\./,"")):[];t.record_extensions=ji(["md",...n])}return Array.isArray(t.explicit_type_keys)||(t.explicit_type_keys=["type","types"]),typeof t.include_subfolders!="boolean"&&(t.include_subfolders=!0),t.validation===void 0&&typeof t.default_validation=="string"&&(t.validation=t.default_validation),t.validation===void 0&&typeof e.default_validation=="string"&&(t.validation=e.default_validation),delete t.default_validation,delete t.extensions,delete e.default_validation,e}function M0(r,e){let t=ve(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 hC(r,e){var n,i;let t={};for(let[s,o]of Object.entries(ve(e.fields)?e.fields:{}))ve(o)&&(t[s]=Ce(o));return{name:typeof e.name=="string"?e.name:(i=(n=r.split("/").pop())==null?void 0:n.replace(/\.md$/,""))!=null?i:"type",fields:t,match:ve(e.match)?Ce(e.match):void 0,filePath:r,specProfile:"v0.2"}}function mC(r,e){var i,s;let t=ve(e.schema)?e.schema:{},n=ve(t.value)?t.value:{};return{name:typeof e.name=="string"?e.name:(s=(i=r.split("/").pop())==null?void 0:i.replace(/\.md$/,""))!=null?s:"type",fields:Sn(n),match:ve(e.match)?Ce(e.match):void 0,collection:ve(e.collection)?Ce(e.collection):void 0,schema:Ce(n),filePath:r,specProfile:"v0.3"}}function yC(r,e,t){let n=Ce(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]=Ce(a.default))}return n}function gC(r,e,t){var i,s;let n=Ce(r);for(let o of e){let a=t.get(o);if(a)for(let[c,l]of Object.entries((s=(i=a.collection)==null?void 0:i.read_defaults)!=null?s:{}))c in n||(n[c]=Ce(l))}return n}async function _C(r,e){let t=(0,it.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 it.TFolder)){if(s)throw new Error(`A file blocks folder ${n}.`);await r.adapter.exists(n)||await r.createFolder(n)}}}async function Fc(r,e,t){let n=(0,it.normalizePath)(e),i=n.lastIndexOf("/");if(i>=0&&await _C(r,n.slice(0,i)),n.startsWith(".mdbase/")){await r.adapter.write(n,t);return}let s=r.getAbstractFileByPath(n);if(s instanceof it.TFolder)throw new Error(`A folder blocks file ${n}.`);s instanceof it.TFile?await r.modify(s,t):await r.create(n,t)}async function po(r,e){let t=(0,it.normalizePath)(e),n=r.getAbstractFileByPath(t);if(n instanceof it.TFile)return r.cachedRead(n);if(await r.adapter.exists(t))return r.adapter.read(t);throw new Error(`File not found: ${e}`)}async function C0(r){var k;let e=await po(r,"mdbase.yaml"),t=(0,it.parseYaml)(e);if(!ve(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===ho?"This collection is already mdbase v0.3.":`Expected an mdbase v0.2.x collection, found ${JSON.stringify(n)}.`);let i=ve(t.settings)?t.settings:{},s=typeof i.types_folder=="string"?(0,it.normalizePath)(i.types_folder):"_types",o=`${s}/`,a=[],c=[],l=[],d=pC(t),u=`${(0,it.stringifyYaml)(d).trimEnd()} +`;a.push({path:"mdbase.yaml",sourceDigest:Nr(e),targetDigest:Nr(u),source:e,target:u});let f=new Map,p=new Map;for(let v of r.getMarkdownFiles().filter(P=>P.path.startsWith(o)).sort((P,O)=>P.path.localeCompare(O.path))){let P=await r.cachedRead(v),O=It(P);if(!O.hasFrontmatter||O.error)throw new Error(`Cannot migrate ${v.path}: ${(k=O.error)!=null?k:"frontmatter is missing"}.`);let $=fC(v.path,n,O.frontmatter),R=hC(v.path,O.frontmatter),S=mC(v.path,$.target);f.set(R.name,R),p.set(S.name,S);let V=`${yt($.target,O.body)} +`;a.push({path:v.path,sourceDigest:Nr(P),targetDigest:Nr(V),source:P,target:V}),c.push($.summary),l.push(...$.diagnostics)}if(!c.length)throw new Error(`No v0.2 type files were found in ${s}.`);let y=0,h=0,m=M0(t,n),g=M0(d,ho),_=r.getMarkdownFiles().filter(v=>!v.path.startsWith(o)).filter(v=>!v.path.startsWith(".mdbase/")).sort((v,P)=>v.path.localeCompare(P.path));for(let[v,P]of _.entries()){let O=It(await r.cachedRead(P));if(O.error){h+=1;continue}let $=fi(P.path,O.frontmatter,m,f),R=fi(P.path,O.frontmatter,g,p),S=yC(O.frontmatter,$,f),V=gC(O.frontmatter,R,p);(Nn($.slice().sort())!==Nn(R.slice().sort())||Nn(S)!==Nn(V))&&l.push({path:P.path,code:"effective_read_changed",message:"The proposed v0.3 types would change this record's resolved types or effective default values.",severity:"lossy"}),y+=1,v>0&&v%250===0&&await new Promise(B=>setTimeout(B,0))}let w=Nr(Nn({sourceVersion:n,operations:a.map(({path:v,sourceDigest:P,targetDigest:O})=>({path:v,sourceDigest:P,targetDigest:O})),diagnostics:l}));return{planVersion:1,analysisId:w,sourceVersion:n,targetVersion:ho,createdAt:new Date().toISOString(),backupLocation:`.mdbase/migrations/v02-to-v03-${w.slice(0,12)}`,operations:a,typeSummaries:c,diagnostics:l,applicable:!l.some(v=>v.severity==="lossy"),recordFilesRewritten:0,recordsVerified:y,recordsSkipped:h}}async function fo(r,e,t){await Fc(r,e,`${JSON.stringify(t,null,2)} +`)}async function N0(r,e,t={}){if(e.planVersion!==1||e.targetVersion!==ho)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 po(r,s.path);if(Nr(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 Fc(r,`${e.backupLocation}/files/${s.path}`,s.source);await fo(r,n,i),i.status="applying",await fo(r,n,i);try{for(let s of e.operations){let o=await po(r,s.path);if(Nr(o)!==s.sourceDigest)throw new Error(`${s.path} changed during migration.`);i.written.push(s.path),await fo(r,n,i),await Fc(r,s.path,s.target);let a=await po(r,s.path);if(Nr(a)!==s.targetDigest)throw new Error(`${s.path} did not verify after write.`)}return i.status="applied",i.completed_at=new Date().toISOString(),await fo(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 Fc(r,a,c.source),Nr(await po(r,a))!==c.sourceDigest&&o.push(a)}catch(l){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 fo(r,n,i)}catch(a){}return{applied:!1,restored:o.length===0,manifestPath:n,written:[...i.written],error:i.error}}}var Uc=require("obsidian");function Ie(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function mr(r){return JSON.parse(JSON.stringify(r))}var bC=new Set(["file","formula","this"]);function wC(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(bC.has(e.toLowerCase()))throw new Error(`Type name '${e}' is reserved.`);return e}function yp(){return{specProfile:"v0.3",originalFrontmatter:{},name:"",description:"",extendsType:"",displayNameKey:"",strictMode:!1,pathPattern:"",filenamePattern:"",matchPathGlob:"",matchFieldsPresent:"",matchWhere:"",fields:[{name:"title",definition:{type:"string",required:!0}}],body:`# Type -Describe the type and intended usage.`,extraFrontmatter:{}}}function eC(r){return Te(r)?Object.entries(r).filter(e=>Te(e[1])).map(([e,t])=>({name:e,definition:br(t)})):[]}function tC(r){return Object.fromEntries(r.map(e=>[e.name,e.definition]))}function rC(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 Ic(r,e,t){let n=r.kind==="mdbase.type",i=n&&Te(r.schema)?r.schema:{},s=Te(i.value)?i.value:{},o=typeof i.ref=="string"?i.ref:"",a=n&&Te(r.collection)?r.collection:{},c=Te(a.display)?a.display:{},l=Te(a.path)?a.path:{},u=eC(n?$n(s):r.fields);n&&nC(u,a.links);let d=Te(r.match)?r.match:{},f=n?s.additionalProperties===!1:r.strict,p=new Set(["name","description","extends","display_name_key","strict","path_pattern","filename_pattern","match","fields"]),m={};for(let[y,b]of Object.entries(r))p.has(y)||(m[y]=br(b));let h="";if(d.where!==void 0)try{h=(0,Pc.stringifyYaml)(d.where).trim()}catch(y){h=""}return{specProfile:n?"v0.3":"v0.2",originalFrontmatter:br(r),name:typeof r.name=="string"&&r.name.trim()?r.name:t,description:typeof r.description=="string"?r.description:"",extendsType:typeof r.extends=="string"?r.extends:"",displayNameKey:n?typeof c.name_field=="string"?c.name_field:"":typeof r.display_name_key=="string"?r.display_name_key:"",strictMode:f==="warn"?"warn":f===!0,pathPattern:n?typeof l.pattern=="string"?l.pattern:"":typeof r.path_pattern=="string"?r.path_pattern:"",filenamePattern:n?"":typeof r.filename_pattern=="string"?r.filename_pattern:"",matchPathGlob:typeof d.path_glob=="string"?d.path_glob:"",matchFieldsPresent:Array.isArray(d.fields_present)?d.fields_present.map(String).join(", "):"",matchWhere:h,fields:u.length||o?u:Yf().fields,body:e.trim()||`# ${t} +Describe the type and intended usage.`,extraFrontmatter:{}}}function vC(r){return Ie(r)?Object.entries(r).filter(e=>Ie(e[1])).map(([e,t])=>({name:e,definition:mr(t)})):[]}function $C(r){return Object.fromEntries(r.map(e=>[e.name,e.definition]))}function SC(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 Vc(r,e,t){let n=r.kind==="mdbase.type",i=n&&Ie(r.schema)?r.schema:{},s=Ie(i.value)?i.value:{},o=typeof i.ref=="string"?i.ref:"",a=n&&Ie(r.collection)?r.collection:{},c=Ie(a.display)?a.display:{},l=Ie(a.path)?a.path:{},d=vC(n?Sn(s):r.fields);n&&EC(d,a.links);let u=Ie(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"]),y={};for(let[m,g]of Object.entries(r))p.has(m)||(y[m]=mr(g));let h="";if(u.where!==void 0)try{h=(0,Uc.stringifyYaml)(u.where).trim()}catch(m){h=""}return{specProfile:n?"v0.3":"v0.2",originalFrontmatter:mr(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 u.path_glob=="string"?u.path_glob:"",matchFieldsPresent:Array.isArray(u.fields_present)?u.fields_present.map(String).join(", "):"",matchWhere:h,fields:d.length||o?d:yp().fields,body:e.trim()||`# ${t} -Type definition for ${t}.`,extraFrontmatter:m,...o?{readOnlyReason:`This type uses schema.ref (${o}). Edit the referenced JSON Schema file directly.`}:{}}}function lo(r){if(r.specProfile!=="v0.3")throw new Error("mdbase v0.2 type definitions are read-only. Migrate the collection before editing.");if(r.readOnlyReason)throw new Error(r.readOnlyReason);let e=r.originalFrontmatter?br(r.originalFrontmatter):{},t=Te(e.schema)?e.schema:{},n=Te(t.value)?t.value:{},i=Object.create(null);for(let h of r.fields){let y=h.name.trim();if(!y)throw new Error("Every field needs a name.");if(Object.prototype.hasOwnProperty.call(i,y))throw new Error(`Duplicate field name: ${y}`);i[y]=br(h.definition)}let s=ZR(r.name),o={...e,kind:"mdbase.type",name:s,version:typeof e.version=="number"?e.version:1,schema:{...t,dialect:"json-schema-2020-12",value:ju(i,n,r.strictMode===!0)}};delete o.schema.ref,r.description.trim()?o.description=r.description.trim():delete o.description;let a=Te(o.match)?br(o.match):{};r.matchPathGlob.trim()?a.path_glob=r.matchPathGlob.trim():delete a.path_glob;let c=r.matchFieldsPresent.split(",").map(h=>h.trim()).filter(Boolean);if(c.length?a.fields_present=c:delete a.fields_present,r.matchWhere.trim()){let h=(0,Pc.parseYaml)(r.matchWhere);if(!Te(h))throw new Error("Match where must be a YAML mapping.");a.where=h}else delete a.where;Object.keys(a).length?o.match=a:delete o.match;let l=Te(o.collection)?br(o.collection):{},u=Te(l.display)?br(l.display):{};if(r.displayNameKey.trim()?u.name_field=r.displayNameKey.trim():delete u.name_field,Object.keys(u).length?l.display=u:delete l.display,r.pathPattern.trim()){let h=Te(l.path)?l.path:{};l.path={...h,pattern:r.pathPattern.trim()}}else if(Te(l.path)&&typeof l.path.pattern=="string"){let h={...l.path};delete h.pattern,Object.keys(h).length?l.path=h:delete l.path}let d=Te(l.links)?br(l.links):{},f=br(d),p=Ww(i),m=Ww($n(n));for(let h of new Set([...m.selectors,...p.selectors]))delete f[h];for(let[h,y]of p.links)f[h]={...Te(d[h])?d[h]:{},target_type:y.target_type,validate_exists:y.validate_exists};Object.keys(f).length?l.links=f:delete l.links,Object.keys(l).length?o.collection=l:delete o.collection;for(let h of["fields","strict","extends","display_name_key","path_pattern","filename_pattern"])delete o[h];return o}var Ae=require("obsidian");var Ci="mdbase-frontmatter",Gw=` +Type definition for ${t}.`,extraFrontmatter:y,...o?{readOnlyReason:`This type uses schema.ref (${o}). Edit the referenced JSON Schema file directly.`}:{}}}function mo(r){if(r.specProfile!=="v0.3")throw new Error("mdbase v0.2 type definitions are read-only. Migrate the collection before editing.");if(r.readOnlyReason)throw new Error(r.readOnlyReason);let e=r.originalFrontmatter?mr(r.originalFrontmatter):{},t=Ie(e.schema)?e.schema:{},n=Ie(t.value)?t.value:{},i=Object.create(null);for(let h of r.fields){let m=h.name.trim();if(!m)throw new Error("Every field needs a name.");if(Object.prototype.hasOwnProperty.call(i,m))throw new Error(`Duplicate field name: ${m}`);i[m]=mr(h.definition)}let s=wC(r.name),o={...e,kind:"mdbase.type",name:s,version:typeof e.version=="number"?e.version:1,schema:{...t,dialect:"json-schema-2020-12",value:Qu(i,n,r.strictMode===!0)}};delete o.schema.ref,r.description.trim()?o.description=r.description.trim():delete o.description;let a=Ie(o.match)?mr(o.match):{};r.matchPathGlob.trim()?a.path_glob=r.matchPathGlob.trim():delete a.path_glob;let c=r.matchFieldsPresent.split(",").map(h=>h.trim()).filter(Boolean);if(c.length?a.fields_present=c:delete a.fields_present,r.matchWhere.trim()){let h=(0,Uc.parseYaml)(r.matchWhere);if(!Ie(h))throw new Error("Match where must be a YAML mapping.");a.where=h}else delete a.where;Object.keys(a).length?o.match=a:delete o.match;let l=Ie(o.collection)?mr(o.collection):{},d=Ie(l.display)?mr(l.display):{};if(r.displayNameKey.trim()?d.name_field=r.displayNameKey.trim():delete d.name_field,Object.keys(d).length?l.display=d:delete l.display,r.pathPattern.trim()){let h=Ie(l.path)?l.path:{};l.path={...h,pattern:r.pathPattern.trim()}}else if(Ie(l.path)&&typeof l.path.pattern=="string"){let h={...l.path};delete h.pattern,Object.keys(h).length?l.path=h:delete l.path}let u=Ie(l.links)?mr(l.links):{},f=mr(u),p=L0(i),y=L0(Sn(n));for(let h of new Set([...y.selectors,...p.selectors]))delete f[h];for(let[h,m]of p.links)f[h]={...Ie(u[h])?u[h]:{},target_type:m.target_type,validate_exists:m.validate_exists};Object.keys(f).length?l.links=f:delete l.links,Object.keys(l).length?o.collection=l:delete o.collection;for(let h of["fields","strict","extends","display_name_key","path_pattern","filename_pattern"])delete o[h];return o}var Ae=require("obsidian");var Di="mdbase-frontmatter",j0=` @@ -189,13 +185,13 @@ Type definition for ${t}.`,extraFrontmatter:m,...o?{readOnlyReason:`This type us -`;var Mn="mdbase-workspace-view",iC=["string","integer","number","boolean","date","datetime","time","enum","link","list","object","any"];function Cn(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function Xf(r){return JSON.parse(JSON.stringify(r))}function Jw(r){return typeof r.type=="string"?r.type:"any"}function sC(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 Yw(r,e,t){Object.defineProperty(r,e,{configurable:!0,enumerable:!0,writable:!0,value:t})}function oC(r,e){if(!r)return["A new type definition will be created."];let t=[];r.name!==e.name&&t.push(`Rename type from ${r.name} to ${e.name}.`),(r.matchPathGlob!==e.matchPathGlob||r.matchFieldsPresent!==e.matchFieldsPresent||r.matchWhere!==e.matchWhere)&&t.push("Membership rules changed; different records may match this type.");let n=new Map(r.fields.map(c=>[c.name,c])),i=new Map(e.fields.map(c=>[c.name,c])),s=[...n.keys()].filter(c=>!i.has(c)),o=[...i.keys()].filter(c=>!n.has(c));o.length&&t.push(`Add ${o.length} field${o.length===1?"":"s"}: ${o.join(", ")}.`),s.length&&t.push(`Remove ${s.length} field${s.length===1?"":"s"}: ${s.join(", ")}.`);let a=[...i.entries()].filter(([c,l])=>{var u;return l.definition.required===!0&&((u=n.get(c))==null?void 0:u.definition.required)!==!0}).map(([c])=>c);return a.length&&t.push(`New required fields may invalidate records: ${a.join(", ")}.`),t.length||t.push("Metadata, schema details, or documentation changed."),t}function Nt(r,e,t,n,i={}){var l;let s=r.createDiv({cls:"mdbase-form-row"}),o=s.createEl("label",{text:e}),a=`mdbase-${Math.random().toString(36).slice(2)}`;o.htmlFor=a,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.value=t,c.placeholder=(l=i.placeholder)!=null?l:"",c.addEventListener("input",()=>n(c.value)),c}function je(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 aC(r){if(r<1e3)return String(r);let e=r<1e4?1:0;return`${(r/1e3).toFixed(e)}k`}var Oc=class extends Ae.ItemView{constructor(t,n){super(t);this.host=n;this.destination="types";this.editorMode="design";this.schema=null;this.query="";this.selectedPath=null;this.model=null;this.originalModel=null;this.yamlDraft="";this.dirty=!1;this.busy=!1;this.migrationPlan=null;this.allowLossy=!1;this.mirrorStatus=null;this.mirrorPreview=null;this.mirrorProgress=null;this.transientMessage="";this.issueQuery="";this.issueSeverity="all";this.issueLimit=250;this.enrollmentVerification="";this.enrollmentAbort=null}getViewType(){return Mn}getDisplayText(){return"mdbase"}getIcon(){return Ci}async onOpen(){this.containerEl.addClass("mdbase-workspace"),await this.refresh(!0)}async onClose(){var t;(t=this.enrollmentAbort)==null||t.abort(),this.enrollmentAbort=null}async refresh(t=!1){try{this.schema=await this.host.loadWorkspaceSchema(t),this.selectedPath&&!this.typeEntries().some(n=>n.filePath===this.selectedPath)&&(this.selectedPath=null,this.model=null,this.originalModel=null),!this.selectedPath&&this.typeEntries().length&&!Ae.Platform.isMobile&&(this.selectedPath=this.typeEntries()[0].filePath),this.selectedPath&&(!this.model||t)&&await this.selectType(this.selectedPath,!1),this.destination==="sync"&&await this.refreshMirrorStatus(),this.render()}catch(n){this.transientMessage=n instanceof Error?n.message:String(n),this.render()}}showDestination(t){this.destination=t,t==="sync"?this.refreshMirrorStatus().then(()=>this.render()):this.render()}typeEntries(){return this.schema?[...this.schema.types.values()].sort((t,n)=>t.name.localeCompare(n.name)):[]}render(){let t=this.containerEl;t.empty(),t.addClass("mdbase-workspace");let n=t.createDiv({cls:"mdbase-shell"});this.renderTopbar(n),this.transientMessage&&n.createDiv({cls:"mdbase-inline-message",text:this.transientMessage}).setAttr("role","status");let i=n.createDiv({cls:"mdbase-workspace-content"});this.destination==="types"?this.renderTypes(i):this.destination==="sync"?this.renderSync(i):this.renderIssues(i)}renderTopbar(t){let n=t.createDiv({cls:"mdbase-topbar"}),i=n.createDiv({cls:"mdbase-identity"}),s=i.createSpan({cls:"mdbase-mark"});s.setAttr("aria-hidden","true"),(0,Ae.setIcon)(s,Ci),i.createSpan({cls:"mdbase-title",text:"mdbase"});let o=n.createDiv({cls:"mdbase-nav"});o.setAttr("role","tablist");for(let[a,c]of[["types","Types"],["sync","Sync"],["issues","Issues"]]){let l=o.createEl("button",{text:c});if(l.addClass("mdbase-nav-button"),l.setAttr("role","tab"),l.setAttr("aria-selected",String(this.destination===a)),this.destination===a&&l.addClass("is-active"),a==="issues"&&this.host.getIssues().length){let u=this.host.getIssues().length;l.createSpan({cls:"mdbase-count",text:aC(u)}).setAttr("title",`${u} issues`)}l.onclick=()=>this.showDestination(a)}}renderTypes(t){if(!this.schema){let i=t.createDiv({cls:"mdbase-empty-state"});i.createEl("h2",{text:"Start an mdbase collection"}),i.createEl("p",{text:"Initialize this vault as a local v0.3 collection, or use Sync to connect an empty vault to a collection authority."});let s=i.createDiv({cls:"mdbase-actions"}),o=s.createEl("button",{text:"Initialize local collection"});o.addClass("mod-cta"),o.disabled=this.busy||this.host.getMirrorProfile()!==null,o.onclick=()=>void this.perform(async()=>{await this.host.initializeCollection(),await this.refresh(!0)});let a=s.createEl("button",{text:"Connect collection authority"});a.onclick=()=>this.showDestination("sync");return}this.schema.config.spec_version.startsWith("0.2.")&&this.renderLegacyBanner(t);let n=t.createDiv({cls:"mdbase-types-layout"});this.model&&n.addClass("has-selection"),this.renderTypeList(n),this.renderTypeEditor(n)}renderLegacyBanner(t){var o;let n=t.createDiv({cls:"mdbase-legacy-banner"}),i=n.createDiv();i.createEl("strong",{text:`mdbase ${(o=this.schema)==null?void 0:o.config.spec_version} compatibility mode`}),i.createEl("p",{text:"Types are readable and validation remains available, but authoring is disabled until a reviewed v0.3 migration."});let s=n.createEl("button",{text:this.migrationPlan?"Review migration":"Analyze migration"});s.disabled=this.busy||this.host.getMirrorProfile()!==null,s.onclick=()=>void this.perform(async()=>{this.migrationPlan=await this.host.analyzeMigration(),this.render()}),this.host.getMirrorProfile()&&n.createDiv({cls:"mdbase-form-description",text:"Hosted resources must be migrated at the collection authority."}),this.migrationPlan&&this.renderMigrationReview(t,this.migrationPlan)}renderMigrationReview(t,n){let i=t.createDiv({cls:"mdbase-migration-review"}),s=i.createDiv({cls:"mdbase-section-header"});s.createEl("h3",{text:"Migration review"}),s.createSpan({cls:"mdbase-spec-badge",text:`${n.sourceVersion} \u2192 ${n.targetVersion}`});let o=i.createDiv({cls:"mdbase-status-list"});je(o,"Files replaced",String(n.operations.length)),je(o,"Type definitions",String(n.typeSummaries.length)),je(o,"Record reads verified",String(n.recordsVerified)),n.recordsSkipped&&je(o,"Records skipped",String(n.recordsSkipped)),je(o,"Record files rewritten","0"),je(o,"Recovery backup",n.backupLocation);let a=i.createDiv({cls:"mdbase-review-list"});n.diagnostics.length||a.createDiv({cls:"mdbase-review-ok",text:"No migration diagnostics."});for(let d of n.diagnostics.slice(0,250)){let f=a.createDiv({cls:"mdbase-review-item"});f.setAttr("data-severity",d.severity),f.createDiv({cls:"mdbase-review-code",text:`${d.severity} \xB7 ${d.path}`}),f.createDiv({text:d.message})}if(n.diagnostics.length>250&&a.createDiv({cls:"mdbase-form-description",text:`Showing 250 of ${n.diagnostics.length} diagnostics.`}),!n.applicable){let d=i.createEl("label",{cls:"mdbase-consent"}),f=d.createEl("input",{type:"checkbox"});f.checked=this.allowLossy,f.onchange=()=>{this.allowLossy=f.checked,this.render()},d.createSpan({text:"I reviewed the lossy diagnostics and want to apply this migration."})}let c=i.createDiv({cls:"mdbase-actions"}),l=c.createEl("button",{text:"Apply migration"});l.addClass("mod-warning"),l.disabled=this.busy||!n.applicable&&!this.allowLossy,l.onclick=()=>void this.perform(async()=>{await this.host.applyMigration(n,this.allowLossy),this.migrationPlan=null,this.allowLossy=!1,this.model=null,this.originalModel=null,await this.refresh(!0)});let u=c.createEl("button",{text:"Close review"});u.onclick=()=>{this.migrationPlan=null,this.render()}}renderTypeList(t){var u,d,f,p;let n=t.createDiv({cls:"mdbase-type-list-pane"}),i=n.createDiv({cls:"mdbase-pane-header"});i.createEl("h2",{text:"Types"});let s=i.createEl("button");s.setAttr("aria-label","Create type"),(0,Ae.setIcon)(s,"plus"),s.disabled=((d=(u=this.schema)==null?void 0:u.config.spec_version.startsWith("0.2."))!=null?d:!0)||((f=this.host.getMirrorProfile())==null?void 0:f.mode)==="read_only",s.onclick=()=>this.createType();let o=n.createEl("input",{type:"search"});o.addClass("mdbase-type-search"),o.placeholder="Search types",o.setAttr("aria-label","Search types"),o.value=this.query,o.oninput=()=>{this.query=o.value,this.render();let m=this.containerEl.querySelector(".mdbase-type-search");m==null||m.focus(),m==null||m.setSelectionRange(m.value.length,m.value.length)};let a=n.createDiv({cls:"mdbase-type-list"}),c=this.query.trim().toLowerCase(),l=this.typeEntries().filter(m=>{var h;return`${m.name} ${(h=m.description)!=null?h:""} ${m.filePath}`.toLowerCase().includes(c)});if(!l.length){a.createDiv({cls:"mdbase-empty-list",text:c?"No matching types.":"No type definitions."});return}for(let m of l){let h=a.createEl("button",{cls:"mdbase-type-row"});m.filePath===this.selectedPath&&h.addClass("is-active"),h.setAttr("aria-current",m.filePath===this.selectedPath?"true":"false"),h.createSpan({cls:"mdbase-type-name",text:m.name}),h.createSpan({cls:"mdbase-type-meta",text:`${Object.keys(m.fields).length} fields \xB7 ${(p=m.specProfile)!=null?p:"v0.2"}`}),h.onclick=()=>void this.selectType(m.filePath)}}renderTypeEditor(t){var h,y,b,g;let n=t.createDiv({cls:"mdbase-type-editor-pane"});if(!this.model){let _=n.createDiv({cls:"mdbase-empty-state"});_.createEl("h2",{text:"Choose a type"}),_.createEl("p",{text:"Select a type definition from the list to inspect or edit it."});return}let i=((h=this.host.getMirrorProfile())==null?void 0:h.mode)==="read_only",s=this.model.specProfile==="v0.2"||i||!!this.model.readOnlyReason,o=(y=this.model.readOnlyReason)!=null?y:i?"This mirror has read-only access. Re-enroll it with write access before editing types.":"This v0.2 type is read-only. Review and apply a collection migration before editing.",a=n.createDiv({cls:"mdbase-editor-header"}),c=a.createEl("button",{cls:"mdbase-mobile-back"});c.setAttr("aria-label","Back to type list"),(0,Ae.setIcon)(c,"arrow-left"),c.onclick=()=>{if(this.dirty){new Ae.Notice("Save or discard the current type changes before going back.");return}this.selectedPath=null,this.model=null,this.originalModel=null,this.render()};let l=a.createDiv(),u=l.createDiv({cls:"mdbase-editor-title-line"});u.createEl("h2",{text:this.model.name||"Untitled type"}),u.createSpan({cls:"mdbase-spec-badge",text:(b=this.model.specProfile)!=null?b:"v0.2"}),this.dirty&&u.createSpan({cls:"mdbase-dirty",text:"Unsaved"}),l.createDiv({cls:"mdbase-editor-path",text:(g=this.selectedPath)!=null?g:"New type"});let d=a.createDiv({cls:"mdbase-editor-actions"});if(this.selectedPath){let _=d.createEl("button",{text:"Open source"});_.onclick=()=>void this.host.openFileByPath(this.selectedPath)}let f=d.createEl("button",{text:"Save"});f.addClass("mod-cta"),f.disabled=s||!this.dirty||this.busy,f.onclick=()=>void this.saveCurrentType(),s&&n.createDiv({cls:"mdbase-readonly-note",text:o});let p=n.createDiv({cls:"mdbase-mode-switch"});p.setAttr("role","tablist");for(let[_,k]of[["design","Design"],["yaml","YAML"]]){let v=p.createEl("button",{text:k});v.setAttr("role","tab"),v.setAttr("aria-selected",String(this.editorMode===_)),this.editorMode===_&&v.addClass("is-active"),v.onclick=()=>this.switchEditorMode(_)}let m=n.createDiv({cls:"mdbase-editor-document"});this.editorMode==="design"?this.renderDesignEditor(m,this.model,s):this.renderYamlEditor(m,s)}renderDesignEditor(t,n,i){let s=t.createEl("section",{cls:"mdbase-editor-section"});s.createEl("h3",{text:"Identity"});let o=Nt(s,"Name",n.name,E=>{n.name=E,this.markDirty()},{description:"Stable type name used by collection records."});o.disabled=i;let a=Nt(s,"Description",n.description,E=>{n.description=E,this.markDirty()},{multiline:!0});a.disabled=i;let c=Nt(s,"Display field",n.displayNameKey,E=>{n.displayNameKey=E,this.markDirty()},{placeholder:"title"});c.disabled=i;let l=s.createEl("label",{cls:"mdbase-checkbox-row"}),u=l.createEl("input",{type:"checkbox"});u.checked=n.strictMode===!0,u.disabled=i,u.onchange=()=>{n.strictMode=u.checked,this.markDirty()},l.createSpan({text:"Reject undeclared fields"});let d=t.createEl("section",{cls:"mdbase-editor-section"});d.createEl("h3",{text:"Membership"});let f=Nt(d,"Path glob",n.matchPathGlob,E=>{n.matchPathGlob=E,this.markDirty()},{placeholder:"Projects/**/*.md"});f.disabled=i;let p=Nt(d,"Fields present",n.matchFieldsPresent,E=>{n.matchFieldsPresent=E,this.markDirty()},{description:"Comma-separated frontmatter keys."});p.disabled=i;let m=Nt(d,"Where",n.matchWhere,E=>{n.matchWhere=E,this.markDirty()},{multiline:!0,description:"YAML predicate, including contains and nested equality conditions.",placeholder:`tags: - contains: task`});m.disabled=i;let h=t.createEl("section",{cls:"mdbase-editor-section"}),y=h.createDiv({cls:"mdbase-section-header"});y.createEl("h3",{text:"Fields"});let b=y.createEl("button",{text:"Add field"});b.disabled=i,b.onclick=()=>{n.fields.push({name:"",definition:{type:"string"}}),this.markDirty(!0)};let g=h.createDiv({cls:"mdbase-fields"});for(let[E,O]of n.fields.entries())this.renderFieldRow(g,O,E,i);n.fields.length||g.createDiv({cls:"mdbase-empty-list",text:"No fields declared."});let _=t.createEl("section",{cls:"mdbase-editor-section"});_.createEl("h3",{text:"Placement"});let k=Nt(_,"Path pattern",n.pathPattern,E=>{n.pathPattern=E,this.markDirty()},{placeholder:"Notes/{title}.md"});k.disabled=i;let v=t.createEl("section",{cls:"mdbase-editor-section mdbase-change-review"});if(v.createEl("h3",{text:"Change review"}),!this.dirty)v.createEl("p",{text:"No pending changes."});else{let E=v.createEl("ul");for(let O of oC(this.originalModel,n))E.createEl("li",{text:O})}}renderFieldRow(t,n,i,s){this.renderFieldDefinition(t,n.definition,{name:n.name,nameLabel:`Field ${i+1} name`,onNameInput:o=>{n.name=o,this.markDirty()},required:n.definition.required===!0,onRequiredChange:o=>{n.definition.required=o,this.markDirty()},onRemove:()=>{var o;(o=this.model)==null||o.fields.splice(i,1),this.markDirty(!0)},readOnly:s,depth:0})}renderFieldDefinition(t,n,i){var u;let s=t.createDiv({cls:"mdbase-field-node"});s.setAttr("data-depth",String(i.depth));let o=s.createDiv({cls:"mdbase-field-row"});if(i.staticLabel)o.createDiv({cls:"mdbase-field-role",text:i.staticLabel});else{let d=o.createEl("input",{type:"text",cls:"mdbase-field-name-control"});d.setAttr("aria-label",i.nameLabel),d.placeholder="fieldName",d.value=(u=i.name)!=null?u:"",d.disabled=i.readOnly,i.onNameInput&&(d.oninput=()=>{var f;return(f=i.onNameInput)==null?void 0:f.call(i,d.value)}),i.onNameCommit&&(d.onchange=()=>{var f;return(f=i.onNameCommit)==null?void 0:f.call(i,d.value,d)})}let a=o.createEl("select",{cls:"mdbase-field-type-control"});a.setAttr("aria-label",`${i.name||i.staticLabel||"Field"} type`);for(let d of iC){let f=d==="any"?"Any value":d[0].toUpperCase()+d.slice(1);a.createEl("option",{value:d,text:f})}a.value=Jw(n),a.disabled=i.readOnly,a.onchange=()=>{n.type=a.value,a.value==="list"&&!Cn(n.items)&&(n.items={type:"string"}),a.value==="object"&&!Cn(n.fields)&&(n.fields={}),a.value==="enum"&&!Array.isArray(n.values)&&(n.values=[]),this.markDirty(!0)};let c=o.createEl("input",{type:"text",cls:"mdbase-field-description-control"});if(c.setAttr("aria-label",`${i.name||i.staticLabel||"Field"} description`),c.placeholder="Description",c.value=typeof n.description=="string"?n.description:"",c.disabled=i.readOnly,c.oninput=()=>{c.value?n.description=c.value:delete n.description,this.markDirty()},i.onRequiredChange){let d=o.createEl("label",{cls:"mdbase-field-required"}),f=d.createEl("input",{type:"checkbox"});f.checked=i.required===!0,f.disabled=i.readOnly,f.onchange=()=>{var p;return(p=i.onRequiredChange)==null?void 0:p.call(i,f.checked)},d.createSpan({text:"Required"})}if(i.onRemove){let d=o.createEl("button",{cls:"mdbase-field-remove"});d.setAttr("aria-label",`Remove ${i.name||i.staticLabel||"field"}`),(0,Ae.setIcon)(d,"trash-2"),d.disabled=i.readOnly,d.onclick=i.onRemove}let l=Jw(n);l==="enum"&&this.renderEnumFieldDetails(s,n,i),l==="link"&&this.renderLinkFieldDetails(s,n,i),l==="list"&&this.renderListFieldDetails(s,n,i),l==="object"&&this.renderObjectFieldDetails(s,n,i)}renderEnumFieldDetails(t,n,i){let s=t.createDiv({cls:"mdbase-field-details mdbase-field-options"}),o=s.createEl("label",{text:"Allowed values"}),a=s.createEl("input",{type:"text"});a.setAttr("aria-label",`${i.name||i.staticLabel||"Enum"} allowed values`),a.placeholder="draft, published, archived",a.value=Array.isArray(n.values)?n.values.map(String).join(", "):"",a.disabled=i.readOnly,a.oninput=()=>{n.values=a.value.split(",").map(c=>c.trim()).filter(Boolean),this.markDirty()},o.htmlFor=a.id=`mdbase-${Math.random().toString(36).slice(2)}`}renderLinkFieldDetails(t,n,i){let s=t.createDiv({cls:"mdbase-field-details mdbase-field-options"}),o=s.createEl("label",{text:"Target type"}),a=s.createEl("input",{type:"text"});a.setAttr("aria-label",`${i.name||i.staticLabel||"Link"} target type`),a.placeholder="Any type",a.value=typeof n.target=="string"?n.target:"",a.disabled=i.readOnly,a.oninput=()=>{a.value.trim()?n.target=a.value.trim():delete n.target,this.markDirty()},o.htmlFor=a.id=`mdbase-${Math.random().toString(36).slice(2)}`;let c=s.createEl("label",{cls:"mdbase-field-required"}),l=c.createEl("input",{type:"checkbox"});l.checked=n.validate_exists===!0,l.disabled=i.readOnly,l.onchange=()=>{n.validate_exists=l.checked,this.markDirty()},c.createSpan({text:"Validate target exists"})}renderListFieldDetails(t,n,i){let s=t.createDiv({cls:"mdbase-field-children"});s.createDiv({cls:"mdbase-field-children-label",text:"List items"});let o=Cn(n.items)?n.items:{type:"any"};!Cn(n.items)&&!i.readOnly&&(n.items=o),this.renderFieldDefinition(s,o,{staticLabel:"Item",nameLabel:"List item",readOnly:i.readOnly,depth:i.depth+1})}renderObjectFieldDetails(t,n,i){let s=t.createDiv({cls:"mdbase-field-children"}),o=s.createDiv({cls:"mdbase-field-children-header"});o.createDiv({cls:"mdbase-field-children-label",text:"Object fields"});let a=o.createEl("button",{text:"Add nested field"});a.disabled=i.readOnly;let c=Cn(n.fields)?n.fields:{};!Cn(n.fields)&&!i.readOnly&&(n.fields=c),a.onclick=()=>{let d=sC(c);Yw(c,d,{type:"string"}),this.markDirty(!0)};let l=s.createDiv({cls:"mdbase-nested-fields"}),u=Object.entries(c).filter(d=>Cn(d[1]));if(!u.length){l.createDiv({cls:"mdbase-empty-list",text:"No nested fields."});return}for(let[d,f]of u){let p=d;this.renderFieldDefinition(l,f,{name:p,nameLabel:`${p} nested field name`,onNameCommit:(m,h)=>{let y=m.trim();if(!y){new Ae.Notice("Nested field name is required."),h.value=p;return}if(y!==p&&Object.prototype.hasOwnProperty.call(c,y)){new Ae.Notice(`Nested field already exists: ${y}`),h.value=p;return}y!==p&&(delete c[p],Yw(c,y,f),p=y,this.markDirty())},required:f.required===!0,onRequiredChange:m=>{f.required=m,this.markDirty()},onRemove:()=>{delete c[p],this.markDirty(!0)},readOnly:i.readOnly,depth:i.depth+1})}}renderYamlEditor(t,n){let i=t.createEl("section",{cls:"mdbase-editor-section mdbase-yaml-section"});i.createEl("h3",{text:"Canonical type document"}),i.createEl("p",{cls:"mdbase-form-description",text:"Unknown v0.3 extensions are preserved. Invalid YAML is never normalized or saved."});let s=i.createEl("textarea",{cls:"mdbase-yaml-editor"});s.setAttr("aria-label","Type definition YAML"),s.value=this.yamlDraft,s.disabled=n,s.spellcheck=!1,s.oninput=()=>{this.yamlDraft=s.value,this.markDirty(!1)}}renderSync(t){var f,p,m,h,y,b;let n=t.createDiv({cls:"mdbase-sync-document"}),i=n.createDiv({cls:"mdbase-document-header"});i.createEl("h2",{text:"Sync"}),i.createEl("p",{text:"Connect this vault to a collection authority and keep ordinary Markdown mirrored locally."});let s=this.host.getMirrorProfile();if(!s){this.renderEnrollment(n);return}let o=n.createEl("section",{cls:"mdbase-editor-section"});o.createEl("h3",{text:"Collection authority"});let a=o.createDiv({cls:"mdbase-status-list"});if(je(a,"Name",s.name),je(a,"Collection",s.collectionId),je(a,"Access",s.mode==="read_write"?"Read and write":"Read only"),je(a,"Provider",s.syncUrl),je(a,"State",(p=(f=this.mirrorStatus)==null?void 0:f.state.replace(/_/g," "))!=null?p:"Checking"),je(a,"Last synced",(h=(m=this.mirrorStatus)==null?void 0:m.last_synced_at)!=null?h:"Never"),this.mirrorProgress){let g=this.mirrorProgress.total,_=o.createEl("progress");_.max=g!=null?g:1,_.value=g==null?0:this.mirrorProgress.completed,g==null&&_.removeAttribute("value"),o.createDiv({cls:"mdbase-progress-label",text:`${this.mirrorProgress.phase}: ${this.mirrorProgress.completed}${g==null?"":` of ${g}`}`})}let c=o.createDiv({cls:"mdbase-actions"}),l=c.createEl("button",{text:"Preview"});l.disabled=this.busy,l.onclick=()=>void this.perform(async()=>{this.mirrorPreview=await this.host.connectSync.preview(),this.render()});let u=c.createEl("button",{text:"Sync now"});u.addClass("mod-cta"),u.disabled=this.busy,u.onclick=()=>void this.perform(async()=>{this.mirrorStatus=await this.host.connectSync.sync(g=>{this.mirrorProgress=g,this.render()}),this.mirrorProgress=null,this.transientMessage="Sync completed and the local checkpoint was verified.",await this.refresh(!0)}),this.mirrorPreview&&this.renderMirrorPreview(n,this.mirrorPreview),(y=this.mirrorStatus)!=null&&y.conflicts.length&&this.renderConflicts(n,this.mirrorStatus),(b=this.mirrorStatus)!=null&&b.local_issues.length&&this.renderLocalMirrorIssues(n,this.mirrorStatus);let d=n.createEl("section",{cls:"mdbase-editor-section"});d.createEl("h3",{text:"Mirror ownership"}),d.createEl("p",{text:"Use this plugin as the only sync owner for this vault. Obsidian protects concurrent operations inside the app; a separate desktop mirror process cannot share that mobile-safe lease."})}renderEnrollment(t){if(this.schema||this.host.connectSync.getAdoptionMarker()){this.renderLocalAdoption(t);return}let n=t.createEl("section",{cls:"mdbase-editor-section mdbase-enrollment"});if(n.createEl("h3",{text:"Connect collection authority"}),n.createEl("p",{text:"Connect will open an approval page. Credentials are stored in Obsidian's secret store and never written into this vault."}),this.enrollmentVerification){let d=n.createDiv({cls:"mdbase-approval-link"});d.createSpan({text:"Approval page: "});let f=d.createEl("a",{text:"Open Connect",href:this.enrollmentVerification});f.setAttr("target","_blank"),f.setAttr("rel","noopener noreferrer")}let i="https://connect.mdbase.dev",s="Obsidian",o="",a="read_write";Nt(n,"Connect URL",i,d=>{i=d},{placeholder:"https://connect.mdbase.dev"}),Nt(n,"Mirror name",s,d=>{s=d}),Nt(n,"Collection ID",o,d=>{o=d},{description:"Optional. Leave blank to choose during approval."});let c=n.createDiv({cls:"mdbase-form-row"});c.createEl("label",{text:"Access"});let l=c.createEl("select");l.createEl("option",{value:"read_write",text:"Read and write"}),l.createEl("option",{value:"read_only",text:"Read only"}),l.value=a,l.onchange=()=>{a=l.value==="read_only"?"read_only":"read_write"};let u=n.createEl("button",{text:"Open Connect approval"});u.addClass("mod-cta"),u.disabled=this.busy,u.onclick=()=>void this.perform(async()=>{var f;(f=this.enrollmentAbort)==null||f.abort();let d=new AbortController;this.enrollmentAbort=d;try{await this.host.connectSync.enroll({controlUrl:i,mirrorName:s,mode:a,...o.trim()?{collectionId:o.trim()}:{}},{signal:d.signal,onVerification:p=>{this.enrollmentVerification=p.verificationUri,this.transientMessage="Approve the mirror in the Connect page. This view will keep waiting securely.",window.open(p.verificationUri,"_blank","noopener,noreferrer"),this.render()},onStatus:p=>{this.transientMessage=p.state==="waiting_for_approval"?"Waiting for approval in Connect\u2026":`Connect is retrying enrollment (attempt ${p.attempt}).`,this.render()}}),this.enrollmentVerification="",this.transientMessage="Mirror enrolled. Preview before the first sync.",await this.refreshMirrorStatus(),this.render()}finally{this.enrollmentAbort===d&&(this.enrollmentAbort=null)}})}renderLocalAdoption(t){var u,d;let n=this.host.connectSync.getAdoptionMarker(),i=t.createEl("section",{cls:"mdbase-editor-section mdbase-enrollment"});i.createEl("h3",{text:"Host this local collection"}),i.createEl("p",{text:n?"This vault has a durable adoption checkpoint. Resume it without creating another hosted collection.":"Hosted mdbase will adopt an exact snapshot and become the collection authority. This vault will then continue as a read-write mirror."});let s=this.enrollmentVerification||(n==null?void 0:n.session.verificationUri);if(s){let f=i.createDiv({cls:"mdbase-approval-link"});f.createSpan({text:"Approval page: "});let p=f.createEl("a",{text:"Open Connect",href:s});p.setAttr("target","_blank"),p.setAttr("rel","noopener noreferrer")}let o=(u=n==null?void 0:n.session.controlUrl)!=null?u:"https://connect.mdbase.dev",a=(d=n==null?void 0:n.session.requested.mirrorName)!=null?d:"Obsidian";if(!n)Nt(i,"Connect URL",o,f=>{o=f},{placeholder:"https://connect.mdbase.dev"}),Nt(i,"Mirror name",a,f=>{a=f});else{let f=i.createDiv({cls:"mdbase-status-list"});je(f,"Collection",n.session.requested.collectionId),je(f,"Phase",n.phase.replace(/_/g," ")),je(f,"Connect",n.session.controlUrl)}let c=i.createDiv({cls:"mdbase-inline-message"});c.createEl("strong",{text:"Authority cut-over: "}),c.appendText("once final staging begins, plugin-managed local edits pause until hosted activation is confirmed. The checkpoint survives app restarts and uncertain network responses.");let l=i.createEl("button",{text:n?"Resume adoption":"Approve and host collection"});if(l.addClass("mod-cta"),l.disabled=this.busy,l.onclick=()=>void this.perform(async()=>{var h;(h=this.enrollmentAbort)==null||h.abort();let f=new AbortController;this.enrollmentAbort=f;let p=y=>{this.enrollmentVerification=y.verificationUri,this.transientMessage="Approve the authority move in Connect, then return here. This checkpoint is safe to resume.",this.render()},m=y=>{this.transientMessage=y.state==="waiting_for_approval"?"Waiting for authority-move approval in Connect\u2026":`Connect is retrying (attempt ${y.attempt}).`,this.render()};try{n?await this.host.connectSync.resumeAdoption({signal:f.signal,onVerification:p,onStatus:m}):await this.host.connectSync.adoptLocalCollection({controlUrl:o,mirrorName:a},{signal:f.signal,onVerification:p,onStatus:m}),this.enrollmentVerification="",this.transientMessage="Hosted mdbase is authoritative and this vault is now its read-write mirror.",await this.refresh(!0)}finally{this.enrollmentAbort===f&&(this.enrollmentAbort=null)}}),n&&!["activating","adopted"].includes(n.phase)){let f=i.createEl("button",{text:"Cancel adoption"});f.disabled=this.busy,f.onclick=()=>void this.perform(async()=>{await this.host.connectSync.cancelAdoption(),this.enrollmentVerification="",this.transientMessage="Collection adoption cancelled. This vault remains the local authority.",await this.refresh(!0)})}}renderMirrorPreview(t,n){let i=t.createEl("section",{cls:"mdbase-editor-section"});i.createEl("h3",{text:"Sync preview"});let s=i.createDiv({cls:"mdbase-status-list"});if(je(s,"Download documents",String(n.download_documents)),je(s,"Upload documents",String(n.upload_documents)),je(s,"Unchanged documents",String(n.unchanged_documents)),n.collisions.length){i.createDiv({cls:"mdbase-inline-error",text:`${n.collisions.length} path collision${n.collisions.length===1?"":"s"} must be resolved before sync.`});let o=i.createEl("ul");for(let a of n.collisions.slice(0,100))o.createEl("li",{text:a})}if(n.local_issues.length){i.createDiv({cls:"mdbase-inline-error",text:`${n.local_issues.length} local file${n.local_issues.length===1?"":"s"} cannot be uploaded until its frontmatter is fixed.`});let o=i.createEl("ul");for(let a of n.local_issues.slice(0,100))o.createEl("li",{text:`${a.path}: ${a.message}`})}}renderConflicts(t,n){var s;let i=t.createEl("section",{cls:"mdbase-editor-section"});i.createEl("h3",{text:"Conflicts"});for(let o of n.conflicts){let a=i.createDiv({cls:"mdbase-conflict-row"}),c=a.createDiv();c.createEl("strong",{text:(s=o.path)!=null?s:o.record_id}),c.createDiv({text:o.message});let l=a.createDiv({cls:"mdbase-actions"});for(let u of["local","remote"]){let d=l.createEl("button",{text:u==="local"?"Keep local":"Use remote"});d.disabled=this.busy,d.onclick=()=>void this.perform(async()=>{this.mirrorStatus=await this.host.connectSync.resolveConflict(o.record_id,u),this.render()})}}}renderLocalMirrorIssues(t,n){let i=t.createEl("section",{cls:"mdbase-editor-section"});i.createEl("h3",{text:"Local files needing attention"}),i.createEl("p",{text:"These files remain untouched and unsynced. Other valid Markdown continues to synchronize."});for(let s of n.local_issues){let o=i.createDiv({cls:"mdbase-conflict-row"}),a=o.createDiv();a.createEl("strong",{text:s.path}),a.createDiv({text:s.message});let l=o.createDiv({cls:"mdbase-actions"}).createEl("button",{text:"Open file"});l.disabled=this.busy,l.onclick=()=>void this.host.openFileByPath(s.path)}}renderIssues(t){var b;let n=t.createDiv({cls:"mdbase-issues-document"}),i=this.host.getIssues(),s=new Set(i.map(g=>g.path)).size,o=n.createDiv({cls:"mdbase-document-header"}),a=o.createDiv();a.createEl("h2",{text:"Issues"}),a.createEl("p",{text:i.length?`${i.length.toLocaleString()} validation issues in ${s.toLocaleString()} files.`:"The collection has no current validation issues."});let c=o.createEl("button",{text:"Validate collection"});c.disabled=this.busy,c.onclick=()=>void this.perform(async()=>{await this.host.validateCollection(),this.render()});let l=n.createDiv({cls:"mdbase-issue-controls"}),u=l.createEl("select");u.setAttr("aria-label","Issue severity"),u.createEl("option",{value:"all",text:"All severities"}),u.createEl("option",{value:"error",text:"Errors"}),u.createEl("option",{value:"warn",text:"Warnings"}),u.value=this.issueSeverity,u.onchange=()=>{this.issueSeverity=u.value==="error"||u.value==="warn"?u.value:"all",this.issueLimit=250,this.render()};let d=l.createEl("input",{type:"search"});d.setAttr("aria-label","Filter issues"),d.placeholder="Filter by path, code, field, or message",d.value=this.issueQuery,d.oninput=()=>{this.issueQuery=d.value,this.issueLimit=250,this.render();let g=this.containerEl.querySelector(".mdbase-issue-controls input[type='search']");g==null||g.focus(),g==null||g.setSelectionRange(g.value.length,g.value.length)};let f=this.issueQuery.trim().toLowerCase(),p=i.filter(g=>{var _;return this.issueSeverity!=="all"&&g.severity!==this.issueSeverity?!1:f?`${g.path} ${g.code} ${(_=g.field)!=null?_:""} ${g.message}`.toLowerCase().includes(f):!0}),m=new Set(p.map(g=>g.path)).size;if(n.createDiv({cls:"mdbase-issues-summary",text:p.length===i.length?`Showing ${Math.min(p.length,this.issueLimit).toLocaleString()} of ${p.length.toLocaleString()} issues`:`${p.length.toLocaleString()} matching issues in ${m.toLocaleString()} files`}),!p.length){n.createDiv({cls:"mdbase-empty-state",text:"No validation issues."});return}let h=p.slice(0,this.issueLimit),y=new Map;for(let g of h)y.set(g.path,[...(b=y.get(g.path))!=null?b:[],g]);for(let[g,_]of y){let k=n.createEl("section",{cls:"mdbase-issue-group"}),v=k.createDiv({cls:"mdbase-issue-group-header"}),E=v.createEl("button",{cls:"mdbase-issue-file-button"});(0,Ae.setIcon)(E.createSpan({cls:"mdbase-issue-file-icon"}),"file-text"),E.createSpan({cls:"mdbase-issue-file-path",text:g}),E.onclick=()=>void this.host.openFileByPath(g),v.createSpan({cls:"mdbase-issue-file-count",text:`${_.length} ${_.length===1?"issue":"issues"}`});for(let O of _){let w=k.createEl("button",{cls:"mdbase-issue-row"});w.setAttr("data-severity",O.severity),w.setAttr("aria-label",`${O.severity==="warn"?"Warning":"Error"}: ${O.message}`),w.createSpan({cls:"mdbase-issue-indicator"}).setAttr("aria-hidden","true");let x=w.createDiv({cls:"mdbase-issue-metadata"});x.createEl("code",{text:O.code}),x.createDiv({cls:"mdbase-issue-context",text:`${O.severity==="warn"?"Warning":"Error"}${O.field?` \xB7 ${O.field}`:""}`}),w.createDiv({cls:"mdbase-issue-row-message",text:O.message}),w.onclick=()=>void this.host.openFileByPath(O.path,O.field)}}if(p.length>h.length){let g=n.createEl("button",{cls:"mdbase-load-more",text:`Load ${Math.min(250,p.length-h.length)} more`});g.onclick=()=>{this.issueLimit+=250,this.render()}}}async selectType(t,n=!0){if(n&&this.dirty&&t!==this.selectedPath){new Ae.Notice("Save or discard the current type changes before switching.");return}let i=await this.host.loadTypeModel(t);this.selectedPath=t,this.model=i,this.originalModel=Xf(i),this.yamlDraft=`${wt(Xw(i),i.body)} -`,this.dirty=!1,this.editorMode="design",this.render()}createType(){if(this.dirty){new Ae.Notice("Save or discard the current type changes before creating another type.");return}let t=Yf();this.selectedPath=null,this.model=t,this.originalModel=null,this.yamlDraft=`${wt(lo(t),t.body)} -`,this.dirty=!0,this.editorMode="design",this.render()}switchEditorMode(t){if(!(!this.model||t===this.editorMode)){if(t==="yaml")try{this.yamlDraft=`${wt(Xw(this.model),this.model.body)} -`}catch(n){new Ae.Notice(n instanceof Error?n.message:String(n));return}else if(!this.readYamlDraftIntoModel())return;this.editorMode=t,this.render()}}readYamlDraftIntoModel(){var n,i;let t=Ct(this.yamlDraft);if(!t.hasFrontmatter||t.error)return new Ae.Notice(`Invalid type YAML: ${(n=t.error)!=null?n:"frontmatter is missing"}`),!1;if(t.frontmatter.kind!=="mdbase.type")return new Ae.Notice("Canonical v0.3 type YAML requires kind: mdbase.type."),!1;try{return this.model=Ic(t.frontmatter,t.body,((i=this.model)==null?void 0:i.name)||"type"),!0}catch(s){return new Ae.Notice(s instanceof Error?s.message:String(s)),!1}}async saveCurrentType(){if(!(!this.model||this.model.specProfile!=="v0.3"||this.model.readOnlyReason)&&!(this.editorMode==="yaml"&&!this.readYamlDraftIntoModel())){if(!this.model.name.trim()){new Ae.Notice("Type name is required.");return}await this.perform(async()=>{let t=await this.host.saveTypeModel(this.model,this.selectedPath);this.selectedPath=t.path,this.originalModel=Xf(this.model),this.dirty=!1,this.transientMessage=`Saved ${t.path}.`,await this.refresh(!0)})}}markDirty(t=!1){var o,a;if(this.dirty=!0,t){this.render();return}let n=this.containerEl.querySelector(".mdbase-editor-title-line");n&&!n.querySelector(".mdbase-dirty")&&n.createSpan({cls:"mdbase-dirty",text:"Unsaved"});let i=this.containerEl.querySelector(".mdbase-editor-actions .mod-cta");i&&((o=this.model)==null?void 0:o.specProfile)==="v0.3"&&!this.model.readOnlyReason&&((a=this.host.getMirrorProfile())==null?void 0:a.mode)!=="read_only"&&(i.disabled=!1);let s=this.containerEl.querySelector(".mdbase-change-review");if(s){let c=s.querySelector("p");c&&c.setText("Pending changes. Review details after leaving the current field.")}}async refreshMirrorStatus(){try{this.mirrorStatus=await this.host.connectSync.status()}catch(t){this.mirrorStatus=null,this.transientMessage=t instanceof Error?t.message:String(t)}}async perform(t){if(!this.busy){this.busy=!0,this.transientMessage="",this.render();try{await t()}catch(n){let i=n instanceof Error?n.message:String(n);this.transientMessage=i,new Ae.Notice(i)}finally{this.busy=!1,this.render()}}}};function Xw(r){var e;return r.specProfile==="v0.3"&&!r.readOnlyReason?lo(r):Xf((e=r.originalFrontmatter)!=null?e:{name:r.name,fields:Object.fromEntries(r.fields.map(t=>[t.name,t.definition]))})}var Mi="mdbase-issues-view",cC={validateOnSave:!0,validateOnOpen:!0,showNoticeOnSave:!1,interopEnabled:!1,mirrorProfile:null};function lC(r){if(!r||typeof r!="object"||Array.isArray(r))return!1;let e=r;return e.version===1&&typeof e.syncUrl=="string"&&typeof e.controlUrl=="string"&&typeof e.collectionId=="string"&&typeof e.replicaId=="string"&&(e.mode==="read_only"||e.mode==="read_write")&&typeof e.name=="string"&&typeof e.enrollmentId=="string"&&typeof e.accessTokenExpiresAt=="string"}function dC(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var uo=class extends D.Modal{constructor(t,n,i="",s=""){super(t);this.resolvePromise=null;this.settled=!1;this.title=n,this.placeholder=i,this.defaultValue=s}openAndGetValue(){return new Promise(t=>{this.settled=!1,this.resolvePromise=t,this.open()})}onOpen(){let{contentEl:t}=this;t.empty(),t.createEl("h3",{text:this.title});let n=t.createEl("input",{type:"text"});n.placeholder=this.placeholder,n.value=this.defaultValue,n.addClass("prompt-input");let i=t.createDiv({cls:"modal-button-container"}),s=i.createEl("button",{text:"Cancel"}),o=i.createEl("button",{text:"OK"});o.addClass("mod-cta"),s.onclick=()=>{this.finish(null),this.close()},o.onclick=()=>{this.finish(n.value.trim()),this.close()},n.addEventListener("keydown",a=>{a.key==="Enter"&&(a.preventDefault(),this.finish(n.value.trim()),this.close()),a.key==="Escape"&&(a.preventDefault(),this.finish(null),this.close())}),window.setTimeout(()=>n.focus(),0)}onClose(){this.settled||this.finish(null),this.contentEl.empty()}finish(t){var n;this.settled||(this.settled=!0,(n=this.resolvePromise)==null||n.call(this,t),this.resolvePromise=null)}},Qf=class extends D.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=>{var a,c,l;let s=(c=(a=i.match)==null?void 0:a.path_glob)!=null?c:"";return`${i.name} ${(l=i.display_name_key)!=null?l:""} ${i.filePath} ${s}`.toLowerCase().includes(n)}).slice(0,100):this.typeDefs.slice(0,100)}renderSuggestion(t,n){var o,a;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((o=t.fields)!=null?o:{}).length} fields`}),(a=t.match)!=null&&a.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 uC(r,e){return new Promise(t=>{new Qf(r,e,i=>{if(i.type==="selected"){t(i.typeDef);return}t(null)}).open()})}var Zf=class extends D.ItemView{constructor(t,n){super(t);this.severityFilter="all";this.query="";this.plugin=n}getViewType(){return Mi}getDisplayText(){return"mdbase issues"}getIcon(){return"shield-alert"}async onOpen(){this.containerEl.empty(),this.containerEl.addClass("mdbase-issues-view"),this.render()}render(){var m;let t=this.containerEl;t.empty(),t.addClass("mdbase-issues-view");let n=t.createDiv({cls:"mdbase-issues-header"});n.createEl("h3",{text:"mdbase Issues"});let s=n.createDiv({cls:"mdbase-issues-header-actions"}).createEl("button",{text:"Refresh"});s.addClass("mod-cta"),s.onclick=()=>{this.plugin.runCollectionValidation(!1)};let o=t.createDiv({cls:"mdbase-issues-controls"}),a=o.createEl("select");a.addClass("mdbase-issues-severity"),a.createEl("option",{value:"all",text:"All severities"}),a.createEl("option",{value:"error",text:"Errors only"}),a.createEl("option",{value:"warn",text:"Warnings only"}),a.value=this.severityFilter,a.onchange=()=>{let h=a.value;(h==="error"||h==="warn"||h==="all")&&(this.severityFilter=h),this.render()};let c=o.createEl("input",{type:"search"});c.addClass("mdbase-issues-query"),c.placeholder="Filter by path, code, message, field",c.value=this.query,c.oninput=()=>{this.query=c.value,this.render()};let l=this.plugin.getIssues(),u=this.query.trim().toLowerCase(),d=l.filter(h=>{var b;return this.severityFilter!=="all"&&h.severity!==this.severityFilter?!1:u?`${h.path} ${h.code} ${h.message} ${(b=h.field)!=null?b:""}`.toLowerCase().includes(u):!0}),f=d.slice(0,500);if(t.createDiv({cls:"mdbase-issues-count",text:d.length>f.length?`Showing ${f.length} of ${d.length} matching issues`:d.length===l.length?`${d.length} issue${d.length===1?"":"s"}`:`${d.length} of ${l.length} issue${l.length===1?"":"s"}`}),d.length===0){t.createDiv({cls:"mdbase-empty",text:l.length===0?"No validation issues.":"No issues match current filters."});return}let p=new Map;for(let h of f){let y=(m=p.get(h.path))!=null?m:[];y.push(h),p.set(h.path,y)}for(let[h,y]of p.entries()){t.createDiv({cls:"mdbase-issue-file",text:h});for(let b of y){let g=t.createDiv({cls:"mdbase-issue-item"});g.setAttr("data-severity",b.severity),g.createDiv({cls:"mdbase-issue-code",text:`${b.severity.toUpperCase()} \xB7 ${b.code}${b.field?` \xB7 ${b.field}`:""}`}),g.createDiv({cls:"mdbase-issue-message",text:b.message});let _=g.createDiv({cls:"mdbase-issue-actions"}),k=_.createEl("button",{text:b.field?"Open field":"Open file"});k.onclick=E=>{E.stopPropagation(),this.plugin.openIssue(b)};let v=this.plugin.getQuickFixLabel(b);if(v){let E=_.createEl("button",{text:v});E.onclick=O=>{O.stopPropagation(),this.plugin.applyQuickFix(b)}}g.onclick=()=>{this.plugin.openIssue(b)}}}}},ep=class extends D.PluginSettingTab{constructor(e,t){super(e,t),this.plugin=t}display(){let{containerEl:e}=this;e.empty(),e.createEl("h2",{text:"mdbase settings"}),new D.Setting(e).setName("Validate on save").setDesc("Run mdbase validation when a markdown file is modified.").addToggle(t=>t.setValue(this.plugin.settings.validateOnSave).onChange(async n=>{this.plugin.settings.validateOnSave=n,await this.plugin.saveSettings()})),new D.Setting(e).setName("Validate on file open").setDesc("Validate the active note when opened.").addToggle(t=>t.setValue(this.plugin.settings.validateOnOpen).onChange(async n=>{this.plugin.settings.validateOnOpen=n,await this.plugin.saveSettings()})),new D.Setting(e).setName("Show notices on save").setDesc("Display a notice when save-time validation finds issues.").addToggle(t=>t.setValue(this.plugin.settings.showNoticeOnSave).onChange(async n=>{this.plugin.settings.showNoticeOnSave=n,await this.plugin.saveSettings()})),new D.Setting(e).setName("Allow local application interoperability").setDesc("Allow installed Obsidian plugins to exchange validated mdbase events and actions in this vault. Contracts establish compatibility; this switch is the separate user grant.").addToggle(t=>t.setValue(this.plugin.settings.interopEnabled).onChange(async n=>{this.plugin.settings.interopEnabled=n,await this.plugin.saveSettings()}))}},Tc=class extends D.Plugin{constructor(t,n){super(t,n);this.issueMap=new Map;this.sortedIssuesCache=null;this.schemaCache=null;this.schemaLoadPromise=null;this.pendingSaveValidations=new Map;this.saveValidationDebounceMs=250;this.connectSync=new kc(t,{getMirrorProfile:()=>this.getMirrorProfile(),saveMirrorProfile:async i=>{this.settings.mirrorProfile=i,await this.saveSettings()}}),this.interopBridge=new ua(t,()=>{var i;return((i=this.settings)==null?void 0:i.interopEnabled)===!0}),this.api={apiVersion:1,interop:this.interopBridge,getInteropStatus:()=>{var i;return{enabled:((i=this.settings)==null?void 0:i.interopEnabled)===!0,profileVersion:"0.1"}}}}async onload(){await this.loadSettings(),await this.connectSync.initialize(),(0,D.addIcon)(Ci,Gw),this.statusBarEl=this.addStatusBarItem(),this.updateStatusBar(),this.registerView(Mn,n=>new Oc(n,this)),this.registerView(Mi,n=>new Zf(n,this)),this.addSettingTab(new ep(this.app,this)),this.addRibbonIcon(Ci,"Open mdbase",()=>void this.openWorkspace()),this.addCommand({id:"mdbase-open",name:"mdbase: Open workspace",callback:()=>void this.openWorkspace()}),this.addCommand({id:"mdbase-initialize-collection",name:"mdbase: Initialize collection",callback:()=>void this.initializeCollectionCommand()}),this.addCommand({id:"mdbase-create-type",name:"mdbase: Create type definition",callback:()=>void this.openWorkspace("types")}),this.addCommand({id:"mdbase-edit-type",name:"mdbase: Edit type definition",callback:()=>void this.openWorkspace("types")}),this.addCommand({id:"mdbase-edit-current-type",name:"mdbase: Edit current type definition",callback:()=>void this.openWorkspace("types")}),this.addCommand({id:"mdbase-create-note-from-type",name:"mdbase: Create note from type",callback:()=>void this.createNoteFromTypeCommand()}),this.addCommand({id:"mdbase-validate-current-note",name:"mdbase: Validate current note",callback:()=>void this.validateCurrentNoteCommand()}),this.addCommand({id:"mdbase-validate-collection",name:"mdbase: Validate collection",callback:()=>void this.runCollectionValidation(!0)}),this.addCommand({id:"mdbase-open-issues-view",name:"mdbase: Open issues view",callback:()=>void this.openWorkspace("issues")}),this.addCommand({id:"mdbase-sync",name:"mdbase: Sync collection authority",callback:()=>void this.syncHostedCollectionCommand()}),this.addCommand({id:"mdbase-open-sync",name:"mdbase: Open sync",callback:()=>void this.openWorkspace("sync")}),this.registerEvent(this.app.vault.on("modify",n=>{n instanceof D.TFile&&this.onVaultModify(n)})),this.registerEvent(this.app.vault.on("rename",(n,i)=>{n instanceof D.TFile&&this.onVaultRename(n,i)})),this.registerEvent(this.app.vault.on("delete",n=>{n instanceof D.TFile&&this.onVaultDelete(n)})),this.registerEvent(this.app.vault.on("create",n=>{n instanceof D.TFile&&this.onVaultCreate(n)})),this.registerEvent(this.app.workspace.on("file-open",n=>{this.settings.validateOnOpen&&(!(n instanceof D.TFile)||n.extension!=="md"||this.validateFileAndStore(n,"open"))}));let t=this.app.workspace.getActiveFile();t&&this.settings.validateOnOpen&&this.validateFileAndStore(t,"open")}async onunload(){await this.interopBridge.dispose(),this.app.workspace.getLeavesOfType(Mn).forEach(t=>t.detach()),this.app.workspace.getLeavesOfType(Mi).forEach(t=>t.detach()),this.clearAllPendingSaveValidations()}async loadSettings(){this.settings=Object.assign({},cC,await this.loadData()),lC(this.settings.mirrorProfile)||(this.settings.mirrorProfile=null)}async saveSettings(){await this.saveData(this.settings)}getIssues(){var t;return(t=this.sortedIssuesCache)!=null||(this.sortedIssuesCache=Array.from(this.issueMap.values()).flat().sort((n,i)=>n.path.localeCompare(i.path)||n.severity.localeCompare(i.severity)||n.code.localeCompare(i.code))),this.sortedIssuesCache}getMirrorProfile(){return this.settings.mirrorProfile?{...this.settings.mirrorProfile}:null}async loadWorkspaceSchema(t=!1){return this.getConfigAndTypes(t)}async loadTypeModel(t){var s;let n=this.app.vault.getAbstractFileByPath((0,D.normalizePath)(t));if(!(n instanceof D.TFile))throw new Error(`Type file not found: ${t}`);let i=Ct(await this.app.vault.cachedRead(n));if(!i.hasFrontmatter||i.error)throw new Error(`Invalid type frontmatter: ${(s=i.error)!=null?s:"frontmatter is missing"}`);return Ic(i.frontmatter,i.body,n.basename)}async saveTypeModel(t,n){var a;if(this.connectSync.assertLocalAuthorityWritable(),((a=this.getMirrorProfile())==null?void 0:a.mode)==="read_only")throw new Error("This mirror has read-only access. Re-enroll it with write access before editing types.");let i=await ci(this.app.vault);if(!i)throw new Error("No mdbase.yaml found.");if(!i.spec_version.startsWith("0.3."))throw new Error("mdbase v0.2 type definitions are read-only. Migrate the collection first.");let s=n?this.app.vault.getAbstractFileByPath((0,D.normalizePath)(n)):null;if(s!=null&&!(s instanceof D.TFile))throw new Error(`Type file not found: ${n}`);let o=await this.writeTypeDefinition(i,t,s);return this.refreshWorkspaceViews(!0),o}async initializeCollection(){this.connectSync.assertLocalAuthorityWritable(),await this.initializeCollectionCommand(),this.refreshWorkspaceViews(!0)}async validateCollection(){await this.runCollectionValidation(!1)}analyzeMigration(){if(this.getMirrorProfile())throw new Error("Collection authority resources must be migrated at the collection authority.");return Hw(this.app.vault)}async applyMigration(t,n){var s,o;if(this.connectSync.assertLocalAuthorityWritable(),this.getMirrorProfile())throw new Error("Collection authority resources must be migrated at the collection authority.");let i=await Kw(this.app.vault,t,{allowLossy:n});if(!i.applied)throw new Error(i.restored?`Migration failed and all writes were rolled back. ${(s=i.error)!=null?s:""}`.trim():`Migration needs manual recovery. See ${i.manifestPath}. ${(o=i.error)!=null?o:""}`.trim());this.invalidateSchemaCache(),new D.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["unknown_field","schema_additional_properties"].includes(t.code)&&t.field?"Remove field":["missing_required","schema_required"].includes(t.code)&&t.field?"Add placeholder":null}async applyQuickFix(t){this.connectSync.assertLocalAuthorityWritable();let n=this.app.vault.getAbstractFileByPath(t.path);if(!(n instanceof D.TFile)){new D.Notice(`File not found: ${t.path}`);return}let i=await this.app.vault.cachedRead(n),s=Ct(i);if(s.error){new D.Notice(`Cannot apply quick fix: invalid frontmatter (${s.error})`);return}if(["unknown_field","schema_additional_properties"].includes(t.code)&&t.field){let o=ya(t.field);if(!(o in s.frontmatter)){new D.Notice(`Field '${o}' not found in frontmatter.`);return}delete s.frontmatter[o],await this.app.vault.modify(n,`${wt(s.frontmatter,s.body)} -`),new D.Notice(`Removed '${o}' from ${n.basename}`),await this.validateFileAndStore(n,"manual");return}if(["missing_required","schema_required"].includes(t.code)&&t.field){let o=ya(t.field);s.frontmatter[o]===void 0&&(s.frontmatter[o]="TODO");let a=s.hasFrontmatter?s.body:i;await this.app.vault.modify(n,`${wt(s.frontmatter,a)} -`),new D.Notice(`Added placeholder '${o}' to ${n.basename}`),await this.validateFileAndStore(n,"manual");return}new D.Notice("No quick fix available for this issue.")}async openFileByPath(t,n){let i=this.app.vault.getAbstractFileByPath(t);if(!(i instanceof D.TFile)){new D.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 D.MarkdownView))return;let s=i.view;if(!(s.file instanceof D.TFile)||s.file.path!==t.path)return;let o=s.editor,a=o.lineCount();if(a<3)return;let c=ya(n),l=new RegExp(`^\\s*${dC(c)}\\s*:`);if(o.getLine(0).trim()==="---")for(let u=1;us.severity==="error").length,i=t.length-n;if(t.length===0){this.statusBarEl.setText("mdbase: no issues");return}this.statusBarEl.setText(`mdbase: ${n} error${n===1?"":"s"}, ${i} warning${i===1?"":"s"}`)}async openIssuesView(){var i;let t=this.app.workspace.getLeavesOfType(Mi)[0];if(t){this.app.workspace.revealLeaf(t),t.view.render();return}let n=(i=this.app.workspace.getRightLeaf(!1))!=null?i:this.app.workspace.getLeaf(!0);await n.setViewState({type:Mi,active:!0}),this.app.workspace.revealLeaf(n)}async openWorkspace(t="types"){let n=this.app.workspace.getLeavesOfType(Mn)[0];if(n){this.app.workspace.revealLeaf(n);let o=n.view;o.showDestination(t),await o.refresh();return}let i=this.app.workspace.getLeaf(!0);await i.setViewState({type:Mn,active:!0}),this.app.workspace.revealLeaf(i),i.view.showDestination(t)}refreshWorkspaceViews(t=!1){for(let n of this.app.workspace.getLeavesOfType(Mn))n.view.refresh(t)}refreshIssueViews(){this.updateStatusBar();for(let t of this.app.workspace.getLeavesOfType(Mi))t.view.render();this.refreshWorkspaceViews()}setFileIssues(t,n){n.length===0?this.issueMap.delete(t):this.issueMap.set(t,n),this.sortedIssuesCache=null,this.refreshIssueViews()}clearFileIssues(t){this.issueMap.has(t)&&(this.issueMap.delete(t),this.sortedIssuesCache=null,this.refreshIssueViews())}moveFileIssues(t,n){let 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())}clearAllPendingSaveValidations(){for(let t of this.pendingSaveValidations.values())window.clearTimeout(t);this.pendingSaveValidations.clear()}clearPendingSaveValidation(t){let n=this.pendingSaveValidations.get(t);n!=null&&(window.clearTimeout(n),this.pendingSaveValidations.delete(t))}scheduleSaveValidation(t){this.clearPendingSaveValidation(t.path);let n=window.setTimeout(()=>{this.pendingSaveValidations.delete(t.path),this.validateFileAndStore(t,"save")},this.saveValidationDebounceMs);this.pendingSaveValidations.set(t.path,n)}isSchemaRelevantPath(t){let n=(0,D.normalizePath)(t);if(n==="mdbase.yaml")return!0;let i=new Set(["_types"]);this.schemaCache&&i.add((0,D.normalizePath)(this.schemaCache.config.settings.types_folder));for(let s of i)if(n===s||n.startsWith(`${s}/`))return!0;return!1}invalidateSchemaCache(){this.schemaCache=null,this.schemaLoadPromise=null}async getConfigAndTypes(t=!1){if(t&&this.invalidateSchemaCache(),this.schemaCache)return this.schemaCache;if(this.schemaLoadPromise)return this.schemaLoadPromise;this.schemaLoadPromise=(async()=>{let n=await ci(this.app.vault);if(!n)return null;let i=await Kb(this.app.vault,n);return{config:n,types:i}})();try{let n=await this.schemaLoadPromise;return n&&(this.schemaCache=n),n}finally{this.schemaLoadPromise=null}}async requireConfigAndTypes(t={}){var s,o;let n=(s=t.background)!=null?s:!1,i=await this.getConfigAndTypes((o=t.forceReload)!=null?o:!1);return i?(i.types.size===0&&!n&&new D.Notice(`No types found in ${i.config.settings.types_folder}`),i):(n||new D.Notice("No mdbase.yaml found. Run 'mdbase: Initialize collection' first."),null)}onVaultModify(t){this.isSchemaRelevantPath(t.path)&&(this.invalidateSchemaCache(),this.refreshWorkspaceViews()),this.settings.validateOnSave&&t.extension==="md"&&this.scheduleSaveValidation(t)}onVaultRename(t,n){(this.isSchemaRelevantPath(n)||this.isSchemaRelevantPath(t.path))&&(this.invalidateSchemaCache(),this.refreshWorkspaceViews()),t.extension==="md"&&(this.clearPendingSaveValidation(n),this.moveFileIssues(n,t.path),this.settings.validateOnSave&&this.scheduleSaveValidation(t))}onVaultDelete(t){this.isSchemaRelevantPath(t.path)&&(this.invalidateSchemaCache(),this.refreshWorkspaceViews()),t.extension==="md"&&(this.clearPendingSaveValidation(t.path),this.clearFileIssues(t.path))}onVaultCreate(t){this.isSchemaRelevantPath(t.path)&&(this.invalidateSchemaCache(),this.refreshWorkspaceViews())}async validateFileAndStore(t,n){let i=await this.requireConfigAndTypes({background:n!=="manual"});if(!i)return n!=="manual"&&this.clearFileIssues(t.path),[];let s=await Vu(this.app.vault,t,i.config,i.types);return this.setFileIssues(t.path,s),n==="save"&&this.settings.showNoticeOnSave&&s.length>0&&new D.Notice(`mdbase: ${s.length} issue${s.length===1?"":"s"} in ${t.basename}`),s}async initializeCollectionCommand(){if(this.connectSync.assertLocalAuthorityWritable(),this.getMirrorProfile()){new D.Notice("This vault is configured as a mirror. Sync it instead of initializing a local collection.");return}let{created:t}=await Bb(this.app.vault);if(this.invalidateSchemaCache(),t.length===0){new D.Notice("mdbase collection already initialized.");return}new D.Notice(`Initialized mdbase collection: ${t.join(", ")}`)}async syncHostedCollectionCommand(){if(!this.getMirrorProfile()){await this.openWorkspace("sync");return}try{let t=await this.connectSync.sync();this.invalidateSchemaCache(),this.refreshWorkspaceViews(!0);let n=t.conflicts.length+t.local_issues.length;new D.Notice(n?`Sync completed with ${n} item${n===1?"":"s"} needing attention.`:"mdbase sync completed.")}catch(t){new D.Notice(`mdbase sync failed: ${t instanceof Error?t.message:String(t)}`),await this.openWorkspace("sync")}}async createNoteFromTypeCommand(){var u,d;this.connectSync.assertLocalAuthorityWritable();let t=await this.requireConfigAndTypes();if(!t)return;if(t.types.size===0){new D.Notice("No type definitions found.");return}let n=await uC(this.app,Array.from(t.types.values()));if(!n)return;let i=Jb(n,t.config),s=Yb(n,i);for(let[f,p]of s){let m=`Required field: ${f}`,h=await new uo(this.app,m,(u=p.type)!=null?u:"string").openAndGetValue();if(h==null)return;if(h.trim().length===0){new D.Notice(`Field '${f}' is required.`);return}try{i[f]=Uu(h,p)}catch(y){new D.Notice(`Invalid value for ${f}: ${y instanceof Error?y.message:String(y)}`);return}}let o=(d=n.display_name_key)!=null?d:"title";if(i[o]==null){let f=await new uo(this.app,`Optional ${o} (used for filename)`,"").openAndGetValue();f&&f.trim().length>0&&(i[o]=f.trim())}let a=await Qb(this.app.vault,n,i),c=await new uo(this.app,"Note path","Relative path in vault",a).openAndGetValue();if(c==null)return;let l=(0,D.normalizePath)(c.trim().length>0?c.trim():a);l.endsWith(".md")||(l=`${l}.md`);try{let f=await Zb(this.app.vault,l,i);await this.app.workspace.getLeaf(!0).openFile(f),new D.Notice(`Created note: ${f.path}`),await this.validateFileAndStore(f,"manual")}catch(f){new D.Notice(f instanceof Error?f.message:String(f))}}async validateCurrentNoteCommand(){let t=this.app.workspace.getActiveFile();if(!(t instanceof D.TFile)||t.extension!=="md"){new D.Notice("Open a markdown note first.");return}let n=await this.validateFileAndStore(t,"manual");n.length===0?new D.Notice("No issues in current note."):(new D.Notice(`Found ${n.length} issue${n.length===1?"":"s"} in current note.`),await this.openIssuesView())}async runCollectionValidation(t){var o;let n=await this.requireConfigAndTypes({background:!1});if(!n)return;let i=await Gb(this.app.vault,n.config,n.types),s=new Map;for(let a of i){let c=(o=s.get(a.path))!=null?o:[];c.push(a),s.set(a.path,c)}if(this.issueMap=s,this.sortedIssuesCache=null,this.refreshIssueViews(),t)if(i.length===0)new D.Notice("Collection validation passed with no issues.");else{let a=i.filter(l=>l.severity==="error").length,c=i.length-a;new D.Notice(`Collection validation: ${a} error(s), ${c} warning(s)`),await this.openIssuesView()}}async ensureFolderExists(t){let n=(0,D.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){let s=n.name.trim();if(!s)throw new Error("Type name is required.");if(!t.spec_version.startsWith("0.3.")||n.specProfile!=="v0.3")throw new Error("mdbase v0.2 type definitions are read-only. Migrate the collection first.");let o=lo(n),a=n.body.trim()||`# ${s} +`;var jn="mdbase-workspace-view",AC=["string","integer","number","boolean","date","datetime","time","enum","link","list","object","any"];function Ln(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function gp(r){return JSON.parse(JSON.stringify(r))}function D0(r){return typeof r.type=="string"?r.type:"any"}function xC(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 q0(r,e,t){Object.defineProperty(r,e,{configurable:!0,enumerable:!0,writable:!0,value:t})}function kC(r,e){if(!r)return["A new type definition will be created."];let t=[];r.name!==e.name&&t.push(`Rename type from ${r.name} to ${e.name}.`),(r.matchPathGlob!==e.matchPathGlob||r.matchFieldsPresent!==e.matchFieldsPresent||r.matchWhere!==e.matchWhere)&&t.push("Membership rules changed; different records may match this type.");let n=new Map(r.fields.map(c=>[c.name,c])),i=new Map(e.fields.map(c=>[c.name,c])),s=[...n.keys()].filter(c=>!i.has(c)),o=[...i.keys()].filter(c=>!n.has(c));o.length&&t.push(`Add ${o.length} field${o.length===1?"":"s"}: ${o.join(", ")}.`),s.length&&t.push(`Remove ${s.length} field${s.length===1?"":"s"}: ${s.join(", ")}.`);let a=[...i.entries()].filter(([c,l])=>{var d;return l.definition.required===!0&&((d=n.get(c))==null?void 0:d.definition.required)!==!0}).map(([c])=>c);return a.length&&t.push(`New required fields may invalidate records: ${a.join(", ")}.`),t.length||t.push("Metadata, schema details, or documentation changed."),t}function Rt(r,e,t,n,i={}){var l;let s=r.createDiv({cls:"mdbase-form-row"}),o=s.createEl("label",{text:e}),a=`mdbase-${Math.random().toString(36).slice(2)}`;o.htmlFor=a,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.value=t,c.placeholder=(l=i.placeholder)!=null?l:"",c.addEventListener("input",()=>n(c.value)),c}function Ne(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 PC(r){if(r<1e3)return String(r);let e=r<1e4?1:0;return`${(r/1e3).toFixed(e)}k`}var Bc=class extends Ae.ItemView{constructor(t,n){super(t);this.host=n;this.destination="types";this.editorMode="design";this.schema=null;this.query="";this.selectedPath=null;this.model=null;this.originalModel=null;this.yamlDraft="";this.dirty=!1;this.busy=!1;this.migrationPlan=null;this.allowLossy=!1;this.mirrorStatus=null;this.mirrorPreview=null;this.mirrorProgress=null;this.transientMessage="";this.issueQuery="";this.issueSeverity="all";this.issueLimit=250;this.enrollmentVerification="";this.enrollmentAbort=null}getViewType(){return jn}getDisplayText(){return"mdbase"}getIcon(){return Di}async onOpen(){this.containerEl.addClass("mdbase-workspace"),await this.refresh(!0)}async onClose(){var t;(t=this.enrollmentAbort)==null||t.abort(),this.enrollmentAbort=null}async refresh(t=!1){try{this.schema=await this.host.loadWorkspaceSchema(t),this.selectedPath&&!this.typeEntries().some(n=>n.filePath===this.selectedPath)&&(this.selectedPath=null,this.model=null,this.originalModel=null),!this.selectedPath&&this.typeEntries().length&&!Ae.Platform.isMobile&&(this.selectedPath=this.typeEntries()[0].filePath),this.selectedPath&&(!this.model||t)&&await this.selectType(this.selectedPath,!1),this.destination==="sync"&&await this.refreshMirrorStatus(),this.render()}catch(n){this.transientMessage=n instanceof Error?n.message:String(n),this.render()}}showDestination(t){this.destination=t,t==="sync"?this.refreshMirrorStatus().then(()=>this.render()):this.render()}typeEntries(){return this.schema?[...this.schema.types.values()].sort((t,n)=>t.name.localeCompare(n.name)):[]}render(){let t=this.containerEl;t.empty(),t.addClass("mdbase-workspace");let n=t.createDiv({cls:"mdbase-shell"});this.renderTopbar(n),this.transientMessage&&n.createDiv({cls:"mdbase-inline-message",text:this.transientMessage}).setAttr("role","status");let i=n.createDiv({cls:"mdbase-workspace-content"});this.destination==="types"?this.renderTypes(i):this.destination==="sync"?this.renderSync(i):this.renderIssues(i)}renderTopbar(t){let n=t.createDiv({cls:"mdbase-topbar"}),i=n.createDiv({cls:"mdbase-identity"}),s=i.createSpan({cls:"mdbase-mark"});s.setAttr("aria-hidden","true"),(0,Ae.setIcon)(s,Di),i.createSpan({cls:"mdbase-title",text:"mdbase"});let o=n.createDiv({cls:"mdbase-nav"});o.setAttr("role","tablist");for(let[a,c]of[["types","Types"],["sync","Sync"],["issues","Issues"]]){let l=o.createEl("button",{text:c});if(l.addClass("mdbase-nav-button"),l.setAttr("role","tab"),l.setAttr("aria-selected",String(this.destination===a)),this.destination===a&&l.addClass("is-active"),a==="issues"&&this.host.getIssues().length){let d=this.host.getIssues().length;l.createSpan({cls:"mdbase-count",text:PC(d)}).setAttr("title",`${d} issues`)}l.onclick=()=>this.showDestination(a)}}renderTypes(t){if(!this.schema){let i=t.createDiv({cls:"mdbase-empty-state"});i.createEl("h2",{text:"Start an mdbase collection"}),i.createEl("p",{text:"Initialize this vault as a local v0.3 collection, or use Sync to connect an empty vault to a collection authority."});let s=i.createDiv({cls:"mdbase-actions"}),o=s.createEl("button",{text:"Initialize local collection"});o.addClass("mod-cta"),o.disabled=this.busy||this.host.getMirrorProfile()!==null,o.onclick=()=>void this.perform(async()=>{await this.host.initializeCollection(),await this.refresh(!0)});let a=s.createEl("button",{text:"Connect collection authority"});a.onclick=()=>this.showDestination("sync");return}this.schema.config.spec_version.startsWith("0.2.")&&this.renderLegacyBanner(t);let n=t.createDiv({cls:"mdbase-types-layout"});this.model&&n.addClass("has-selection"),this.renderTypeList(n),this.renderTypeEditor(n)}renderLegacyBanner(t){var o;let n=t.createDiv({cls:"mdbase-legacy-banner"}),i=n.createDiv();i.createEl("strong",{text:`mdbase ${(o=this.schema)==null?void 0:o.config.spec_version} compatibility mode`}),i.createEl("p",{text:"Types are readable and validation remains available, but authoring is disabled until a reviewed v0.3 migration."});let s=n.createEl("button",{text:this.migrationPlan?"Review migration":"Analyze migration"});s.disabled=this.busy||this.host.getMirrorProfile()!==null,s.onclick=()=>void this.perform(async()=>{this.migrationPlan=await this.host.analyzeMigration(),this.render()}),this.host.getMirrorProfile()&&n.createDiv({cls:"mdbase-form-description",text:"Hosted resources must be migrated at the collection authority."}),this.migrationPlan&&this.renderMigrationReview(t,this.migrationPlan)}renderMigrationReview(t,n){let i=t.createDiv({cls:"mdbase-migration-review"}),s=i.createDiv({cls:"mdbase-section-header"});s.createEl("h3",{text:"Migration review"}),s.createSpan({cls:"mdbase-spec-badge",text:`${n.sourceVersion} \u2192 ${n.targetVersion}`});let o=i.createDiv({cls:"mdbase-status-list"});Ne(o,"Files replaced",String(n.operations.length)),Ne(o,"Type definitions",String(n.typeSummaries.length)),Ne(o,"Record reads verified",String(n.recordsVerified)),n.recordsSkipped&&Ne(o,"Records skipped",String(n.recordsSkipped)),Ne(o,"Record files rewritten","0"),Ne(o,"Recovery backup",n.backupLocation);let a=i.createDiv({cls:"mdbase-review-list"});n.diagnostics.length||a.createDiv({cls:"mdbase-review-ok",text:"No migration diagnostics."});for(let u of n.diagnostics.slice(0,250)){let f=a.createDiv({cls:"mdbase-review-item"});f.setAttr("data-severity",u.severity),f.createDiv({cls:"mdbase-review-code",text:`${u.severity} \xB7 ${u.path}`}),f.createDiv({text:u.message})}if(n.diagnostics.length>250&&a.createDiv({cls:"mdbase-form-description",text:`Showing 250 of ${n.diagnostics.length} diagnostics.`}),!n.applicable){let u=i.createEl("label",{cls:"mdbase-consent"}),f=u.createEl("input",{type:"checkbox"});f.checked=this.allowLossy,f.onchange=()=>{this.allowLossy=f.checked,this.render()},u.createSpan({text:"I reviewed the lossy diagnostics and want to apply this migration."})}let c=i.createDiv({cls:"mdbase-actions"}),l=c.createEl("button",{text:"Apply migration"});l.addClass("mod-warning"),l.disabled=this.busy||!n.applicable&&!this.allowLossy,l.onclick=()=>void this.perform(async()=>{await this.host.applyMigration(n,this.allowLossy),this.migrationPlan=null,this.allowLossy=!1,this.model=null,this.originalModel=null,await this.refresh(!0)});let d=c.createEl("button",{text:"Close review"});d.onclick=()=>{this.migrationPlan=null,this.render()}}renderTypeList(t){var d,u,f,p;let n=t.createDiv({cls:"mdbase-type-list-pane"}),i=n.createDiv({cls:"mdbase-pane-header"});i.createEl("h2",{text:"Types"});let s=i.createEl("button");s.setAttr("aria-label","Create type"),(0,Ae.setIcon)(s,"plus"),s.disabled=((u=(d=this.schema)==null?void 0:d.config.spec_version.startsWith("0.2."))!=null?u:!0)||((f=this.host.getMirrorProfile())==null?void 0:f.mode)==="read_only",s.onclick=()=>this.createType();let o=n.createEl("input",{type:"search"});o.addClass("mdbase-type-search"),o.placeholder="Search types",o.setAttr("aria-label","Search types"),o.value=this.query,o.oninput=()=>{this.query=o.value,this.render();let y=this.containerEl.querySelector(".mdbase-type-search");y==null||y.focus(),y==null||y.setSelectionRange(y.value.length,y.value.length)};let a=n.createDiv({cls:"mdbase-type-list"}),c=this.query.trim().toLowerCase(),l=this.typeEntries().filter(y=>{var h;return`${y.name} ${(h=y.description)!=null?h:""} ${y.filePath}`.toLowerCase().includes(c)});if(!l.length){a.createDiv({cls:"mdbase-empty-list",text:c?"No matching types.":"No type definitions."});return}for(let y of l){let h=a.createEl("button",{cls:"mdbase-type-row"});y.filePath===this.selectedPath&&h.addClass("is-active"),h.setAttr("aria-current",y.filePath===this.selectedPath?"true":"false"),h.createSpan({cls:"mdbase-type-name",text:y.name}),h.createSpan({cls:"mdbase-type-meta",text:`${Object.keys(y.fields).length} fields \xB7 ${(p=y.specProfile)!=null?p:"v0.2"}`}),h.onclick=()=>void this.selectType(y.filePath)}}renderTypeEditor(t){var h,m,g,_;let n=t.createDiv({cls:"mdbase-type-editor-pane"});if(!this.model){let w=n.createDiv({cls:"mdbase-empty-state"});w.createEl("h2",{text:"Choose a type"}),w.createEl("p",{text:"Select a type definition from the list to inspect or edit it."});return}let i=((h=this.host.getMirrorProfile())==null?void 0:h.mode)==="read_only",s=this.model.specProfile==="v0.2"||i||!!this.model.readOnlyReason,o=(m=this.model.readOnlyReason)!=null?m:i?"This mirror has read-only access. Re-enroll it with write access before editing types.":"This v0.2 type is read-only. Review and apply a collection migration before editing.",a=n.createDiv({cls:"mdbase-editor-header"}),c=a.createEl("button",{cls:"mdbase-mobile-back"});c.setAttr("aria-label","Back to type list"),(0,Ae.setIcon)(c,"arrow-left"),c.onclick=()=>{if(this.dirty){new Ae.Notice("Save or discard the current type changes before going back.");return}this.selectedPath=null,this.model=null,this.originalModel=null,this.render()};let l=a.createDiv(),d=l.createDiv({cls:"mdbase-editor-title-line"});d.createEl("h2",{text:this.model.name||"Untitled type"}),d.createSpan({cls:"mdbase-spec-badge",text:(g=this.model.specProfile)!=null?g:"v0.2"}),this.dirty&&d.createSpan({cls:"mdbase-dirty",text:"Unsaved"}),l.createDiv({cls:"mdbase-editor-path",text:(_=this.selectedPath)!=null?_:"New type"});let u=a.createDiv({cls:"mdbase-editor-actions"});if(this.selectedPath){let w=u.createEl("button",{text:"Open source"});w.onclick=()=>void this.host.openFileByPath(this.selectedPath)}let f=u.createEl("button",{text:"Save"});f.addClass("mod-cta"),f.disabled=s||!this.dirty||this.busy,f.onclick=()=>void this.saveCurrentType(),s&&n.createDiv({cls:"mdbase-readonly-note",text:o});let p=n.createDiv({cls:"mdbase-mode-switch"});p.setAttr("role","tablist");for(let[w,k]of[["design","Design"],["yaml","YAML"]]){let v=p.createEl("button",{text:k});v.setAttr("role","tab"),v.setAttr("aria-selected",String(this.editorMode===w)),this.editorMode===w&&v.addClass("is-active"),v.onclick=()=>this.switchEditorMode(w)}let y=n.createDiv({cls:"mdbase-editor-document"});this.editorMode==="design"?this.renderDesignEditor(y,this.model,s):this.renderYamlEditor(y,s)}renderDesignEditor(t,n,i){let s=t.createEl("section",{cls:"mdbase-editor-section"});s.createEl("h3",{text:"Identity"});let o=Rt(s,"Name",n.name,P=>{n.name=P,this.markDirty()},{description:"Stable type name used by collection records."});o.disabled=i;let a=Rt(s,"Description",n.description,P=>{n.description=P,this.markDirty()},{multiline:!0});a.disabled=i;let c=Rt(s,"Display field",n.displayNameKey,P=>{n.displayNameKey=P,this.markDirty()},{placeholder:"title"});c.disabled=i;let l=s.createEl("label",{cls:"mdbase-checkbox-row"}),d=l.createEl("input",{type:"checkbox"});d.checked=n.strictMode===!0,d.disabled=i,d.onchange=()=>{n.strictMode=d.checked,this.markDirty()},l.createSpan({text:"Reject undeclared fields"});let u=t.createEl("section",{cls:"mdbase-editor-section"});u.createEl("h3",{text:"Membership"});let f=Rt(u,"Path glob",n.matchPathGlob,P=>{n.matchPathGlob=P,this.markDirty()},{placeholder:"Projects/**/*.md"});f.disabled=i;let p=Rt(u,"Fields present",n.matchFieldsPresent,P=>{n.matchFieldsPresent=P,this.markDirty()},{description:"Comma-separated frontmatter keys."});p.disabled=i;let y=Rt(u,"Where",n.matchWhere,P=>{n.matchWhere=P,this.markDirty()},{multiline:!0,description:"YAML predicate, including contains and nested equality conditions.",placeholder:`tags: + contains: task`});y.disabled=i;let h=t.createEl("section",{cls:"mdbase-editor-section"}),m=h.createDiv({cls:"mdbase-section-header"});m.createEl("h3",{text:"Fields"});let g=m.createEl("button",{text:"Add field"});g.disabled=i,g.onclick=()=>{n.fields.push({name:"",definition:{type:"string"}}),this.markDirty(!0)};let _=h.createDiv({cls:"mdbase-fields"});for(let[P,O]of n.fields.entries())this.renderFieldRow(_,O,P,i);n.fields.length||_.createDiv({cls:"mdbase-empty-list",text:"No fields declared."});let w=t.createEl("section",{cls:"mdbase-editor-section"});w.createEl("h3",{text:"Placement"});let k=Rt(w,"Path pattern",n.pathPattern,P=>{n.pathPattern=P,this.markDirty()},{placeholder:"Notes/{title}.md"});k.disabled=i;let v=t.createEl("section",{cls:"mdbase-editor-section mdbase-change-review"});if(v.createEl("h3",{text:"Change review"}),!this.dirty)v.createEl("p",{text:"No pending changes."});else{let P=v.createEl("ul");for(let O of kC(this.originalModel,n))P.createEl("li",{text:O})}}renderFieldRow(t,n,i,s){this.renderFieldDefinition(t,n.definition,{name:n.name,nameLabel:`Field ${i+1} name`,onNameInput:o=>{n.name=o,this.markDirty()},required:n.definition.required===!0,onRequiredChange:o=>{n.definition.required=o,this.markDirty()},onRemove:()=>{var o;(o=this.model)==null||o.fields.splice(i,1),this.markDirty(!0)},readOnly:s,depth:0})}renderFieldDefinition(t,n,i){var d;let s=t.createDiv({cls:"mdbase-field-node"});s.setAttr("data-depth",String(i.depth));let o=s.createDiv({cls:"mdbase-field-row"});if(i.staticLabel)o.createDiv({cls:"mdbase-field-role",text:i.staticLabel});else{let u=o.createEl("input",{type:"text",cls:"mdbase-field-name-control"});u.setAttr("aria-label",i.nameLabel),u.placeholder="fieldName",u.value=(d=i.name)!=null?d:"",u.disabled=i.readOnly,i.onNameInput&&(u.oninput=()=>{var f;return(f=i.onNameInput)==null?void 0:f.call(i,u.value)}),i.onNameCommit&&(u.onchange=()=>{var f;return(f=i.onNameCommit)==null?void 0:f.call(i,u.value,u)})}let a=o.createEl("select",{cls:"mdbase-field-type-control"});a.setAttr("aria-label",`${i.name||i.staticLabel||"Field"} type`);for(let u of AC){let f=u==="any"?"Any value":u[0].toUpperCase()+u.slice(1);a.createEl("option",{value:u,text:f})}a.value=D0(n),a.disabled=i.readOnly,a.onchange=()=>{n.type=a.value,a.value==="list"&&!Ln(n.items)&&(n.items={type:"string"}),a.value==="object"&&!Ln(n.fields)&&(n.fields={}),a.value==="enum"&&!Array.isArray(n.values)&&(n.values=[]),this.markDirty(!0)};let c=o.createEl("input",{type:"text",cls:"mdbase-field-description-control"});if(c.setAttr("aria-label",`${i.name||i.staticLabel||"Field"} description`),c.placeholder="Description",c.value=typeof n.description=="string"?n.description:"",c.disabled=i.readOnly,c.oninput=()=>{c.value?n.description=c.value:delete n.description,this.markDirty()},i.onRequiredChange){let u=o.createEl("label",{cls:"mdbase-field-required"}),f=u.createEl("input",{type:"checkbox"});f.checked=i.required===!0,f.disabled=i.readOnly,f.onchange=()=>{var p;return(p=i.onRequiredChange)==null?void 0:p.call(i,f.checked)},u.createSpan({text:"Required"})}if(i.onRemove){let u=o.createEl("button",{cls:"mdbase-field-remove"});u.setAttr("aria-label",`Remove ${i.name||i.staticLabel||"field"}`),(0,Ae.setIcon)(u,"trash-2"),u.disabled=i.readOnly,u.onclick=i.onRemove}let l=D0(n);l==="enum"&&this.renderEnumFieldDetails(s,n,i),l==="link"&&this.renderLinkFieldDetails(s,n,i),l==="list"&&this.renderListFieldDetails(s,n,i),l==="object"&&this.renderObjectFieldDetails(s,n,i)}renderEnumFieldDetails(t,n,i){let s=t.createDiv({cls:"mdbase-field-details mdbase-field-options"}),o=s.createEl("label",{text:"Allowed values"}),a=s.createEl("input",{type:"text"});a.setAttr("aria-label",`${i.name||i.staticLabel||"Enum"} allowed values`),a.placeholder="draft, published, archived",a.value=Array.isArray(n.values)?n.values.map(String).join(", "):"",a.disabled=i.readOnly,a.oninput=()=>{n.values=a.value.split(",").map(c=>c.trim()).filter(Boolean),this.markDirty()},o.htmlFor=a.id=`mdbase-${Math.random().toString(36).slice(2)}`}renderLinkFieldDetails(t,n,i){let s=t.createDiv({cls:"mdbase-field-details mdbase-field-options"}),o=s.createEl("label",{text:"Target type"}),a=s.createEl("input",{type:"text"});a.setAttr("aria-label",`${i.name||i.staticLabel||"Link"} target type`),a.placeholder="Any type",a.value=typeof n.target=="string"?n.target:"",a.disabled=i.readOnly,a.oninput=()=>{a.value.trim()?n.target=a.value.trim():delete n.target,this.markDirty()},o.htmlFor=a.id=`mdbase-${Math.random().toString(36).slice(2)}`;let c=s.createEl("label",{cls:"mdbase-field-required"}),l=c.createEl("input",{type:"checkbox"});l.checked=n.validate_exists===!0,l.disabled=i.readOnly,l.onchange=()=>{n.validate_exists=l.checked,this.markDirty()},c.createSpan({text:"Validate target exists"})}renderListFieldDetails(t,n,i){let s=t.createDiv({cls:"mdbase-field-children"});s.createDiv({cls:"mdbase-field-children-label",text:"List items"});let o=Ln(n.items)?n.items:{type:"any"};!Ln(n.items)&&!i.readOnly&&(n.items=o),this.renderFieldDefinition(s,o,{staticLabel:"Item",nameLabel:"List item",readOnly:i.readOnly,depth:i.depth+1})}renderObjectFieldDetails(t,n,i){let s=t.createDiv({cls:"mdbase-field-children"}),o=s.createDiv({cls:"mdbase-field-children-header"});o.createDiv({cls:"mdbase-field-children-label",text:"Object fields"});let a=o.createEl("button",{text:"Add nested field"});a.disabled=i.readOnly;let c=Ln(n.fields)?n.fields:{};!Ln(n.fields)&&!i.readOnly&&(n.fields=c),a.onclick=()=>{let u=xC(c);q0(c,u,{type:"string"}),this.markDirty(!0)};let l=s.createDiv({cls:"mdbase-nested-fields"}),d=Object.entries(c).filter(u=>Ln(u[1]));if(!d.length){l.createDiv({cls:"mdbase-empty-list",text:"No nested fields."});return}for(let[u,f]of d){let p=u;this.renderFieldDefinition(l,f,{name:p,nameLabel:`${p} nested field name`,onNameCommit:(y,h)=>{let m=y.trim();if(!m){new Ae.Notice("Nested field name is required."),h.value=p;return}if(m!==p&&Object.prototype.hasOwnProperty.call(c,m)){new Ae.Notice(`Nested field already exists: ${m}`),h.value=p;return}m!==p&&(delete c[p],q0(c,m,f),p=m,this.markDirty())},required:f.required===!0,onRequiredChange:y=>{f.required=y,this.markDirty()},onRemove:()=>{delete c[p],this.markDirty(!0)},readOnly:i.readOnly,depth:i.depth+1})}}renderYamlEditor(t,n){let i=t.createEl("section",{cls:"mdbase-editor-section mdbase-yaml-section"});i.createEl("h3",{text:"Canonical type document"}),i.createEl("p",{cls:"mdbase-form-description",text:"Unknown v0.3 extensions are preserved. Invalid YAML is never normalized or saved."});let s=i.createEl("textarea",{cls:"mdbase-yaml-editor"});s.setAttr("aria-label","Type definition YAML"),s.value=this.yamlDraft,s.disabled=n,s.spellcheck=!1,s.oninput=()=>{this.yamlDraft=s.value,this.markDirty(!1)}}renderSync(t){var y,h,m,g,_,w,k,v,P,O;let n=t.createDiv({cls:"mdbase-sync-document"}),i=n.createDiv({cls:"mdbase-document-header"});i.createEl("h2",{text:"Sync"}),i.createEl("p",{text:"Connect this vault to a collection authority and keep ordinary Markdown mirrored locally."});let s=this.host.getMirrorProfile();if(!s){this.renderEnrollment(n);return}let o=n.createEl("section",{cls:"mdbase-editor-section"});o.createEl("h3",{text:"Collection authority"});let a=o.createDiv({cls:"mdbase-status-list"});if(Ne(a,"Name",s.name),Ne(a,"Collection",s.collectionId),Ne(a,"Access",s.mode==="read_write"?"Read and write":"Read only"),Ne(a,"Provider",s.syncUrl),Ne(a,"State",(h=(y=this.mirrorStatus)==null?void 0:y.state.replace(/_/g," "))!=null?h:"Checking"),Ne(a,"Last synced",(g=(m=this.mirrorStatus)==null?void 0:m.last_synced_at)!=null?g:"Never"),this.mirrorProgress){let $=this.mirrorProgress.total,R=o.createEl("progress");R.max=$!=null?$:1,R.value=$==null?0:this.mirrorProgress.completed,$==null&&R.removeAttribute("value"),o.createDiv({cls:"mdbase-progress-label",text:`${this.mirrorProgress.phase}: ${this.mirrorProgress.completed}${$==null?"":` of ${$}`}`});let S=o.createEl("button",{text:"Stop safely"});S.onclick=()=>{this.host.connectSync.cancelSync(),this.transientMessage="Stopping after the current action boundary\u2026",this.render()}}let c=o.createDiv({cls:"mdbase-actions"}),l=c.createEl("button",{text:"Preview"});l.disabled=this.busy,l.onclick=()=>void this.perform(async()=>{this.mirrorPreview=await this.host.connectSync.preview(),this.transientMessage=this.mirrorPreview.entries.length?"Review the engine plan below, then sync when ready.":"No content effects are needed; confirm the sync checkpoint when ready.",this.render()});let d=(w=(_=this.mirrorPreview)==null?void 0:_.plan.actions.filter($=>$.command!=="advance_checkpoint").length)!=null?w:0,u=((v=(k=this.mirrorPreview)==null?void 0:k.plan.summary.blocking_issues)!=null?v:0)>0,f=c.createEl("button",{text:this.mirrorPreview?d?`Sync ${d} ${d===1?"outcome":"outcomes"}`:"Confirm sync checkpoint":"Review before syncing"});f.addClass("mod-cta"),f.disabled=this.busy||!this.mirrorPreview||u,f.onclick=()=>void this.perform(async()=>{var R,S;let $=await this.host.connectSync.sync(this.mirrorPreview,V=>{this.mirrorProgress=V,this.render()});this.mirrorStatus=await this.host.connectSync.status(),this.mirrorPreview=await this.host.connectSync.preview(),this.mirrorProgress=null,this.transientMessage=$.status==="applied"?"Sync completed and the local checkpoint was verified.":$.status==="attention"?"Sync checkpointed completed actions and recorded the items that need attention.":$.status==="cancelled"?`Sync stopped safely after ${$.applied} actions; ${$.pending} remain pending.`:$.status==="stale"?"The reviewed plan became stale. Review the new engine plan before syncing again.":`Sync stopped at a durable action boundary: ${(S=(R=$.failure)==null?void 0:R.message)!=null?S:$.status}.`,await this.refresh(!0)}),this.mirrorPreview&&this.renderMirrorPreview(n,this.mirrorPreview),(P=this.mirrorStatus)!=null&&P.conflicts.length&&this.renderConflicts(n,this.mirrorStatus),(O=this.mirrorStatus)!=null&&O.local_issues.length&&this.renderLocalMirrorIssues(n,this.mirrorStatus);let p=n.createEl("section",{cls:"mdbase-editor-section"});p.createEl("h3",{text:"Mirror ownership"}),p.createEl("p",{text:"Use this plugin as the only sync owner for this vault. Obsidian protects concurrent operations inside the app; a separate desktop mirror process cannot share that mobile-safe lease."})}renderEnrollment(t){if(this.schema||this.host.connectSync.getAdoptionMarker()){this.renderLocalAdoption(t);return}let n=t.createEl("section",{cls:"mdbase-editor-section mdbase-enrollment"});if(n.createEl("h3",{text:"Connect collection authority"}),n.createEl("p",{text:"Connect will open an approval page. Credentials are stored in Obsidian's secret store and never written into this vault."}),this.enrollmentVerification){let u=n.createDiv({cls:"mdbase-approval-link"});u.createSpan({text:"Approval page: "});let f=u.createEl("a",{text:"Open Connect",href:this.enrollmentVerification});f.setAttr("target","_blank"),f.setAttr("rel","noopener noreferrer")}let i="https://connect.mdbase.dev",s="Obsidian",o="",a="read_write";Rt(n,"Connect URL",i,u=>{i=u},{placeholder:"https://connect.mdbase.dev"}),Rt(n,"Mirror name",s,u=>{s=u}),Rt(n,"Collection ID",o,u=>{o=u},{description:"Optional. Leave blank to choose during approval."});let c=n.createDiv({cls:"mdbase-form-row"});c.createEl("label",{text:"Access"});let l=c.createEl("select");l.createEl("option",{value:"read_write",text:"Read and write"}),l.createEl("option",{value:"read_only",text:"Read only"}),l.value=a,l.onchange=()=>{a=l.value==="read_only"?"read_only":"read_write"};let d=n.createEl("button",{text:"Open Connect approval"});d.addClass("mod-cta"),d.disabled=this.busy,d.onclick=()=>void this.perform(async()=>{var f;(f=this.enrollmentAbort)==null||f.abort();let u=new AbortController;this.enrollmentAbort=u;try{await this.host.connectSync.enroll({controlUrl:i,mirrorName:s,mode:a,...o.trim()?{collectionId:o.trim()}:{}},{signal:u.signal,onVerification:p=>{this.enrollmentVerification=p.verificationUri,this.transientMessage="Approve the mirror in the Connect page. This view will keep waiting securely.",window.open(p.verificationUri,"_blank","noopener,noreferrer"),this.render()},onStatus:p=>{this.transientMessage=p.state==="waiting_for_approval"?"Waiting for approval in Connect\u2026":`Connect is retrying enrollment (attempt ${p.attempt}).`,this.render()}}),this.enrollmentVerification="",this.transientMessage="Mirror enrolled. Preview before the first sync.",await this.refreshMirrorStatus(),this.render()}finally{this.enrollmentAbort===u&&(this.enrollmentAbort=null)}})}renderLocalAdoption(t){var d,u;let n=this.host.connectSync.getAdoptionMarker(),i=t.createEl("section",{cls:"mdbase-editor-section mdbase-enrollment"});i.createEl("h3",{text:"Host this local collection"}),i.createEl("p",{text:n?"This vault has a durable adoption checkpoint. Resume it without creating another hosted collection.":"Hosted mdbase will adopt an exact snapshot and become the collection authority. This vault will then continue as a read-write mirror."});let s=this.enrollmentVerification||(n==null?void 0:n.session.verificationUri);if(s){let f=i.createDiv({cls:"mdbase-approval-link"});f.createSpan({text:"Approval page: "});let p=f.createEl("a",{text:"Open Connect",href:s});p.setAttr("target","_blank"),p.setAttr("rel","noopener noreferrer")}let o=(d=n==null?void 0:n.session.controlUrl)!=null?d:"https://connect.mdbase.dev",a=(u=n==null?void 0:n.session.requested.mirrorName)!=null?u:"Obsidian";if(!n)Rt(i,"Connect URL",o,f=>{o=f},{placeholder:"https://connect.mdbase.dev"}),Rt(i,"Mirror name",a,f=>{a=f});else{let f=i.createDiv({cls:"mdbase-status-list"});Ne(f,"Collection",n.session.requested.collectionId),Ne(f,"Phase",n.phase.replace(/_/g," ")),Ne(f,"Connect",n.session.controlUrl)}let c=i.createDiv({cls:"mdbase-inline-message"});c.createEl("strong",{text:"Authority cut-over: "}),c.appendText("once final staging begins, plugin-managed local edits pause until hosted activation is confirmed. The checkpoint survives app restarts and uncertain network responses.");let l=i.createEl("button",{text:n?"Resume adoption":"Approve and host collection"});if(l.addClass("mod-cta"),l.disabled=this.busy,l.onclick=()=>void this.perform(async()=>{var h;(h=this.enrollmentAbort)==null||h.abort();let f=new AbortController;this.enrollmentAbort=f;let p=m=>{this.enrollmentVerification=m.verificationUri,this.transientMessage="Approve the authority move in Connect, then return here. This checkpoint is safe to resume.",this.render()},y=m=>{this.transientMessage=m.state==="waiting_for_approval"?"Waiting for authority-move approval in Connect\u2026":`Connect is retrying (attempt ${m.attempt}).`,this.render()};try{n?await this.host.connectSync.resumeAdoption({signal:f.signal,onVerification:p,onStatus:y}):await this.host.connectSync.adoptLocalCollection({controlUrl:o,mirrorName:a},{signal:f.signal,onVerification:p,onStatus:y}),this.enrollmentVerification="",this.transientMessage="Hosted mdbase is authoritative and this vault is now its read-write mirror.",await this.refresh(!0)}finally{this.enrollmentAbort===f&&(this.enrollmentAbort=null)}}),n&&!["activating","adopted"].includes(n.phase)){let f=i.createEl("button",{text:"Cancel adoption"});f.disabled=this.busy,f.onclick=()=>void this.perform(async()=>{await this.host.connectSync.cancelAdoption(),this.enrollmentVerification="",this.transientMessage="Collection adoption cancelled. This vault remains the local authority.",await this.refresh(!0)})}}renderMirrorPreview(t,n){let i=t.createEl("section",{cls:"mdbase-editor-section"});i.createEl("h3",{text:"Sync preview"});let s=i.createDiv({cls:"mdbase-status-list"});if(Ne(s,"Download documents",String(n.download_documents)),Ne(s,"Upload documents",String(n.upload_documents)),Ne(s,"Unchanged documents",String(n.unchanged_documents)),Ne(s,"Plan",n.plan.fingerprint),n.entries.length){let o=i.createEl("ul");for(let a of n.entries.slice(0,200))o.createEl("li",{text:`${a.direction==="attention"?"Attention":a.direction}: ${a.path} \u2014 ${a.detail}`})}if(n.collisions.length){i.createDiv({cls:"mdbase-inline-error",text:`${n.collisions.length} path collision${n.collisions.length===1?"":"s"} must be resolved before sync.`});let o=i.createEl("ul");for(let a of n.collisions.slice(0,100))o.createEl("li",{text:a})}if(n.local_issues.length){i.createDiv({cls:"mdbase-inline-error",text:`${n.local_issues.length} local file${n.local_issues.length===1?"":"s"} cannot be uploaded until its frontmatter is fixed.`});let o=i.createEl("ul");for(let a of n.local_issues.slice(0,100))o.createEl("li",{text:`${a.path}: ${a.message}`})}}renderConflicts(t,n){var s;let i=t.createEl("section",{cls:"mdbase-editor-section"});i.createEl("h3",{text:"Conflicts"});for(let o of n.conflicts){let a=i.createDiv({cls:"mdbase-conflict-row"}),c=a.createDiv();c.createEl("strong",{text:(s=o.path)!=null?s:o.record_id}),c.createDiv({text:o.message});let l=a.createDiv({cls:"mdbase-actions"});for(let d of["local","remote"]){let u=l.createEl("button",{text:d==="local"?"Keep local":"Use remote"});u.disabled=this.busy,u.onclick=()=>void this.perform(async()=>{this.mirrorStatus=await this.host.connectSync.resolveConflict(o.record_id,d),this.render()})}}}renderLocalMirrorIssues(t,n){let i=t.createEl("section",{cls:"mdbase-editor-section"});i.createEl("h3",{text:"Local files needing attention"}),i.createEl("p",{text:"These files remain untouched and unsynced. Other valid Markdown continues to synchronize."});for(let s of n.local_issues){let o=i.createDiv({cls:"mdbase-conflict-row"}),a=o.createDiv();a.createEl("strong",{text:s.path}),a.createDiv({text:s.message});let l=o.createDiv({cls:"mdbase-actions"}).createEl("button",{text:"Open file"});l.disabled=this.busy,l.onclick=()=>void this.host.openFileByPath(s.path)}}renderIssues(t){var g;let n=t.createDiv({cls:"mdbase-issues-document"}),i=this.host.getIssues(),s=new Set(i.map(_=>_.path)).size,o=n.createDiv({cls:"mdbase-document-header"}),a=o.createDiv();a.createEl("h2",{text:"Issues"}),a.createEl("p",{text:i.length?`${i.length.toLocaleString()} validation issues in ${s.toLocaleString()} files.`:"The collection has no current validation issues."});let c=o.createEl("button",{text:"Validate collection"});c.disabled=this.busy,c.onclick=()=>void this.perform(async()=>{await this.host.validateCollection(),this.render()});let l=n.createDiv({cls:"mdbase-issue-controls"}),d=l.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.render()};let u=l.createEl("input",{type:"search"});u.setAttr("aria-label","Filter issues"),u.placeholder="Filter by path, code, field, or message",u.value=this.issueQuery,u.oninput=()=>{this.issueQuery=u.value,this.issueLimit=250,this.render();let _=this.containerEl.querySelector(".mdbase-issue-controls input[type='search']");_==null||_.focus(),_==null||_.setSelectionRange(_.value.length,_.value.length)};let f=this.issueQuery.trim().toLowerCase(),p=i.filter(_=>{var w;return this.issueSeverity!=="all"&&_.severity!==this.issueSeverity?!1:f?`${_.path} ${_.code} ${(w=_.field)!=null?w:""} ${_.message}`.toLowerCase().includes(f):!0}),y=new Set(p.map(_=>_.path)).size;if(n.createDiv({cls:"mdbase-issues-summary",text:p.length===i.length?`Showing ${Math.min(p.length,this.issueLimit).toLocaleString()} of ${p.length.toLocaleString()} issues`:`${p.length.toLocaleString()} matching issues in ${y.toLocaleString()} files`}),!p.length){n.createDiv({cls:"mdbase-empty-state",text:"No validation issues."});return}let h=p.slice(0,this.issueLimit),m=new Map;for(let _ of h)m.set(_.path,[...(g=m.get(_.path))!=null?g:[],_]);for(let[_,w]of m){let k=n.createEl("section",{cls:"mdbase-issue-group"}),v=k.createDiv({cls:"mdbase-issue-group-header"}),P=v.createEl("button",{cls:"mdbase-issue-file-button"});(0,Ae.setIcon)(P.createSpan({cls:"mdbase-issue-file-icon"}),"file-text"),P.createSpan({cls:"mdbase-issue-file-path",text:_}),P.onclick=()=>void this.host.openFileByPath(_),v.createSpan({cls:"mdbase-issue-file-count",text:`${w.length} ${w.length===1?"issue":"issues"}`});for(let O of w){let $=k.createEl("button",{cls:"mdbase-issue-row"});$.setAttr("data-severity",O.severity),$.setAttr("aria-label",`${O.severity==="warn"?"Warning":"Error"}: ${O.message}`),$.createSpan({cls:"mdbase-issue-indicator"}).setAttr("aria-hidden","true");let R=$.createDiv({cls:"mdbase-issue-metadata"});R.createEl("code",{text:O.code}),R.createDiv({cls:"mdbase-issue-context",text:`${O.severity==="warn"?"Warning":"Error"}${O.field?` \xB7 ${O.field}`:""}`}),$.createDiv({cls:"mdbase-issue-row-message",text:O.message}),$.onclick=()=>void this.host.openFileByPath(O.path,O.field)}}if(p.length>h.length){let _=n.createEl("button",{cls:"mdbase-load-more",text:`Load ${Math.min(250,p.length-h.length)} more`});_.onclick=()=>{this.issueLimit+=250,this.render()}}}async selectType(t,n=!0){if(n&&this.dirty&&t!==this.selectedPath){new Ae.Notice("Save or discard the current type changes before switching.");return}let i=await this.host.loadTypeModel(t);this.selectedPath=t,this.model=i,this.originalModel=gp(i),this.yamlDraft=`${yt(F0(i),i.body)} +`,this.dirty=!1,this.editorMode="design",this.render()}createType(){if(this.dirty){new Ae.Notice("Save or discard the current type changes before creating another type.");return}let t=yp();this.selectedPath=null,this.model=t,this.originalModel=null,this.yamlDraft=`${yt(mo(t),t.body)} +`,this.dirty=!0,this.editorMode="design",this.render()}switchEditorMode(t){if(!(!this.model||t===this.editorMode)){if(t==="yaml")try{this.yamlDraft=`${yt(F0(this.model),this.model.body)} +`}catch(n){new Ae.Notice(n instanceof Error?n.message:String(n));return}else if(!this.readYamlDraftIntoModel())return;this.editorMode=t,this.render()}}readYamlDraftIntoModel(){var n,i;let t=It(this.yamlDraft);if(!t.hasFrontmatter||t.error)return new Ae.Notice(`Invalid type YAML: ${(n=t.error)!=null?n:"frontmatter is missing"}`),!1;if(t.frontmatter.kind!=="mdbase.type")return new Ae.Notice("Canonical v0.3 type YAML requires kind: mdbase.type."),!1;try{return this.model=Vc(t.frontmatter,t.body,((i=this.model)==null?void 0:i.name)||"type"),!0}catch(s){return new Ae.Notice(s instanceof Error?s.message:String(s)),!1}}async saveCurrentType(){if(!(!this.model||this.model.specProfile!=="v0.3"||this.model.readOnlyReason)&&!(this.editorMode==="yaml"&&!this.readYamlDraftIntoModel())){if(!this.model.name.trim()){new Ae.Notice("Type name is required.");return}await this.perform(async()=>{let t=await this.host.saveTypeModel(this.model,this.selectedPath);this.selectedPath=t.path,this.originalModel=gp(this.model),this.dirty=!1,this.transientMessage=`Saved ${t.path}.`,await this.refresh(!0)})}}markDirty(t=!1){var o,a;if(this.dirty=!0,t){this.render();return}let n=this.containerEl.querySelector(".mdbase-editor-title-line");n&&!n.querySelector(".mdbase-dirty")&&n.createSpan({cls:"mdbase-dirty",text:"Unsaved"});let i=this.containerEl.querySelector(".mdbase-editor-actions .mod-cta");i&&((o=this.model)==null?void 0:o.specProfile)==="v0.3"&&!this.model.readOnlyReason&&((a=this.host.getMirrorProfile())==null?void 0:a.mode)!=="read_only"&&(i.disabled=!1);let s=this.containerEl.querySelector(".mdbase-change-review");if(s){let c=s.querySelector("p");c&&c.setText("Pending changes. Review details after leaving the current field.")}}async refreshMirrorStatus(){try{this.mirrorStatus=await this.host.connectSync.status()}catch(t){this.mirrorStatus=null,this.transientMessage=t instanceof Error?t.message:String(t)}}async perform(t){if(!this.busy){this.busy=!0,this.transientMessage="",this.render();try{await t()}catch(n){let i=n instanceof Error?n.message:String(n);this.transientMessage=i,new Ae.Notice(i)}finally{this.busy=!1,this.render()}}}};function F0(r){var e;return r.specProfile==="v0.3"&&!r.readOnlyReason?mo(r):gp((e=r.originalFrontmatter)!=null?e:{name:r.name,fields:Object.fromEntries(r.fields.map(t=>[t.name,t.definition]))})}var qi="mdbase-issues-view",IC={validateOnSave:!0,validateOnOpen:!0,showNoticeOnSave:!1,interopEnabled:!1,mirrorProfile:null};function OC(r){if(!r||typeof r!="object"||Array.isArray(r))return!1;let e=r;return e.version===1&&typeof e.syncUrl=="string"&&typeof e.controlUrl=="string"&&typeof e.collectionId=="string"&&typeof e.replicaId=="string"&&(e.mode==="read_only"||e.mode==="read_write")&&typeof e.name=="string"&&typeof e.enrollmentId=="string"&&typeof e.accessTokenExpiresAt=="string"}function RC(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var yo=class extends L.Modal{constructor(t,n,i="",s=""){super(t);this.resolvePromise=null;this.settled=!1;this.title=n,this.placeholder=i,this.defaultValue=s}openAndGetValue(){return new Promise(t=>{this.settled=!1,this.resolvePromise=t,this.open()})}onOpen(){let{contentEl:t}=this;t.empty(),t.createEl("h3",{text:this.title});let n=t.createEl("input",{type:"text"});n.placeholder=this.placeholder,n.value=this.defaultValue,n.addClass("prompt-input");let i=t.createDiv({cls:"modal-button-container"}),s=i.createEl("button",{text:"Cancel"}),o=i.createEl("button",{text:"OK"});o.addClass("mod-cta"),s.onclick=()=>{this.finish(null),this.close()},o.onclick=()=>{this.finish(n.value.trim()),this.close()},n.addEventListener("keydown",a=>{a.key==="Enter"&&(a.preventDefault(),this.finish(n.value.trim()),this.close()),a.key==="Escape"&&(a.preventDefault(),this.finish(null),this.close())}),window.setTimeout(()=>n.focus(),0)}onClose(){this.settled||this.finish(null),this.contentEl.empty()}finish(t){var n;this.settled||(this.settled=!0,(n=this.resolvePromise)==null||n.call(this,t),this.resolvePromise=null)}},_p=class extends L.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=>{var a,c,l;let s=(c=(a=i.match)==null?void 0:a.path_glob)!=null?c:"";return`${i.name} ${(l=i.display_name_key)!=null?l:""} ${i.filePath} ${s}`.toLowerCase().includes(n)}).slice(0,100):this.typeDefs.slice(0,100)}renderSuggestion(t,n){var o,a;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((o=t.fields)!=null?o:{}).length} fields`}),(a=t.match)!=null&&a.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 TC(r,e){return new Promise(t=>{new _p(r,e,i=>{if(i.type==="selected"){t(i.typeDef);return}t(null)}).open()})}var bp=class extends L.ItemView{constructor(t,n){super(t);this.severityFilter="all";this.query="";this.plugin=n}getViewType(){return qi}getDisplayText(){return"mdbase issues"}getIcon(){return"shield-alert"}async onOpen(){this.containerEl.empty(),this.containerEl.addClass("mdbase-issues-view"),this.render()}render(){var y;let t=this.containerEl;t.empty(),t.addClass("mdbase-issues-view");let n=t.createDiv({cls:"mdbase-issues-header"});n.createEl("h3",{text:"mdbase Issues"});let s=n.createDiv({cls:"mdbase-issues-header-actions"}).createEl("button",{text:"Refresh"});s.addClass("mod-cta"),s.onclick=()=>{this.plugin.runCollectionValidation(!1)};let o=t.createDiv({cls:"mdbase-issues-controls"}),a=o.createEl("select");a.addClass("mdbase-issues-severity"),a.createEl("option",{value:"all",text:"All severities"}),a.createEl("option",{value:"error",text:"Errors only"}),a.createEl("option",{value:"warn",text:"Warnings only"}),a.value=this.severityFilter,a.onchange=()=>{let h=a.value;(h==="error"||h==="warn"||h==="all")&&(this.severityFilter=h),this.render()};let c=o.createEl("input",{type:"search"});c.addClass("mdbase-issues-query"),c.placeholder="Filter by path, code, message, field",c.value=this.query,c.oninput=()=>{this.query=c.value,this.render()};let l=this.plugin.getIssues(),d=this.query.trim().toLowerCase(),u=l.filter(h=>{var g;return this.severityFilter!=="all"&&h.severity!==this.severityFilter?!1:d?`${h.path} ${h.code} ${h.message} ${(g=h.field)!=null?g:""}`.toLowerCase().includes(d):!0}),f=u.slice(0,500);if(t.createDiv({cls:"mdbase-issues-count",text:u.length>f.length?`Showing ${f.length} of ${u.length} matching issues`:u.length===l.length?`${u.length} issue${u.length===1?"":"s"}`:`${u.length} of ${l.length} issue${l.length===1?"":"s"}`}),u.length===0){t.createDiv({cls:"mdbase-empty",text:l.length===0?"No validation issues.":"No issues match current filters."});return}let p=new Map;for(let h of f){let m=(y=p.get(h.path))!=null?y:[];m.push(h),p.set(h.path,m)}for(let[h,m]of p.entries()){t.createDiv({cls:"mdbase-issue-file",text:h});for(let g of m){let _=t.createDiv({cls:"mdbase-issue-item"});_.setAttr("data-severity",g.severity),_.createDiv({cls:"mdbase-issue-code",text:`${g.severity.toUpperCase()} \xB7 ${g.code}${g.field?` \xB7 ${g.field}`:""}`}),_.createDiv({cls:"mdbase-issue-message",text:g.message});let w=_.createDiv({cls:"mdbase-issue-actions"}),k=w.createEl("button",{text:g.field?"Open field":"Open file"});k.onclick=P=>{P.stopPropagation(),this.plugin.openIssue(g)};let v=this.plugin.getQuickFixLabel(g);if(v){let P=w.createEl("button",{text:v});P.onclick=O=>{O.stopPropagation(),this.plugin.applyQuickFix(g)}}_.onclick=()=>{this.plugin.openIssue(g)}}}}},wp=class extends L.PluginSettingTab{constructor(e,t){super(e,t),this.plugin=t}display(){let{containerEl:e}=this;e.empty(),e.createEl("h2",{text:"mdbase settings"}),new L.Setting(e).setName("Validate on save").setDesc("Run mdbase validation when a markdown file is modified.").addToggle(t=>t.setValue(this.plugin.settings.validateOnSave).onChange(async n=>{this.plugin.settings.validateOnSave=n,await this.plugin.saveSettings()})),new L.Setting(e).setName("Validate on file open").setDesc("Validate the active note when opened.").addToggle(t=>t.setValue(this.plugin.settings.validateOnOpen).onChange(async n=>{this.plugin.settings.validateOnOpen=n,await this.plugin.saveSettings()})),new L.Setting(e).setName("Show notices on save").setDesc("Display a notice when save-time validation finds issues.").addToggle(t=>t.setValue(this.plugin.settings.showNoticeOnSave).onChange(async n=>{this.plugin.settings.showNoticeOnSave=n,await this.plugin.saveSettings()})),new L.Setting(e).setName("Allow local application interoperability").setDesc("Allow installed Obsidian plugins to exchange validated mdbase events and actions in this vault. Contracts establish compatibility; this switch is the separate user grant.").addToggle(t=>t.setValue(this.plugin.settings.interopEnabled).onChange(async n=>{this.plugin.settings.interopEnabled=n,await this.plugin.saveSettings()}))}},zc=class extends L.Plugin{constructor(t,n){super(t,n);this.issueMap=new Map;this.sortedIssuesCache=null;this.schemaCache=null;this.schemaLoadPromise=null;this.pendingSaveValidations=new Map;this.saveValidationDebounceMs=250;this.connectSync=new qc(t,{getMirrorProfile:()=>this.getMirrorProfile(),saveMirrorProfile:async i=>{this.settings.mirrorProfile=i,await this.saveSettings()}}),this.interopBridge=new ya(t,()=>{var i;return((i=this.settings)==null?void 0:i.interopEnabled)===!0}),this.api={apiVersion:1,interop:this.interopBridge,getInteropStatus:()=>{var i;return{enabled:((i=this.settings)==null?void 0:i.interopEnabled)===!0,profileVersion:"0.1"}}}}async onload(){await this.loadSettings(),await this.connectSync.initialize(),(0,L.addIcon)(Di,j0),this.statusBarEl=this.addStatusBarItem(),this.updateStatusBar(),this.registerView(jn,n=>new Bc(n,this)),this.registerView(qi,n=>new bp(n,this)),this.addSettingTab(new wp(this.app,this)),this.addRibbonIcon(Di,"Open mdbase",()=>void this.openWorkspace()),this.addCommand({id:"mdbase-open",name:"mdbase: Open workspace",callback:()=>void this.openWorkspace()}),this.addCommand({id:"mdbase-initialize-collection",name:"mdbase: Initialize collection",callback:()=>void this.initializeCollectionCommand()}),this.addCommand({id:"mdbase-create-type",name:"mdbase: Create type definition",callback:()=>void this.openWorkspace("types")}),this.addCommand({id:"mdbase-edit-type",name:"mdbase: Edit type definition",callback:()=>void this.openWorkspace("types")}),this.addCommand({id:"mdbase-edit-current-type",name:"mdbase: Edit current type definition",callback:()=>void this.openWorkspace("types")}),this.addCommand({id:"mdbase-create-note-from-type",name:"mdbase: Create note from type",callback:()=>void this.createNoteFromTypeCommand()}),this.addCommand({id:"mdbase-validate-current-note",name:"mdbase: Validate current note",callback:()=>void this.validateCurrentNoteCommand()}),this.addCommand({id:"mdbase-validate-collection",name:"mdbase: Validate collection",callback:()=>void this.runCollectionValidation(!0)}),this.addCommand({id:"mdbase-open-issues-view",name:"mdbase: Open issues view",callback:()=>void this.openWorkspace("issues")}),this.addCommand({id:"mdbase-sync",name:"mdbase: Sync collection authority",callback:()=>void this.syncHostedCollectionCommand()}),this.addCommand({id:"mdbase-open-sync",name:"mdbase: Open sync",callback:()=>void this.openWorkspace("sync")}),this.registerEvent(this.app.vault.on("modify",n=>{n instanceof L.TFile&&this.onVaultModify(n)})),this.registerEvent(this.app.vault.on("rename",(n,i)=>{n instanceof L.TFile&&this.onVaultRename(n,i)})),this.registerEvent(this.app.vault.on("delete",n=>{n instanceof L.TFile&&this.onVaultDelete(n)})),this.registerEvent(this.app.vault.on("create",n=>{n instanceof L.TFile&&this.onVaultCreate(n)})),this.registerEvent(this.app.workspace.on("file-open",n=>{this.settings.validateOnOpen&&(!(n instanceof L.TFile)||n.extension!=="md"||this.validateFileAndStore(n,"open"))}));let t=this.app.workspace.getActiveFile();t&&this.settings.validateOnOpen&&this.validateFileAndStore(t,"open")}async onunload(){await this.interopBridge.dispose(),this.app.workspace.getLeavesOfType(jn).forEach(t=>t.detach()),this.app.workspace.getLeavesOfType(qi).forEach(t=>t.detach()),this.clearAllPendingSaveValidations()}async loadSettings(){this.settings=Object.assign({},IC,await this.loadData()),OC(this.settings.mirrorProfile)||(this.settings.mirrorProfile=null)}async saveSettings(){await this.saveData(this.settings)}getIssues(){var t;return(t=this.sortedIssuesCache)!=null||(this.sortedIssuesCache=Array.from(this.issueMap.values()).flat().sort((n,i)=>n.path.localeCompare(i.path)||n.severity.localeCompare(i.severity)||n.code.localeCompare(i.code))),this.sortedIssuesCache}getMirrorProfile(){return this.settings.mirrorProfile?{...this.settings.mirrorProfile}:null}async loadWorkspaceSchema(t=!1){return this.getConfigAndTypes(t)}async loadTypeModel(t){var s;let n=this.app.vault.getAbstractFileByPath((0,L.normalizePath)(t));if(!(n instanceof L.TFile))throw new Error(`Type file not found: ${t}`);let i=It(await this.app.vault.cachedRead(n));if(!i.hasFrontmatter||i.error)throw new Error(`Invalid type frontmatter: ${(s=i.error)!=null?s:"frontmatter is missing"}`);return Vc(i.frontmatter,i.body,n.basename)}async saveTypeModel(t,n){var a;if(this.connectSync.assertLocalAuthorityWritable(),((a=this.getMirrorProfile())==null?void 0:a.mode)==="read_only")throw new Error("This mirror has read-only access. Re-enroll it with write access before editing types.");let i=await ui(this.app.vault);if(!i)throw new Error("No mdbase.yaml found.");if(!i.spec_version.startsWith("0.3."))throw new Error("mdbase v0.2 type definitions are read-only. Migrate the collection first.");let s=n?this.app.vault.getAbstractFileByPath((0,L.normalizePath)(n)):null;if(s!=null&&!(s instanceof L.TFile))throw new Error(`Type file not found: ${n}`);let o=await this.writeTypeDefinition(i,t,s);return this.refreshWorkspaceViews(!0),o}async initializeCollection(){this.connectSync.assertLocalAuthorityWritable(),await this.initializeCollectionCommand(),this.refreshWorkspaceViews(!0)}async validateCollection(){await this.runCollectionValidation(!1)}analyzeMigration(){if(this.getMirrorProfile())throw new Error("Collection authority resources must be migrated at the collection authority.");return C0(this.app.vault)}async applyMigration(t,n){var s,o;if(this.connectSync.assertLocalAuthorityWritable(),this.getMirrorProfile())throw new Error("Collection authority resources must be migrated at the collection authority.");let i=await N0(this.app.vault,t,{allowLossy:n});if(!i.applied)throw new Error(i.restored?`Migration failed and all writes were rolled back. ${(s=i.error)!=null?s:""}`.trim():`Migration needs manual recovery. See ${i.manifestPath}. ${(o=i.error)!=null?o:""}`.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["unknown_field","schema_additional_properties"].includes(t.code)&&t.field?"Remove field":["missing_required","schema_required"].includes(t.code)&&t.field?"Add placeholder":null}async applyQuickFix(t){this.connectSync.assertLocalAuthorityWritable();let n=this.app.vault.getAbstractFileByPath(t.path);if(!(n instanceof L.TFile)){new L.Notice(`File not found: ${t.path}`);return}let i=await this.app.vault.cachedRead(n),s=It(i);if(s.error){new L.Notice(`Cannot apply quick fix: invalid frontmatter (${s.error})`);return}if(["unknown_field","schema_additional_properties"].includes(t.code)&&t.field){let o=va(t.field);if(!(o in s.frontmatter)){new L.Notice(`Field '${o}' not found in frontmatter.`);return}delete s.frontmatter[o],await this.app.vault.modify(n,`${yt(s.frontmatter,s.body)} +`),new L.Notice(`Removed '${o}' from ${n.basename}`),await this.validateFileAndStore(n,"manual");return}if(["missing_required","schema_required"].includes(t.code)&&t.field){let o=va(t.field);s.frontmatter[o]===void 0&&(s.frontmatter[o]="TODO");let a=s.hasFrontmatter?s.body:i;await this.app.vault.modify(n,`${yt(s.frontmatter,a)} +`),new L.Notice(`Added placeholder '${o}' to ${n.basename}`),await this.validateFileAndStore(n,"manual");return}new L.Notice("No quick fix available for this issue.")}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=va(n),l=new RegExp(`^\\s*${RC(c)}\\s*:`);if(o.getLine(0).trim()==="---")for(let d=1;ds.severity==="error").length,i=t.length-n;if(t.length===0){this.statusBarEl.setText("mdbase: no issues");return}this.statusBarEl.setText(`mdbase: ${n} error${n===1?"":"s"}, ${i} warning${i===1?"":"s"}`)}async openIssuesView(){var i;let t=this.app.workspace.getLeavesOfType(qi)[0];if(t){this.app.workspace.revealLeaf(t),t.view.render();return}let n=(i=this.app.workspace.getRightLeaf(!1))!=null?i:this.app.workspace.getLeaf(!0);await n.setViewState({type:qi,active:!0}),this.app.workspace.revealLeaf(n)}async openWorkspace(t="types"){let n=this.app.workspace.getLeavesOfType(jn)[0];if(n){this.app.workspace.revealLeaf(n);let o=n.view;o.showDestination(t),await o.refresh();return}let i=this.app.workspace.getLeaf(!0);await i.setViewState({type:jn,active:!0}),this.app.workspace.revealLeaf(i),i.view.showDestination(t)}refreshWorkspaceViews(t=!1){for(let n of this.app.workspace.getLeavesOfType(jn))n.view.refresh(t)}refreshIssueViews(){this.updateStatusBar();for(let t of this.app.workspace.getLeavesOfType(qi))t.view.render();this.refreshWorkspaceViews()}setFileIssues(t,n){n.length===0?this.issueMap.delete(t):this.issueMap.set(t,n),this.sortedIssuesCache=null,this.refreshIssueViews()}clearFileIssues(t){this.issueMap.has(t)&&(this.issueMap.delete(t),this.sortedIssuesCache=null,this.refreshIssueViews())}moveFileIssues(t,n){let 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())}clearAllPendingSaveValidations(){for(let t of this.pendingSaveValidations.values())window.clearTimeout(t);this.pendingSaveValidations.clear()}clearPendingSaveValidation(t){let n=this.pendingSaveValidations.get(t);n!=null&&(window.clearTimeout(n),this.pendingSaveValidations.delete(t))}scheduleSaveValidation(t){this.clearPendingSaveValidation(t.path);let n=window.setTimeout(()=>{this.pendingSaveValidations.delete(t.path),this.validateFileAndStore(t,"save")},this.saveValidationDebounceMs);this.pendingSaveValidations.set(t.path,n)}isSchemaRelevantPath(t){let n=(0,L.normalizePath)(t);if(n==="mdbase.yaml")return!0;let i=new Set(["_types"]);this.schemaCache&&i.add((0,L.normalizePath)(this.schemaCache.config.settings.types_folder));for(let s of i)if(n===s||n.startsWith(`${s}/`))return!0;return!1}invalidateSchemaCache(){this.schemaCache=null,this.schemaLoadPromise=null}async getConfigAndTypes(t=!1){if(t&&this.invalidateSchemaCache(),this.schemaCache)return this.schemaCache;if(this.schemaLoadPromise)return this.schemaLoadPromise;this.schemaLoadPromise=(async()=>{let n=await ui(this.app.vault);if(!n)return null;let i=await pb(this.app.vault,n);return{config:n,types:i}})();try{let n=await this.schemaLoadPromise;return n&&(this.schemaCache=n),n}finally{this.schemaLoadPromise=null}}async requireConfigAndTypes(t={}){var s,o;let n=(s=t.background)!=null?s:!1,i=await this.getConfigAndTypes((o=t.forceReload)!=null?o:!1);return i?(i.types.size===0&&!n&&new L.Notice(`No types found in ${i.config.settings.types_folder}`),i):(n||new L.Notice("No mdbase.yaml found. Run 'mdbase: Initialize collection' first."),null)}onVaultModify(t){this.isSchemaRelevantPath(t.path)&&(this.invalidateSchemaCache(),this.refreshWorkspaceViews()),this.settings.validateOnSave&&t.extension==="md"&&this.scheduleSaveValidation(t)}onVaultRename(t,n){(this.isSchemaRelevantPath(n)||this.isSchemaRelevantPath(t.path))&&(this.invalidateSchemaCache(),this.refreshWorkspaceViews()),t.extension==="md"&&(this.clearPendingSaveValidation(n),this.moveFileIssues(n,t.path),this.settings.validateOnSave&&this.scheduleSaveValidation(t))}onVaultDelete(t){this.isSchemaRelevantPath(t.path)&&(this.invalidateSchemaCache(),this.refreshWorkspaceViews()),t.extension==="md"&&(this.clearPendingSaveValidation(t.path),this.clearFileIssues(t.path))}onVaultCreate(t){this.isSchemaRelevantPath(t.path)&&(this.invalidateSchemaCache(),this.refreshWorkspaceViews())}async validateFileAndStore(t,n){let i=await this.requireConfigAndTypes({background:n!=="manual"});if(!i)return n!=="manual"&&this.clearFileIssues(t.path),[];let s=await ef(this.app.vault,t,i.config,i.types);return this.setFileIssues(t.path,s),n==="save"&&this.settings.showNoticeOnSave&&s.length>0&&new L.Notice(`mdbase: ${s.length} issue${s.length===1?"":"s"} in ${t.basename}`),s}async initializeCollectionCommand(){if(this.connectSync.assertLocalAuthorityWritable(),this.getMirrorProfile()){new L.Notice("This vault is configured as a mirror. Sync it instead of initializing a local collection.");return}let{created:t}=await db(this.app.vault);if(this.invalidateSchemaCache(),t.length===0){new L.Notice("mdbase collection already initialized.");return}new L.Notice(`Initialized mdbase collection: ${t.join(", ")}`)}async syncHostedCollectionCommand(){var t,n,i,s;if(!this.getMirrorProfile()){await this.openWorkspace("sync");return}try{let o=await this.connectSync.preview(),a=await this.connectSync.sync(o),c=await this.connectSync.status();this.invalidateSchemaCache(),this.refreshWorkspaceViews(!0);let l=((t=c==null?void 0:c.conflicts.length)!=null?t:0)+((n=c==null?void 0:c.local_issues.length)!=null?n:0);new L.Notice(a.status==="stale"?"The sync plan changed before it could apply. Review the new plan in the mdbase workspace.":a.status==="failed"||a.status==="blocked"?`mdbase sync stopped safely: ${(s=(i=a.failure)==null?void 0:i.message)!=null?s:a.status}.`:l?`Sync completed with ${l} item${l===1?"":"s"} needing attention.`:"mdbase sync completed.")}catch(o){new L.Notice(`mdbase sync failed: ${o instanceof Error?o.message:String(o)}`),await this.openWorkspace("sync")}}async createNoteFromTypeCommand(){var d,u;this.connectSync.assertLocalAuthorityWritable();let t=await this.requireConfigAndTypes();if(!t)return;if(t.types.size===0){new L.Notice("No type definitions found.");return}let n=await TC(this.app,Array.from(t.types.values()));if(!n)return;let i=yb(n,t.config),s=gb(n,i);for(let[f,p]of s){let y=`Required field: ${f}`,h=await new yo(this.app,y,(d=p.type)!=null?d:"string").openAndGetValue();if(h==null)return;if(h.trim().length===0){new L.Notice(`Field '${f}' is required.`);return}try{i[f]=tf(h,p)}catch(m){new L.Notice(`Invalid value for ${f}: ${m instanceof Error?m.message:String(m)}`);return}}let o=(u=n.display_name_key)!=null?u:"title";if(i[o]==null){let f=await new yo(this.app,`Optional ${o} (used for filename)`,"").openAndGetValue();f&&f.trim().length>0&&(i[o]=f.trim())}let a=await bb(this.app.vault,n,i),c=await new yo(this.app,"Note path","Relative path in vault",a).openAndGetValue();if(c==null)return;let l=(0,L.normalizePath)(c.trim().length>0?c.trim():a);l.endsWith(".md")||(l=`${l}.md`);try{let f=await wb(this.app.vault,l,i);await this.app.workspace.getLeaf(!0).openFile(f),new L.Notice(`Created note: ${f.path}`),await this.validateFileAndStore(f,"manual")}catch(f){new L.Notice(f instanceof Error?f.message:String(f))}}async validateCurrentNoteCommand(){let t=this.app.workspace.getActiveFile();if(!(t instanceof L.TFile)||t.extension!=="md"){new L.Notice("Open a markdown note first.");return}let n=await this.validateFileAndStore(t,"manual");n.length===0?new L.Notice("No issues in current note."):(new L.Notice(`Found ${n.length} issue${n.length===1?"":"s"} in current note.`),await this.openIssuesView())}async runCollectionValidation(t){var o;let n=await this.requireConfigAndTypes({background:!1});if(!n)return;let i=await mb(this.app.vault,n.config,n.types),s=new Map;for(let a of i){let c=(o=s.get(a.path))!=null?o:[];c.push(a),s.set(a.path,c)}if(this.issueMap=s,this.sortedIssuesCache=null,this.refreshIssueViews(),t)if(i.length===0)new L.Notice("Collection validation passed with no issues.");else{let a=i.filter(l=>l.severity==="error").length,c=i.length-a;new L.Notice(`Collection validation: ${a} error(s), ${c} warning(s)`),await this.openIssuesView()}}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){let s=n.name.trim();if(!s)throw new Error("Type name is required.");if(!t.spec_version.startsWith("0.3.")||n.specProfile!=="v0.3")throw new Error("mdbase v0.2 type definitions are read-only. Migrate the collection first.");let o=mo(n),a=n.body.trim()||`# ${s} -Type definition for ${s}.`,c=`${wt(o,a)} -`,l=(0,D.normalizePath)(t.settings.types_folder),u=(0,D.normalizePath)(`${l}/${s}.md`);if(!i){if(await this.ensureFolderExists(l),await this.app.vault.adapter.exists(u))throw new Error(`Type already exists: ${u}`);let y=await this.app.vault.create(u,c);return this.invalidateSchemaCache(),y}let d=i.path.lastIndexOf("/"),f=d>=0?i.path.slice(0,d):"",m=(0,D.normalizePath)(`${f?`${f}/`:""}${s}.md`)||u;if(m!==i.path&&await this.app.vault.adapter.exists(m))throw new Error(`Cannot rename type file to ${m}; file already exists.`);m!==i.path&&await this.app.fileManager.renameFile(i,m);let h=this.app.vault.getAbstractFileByPath(m);if(!(h instanceof D.TFile))throw new Error(`Unable to access updated type file: ${m}`);return await this.app.vault.modify(h,c),this.invalidateSchemaCache(),h}}; +Type definition for ${s}.`,c=`${yt(o,a)} +`,l=(0,L.normalizePath)(t.settings.types_folder),d=(0,L.normalizePath)(`${l}/${s}.md`);if(!i){if(await this.ensureFolderExists(l),await this.app.vault.adapter.exists(d))throw new Error(`Type already exists: ${d}`);let m=await this.app.vault.create(d,c);return this.invalidateSchemaCache(),m}let u=i.path.lastIndexOf("/"),f=u>=0?i.path.slice(0,u):"",y=(0,L.normalizePath)(`${f?`${f}/`:""}${s}.md`)||d;if(y!==i.path&&await this.app.vault.adapter.exists(y))throw new Error(`Cannot rename type file to ${y}; file already exists.`);y!==i.path&&await this.app.fileManager.renameFile(i,y);let h=this.app.vault.getAbstractFileByPath(y);if(!(h instanceof L.TFile))throw new Error(`Unable to access updated type file: ${y}`);return await this.app.vault.modify(h,c),this.invalidateSchemaCache(),h}}; diff --git a/main.ts b/main.ts index 2176315..d7c4f38 100644 --- a/main.ts +++ b/main.ts @@ -1095,12 +1095,18 @@ export default class MdbasePlugin extends Plugin { return; } try { - const status = await this.connectSync.sync(); + const reviewed = await this.connectSync.preview(); + const outcome = await this.connectSync.sync(reviewed); + const status = await this.connectSync.status(); this.invalidateSchemaCache(); this.refreshWorkspaceViews(true); - const attentionCount = status.conflicts.length + status.local_issues.length; + const attentionCount = (status?.conflicts.length ?? 0) + (status?.local_issues.length ?? 0); new Notice( - attentionCount + outcome.status === "stale" + ? "The sync plan changed before it could apply. Review the new plan in the mdbase workspace." + : outcome.status === "failed" || outcome.status === "blocked" + ? `mdbase sync stopped safely: ${outcome.failure?.message ?? outcome.status}.` + : attentionCount ? `Sync completed with ${attentionCount} item${attentionCount === 1 ? "" : "s"} needing attention.` : "mdbase sync completed.", ); diff --git a/scripts/check-mobile.mjs b/scripts/check-mobile.mjs index 8675f67..66af3a9 100644 --- a/scripts/check-mobile.mjs +++ b/scripts/check-mobile.mjs @@ -4,7 +4,10 @@ import { readFile } from "node:fs/promises"; const bundle = await readFile(new URL("../main.js", import.meta.url)); const source = bundle.toString("utf8"); const gzipBytes = gzipSync(bundle).byteLength; -const rawBudget = 575 * 1024; +// Canonical plan rendering and structured apply/cancellation outcomes replace +// the old initialization-only preview. Keep gzip fixed while allowing the +// bounded engine-plan UI and vacancy-checked move adapter 17 KiB of raw room. +const rawBudget = 592 * 1024; const gzipBudget = 170 * 1024; const forbidden = [ /require\((["'])node:(?:fs|path|crypto|os|worker_threads|child_process)\1\)/, diff --git a/src/connectSync.ts b/src/connectSync.ts index 3fd8df1..3b56d4d 100644 --- a/src/connectSync.ts +++ b/src/connectSync.ts @@ -37,9 +37,9 @@ import { } from "@mdbase-dev/connect-sync/adoption"; import { DirectoryMirror, + type MirrorApplyResult, type DirectoryMirrorOptions, type MirrorFileSystem, - type MirrorInitializationPreview, type MirrorLease, type MirrorProgress, type MirrorState, @@ -60,6 +60,7 @@ import { loadMdbaseConfig, normalizeSafeRelativePath, } from "./mdbaseCore"; +import { type MdbaseSyncPreview, previewFromPlan } from "./syncPreview"; export interface MirrorProfile { version: 1; @@ -107,7 +108,7 @@ export interface ConnectSyncSettingsHost { const ROLE_MARKER_PATH = ".mdbase/connect-role.json"; const ADOPTION_MARKER_PATH = ".mdbase/authority-adoption.json"; const ADOPTION_SNAPSHOT_PATH = ".mdbase/authority-adoption-snapshot.json"; -const STATE_DATABASE = "mdbase-obsidian-connect"; +const STATE_DATABASE = "mdbase-obsidian-connect-exact-v1"; const STATE_STORE = "mirrors"; const ACCESS_SECRET_PREFIX = "mdbase-connect-access-"; const REFRESH_SECRET_PREFIX = "mdbase-connect-refresh-"; @@ -387,6 +388,12 @@ async function ensureFolder(vault: Vault, path: string): Promise { export class ObsidianMirrorFileSystem implements MirrorFileSystem { constructor(private readonly vault: Vault) {} + async exists(input: string): Promise { + const path = safeMirrorPath(input); + return this.vault.getAbstractFileByPath(path) !== null + || await this.vault.adapter.exists(path); + } + async read(input: string): Promise { const path = safeMirrorPath(input); const file = this.vault.getAbstractFileByPath(path); @@ -412,6 +419,21 @@ export class ObsidianMirrorFileSystem implements MirrorFileSystem { } } + async move(sourceInput: string, targetInput: string): Promise { + const source = safeMirrorPath(sourceInput); + const target = safeMirrorPath(targetInput); + const slash = target.lastIndexOf("/"); + if (slash >= 0) await ensureFolder(this.vault, target.slice(0, slash)); + const sourceFile = this.vault.getAbstractFileByPath(source); + if (!(sourceFile instanceof TFile)) { + throw new SyncError("mirror_path_collision", `Expected a file at ${source}.`); + } + if (this.vault.getAbstractFileByPath(target) !== null || await this.vault.adapter.exists(target)) { + throw new SyncError("mirror_path_collision", `A file or folder blocks ${target}.`); + } + await this.vault.rename(sourceFile, target); + } + async remove(input: string): Promise { const path = safeMirrorPath(input); const existing = this.vault.getAbstractFileByPath(path); @@ -574,6 +596,7 @@ export interface ConnectSyncControllerOptions { export class ConnectSyncController { private progress: MirrorProgress | null = null; + private syncAbort: AbortController | null = null; private readonly fileSystem: MirrorFileSystem; private readonly enrollmentClient: MirrorEnrollmentClient; private readonly adoptionClient: AuthorityAdoptionClient; @@ -607,6 +630,10 @@ export class ConnectSyncController { return this.progress ? { ...this.progress } : null; } + cancelSync(): void { + this.syncAbort?.abort(); + } + getAdoptionMarker(): Readonly | null { return this.adoptionMarker ? JSON.parse(JSON.stringify(this.adoptionMarker)) as AdoptionMarker : null; } @@ -727,9 +754,9 @@ export class ConnectSyncController { return this.requireProfile(); } - async preview(): Promise { + async preview(): Promise { const mirror = await this.createMirror(); - return mirror.previewInitialization(); + return previewFromPlan(await mirror.inspect()); } async status(): Promise { @@ -740,16 +767,24 @@ export class ConnectSyncController { return mirror.status(); } - async sync(onProgress?: (progress: MirrorProgress) => void): Promise { + async sync( + reviewed: MdbaseSyncPreview, + onProgress?: (progress: MirrorProgress) => void, + ): Promise { + if (this.syncAbort) { + throw new SyncError("mirror_busy", "Synchronization is already running for this vault."); + } + const abort = new AbortController(); + this.syncAbort = abort; const mirror = await this.createMirror((next) => { this.progress = next; onProgress?.({ ...next }); }); try { - await mirror.sync(); - return mirror.status(); + return await mirror.apply(reviewed.plan, { signal: abort.signal }); } finally { this.progress = null; + this.syncAbort = null; } } diff --git a/src/syncPreview.ts b/src/syncPreview.ts new file mode 100644 index 0000000..c087e5e --- /dev/null +++ b/src/syncPreview.ts @@ -0,0 +1,119 @@ +import type { + MirrorInitializationPreview, + MirrorPlanAction, + MirrorSyncPlan, +} from "@mdbase-dev/connect-sync/mirror"; + +export type SyncPreviewDirection = "download" | "upload" | "attention"; +export type SyncPreviewAction = "create" | "update" | "rename" | "delete" | "replace" | "fix"; + +export interface SyncPreviewEntry { + kind: "document" | "file"; + path: string; + direction: SyncPreviewDirection; + action: SyncPreviewAction; + detail: string; + recordId?: string; + fileId?: string; +} + +/** UI projection of the engine-owned plan. It contains no independent diff logic. */ +export interface MdbaseSyncPreview extends MirrorInitializationPreview { + plan: MirrorSyncPlan; + phase: MirrorSyncPlan["kind"]; + entries: SyncPreviewEntry[]; + cursor: number | null; + remoteHead: number; +} + +export function previewFromPlan(plan: MirrorSyncPlan): MdbaseSyncPreview { + const entries = [ + ...plan.actions.flatMap((action) => action.command === "advance_checkpoint" ? [] : [actionEntry(action)]), + ...plan.issues.map((issue): SyncPreviewEntry => ({ + kind: "document", + path: issue.path ?? "Sync engine", + direction: "attention", + action: "fix", + detail: issue.message, + })), + ]; + return { + plan, + phase: plan.kind, + entries, + cursor: plan.base_cursor, + remoteHead: plan.authority_cursor, + already_initialized: plan.kind === "incremental", + download_documents: plan.actions.filter((action) => + ["write_local", "move_local", "delete_local"].includes(action.command) + && ("target" in action ? action.target.entity !== "file" : "source" in action && action.source.entity !== "file")).length, + upload_documents: plan.actions.filter((action) => + ["put_remote", "move_remote", "delete_remote"].includes(action.command) + && ("target" in action ? action.target.entity === "record" : "source" in action && action.source.entity === "record")).length, + unchanged_documents: 0, + download_files: plan.actions.filter((action) => + ["write_local", "move_local", "delete_local"].includes(action.command) + && ("target" in action ? action.target.entity === "file" : "source" in action && action.source.entity === "file")).length, + upload_files: plan.actions.filter((action) => + ["put_remote", "move_remote", "delete_remote"].includes(action.command) + && ("target" in action ? action.target.entity === "file" : "source" in action && action.source.entity === "file")).length, + unchanged_files: 0, + collisions: plan.issues + .filter((issue) => issue.blocking && issue.code === "local_collision" && issue.path) + .map((issue) => issue.path!), + local_issues: plan.issues + .filter((issue): issue is typeof issue & { path: string } => + issue.code === "invalid_frontmatter" && issue.path !== undefined) + .map((issue) => ({ + code: "invalid_frontmatter" as const, + message: issue.message, + path: issue.path, + })), + }; +} + +function actionEntry(action: MirrorPlanAction): SyncPreviewEntry { + if (action.command === "advance_checkpoint") { + throw new Error("Checkpoint actions are not preview entries."); + } + if (action.command === "record_conflict") { + const object = action.local.state === "exact" + ? action.local.object + : action.remote.state === "exact" + ? action.remote.object + : undefined; + return { + kind: action.entity === "file" ? "file" : "document", + path: object?.path ?? action.identity, + direction: "attention", + action: "fix", + detail: `Local and hosted ${action.entity} changes conflict (${action.conflict_kind.replace(/_/g, " ")}).`, + ...(action.entity === "record" ? { recordId: action.identity } : { fileId: action.identity }), + }; + } + const localCommand = action.command.endsWith("_local"); + const object = "target" in action ? action.target : action.source; + const path = action.command === "move_local" || action.command === "move_remote" + ? action.target_path + : object.path; + const creates = (action.command === "write_local" && action.expected_local.state === "absent") + || (action.command === "put_remote" && action.expected_remote.state === "absent"); + const verb = action.command.startsWith("move_") + ? "rename" + : action.command.startsWith("delete_") + ? "delete" + : creates + ? "create" + : "update"; + const operation = action.command.split("_")[0]; + const movement = action.command.startsWith("move_") ? ` from ${object.path}` : ""; + return { + kind: object.entity === "file" ? "file" : "document", + path, + direction: localCommand ? "download" : "upload", + action: verb, + detail: `${localCommand ? "Hosted" : "Local"} ${object.entity} will ${operation}${movement}.`, + ...(object.entity === "record" ? { recordId: object.identity } : {}), + ...(object.entity === "file" ? { fileId: object.identity } : {}), + }; +} diff --git a/src/workspaceView.ts b/src/workspaceView.ts index 8206436..03a5c3f 100644 --- a/src/workspaceView.ts +++ b/src/workspaceView.ts @@ -6,7 +6,7 @@ import { TFile, WorkspaceLeaf, } from "obsidian"; -import type { MirrorInitializationPreview, MirrorProgress, MirrorStatus } from "@mdbase-dev/connect-sync/mirror"; +import type { MirrorProgress, MirrorStatus } from "@mdbase-dev/connect-sync/mirror"; import type { AuthorityAdoptionStatus } from "@mdbase-dev/connect-sync/adoption"; import type { ConnectSyncController, @@ -20,6 +20,7 @@ import type { import { formatMarkdown, parseFrontmatter } from "./mdbaseCore"; import type { V02MigrationPlan } from "./migration"; import { MDBASE_ICON_ID } from "./mdbaseIcon"; +import type { MdbaseSyncPreview } from "./syncPreview"; import type { TypeEditorField, TypeEditorModel } from "./typeEditorTypes"; import { createDefaultTypeModel, @@ -169,7 +170,7 @@ export class MdbaseWorkspaceView extends ItemView { private migrationPlan: V02MigrationPlan | null = null; private allowLossy = false; private mirrorStatus: MirrorStatus | null = null; - private mirrorPreview: MirrorInitializationPreview | null = null; + private mirrorPreview: MdbaseSyncPreview | null = null; private mirrorProgress: MirrorProgress | null = null; private transientMessage = ""; private issueQuery = ""; @@ -868,24 +869,52 @@ export class MdbaseWorkspaceView extends ItemView { cls: "mdbase-progress-label", text: `${this.mirrorProgress.phase}: ${this.mirrorProgress.completed}${total == null ? "" : ` of ${total}`}`, }); + const cancel = status.createEl("button", { text: "Stop safely" }); + cancel.onclick = () => { + this.host.connectSync.cancelSync(); + this.transientMessage = "Stopping after the current action boundary…"; + this.render(); + }; } const actions = status.createDiv({ cls: "mdbase-actions" }); const preview = actions.createEl("button", { text: "Preview" }); preview.disabled = this.busy; preview.onclick = () => void this.perform(async () => { this.mirrorPreview = await this.host.connectSync.preview(); + this.transientMessage = this.mirrorPreview.entries.length + ? "Review the engine plan below, then sync when ready." + : "No content effects are needed; confirm the sync checkpoint when ready."; this.render(); }); - const sync = actions.createEl("button", { text: "Sync now" }); + const plannedOutcomeCount = this.mirrorPreview?.plan.actions + .filter((action) => action.command !== "advance_checkpoint").length ?? 0; + const hasBlockingIssue = (this.mirrorPreview?.plan.summary.blocking_issues ?? 0) > 0; + const sync = actions.createEl("button", { + text: this.mirrorPreview + ? plannedOutcomeCount + ? `Sync ${plannedOutcomeCount} ${plannedOutcomeCount === 1 ? "outcome" : "outcomes"}` + : "Confirm sync checkpoint" + : "Review before syncing", + }); sync.addClass("mod-cta"); - sync.disabled = this.busy; + sync.disabled = this.busy || !this.mirrorPreview || hasBlockingIssue; sync.onclick = () => void this.perform(async () => { - this.mirrorStatus = await this.host.connectSync.sync((progress) => { + const outcome = await this.host.connectSync.sync(this.mirrorPreview!, (progress) => { this.mirrorProgress = progress; this.render(); }); + this.mirrorStatus = await this.host.connectSync.status(); + this.mirrorPreview = await this.host.connectSync.preview(); this.mirrorProgress = null; - this.transientMessage = "Sync completed and the local checkpoint was verified."; + this.transientMessage = outcome.status === "applied" + ? "Sync completed and the local checkpoint was verified." + : outcome.status === "attention" + ? "Sync checkpointed completed actions and recorded the items that need attention." + : outcome.status === "cancelled" + ? `Sync stopped safely after ${outcome.applied} actions; ${outcome.pending} remain pending.` + : outcome.status === "stale" + ? "The reviewed plan became stale. Review the new engine plan before syncing again." + : `Sync stopped at a durable action boundary: ${outcome.failure?.message ?? outcome.status}.`; await this.refresh(true); }); @@ -1074,13 +1103,22 @@ export class MdbaseWorkspaceView extends ItemView { } } - private renderMirrorPreview(container: HTMLElement, preview: MirrorInitializationPreview): void { + private renderMirrorPreview(container: HTMLElement, preview: MdbaseSyncPreview): void { const section = container.createEl("section", { cls: "mdbase-editor-section" }); section.createEl("h3", { text: "Sync preview" }); const values = section.createDiv({ cls: "mdbase-status-list" }); renderStatus(values, "Download documents", String(preview.download_documents)); renderStatus(values, "Upload documents", String(preview.upload_documents)); renderStatus(values, "Unchanged documents", String(preview.unchanged_documents)); + renderStatus(values, "Plan", preview.plan.fingerprint); + if (preview.entries.length) { + const list = section.createEl("ul"); + for (const entry of preview.entries.slice(0, 200)) { + list.createEl("li", { + text: `${entry.direction === "attention" ? "Attention" : entry.direction}: ${entry.path} — ${entry.detail}`, + }); + } + } if (preview.collisions.length) { section.createDiv({ cls: "mdbase-inline-error", diff --git a/test/syncPreview.test.ts b/test/syncPreview.test.ts new file mode 100644 index 0000000..659530a --- /dev/null +++ b/test/syncPreview.test.ts @@ -0,0 +1,109 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import type { MirrorSyncPlan } from "@mdbase-dev/connect-sync/mirror"; +import { previewFromPlan } from "../src/syncPreview"; + +function plan(overrides: Partial = {}): MirrorSyncPlan { + return { + plan_version: 1, + engine_profile: "exact_document_plan_only_v1", + protocol_profile: "exact_document_v1", + planner_policy: "three_way_exact_document_v1", + projection_policy: "portable_mirror_projection_v1", + fingerprint: `sha256:${"0".repeat(64)}`, + replica_id: "replica", + mode: "read_write", + kind: "incremental", + base_cursor: 4, + authority_cursor: 6, + scope_epoch: 1, + checkpoint_generation: 2, + selective_sync: { file_classes: [], excluded_folders: [] }, + actions: [], + issues: [], + summary: { uploads: 0, downloads: 0, conflicts: 0, blocking_issues: 0 }, + ...overrides, + }; +} + +test("sync preview is a direct projection of the engine-owned plan", () => { + const preview = previewFromPlan(plan({ + actions: [ + { + command: "move_local", + action_id: "move-record", + depends_on: [], + source: { + entity: "record", + identity: "record-1", + path: "notes/old.md", + revision: `sha256:${"1".repeat(64)}`, + payload_revision: `sha256:${"1".repeat(64)}`, + }, + target_path: "notes/new.md", + expected_source_owner: { state: "absent" }, + expected_target_owner: { state: "absent" }, + reason: "remote_change", + }, + { + command: "put_remote", + action_id: "put-file", + depends_on: [], + target: { + entity: "file", + identity: "file-1", + path: "Media/local.png", + revision: `sha256:${"2".repeat(64)}`, + payload_revision: `sha256:${"2".repeat(64)}`, + size: 12, + }, + payload_revision: `sha256:${"2".repeat(64)}`, + expected_remote: { state: "absent" }, + expected_local: { state: "absent" }, + idempotency_key: "put-file", + reason: "local_change", + }, + ], + summary: { uploads: 1, downloads: 1, conflicts: 0, blocking_issues: 0 }, + })); + + assert.equal(preview.plan.fingerprint, `sha256:${"0".repeat(64)}`); + assert.deepEqual(preview.entries.map((entry) => [entry.direction, entry.action, entry.path]), [ + ["download", "rename", "notes/new.md"], + ["upload", "create", "Media/local.png"], + ]); + assert.equal(preview.download_documents, 1); + assert.equal(preview.upload_files, 1); +}); + +test("plan conflicts and blocking issues are shown as attention without inventing transfers", () => { + const preview = previewFromPlan(plan({ + actions: [{ + command: "record_conflict", + action_id: "conflict-record", + depends_on: [], + entity: "record", + identity: "record-1", + local: { state: "exact", object: { + entity: "record", + identity: "record-1", + path: "notes/conflict.md", + revision: `sha256:${"3".repeat(64)}`, + payload_revision: `sha256:${"3".repeat(64)}`, + } }, + remote: { state: "absent" }, + conflict_kind: "delete_vs_change", + reason: "remote_change", + }], + issues: [{ + code: "local_collision", + message: "Different local bytes occupy this path.", + path: "notes/collision.md", + blocking: true, + }], + summary: { uploads: 1, downloads: 0, conflicts: 1, blocking_issues: 1 }, + })); + + assert.deepEqual(preview.entries.map((entry) => entry.direction), ["attention", "attention"]); + assert.deepEqual(preview.collisions, ["notes/collision.md"]); +}); diff --git a/test/v3-foundations.test.ts b/test/v3-foundations.test.ts index 751200d..f6427a5 100644 --- a/test/v3-foundations.test.ts +++ b/test/v3-foundations.test.ts @@ -120,6 +120,17 @@ class MemoryVault { this.files.set(file.path, { file, content }); } + async rename(file: TFile, target: string): Promise { + const normalized = normalizePath(target); + if (this.files.has(normalized) || this.folders.has(normalized)) { + throw new Error(`exists ${normalized}`); + } + const entry = this.files.get(file.path); + if (!entry) throw new Error(`missing ${file.path}`); + this.files.delete(file.path); + this.files.set(normalized, { ...entry, file: new TestFile(normalized) }); + } + async readBinary(file: TFile): Promise { const entry = this.files.get(file.path); if (!entry) throw new Error(`missing ${file.path}`); @@ -526,16 +537,22 @@ test("type model edits recursive lists, objects, and nested links without flatte ); }); -test("Obsidian mirror adapter rejects traversal and reserved paths", async () => { +test("Obsidian mirror adapter rejects unsafe paths and performs vacancy-checked moves", async () => { const vault = new MemoryVault(); const fs = new ObsidianMirrorFileSystem(vault as never); await assert.rejects(fs.write("../escape.md", "x"), /escapes the collection root/); await assert.rejects(fs.write(".obsidian/plugins/evil.js", "x"), /reserved path/); await assert.rejects(fs.write(".mdbase/connect-role.json", "x"), /reserved path/); await fs.write("notes/ok.md", "hello"); + assert.equal(await fs.exists("notes/ok.md"), true); assert.equal(await fs.read("notes/ok.md"), "hello"); - await fs.remove("notes/ok.md"); + await fs.move("notes/ok.md", "notes/moved.md"); assert.equal(await fs.read("notes/ok.md"), null); + assert.equal(await fs.read("notes/moved.md"), "hello"); + await fs.write("notes/occupied.md", "occupied"); + await assert.rejects(fs.move("notes/moved.md", "notes/occupied.md"), /blocks/); + await fs.remove("notes/moved.md"); + assert.equal(await fs.exists("notes/moved.md"), false); }); test("Obsidian mirror adapter round-trips and verifies binary files", async () => { @@ -895,7 +912,11 @@ test("writable mirror uploads local edits and collision preflight makes no write fileSystem: new ObsidianMirrorFileSystem(collisionVault as never), stateStore: collisionState, }); - await assert.rejects(checkedMirror.sync(), /already exist|collis|differ/i); + const collision = await checkedMirror.sync(); + assert.equal(collision.status, "attention"); + assert.deepEqual(collision.issues.map((issue) => [issue.code, issue.path, issue.blocking]), [ + ["local_collision", "notes/one.md", true], + ]); assert.equal(collisionVault.read("notes/one.md"), "unmanaged bytes"); assert.equal(await collisionState.read(), null); }); @@ -926,10 +947,16 @@ test("interrupted mirror write does not advance the checkpoint and a retry conve fileSystem: new ObsidianMirrorFileSystem(vault as never), stateStore: state, }); - await assert.rejects(mirror.sync(), /injected adapter create failure/); - assert.equal(await state.read(), null); + const interrupted = await mirror.sync(); + assert.equal(interrupted.status, "failed", JSON.stringify(interrupted)); + assert.match(interrupted.failure?.message ?? "", /injected adapter create failure/); + const recovery = await state.read(); + assert.equal(recovery?.generation, 0); + assert.equal(recovery?.batch?.phase, "blocked"); + assert.equal(recovery?.batch?.next_action, 1); vault.failCreatePath = null; - await mirror.sync(); + const applied = await mirror.sync(); + assert.equal(applied.status, "applied", JSON.stringify(applied)); assert.equal((await mirror.status()).state, "up_to_date"); assert.equal(vault.getMarkdownFiles().length, 2); }); From 00d272a871835088cd93638440263e14d0a658fb Mon Sep 17 00:00:00 2001 From: callumalpass Date: Fri, 7 Aug 2026 09:44:32 +1000 Subject: [PATCH 2/3] chore(sync): consume beta.40 engine packages --- main.js | 196 +++++++++++++++++++++++----------------------- package-lock.json | 24 +++--- package.json | 4 +- 3 files changed, 114 insertions(+), 110 deletions(-) diff --git a/main.js b/main.js index 71f2d83..981b412 100644 --- a/main.js +++ b/main.js @@ -3,96 +3,96 @@ THIS IS A GENERATED/BUNDLED FILE BY ESBUILD if you want to view the source, please visit the github repository of this plugin */ -var V0=Object.create;var Fi=Object.defineProperty;var B0=Object.getOwnPropertyDescriptor;var z0=Object.getOwnPropertyNames;var H0=Object.getPrototypeOf,K0=Object.prototype.hasOwnProperty;var W0=(r,e,t)=>e in r?Fi(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var vp=(r,e)=>()=>(r&&(e=r(r=0)),e);var A=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),G0=(r,e)=>{for(var t in e)Fi(r,t,{get:e[t],enumerable:!0})},$p=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of z0(e))!K0.call(r,i)&&i!==t&&Fi(r,i,{get:()=>e[i],enumerable:!(n=B0(e,i))||n.enumerable});return r};var dn=(r,e,t)=>(t=r!=null?V0(H0(r)):{},$p(e||!r||!r.__esModule?Fi(t,"default",{value:r,enumerable:!0}):t,r)),J0=r=>$p(Fi({},"__esModule",{value:!0}),r);var I=(r,e,t)=>W0(r,typeof e!="symbol"?e+"":e,t);var zi=A(ce=>{"use strict";Object.defineProperty(ce,"__esModule",{value:!0});ce.regexpCode=ce.getEsmExportName=ce.getProperty=ce.safeStringify=ce.stringify=ce.strConcat=ce.addCodeArg=ce.str=ce._=ce.nil=ce._Code=ce.Name=ce.IDENTIFIER=ce._CodeOrName=void 0;var Vi=class{};ce._CodeOrName=Vi;ce.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var un=class extends Vi{constructor(e){if(super(),!ce.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}}};ce.Name=un;var vt=class extends Vi{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 un&&(t[n.str]=(t[n.str]||0)+1),t),{})}};ce._Code=vt;ce.nil=new vt("");function Sp(r,...e){let t=[r[0]],n=0;for(;n{"use strict";Object.defineProperty(ot,"__esModule",{value:!0});ot.ValueScope=ot.ValueScopeName=ot.Scope=ot.varKinds=ot.UsedValueState=void 0;var st=zi(),Wc=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},_o;(function(r){r[r.Started=0]="Started",r[r.Completed=1]="Completed"})(_o||(ot.UsedValueState=_o={}));ot.varKinds={const:new st.Name("const"),let:new st.Name("let"),var:new st.Name("var")};var bo=class{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t}toName(e){return e instanceof st.Name?e:this.name(e)}name(e){return new st.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}}};ot.Scope=bo;var wo=class extends st.Name{constructor(e,t){super(t),this.prefix=e}setValue(e,{property:t,itemIndex:n}){this.value=e,this.scopePath=(0,st._)`.${new st.Name(t)}[${n}]`}};ot.ValueScopeName=wo;var iv=(0,st._)`\n`,Gc=class extends bo{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?iv:st.nil}}get(){return this._scope}name(e){return new wo(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 d=a.get(o);if(d)return d}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,st._)`${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=st.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,_o.Started);let d=t(l);if(d){let u=this.opts.es5?ot.varKinds.var:ot.varKinds.const;s=(0,st._)`${s}${u} ${l} = ${d};${this.opts._n}`}else if(d=i==null?void 0:i(l))s=(0,st._)`${s}${d}${this.opts._n}`;else throw new Wc(l);c.set(l,_o.Completed)})}return s}};ot.ValueScope=Gc});var H=A(Y=>{"use strict";Object.defineProperty(Y,"__esModule",{value:!0});Y.or=Y.and=Y.not=Y.CodeGen=Y.operators=Y.varKinds=Y.ValueScopeName=Y.ValueScope=Y.Scope=Y.Name=Y.regexpCode=Y.stringify=Y.getProperty=Y.nil=Y.strConcat=Y.str=Y._=void 0;var ie=zi(),Tt=Jc(),Dr=zi();Object.defineProperty(Y,"_",{enumerable:!0,get:function(){return Dr._}});Object.defineProperty(Y,"str",{enumerable:!0,get:function(){return Dr.str}});Object.defineProperty(Y,"strConcat",{enumerable:!0,get:function(){return Dr.strConcat}});Object.defineProperty(Y,"nil",{enumerable:!0,get:function(){return Dr.nil}});Object.defineProperty(Y,"getProperty",{enumerable:!0,get:function(){return Dr.getProperty}});Object.defineProperty(Y,"stringify",{enumerable:!0,get:function(){return Dr.stringify}});Object.defineProperty(Y,"regexpCode",{enumerable:!0,get:function(){return Dr.regexpCode}});Object.defineProperty(Y,"Name",{enumerable:!0,get:function(){return Dr.Name}});var Eo=Jc();Object.defineProperty(Y,"Scope",{enumerable:!0,get:function(){return Eo.Scope}});Object.defineProperty(Y,"ValueScope",{enumerable:!0,get:function(){return Eo.ValueScope}});Object.defineProperty(Y,"ValueScopeName",{enumerable:!0,get:function(){return Eo.ValueScopeName}});Object.defineProperty(Y,"varKinds",{enumerable:!0,get:function(){return Eo.varKinds}});Y.operators={GT:new ie._Code(">"),GTE:new ie._Code(">="),LT:new ie._Code("<"),LTE:new ie._Code("<="),EQ:new ie._Code("==="),NEQ:new ie._Code("!=="),NOT:new ie._Code("!"),OR:new ie._Code("||"),AND:new ie._Code("&&"),ADD:new ie._Code("+")};var yr=class{optimizeNodes(){return this}optimizeNames(e,t){return this}},Yc=class extends yr{constructor(e,t,n){super(),this.varKind=e,this.name=t,this.rhs=n}render({es5:e,_n:t}){let n=e?Tt.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=qn(this.rhs,e,t)),this}get names(){return this.rhs instanceof ie._CodeOrName?this.rhs.names:{}}},vo=class extends yr{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 ie.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=qn(this.rhs,e,t),this}get names(){let e=this.lhs instanceof ie.Name?{}:{...this.lhs.names};return So(e,this.rhs)}},Xc=class extends vo{constructor(e,t,n,i){super(e,n,i),this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Qc=class extends yr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Zc=class extends yr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},el=class extends yr{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},tl=class extends yr{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=qn(this.code,e,t),this}get names(){return this.code instanceof ie._CodeOrName?this.code.names:{}}},Hi=class extends yr{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)||(sv(e,s.names),n.splice(i,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>hn(e,t.names),{})}},gr=class extends Hi{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},rl=class extends Hi{},Dn=class extends gr{};Dn.kind="else";var fn=class r extends gr{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 Dn(n):n}if(t)return e===!1?t instanceof r?t:t.nodes:this.nodes.length?this:new r(Ap(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=qn(this.condition,e,t),this}get names(){let e=super.names;return So(e,this.condition),this.else&&hn(e,this.else.names),e}};fn.kind="if";var pn=class extends gr{};pn.kind="for";var nl=class extends pn{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=qn(this.iteration,e,t),this}get names(){return hn(super.names,this.iteration.names)}},il=class extends pn{constructor(e,t,n,i){super(),this.varKind=e,this.name=t,this.from=n,this.to=i}render(e){let t=e.es5?Tt.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=So(super.names,this.from);return So(e,this.to)}},$o=class extends pn{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=qn(this.iterable,e,t),this}get names(){return hn(super.names,this.iterable.names)}},Ki=class extends gr{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)}};Ki.kind="func";var Wi=class extends Hi{render(e){return"return "+super.render(e)}};Wi.kind="return";var sl=class extends gr{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&&hn(e,this.catch.names),this.finally&&hn(e,this.finally.names),e}},Gi=class extends gr{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};Gi.kind="catch";var Ji=class extends gr{render(e){return"finally"+super.render(e)}};Ji.kind="finally";var ol=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?` -`:""},this._extScope=e,this._scope=new Tt.Scope({parent:e}),this._nodes=[new rl]}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 Yc(e,s,n)),s}const(e,t,n){return this._def(Tt.varKinds.const,e,t,n)}let(e,t,n){return this._def(Tt.varKinds.let,e,t,n)}var(e,t,n){return this._def(Tt.varKinds.var,e,t,n)}assign(e,t,n){return this._leafNode(new vo(e,t,n))}add(e,t){return this._leafNode(new Xc(e,Y.operators.ADD,t))}code(e){return typeof e=="function"?e():e!==ie.nil&&this._leafNode(new tl(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,ie.addCodeArg)(t,i));return t.push("}"),new ie._Code(t)}if(e,t,n){if(this._blockNode(new fn(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 fn(e))}else(){return this._elseNode(new Dn)}endIf(){return this._endBlockNode(fn,Dn)}_for(e,t){return this._blockNode(e),t&&this.code(t).endFor(),this}for(e,t){return this._for(new nl(e),t)}forRange(e,t,n,i,s=this.opts.es5?Tt.varKinds.var:Tt.varKinds.let){let o=this._scope.toName(e);return this._for(new il(s,o,t,n),()=>i(o))}forOf(e,t,n,i=Tt.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let o=t instanceof ie.Name?t:this.var("_arr",t);return this.forRange("_i",0,(0,ie._)`${o}.length`,a=>{this.var(s,(0,ie._)`${o}[${a}]`),n(s)})}return this._for(new $o("of",i,s,t),()=>n(s))}forIn(e,t,n,i=this.opts.es5?Tt.varKinds.var:Tt.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,ie._)`Object.keys(${t})`,n);let s=this._scope.toName(e);return this._for(new $o("in",i,s,t),()=>n(s))}endFor(){return this._endBlockNode(pn)}label(e){return this._leafNode(new Qc(e))}break(e){return this._leafNode(new Zc(e))}return(e){let t=new Wi;if(this._blockNode(t),this.code(e),t.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Wi)}try(e,t,n){if(!t&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let i=new sl;if(this._blockNode(i),this.code(e),t){let s=this.name("e");this._currNode=i.catch=new Gi(s),t(s)}return n&&(this._currNode=i.finally=new Ji,this.code(n)),this._endBlockNode(Gi,Ji)}throw(e){return this._leafNode(new el(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=ie.nil,n,i){return this._blockNode(new Ki(e,t,n)),i&&this.code(i).endFunc(),this}endFunc(){return this._endBlockNode(Ki)}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 fn))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=ol;function hn(r,e){for(let t in e)r[t]=(r[t]||0)+(e[t]||0);return r}function So(r,e){return e instanceof ie._CodeOrName?hn(r,e.names):r}function qn(r,e,t){if(r instanceof ie.Name)return n(r);if(!i(r))return r;return new ie._Code(r._items.reduce((s,o)=>(o instanceof ie.Name&&(o=n(o)),o instanceof ie._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 ie._Code&&s._items.some(o=>o instanceof ie.Name&&e[o.str]===1&&t[o.str]!==void 0)}}function sv(r,e){for(let t in e)r[t]=(r[t]||0)-(e[t]||0)}function Ap(r){return typeof r=="boolean"||typeof r=="number"||r===null?!r:(0,ie._)`!${al(r)}`}Y.not=Ap;var ov=xp(Y.operators.AND);function av(...r){return r.reduce(ov)}Y.and=av;var cv=xp(Y.operators.OR);function lv(...r){return r.reduce(cv)}Y.or=lv;function xp(r){return(e,t)=>e===ie.nil?t:t===ie.nil?e:(0,ie._)`${al(e)} ${r} ${al(t)}`}function al(r){return r instanceof ie.Name?r:(0,ie._)`(${r})`}});var Q=A(X=>{"use strict";Object.defineProperty(X,"__esModule",{value:!0});X.checkStrictMode=X.getErrorPath=X.Type=X.useFunc=X.setEvaluated=X.evaluatedPropsToName=X.mergeEvaluated=X.eachItem=X.unescapeJsonPointer=X.escapeJsonPointer=X.escapeFragment=X.unescapeFragment=X.schemaRefOrVal=X.schemaHasRulesButRef=X.schemaHasRules=X.checkUnknownRules=X.alwaysValidSchema=X.toHash=void 0;var pe=H(),dv=zi();function uv(r){let e={};for(let t of r)e[t]=!0;return e}X.toHash=uv;function fv(r,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(Ip(r,e),!Op(e,r.self.RULES.all))}X.alwaysValidSchema=fv;function Ip(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]||Mp(r,`unknown keyword: "${s}"`)}X.checkUnknownRules=Ip;function Op(r,e){if(typeof r=="boolean")return!r;for(let t in r)if(e[t])return!0;return!1}X.schemaHasRules=Op;function pv(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=pv;function hv({topSchemaRef:r,schemaPath:e},t,n,i){if(!i){if(typeof t=="number"||typeof t=="boolean")return t;if(typeof t=="string")return(0,pe._)`${t}`}return(0,pe._)`${r}${e}${(0,pe.getProperty)(n)}`}X.schemaRefOrVal=hv;function mv(r){return Rp(decodeURIComponent(r))}X.unescapeFragment=mv;function yv(r){return encodeURIComponent(ll(r))}X.escapeFragment=yv;function ll(r){return typeof r=="number"?`${r}`:r.replace(/~/g,"~0").replace(/\//g,"~1")}X.escapeJsonPointer=ll;function Rp(r){return r.replace(/~1/g,"/").replace(/~0/g,"~")}X.unescapeJsonPointer=Rp;function gv(r,e){if(Array.isArray(r))for(let t of r)e(t);else e(r)}X.eachItem=gv;function kp({mergeNames:r,mergeToName:e,mergeValues:t,resultToName:n}){return(i,s,o,a)=>{let c=o===void 0?s:o instanceof pe.Name?(s instanceof pe.Name?r(i,s,o):e(i,s,o),o):s instanceof pe.Name?(e(i,o,s),s):t(s,o);return a===pe.Name&&!(c instanceof pe.Name)?n(i,c):c}}X.mergeEvaluated={props:kp({mergeNames:(r,e,t)=>r.if((0,pe._)`${t} !== true && ${e} !== undefined`,()=>{r.if((0,pe._)`${e} === true`,()=>r.assign(t,!0),()=>r.assign(t,(0,pe._)`${t} || {}`).code((0,pe._)`Object.assign(${t}, ${e})`))}),mergeToName:(r,e,t)=>r.if((0,pe._)`${t} !== true`,()=>{e===!0?r.assign(t,!0):(r.assign(t,(0,pe._)`${t} || {}`),dl(r,t,e))}),mergeValues:(r,e)=>r===!0?!0:{...r,...e},resultToName:Tp}),items:kp({mergeNames:(r,e,t)=>r.if((0,pe._)`${t} !== true && ${e} !== undefined`,()=>r.assign(t,(0,pe._)`${e} === true ? true : ${t} > ${e} ? ${t} : ${e}`)),mergeToName:(r,e,t)=>r.if((0,pe._)`${t} !== true`,()=>r.assign(t,e===!0?!0:(0,pe._)`${t} > ${e} ? ${t} : ${e}`)),mergeValues:(r,e)=>r===!0?!0:Math.max(r,e),resultToName:(r,e)=>r.var("items",e)})};function Tp(r,e){if(e===!0)return r.var("props",!0);let t=r.var("props",(0,pe._)`{}`);return e!==void 0&&dl(r,t,e),t}X.evaluatedPropsToName=Tp;function dl(r,e,t){Object.keys(t).forEach(n=>r.assign((0,pe._)`${e}${(0,pe.getProperty)(n)}`,!0))}X.setEvaluated=dl;var Pp={};function _v(r,e){return r.scopeValue("func",{ref:e,code:Pp[e.code]||(Pp[e.code]=new dv._Code(e.code))})}X.useFunc=_v;var cl;(function(r){r[r.Num=0]="Num",r[r.Str=1]="Str"})(cl||(X.Type=cl={}));function bv(r,e,t){if(r instanceof pe.Name){let n=e===cl.Num;return t?n?(0,pe._)`"[" + ${r} + "]"`:(0,pe._)`"['" + ${r} + "']"`:n?(0,pe._)`"/" + ${r}`:(0,pe._)`"/" + ${r}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return t?(0,pe.getProperty)(r).toString():"/"+ll(r)}X.getErrorPath=bv;function Mp(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=Mp});var $t=A(ul=>{"use strict";Object.defineProperty(ul,"__esModule",{value:!0});var Be=H(),wv={data:new Be.Name("data"),valCxt:new Be.Name("valCxt"),instancePath:new Be.Name("instancePath"),parentData:new Be.Name("parentData"),parentDataProperty:new Be.Name("parentDataProperty"),rootData:new Be.Name("rootData"),dynamicAnchors:new Be.Name("dynamicAnchors"),vErrors:new Be.Name("vErrors"),errors:new Be.Name("errors"),this:new Be.Name("this"),self:new Be.Name("self"),scope:new Be.Name("scope"),json:new Be.Name("json"),jsonPos:new Be.Name("jsonPos"),jsonLen:new Be.Name("jsonLen"),jsonPart:new Be.Name("jsonPart")};ul.default=wv});var Yi=A(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 ae=H(),Ao=Q(),Ye=$t();ze.keywordError={message:({keyword:r})=>(0,ae.str)`must pass "${r}" keyword validation`};ze.keyword$DataError={message:({keyword:r,schemaType:e})=>e?(0,ae.str)`"${r}" keyword must be ${e} ($data)`:(0,ae.str)`"${r}" keyword is invalid ($data)`};function vv(r,e=ze.keywordError,t,n){let{it:i}=r,{gen:s,compositeRule:o,allErrors:a}=i,c=Lp(r,e,t);(n!=null?n:o||a)?Cp(s,c):Np(i,(0,ae._)`[${c}]`)}ze.reportError=vv;function $v(r,e=ze.keywordError,t){let{it:n}=r,{gen:i,compositeRule:s,allErrors:o}=n,a=Lp(r,e,t);Cp(i,a),s||o||Np(n,Ye.default.vErrors)}ze.reportExtraError=$v;function Sv(r,e){r.assign(Ye.default.errors,e),r.if((0,ae._)`${Ye.default.vErrors} !== null`,()=>r.if(e,()=>r.assign((0,ae._)`${Ye.default.vErrors}.length`,e),()=>r.assign(Ye.default.vErrors,null)))}ze.resetErrorsCount=Sv;function Ev({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,Ye.default.errors,a=>{r.const(o,(0,ae._)`${Ye.default.vErrors}[${a}]`),r.if((0,ae._)`${o}.instancePath === undefined`,()=>r.assign((0,ae._)`${o}.instancePath`,(0,ae.strConcat)(Ye.default.instancePath,s.errorPath))),r.assign((0,ae._)`${o}.schemaPath`,(0,ae.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(r.assign((0,ae._)`${o}.schema`,t),r.assign((0,ae._)`${o}.data`,n))})}ze.extendErrors=Ev;function Cp(r,e){let t=r.const("err",e);r.if((0,ae._)`${Ye.default.vErrors} === null`,()=>r.assign(Ye.default.vErrors,(0,ae._)`[${t}]`),(0,ae._)`${Ye.default.vErrors}.push(${t})`),r.code((0,ae._)`${Ye.default.errors}++`)}function Np(r,e){let{gen:t,validateName:n,schemaEnv:i}=r;i.$async?t.throw((0,ae._)`new ${r.ValidationError}(${e})`):(t.assign((0,ae._)`${n}.errors`,e),t.return(!1))}var mn={keyword:new ae.Name("keyword"),schemaPath:new ae.Name("schemaPath"),params:new ae.Name("params"),propertyName:new ae.Name("propertyName"),message:new ae.Name("message"),schema:new ae.Name("schema"),parentSchema:new ae.Name("parentSchema")};function Lp(r,e,t){let{createErrors:n}=r.it;return n===!1?(0,ae._)`{}`:Av(r,e,t)}function Av(r,e,t={}){let{gen:n,it:i}=r,s=[xv(i,t),kv(r,t)];return Pv(r,e,s),n.object(...s)}function xv({errorPath:r},{instancePath:e}){let t=e?(0,ae.str)`${r}${(0,Ao.getErrorPath)(e,Ao.Type.Str)}`:r;return[Ye.default.instancePath,(0,ae.strConcat)(Ye.default.instancePath,t)]}function kv({keyword:r,it:{errSchemaPath:e}},{schemaPath:t,parentSchema:n}){let i=n?e:(0,ae.str)`${e}/${r}`;return t&&(i=(0,ae.str)`${i}${(0,Ao.getErrorPath)(t,Ao.Type.Str)}`),[mn.schemaPath,i]}function Pv(r,{params:e,message:t},n){let{keyword:i,data:s,schemaValue:o,it:a}=r,{opts:c,propertyName:l,topSchemaRef:d,schemaPath:u}=a;n.push([mn.keyword,i],[mn.params,typeof e=="function"?e(r):e||(0,ae._)`{}`]),c.messages&&n.push([mn.message,typeof t=="function"?t(r):t]),c.verbose&&n.push([mn.schema,o],[mn.parentSchema,(0,ae._)`${d}${u}`],[Ye.default.data,s]),l&&n.push([mn.propertyName,l])}});var Dp=A(Fn=>{"use strict";Object.defineProperty(Fn,"__esModule",{value:!0});Fn.boolOrEmptySchema=Fn.topBoolOrEmptySchema=void 0;var Iv=Yi(),Ov=H(),Rv=$t(),Tv={message:"boolean schema is false"};function Mv(r){let{gen:e,schema:t,validateName:n}=r;t===!1?jp(r,!1):typeof t=="object"&&t.$async===!0?e.return(Rv.default.data):(e.assign((0,Ov._)`${n}.errors`,null),e.return(!0))}Fn.topBoolOrEmptySchema=Mv;function Cv(r,e){let{gen:t,schema:n}=r;n===!1?(t.var(e,!1),jp(r)):t.var(e,!0)}Fn.boolOrEmptySchema=Cv;function jp(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,Iv.reportError)(i,Tv,void 0,e)}});var fl=A(Un=>{"use strict";Object.defineProperty(Un,"__esModule",{value:!0});Un.getRules=Un.isJSONType=void 0;var Nv=["string","number","integer","boolean","null","object","array"],Lv=new Set(Nv);function jv(r){return typeof r=="string"&&Lv.has(r)}Un.isJSONType=jv;function Dv(){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:{}}}Un.getRules=Dv});var pl=A(qr=>{"use strict";Object.defineProperty(qr,"__esModule",{value:!0});qr.shouldUseRule=qr.shouldUseGroup=qr.schemaHasRulesForType=void 0;function qv({schema:r,self:e},t){let n=e.RULES.types[t];return n&&n!==!0&&qp(r,n)}qr.schemaHasRulesForType=qv;function qp(r,e){return e.rules.some(t=>Fp(r,t))}qr.shouldUseGroup=qp;function Fp(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))}qr.shouldUseRule=Fp});var Xi=A(He=>{"use strict";Object.defineProperty(He,"__esModule",{value:!0});He.reportTypeError=He.checkDataTypes=He.checkDataType=He.coerceAndCheckDataType=He.getJSONTypes=He.getSchemaTypes=He.DataType=void 0;var Fv=fl(),Uv=pl(),Vv=Yi(),W=H(),Up=Q(),Vn;(function(r){r[r.Correct=0]="Correct",r[r.Wrong=1]="Wrong"})(Vn||(He.DataType=Vn={}));function Bv(r){let e=Vp(r.type);if(e.includes("null")){if(r.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&r.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');r.nullable===!0&&e.push("null")}return e}He.getSchemaTypes=Bv;function Vp(r){let e=Array.isArray(r)?r:r?[r]:[];if(e.every(Fv.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}He.getJSONTypes=Vp;function zv(r,e){let{gen:t,data:n,opts:i}=r,s=Hv(e,i.coerceTypes),o=e.length>0&&!(s.length===0&&e.length===1&&(0,Uv.schemaHasRulesForType)(r,e[0]));if(o){let a=ml(e,n,i.strictNumbers,Vn.Wrong);t.if(a,()=>{s.length?Kv(r,e,s):yl(r)})}return o}He.coerceAndCheckDataType=zv;var Bp=new Set(["string","number","integer","boolean","null"]);function Hv(r,e){return e?r.filter(t=>Bp.has(t)||e==="array"&&t==="array"):[]}function Kv(r,e,t){let{gen:n,data:i,opts:s}=r,o=n.let("dataType",(0,W._)`typeof ${i}`),a=n.let("coerced",(0,W._)`undefined`);s.coerceTypes==="array"&&n.if((0,W._)`${o} == 'object' && Array.isArray(${i}) && ${i}.length == 1`,()=>n.assign(i,(0,W._)`${i}[0]`).assign(o,(0,W._)`typeof ${i}`).if(ml(e,i,s.strictNumbers),()=>n.assign(a,i))),n.if((0,W._)`${a} !== undefined`);for(let l of t)(Bp.has(l)||l==="array"&&s.coerceTypes==="array")&&c(l);n.else(),yl(r),n.endIf(),n.if((0,W._)`${a} !== undefined`,()=>{n.assign(i,a),Wv(r,a)});function c(l){switch(l){case"string":n.elseIf((0,W._)`${o} == "number" || ${o} == "boolean"`).assign(a,(0,W._)`"" + ${i}`).elseIf((0,W._)`${i} === null`).assign(a,(0,W._)`""`);return;case"number":n.elseIf((0,W._)`${o} == "boolean" || ${i} === null +var j0=Object.create;var Vi=Object.defineProperty;var D0=Object.getOwnPropertyDescriptor;var q0=Object.getOwnPropertyNames;var F0=Object.getPrototypeOf,V0=Object.prototype.hasOwnProperty;var U0=(r,e,t)=>e in r?Vi(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var A=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),B0=(r,e)=>{for(var t in e)Vi(r,t,{get:e[t],enumerable:!0})},vp=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of q0(e))!V0.call(r,i)&&i!==t&&Vi(r,i,{get:()=>e[i],enumerable:!(n=D0(e,i))||n.enumerable});return r};var fn=(r,e,t)=>(t=r!=null?j0(F0(r)):{},vp(e||!r||!r.__esModule?Vi(t,"default",{value:r,enumerable:!0}):t,r)),z0=r=>vp(Vi({},"__esModule",{value:!0}),r);var I=(r,e,t)=>U0(r,typeof e!="symbol"?e+"":e,t);var Hi=A(ce=>{"use strict";Object.defineProperty(ce,"__esModule",{value:!0});ce.regexpCode=ce.getEsmExportName=ce.getProperty=ce.safeStringify=ce.stringify=ce.strConcat=ce.addCodeArg=ce.str=ce._=ce.nil=ce._Code=ce.Name=ce.IDENTIFIER=ce._CodeOrName=void 0;var Bi=class{};ce._CodeOrName=Bi;ce.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var pn=class extends Bi{constructor(e){if(super(),!ce.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}}};ce.Name=pn;var wt=class extends Bi{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 pn&&(t[n.str]=(t[n.str]||0)+1),t),{})}};ce._Code=wt;ce.nil=new wt("");function $p(r,...e){let t=[r[0]],n=0;for(;n{"use strict";Object.defineProperty(st,"__esModule",{value:!0});st.ValueScope=st.ValueScopeName=st.Scope=st.varKinds=st.UsedValueState=void 0;var it=Hi(),Wc=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},bo;(function(r){r[r.Started=0]="Started",r[r.Completed=1]="Completed"})(bo||(st.UsedValueState=bo={}));st.varKinds={const:new it.Name("const"),let:new it.Name("let"),var:new it.Name("var")};var wo=class{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t}toName(e){return e instanceof it.Name?e:this.name(e)}name(e){return new it.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}}};st.Scope=wo;var vo=class extends it.Name{constructor(e,t){super(t),this.prefix=e}setValue(e,{property:t,itemIndex:n}){this.value=e,this.scopePath=(0,it._)`.${new it.Name(t)}[${n}]`}};st.ValueScopeName=vo;var Z0=(0,it._)`\n`,Gc=class extends wo{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?Z0:it.nil}}get(){return this._scope}name(e){return new vo(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 d=a.get(o);if(d)return d}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,it._)`${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=it.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,bo.Started);let d=t(l);if(d){let u=this.opts.es5?st.varKinds.var:st.varKinds.const;s=(0,it._)`${s}${u} ${l} = ${d};${this.opts._n}`}else if(d=i==null?void 0:i(l))s=(0,it._)`${s}${d}${this.opts._n}`;else throw new Wc(l);c.set(l,bo.Completed)})}return s}};st.ValueScope=Gc});var H=A(Y=>{"use strict";Object.defineProperty(Y,"__esModule",{value:!0});Y.or=Y.and=Y.not=Y.CodeGen=Y.operators=Y.varKinds=Y.ValueScopeName=Y.ValueScope=Y.Scope=Y.Name=Y.regexpCode=Y.stringify=Y.getProperty=Y.nil=Y.strConcat=Y.str=Y._=void 0;var ie=Hi(),Rt=Jc(),Fr=Hi();Object.defineProperty(Y,"_",{enumerable:!0,get:function(){return Fr._}});Object.defineProperty(Y,"str",{enumerable:!0,get:function(){return Fr.str}});Object.defineProperty(Y,"strConcat",{enumerable:!0,get:function(){return Fr.strConcat}});Object.defineProperty(Y,"nil",{enumerable:!0,get:function(){return Fr.nil}});Object.defineProperty(Y,"getProperty",{enumerable:!0,get:function(){return Fr.getProperty}});Object.defineProperty(Y,"stringify",{enumerable:!0,get:function(){return Fr.stringify}});Object.defineProperty(Y,"regexpCode",{enumerable:!0,get:function(){return Fr.regexpCode}});Object.defineProperty(Y,"Name",{enumerable:!0,get:function(){return Fr.Name}});var Ao=Jc();Object.defineProperty(Y,"Scope",{enumerable:!0,get:function(){return Ao.Scope}});Object.defineProperty(Y,"ValueScope",{enumerable:!0,get:function(){return Ao.ValueScope}});Object.defineProperty(Y,"ValueScopeName",{enumerable:!0,get:function(){return Ao.ValueScopeName}});Object.defineProperty(Y,"varKinds",{enumerable:!0,get:function(){return Ao.varKinds}});Y.operators={GT:new ie._Code(">"),GTE:new ie._Code(">="),LT:new ie._Code("<"),LTE:new ie._Code("<="),EQ:new ie._Code("==="),NEQ:new ie._Code("!=="),NOT:new ie._Code("!"),OR:new ie._Code("||"),AND:new ie._Code("&&"),ADD:new ie._Code("+")};var yr=class{optimizeNodes(){return this}optimizeNames(e,t){return this}},Yc=class extends yr{constructor(e,t,n){super(),this.varKind=e,this.name=t,this.rhs=n}render({es5:e,_n:t}){let n=e?Rt.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=Vn(this.rhs,e,t)),this}get names(){return this.rhs instanceof ie._CodeOrName?this.rhs.names:{}}},$o=class extends yr{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 ie.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Vn(this.rhs,e,t),this}get names(){let e=this.lhs instanceof ie.Name?{}:{...this.lhs.names};return Eo(e,this.rhs)}},Xc=class extends $o{constructor(e,t,n,i){super(e,n,i),this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Qc=class extends yr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Zc=class extends yr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},el=class extends yr{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},tl=class extends yr{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=Vn(this.code,e,t),this}get names(){return this.code instanceof ie._CodeOrName?this.code.names:{}}},Ki=class extends yr{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)||(ev(e,s.names),n.splice(i,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>yn(e,t.names),{})}},gr=class extends Ki{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},rl=class extends Ki{},Fn=class extends gr{};Fn.kind="else";var hn=class r extends gr{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 Fn(n):n}if(t)return e===!1?t instanceof r?t:t.nodes:this.nodes.length?this:new r(Ep(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=Vn(this.condition,e,t),this}get names(){let e=super.names;return Eo(e,this.condition),this.else&&yn(e,this.else.names),e}};hn.kind="if";var mn=class extends gr{};mn.kind="for";var nl=class extends mn{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=Vn(this.iteration,e,t),this}get names(){return yn(super.names,this.iteration.names)}},il=class extends mn{constructor(e,t,n,i){super(),this.varKind=e,this.name=t,this.from=n,this.to=i}render(e){let t=e.es5?Rt.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=Eo(super.names,this.from);return Eo(e,this.to)}},So=class extends mn{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=Vn(this.iterable,e,t),this}get names(){return yn(super.names,this.iterable.names)}},Wi=class extends gr{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)}};Wi.kind="func";var Gi=class extends Ki{render(e){return"return "+super.render(e)}};Gi.kind="return";var sl=class extends gr{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&&yn(e,this.catch.names),this.finally&&yn(e,this.finally.names),e}},Ji=class extends gr{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};Ji.kind="catch";var Yi=class extends gr{render(e){return"finally"+super.render(e)}};Yi.kind="finally";var ol=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?` +`:""},this._extScope=e,this._scope=new Rt.Scope({parent:e}),this._nodes=[new rl]}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 Yc(e,s,n)),s}const(e,t,n){return this._def(Rt.varKinds.const,e,t,n)}let(e,t,n){return this._def(Rt.varKinds.let,e,t,n)}var(e,t,n){return this._def(Rt.varKinds.var,e,t,n)}assign(e,t,n){return this._leafNode(new $o(e,t,n))}add(e,t){return this._leafNode(new Xc(e,Y.operators.ADD,t))}code(e){return typeof e=="function"?e():e!==ie.nil&&this._leafNode(new tl(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,ie.addCodeArg)(t,i));return t.push("}"),new ie._Code(t)}if(e,t,n){if(this._blockNode(new hn(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 hn(e))}else(){return this._elseNode(new Fn)}endIf(){return this._endBlockNode(hn,Fn)}_for(e,t){return this._blockNode(e),t&&this.code(t).endFor(),this}for(e,t){return this._for(new nl(e),t)}forRange(e,t,n,i,s=this.opts.es5?Rt.varKinds.var:Rt.varKinds.let){let o=this._scope.toName(e);return this._for(new il(s,o,t,n),()=>i(o))}forOf(e,t,n,i=Rt.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let o=t instanceof ie.Name?t:this.var("_arr",t);return this.forRange("_i",0,(0,ie._)`${o}.length`,a=>{this.var(s,(0,ie._)`${o}[${a}]`),n(s)})}return this._for(new So("of",i,s,t),()=>n(s))}forIn(e,t,n,i=this.opts.es5?Rt.varKinds.var:Rt.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,ie._)`Object.keys(${t})`,n);let s=this._scope.toName(e);return this._for(new So("in",i,s,t),()=>n(s))}endFor(){return this._endBlockNode(mn)}label(e){return this._leafNode(new Qc(e))}break(e){return this._leafNode(new Zc(e))}return(e){let t=new Gi;if(this._blockNode(t),this.code(e),t.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Gi)}try(e,t,n){if(!t&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let i=new sl;if(this._blockNode(i),this.code(e),t){let s=this.name("e");this._currNode=i.catch=new Ji(s),t(s)}return n&&(this._currNode=i.finally=new Yi,this.code(n)),this._endBlockNode(Ji,Yi)}throw(e){return this._leafNode(new el(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=ie.nil,n,i){return this._blockNode(new Wi(e,t,n)),i&&this.code(i).endFunc(),this}endFunc(){return this._endBlockNode(Wi)}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 hn))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=ol;function yn(r,e){for(let t in e)r[t]=(r[t]||0)+(e[t]||0);return r}function Eo(r,e){return e instanceof ie._CodeOrName?yn(r,e.names):r}function Vn(r,e,t){if(r instanceof ie.Name)return n(r);if(!i(r))return r;return new ie._Code(r._items.reduce((s,o)=>(o instanceof ie.Name&&(o=n(o)),o instanceof ie._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 ie._Code&&s._items.some(o=>o instanceof ie.Name&&e[o.str]===1&&t[o.str]!==void 0)}}function ev(r,e){for(let t in e)r[t]=(r[t]||0)-(e[t]||0)}function Ep(r){return typeof r=="boolean"||typeof r=="number"||r===null?!r:(0,ie._)`!${al(r)}`}Y.not=Ep;var tv=Ap(Y.operators.AND);function rv(...r){return r.reduce(tv)}Y.and=rv;var nv=Ap(Y.operators.OR);function iv(...r){return r.reduce(nv)}Y.or=iv;function Ap(r){return(e,t)=>e===ie.nil?t:t===ie.nil?e:(0,ie._)`${al(e)} ${r} ${al(t)}`}function al(r){return r instanceof ie.Name?r:(0,ie._)`(${r})`}});var Q=A(X=>{"use strict";Object.defineProperty(X,"__esModule",{value:!0});X.checkStrictMode=X.getErrorPath=X.Type=X.useFunc=X.setEvaluated=X.evaluatedPropsToName=X.mergeEvaluated=X.eachItem=X.unescapeJsonPointer=X.escapeJsonPointer=X.escapeFragment=X.unescapeFragment=X.schemaRefOrVal=X.schemaHasRulesButRef=X.schemaHasRules=X.checkUnknownRules=X.alwaysValidSchema=X.toHash=void 0;var pe=H(),sv=Hi();function ov(r){let e={};for(let t of r)e[t]=!0;return e}X.toHash=ov;function av(r,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(Pp(r,e),!Ip(e,r.self.RULES.all))}X.alwaysValidSchema=av;function Pp(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]||Tp(r,`unknown keyword: "${s}"`)}X.checkUnknownRules=Pp;function Ip(r,e){if(typeof r=="boolean")return!r;for(let t in r)if(e[t])return!0;return!1}X.schemaHasRules=Ip;function cv(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=cv;function lv({topSchemaRef:r,schemaPath:e},t,n,i){if(!i){if(typeof t=="number"||typeof t=="boolean")return t;if(typeof t=="string")return(0,pe._)`${t}`}return(0,pe._)`${r}${e}${(0,pe.getProperty)(n)}`}X.schemaRefOrVal=lv;function dv(r){return Op(decodeURIComponent(r))}X.unescapeFragment=dv;function uv(r){return encodeURIComponent(ll(r))}X.escapeFragment=uv;function ll(r){return typeof r=="number"?`${r}`:r.replace(/~/g,"~0").replace(/\//g,"~1")}X.escapeJsonPointer=ll;function Op(r){return r.replace(/~1/g,"/").replace(/~0/g,"~")}X.unescapeJsonPointer=Op;function fv(r,e){if(Array.isArray(r))for(let t of r)e(t);else e(r)}X.eachItem=fv;function kp({mergeNames:r,mergeToName:e,mergeValues:t,resultToName:n}){return(i,s,o,a)=>{let c=o===void 0?s:o instanceof pe.Name?(s instanceof pe.Name?r(i,s,o):e(i,s,o),o):s instanceof pe.Name?(e(i,o,s),s):t(s,o);return a===pe.Name&&!(c instanceof pe.Name)?n(i,c):c}}X.mergeEvaluated={props:kp({mergeNames:(r,e,t)=>r.if((0,pe._)`${t} !== true && ${e} !== undefined`,()=>{r.if((0,pe._)`${e} === true`,()=>r.assign(t,!0),()=>r.assign(t,(0,pe._)`${t} || {}`).code((0,pe._)`Object.assign(${t}, ${e})`))}),mergeToName:(r,e,t)=>r.if((0,pe._)`${t} !== true`,()=>{e===!0?r.assign(t,!0):(r.assign(t,(0,pe._)`${t} || {}`),dl(r,t,e))}),mergeValues:(r,e)=>r===!0?!0:{...r,...e},resultToName:Rp}),items:kp({mergeNames:(r,e,t)=>r.if((0,pe._)`${t} !== true && ${e} !== undefined`,()=>r.assign(t,(0,pe._)`${e} === true ? true : ${t} > ${e} ? ${t} : ${e}`)),mergeToName:(r,e,t)=>r.if((0,pe._)`${t} !== true`,()=>r.assign(t,e===!0?!0:(0,pe._)`${t} > ${e} ? ${t} : ${e}`)),mergeValues:(r,e)=>r===!0?!0:Math.max(r,e),resultToName:(r,e)=>r.var("items",e)})};function Rp(r,e){if(e===!0)return r.var("props",!0);let t=r.var("props",(0,pe._)`{}`);return e!==void 0&&dl(r,t,e),t}X.evaluatedPropsToName=Rp;function dl(r,e,t){Object.keys(t).forEach(n=>r.assign((0,pe._)`${e}${(0,pe.getProperty)(n)}`,!0))}X.setEvaluated=dl;var xp={};function pv(r,e){return r.scopeValue("func",{ref:e,code:xp[e.code]||(xp[e.code]=new sv._Code(e.code))})}X.useFunc=pv;var cl;(function(r){r[r.Num=0]="Num",r[r.Str=1]="Str"})(cl||(X.Type=cl={}));function hv(r,e,t){if(r instanceof pe.Name){let n=e===cl.Num;return t?n?(0,pe._)`"[" + ${r} + "]"`:(0,pe._)`"['" + ${r} + "']"`:n?(0,pe._)`"/" + ${r}`:(0,pe._)`"/" + ${r}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return t?(0,pe.getProperty)(r).toString():"/"+ll(r)}X.getErrorPath=hv;function Tp(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=Tp});var vt=A(ul=>{"use strict";Object.defineProperty(ul,"__esModule",{value:!0});var Ue=H(),mv={data:new Ue.Name("data"),valCxt:new Ue.Name("valCxt"),instancePath:new Ue.Name("instancePath"),parentData:new Ue.Name("parentData"),parentDataProperty:new Ue.Name("parentDataProperty"),rootData:new Ue.Name("rootData"),dynamicAnchors:new Ue.Name("dynamicAnchors"),vErrors:new Ue.Name("vErrors"),errors:new Ue.Name("errors"),this:new Ue.Name("this"),self:new Ue.Name("self"),scope:new Ue.Name("scope"),json:new Ue.Name("json"),jsonPos:new Ue.Name("jsonPos"),jsonLen:new Ue.Name("jsonLen"),jsonPart:new Ue.Name("jsonPart")};ul.default=mv});var Xi=A(Be=>{"use strict";Object.defineProperty(Be,"__esModule",{value:!0});Be.extendErrors=Be.resetErrorsCount=Be.reportExtraError=Be.reportError=Be.keyword$DataError=Be.keywordError=void 0;var ae=H(),ko=Q(),Je=vt();Be.keywordError={message:({keyword:r})=>(0,ae.str)`must pass "${r}" keyword validation`};Be.keyword$DataError={message:({keyword:r,schemaType:e})=>e?(0,ae.str)`"${r}" keyword must be ${e} ($data)`:(0,ae.str)`"${r}" keyword is invalid ($data)`};function yv(r,e=Be.keywordError,t,n){let{it:i}=r,{gen:s,compositeRule:o,allErrors:a}=i,c=Np(r,e,t);(n!=null?n:o||a)?Cp(s,c):Mp(i,(0,ae._)`[${c}]`)}Be.reportError=yv;function gv(r,e=Be.keywordError,t){let{it:n}=r,{gen:i,compositeRule:s,allErrors:o}=n,a=Np(r,e,t);Cp(i,a),s||o||Mp(n,Je.default.vErrors)}Be.reportExtraError=gv;function _v(r,e){r.assign(Je.default.errors,e),r.if((0,ae._)`${Je.default.vErrors} !== null`,()=>r.if(e,()=>r.assign((0,ae._)`${Je.default.vErrors}.length`,e),()=>r.assign(Je.default.vErrors,null)))}Be.resetErrorsCount=_v;function bv({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,Je.default.errors,a=>{r.const(o,(0,ae._)`${Je.default.vErrors}[${a}]`),r.if((0,ae._)`${o}.instancePath === undefined`,()=>r.assign((0,ae._)`${o}.instancePath`,(0,ae.strConcat)(Je.default.instancePath,s.errorPath))),r.assign((0,ae._)`${o}.schemaPath`,(0,ae.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(r.assign((0,ae._)`${o}.schema`,t),r.assign((0,ae._)`${o}.data`,n))})}Be.extendErrors=bv;function Cp(r,e){let t=r.const("err",e);r.if((0,ae._)`${Je.default.vErrors} === null`,()=>r.assign(Je.default.vErrors,(0,ae._)`[${t}]`),(0,ae._)`${Je.default.vErrors}.push(${t})`),r.code((0,ae._)`${Je.default.errors}++`)}function Mp(r,e){let{gen:t,validateName:n,schemaEnv:i}=r;i.$async?t.throw((0,ae._)`new ${r.ValidationError}(${e})`):(t.assign((0,ae._)`${n}.errors`,e),t.return(!1))}var gn={keyword:new ae.Name("keyword"),schemaPath:new ae.Name("schemaPath"),params:new ae.Name("params"),propertyName:new ae.Name("propertyName"),message:new ae.Name("message"),schema:new ae.Name("schema"),parentSchema:new ae.Name("parentSchema")};function Np(r,e,t){let{createErrors:n}=r.it;return n===!1?(0,ae._)`{}`:wv(r,e,t)}function wv(r,e,t={}){let{gen:n,it:i}=r,s=[vv(i,t),$v(r,t)];return Sv(r,e,s),n.object(...s)}function vv({errorPath:r},{instancePath:e}){let t=e?(0,ae.str)`${r}${(0,ko.getErrorPath)(e,ko.Type.Str)}`:r;return[Je.default.instancePath,(0,ae.strConcat)(Je.default.instancePath,t)]}function $v({keyword:r,it:{errSchemaPath:e}},{schemaPath:t,parentSchema:n}){let i=n?e:(0,ae.str)`${e}/${r}`;return t&&(i=(0,ae.str)`${i}${(0,ko.getErrorPath)(t,ko.Type.Str)}`),[gn.schemaPath,i]}function Sv(r,{params:e,message:t},n){let{keyword:i,data:s,schemaValue:o,it:a}=r,{opts:c,propertyName:l,topSchemaRef:d,schemaPath:u}=a;n.push([gn.keyword,i],[gn.params,typeof e=="function"?e(r):e||(0,ae._)`{}`]),c.messages&&n.push([gn.message,typeof t=="function"?t(r):t]),c.verbose&&n.push([gn.schema,o],[gn.parentSchema,(0,ae._)`${d}${u}`],[Je.default.data,s]),l&&n.push([gn.propertyName,l])}});var jp=A(Un=>{"use strict";Object.defineProperty(Un,"__esModule",{value:!0});Un.boolOrEmptySchema=Un.topBoolOrEmptySchema=void 0;var Ev=Xi(),Av=H(),kv=vt(),xv={message:"boolean schema is false"};function Pv(r){let{gen:e,schema:t,validateName:n}=r;t===!1?Lp(r,!1):typeof t=="object"&&t.$async===!0?e.return(kv.default.data):(e.assign((0,Av._)`${n}.errors`,null),e.return(!0))}Un.topBoolOrEmptySchema=Pv;function Iv(r,e){let{gen:t,schema:n}=r;n===!1?(t.var(e,!1),Lp(r)):t.var(e,!0)}Un.boolOrEmptySchema=Iv;function Lp(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,Ev.reportError)(i,xv,void 0,e)}});var fl=A(Bn=>{"use strict";Object.defineProperty(Bn,"__esModule",{value:!0});Bn.getRules=Bn.isJSONType=void 0;var Ov=["string","number","integer","boolean","null","object","array"],Rv=new Set(Ov);function Tv(r){return typeof r=="string"&&Rv.has(r)}Bn.isJSONType=Tv;function Cv(){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:{}}}Bn.getRules=Cv});var pl=A(Vr=>{"use strict";Object.defineProperty(Vr,"__esModule",{value:!0});Vr.shouldUseRule=Vr.shouldUseGroup=Vr.schemaHasRulesForType=void 0;function Mv({schema:r,self:e},t){let n=e.RULES.types[t];return n&&n!==!0&&Dp(r,n)}Vr.schemaHasRulesForType=Mv;function Dp(r,e){return e.rules.some(t=>qp(r,t))}Vr.shouldUseGroup=Dp;function qp(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))}Vr.shouldUseRule=qp});var Qi=A(ze=>{"use strict";Object.defineProperty(ze,"__esModule",{value:!0});ze.reportTypeError=ze.checkDataTypes=ze.checkDataType=ze.coerceAndCheckDataType=ze.getJSONTypes=ze.getSchemaTypes=ze.DataType=void 0;var Nv=fl(),Lv=pl(),jv=Xi(),W=H(),Fp=Q(),zn;(function(r){r[r.Correct=0]="Correct",r[r.Wrong=1]="Wrong"})(zn||(ze.DataType=zn={}));function Dv(r){let e=Vp(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}ze.getSchemaTypes=Dv;function Vp(r){let e=Array.isArray(r)?r:r?[r]:[];if(e.every(Nv.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}ze.getJSONTypes=Vp;function qv(r,e){let{gen:t,data:n,opts:i}=r,s=Fv(e,i.coerceTypes),o=e.length>0&&!(s.length===0&&e.length===1&&(0,Lv.schemaHasRulesForType)(r,e[0]));if(o){let a=ml(e,n,i.strictNumbers,zn.Wrong);t.if(a,()=>{s.length?Vv(r,e,s):yl(r)})}return o}ze.coerceAndCheckDataType=qv;var Up=new Set(["string","number","integer","boolean","null"]);function Fv(r,e){return e?r.filter(t=>Up.has(t)||e==="array"&&t==="array"):[]}function Vv(r,e,t){let{gen:n,data:i,opts:s}=r,o=n.let("dataType",(0,W._)`typeof ${i}`),a=n.let("coerced",(0,W._)`undefined`);s.coerceTypes==="array"&&n.if((0,W._)`${o} == 'object' && Array.isArray(${i}) && ${i}.length == 1`,()=>n.assign(i,(0,W._)`${i}[0]`).assign(o,(0,W._)`typeof ${i}`).if(ml(e,i,s.strictNumbers),()=>n.assign(a,i))),n.if((0,W._)`${a} !== undefined`);for(let l of t)(Up.has(l)||l==="array"&&s.coerceTypes==="array")&&c(l);n.else(),yl(r),n.endIf(),n.if((0,W._)`${a} !== undefined`,()=>{n.assign(i,a),Uv(r,a)});function c(l){switch(l){case"string":n.elseIf((0,W._)`${o} == "number" || ${o} == "boolean"`).assign(a,(0,W._)`"" + ${i}`).elseIf((0,W._)`${i} === null`).assign(a,(0,W._)`""`);return;case"number":n.elseIf((0,W._)`${o} == "boolean" || ${i} === null || (${o} == "string" && ${i} && ${i} == +${i})`).assign(a,(0,W._)`+${i}`);return;case"integer":n.elseIf((0,W._)`${o} === "boolean" || ${i} === null || (${o} === "string" && ${i} && ${i} == +${i} && !(${i} % 1))`).assign(a,(0,W._)`+${i}`);return;case"boolean":n.elseIf((0,W._)`${i} === "false" || ${i} === 0 || ${i} === null`).assign(a,!1).elseIf((0,W._)`${i} === "true" || ${i} === 1`).assign(a,!0);return;case"null":n.elseIf((0,W._)`${i} === "" || ${i} === 0 || ${i} === false`),n.assign(a,null);return;case"array":n.elseIf((0,W._)`${o} === "string" || ${o} === "number" - || ${o} === "boolean" || ${i} === null`).assign(a,(0,W._)`[${i}]`)}}}function Wv({gen:r,parentData:e,parentDataProperty:t},n){r.if((0,W._)`${e} !== undefined`,()=>r.assign((0,W._)`${e}[${t}]`,n))}function hl(r,e,t,n=Vn.Correct){let i=n===Vn.Correct?W.operators.EQ:W.operators.NEQ,s;switch(r){case"null":return(0,W._)`${e} ${i} null`;case"array":s=(0,W._)`Array.isArray(${e})`;break;case"object":s=(0,W._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=o((0,W._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=o();break;default:return(0,W._)`typeof ${e} ${i} ${r}`}return n===Vn.Correct?s:(0,W.not)(s);function o(a=W.nil){return(0,W.and)((0,W._)`typeof ${e} == "number"`,a,t?(0,W._)`isFinite(${e})`:W.nil)}}He.checkDataType=hl;function ml(r,e,t,n){if(r.length===1)return hl(r[0],e,t,n);let i,s=(0,Up.toHash)(r);if(s.array&&s.object){let o=(0,W._)`typeof ${e} != "object"`;i=s.null?o:(0,W._)`!${e} || ${o}`,delete s.null,delete s.array,delete s.object}else i=W.nil;s.number&&delete s.integer;for(let o in s)i=(0,W.and)(i,hl(o,e,t,n));return i}He.checkDataTypes=ml;var Gv={message:({schema:r})=>`must be ${r}`,params:({schema:r,schemaValue:e})=>typeof r=="string"?(0,W._)`{type: ${r}}`:(0,W._)`{type: ${e}}`};function yl(r){let e=Jv(r);(0,Vv.reportError)(e,Gv)}He.reportTypeError=yl;function Jv(r){let{gen:e,data:t,schema:n}=r,i=(0,Up.schemaRefOrVal)(r,n,"type");return{gen:e,keyword:"type",data:t,schema:n.type,schemaCode:i,schemaValue:i,parentSchema:n,params:{},it:r}}});var Hp=A(xo=>{"use strict";Object.defineProperty(xo,"__esModule",{value:!0});xo.assignDefaults=void 0;var Bn=H(),Yv=Q();function Xv(r,e){let{properties:t,items:n}=r.schema;if(e==="object"&&t)for(let i in t)zp(r,i,t[i].default);else e==="array"&&Array.isArray(n)&&n.forEach((i,s)=>zp(r,s,i.default))}xo.assignDefaults=Xv;function zp(r,e,t){let{gen:n,compositeRule:i,data:s,opts:o}=r;if(t===void 0)return;let a=(0,Bn._)`${s}${(0,Bn.getProperty)(e)}`;if(i){(0,Yv.checkStrictMode)(r,`default is ignored for: ${a}`);return}let c=(0,Bn._)`${a} === undefined`;o.useDefaults==="empty"&&(c=(0,Bn._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,Bn._)`${a} = ${(0,Bn.stringify)(t)}`)}});var St=A(ue=>{"use strict";Object.defineProperty(ue,"__esModule",{value:!0});ue.validateUnion=ue.validateArray=ue.usePattern=ue.callValidateCode=ue.schemaProperties=ue.allSchemaProperties=ue.noPropertyInData=ue.propertyInData=ue.isOwnProperty=ue.hasPropFunc=ue.reportMissingProp=ue.checkMissingProp=ue.checkReportMissingProp=void 0;var ge=H(),gl=Q(),Fr=$t(),Qv=Q();function Zv(r,e){let{gen:t,data:n,it:i}=r;t.if(bl(t,n,e,i.opts.ownProperties),()=>{r.setParams({missingProperty:(0,ge._)`${e}`},!0),r.error()})}ue.checkReportMissingProp=Zv;function e$({gen:r,data:e,it:{opts:t}},n,i){return(0,ge.or)(...n.map(s=>(0,ge.and)(bl(r,e,s,t.ownProperties),(0,ge._)`${i} = ${s}`)))}ue.checkMissingProp=e$;function t$(r,e){r.setParams({missingProperty:e},!0),r.error()}ue.reportMissingProp=t$;function Kp(r){return r.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,ge._)`Object.prototype.hasOwnProperty`})}ue.hasPropFunc=Kp;function _l(r,e,t){return(0,ge._)`${Kp(r)}.call(${e}, ${t})`}ue.isOwnProperty=_l;function r$(r,e,t,n){let i=(0,ge._)`${e}${(0,ge.getProperty)(t)} !== undefined`;return n?(0,ge._)`${i} && ${_l(r,e,t)}`:i}ue.propertyInData=r$;function bl(r,e,t,n){let i=(0,ge._)`${e}${(0,ge.getProperty)(t)} === undefined`;return n?(0,ge.or)(i,(0,ge.not)(_l(r,e,t))):i}ue.noPropertyInData=bl;function Wp(r){return r?Object.keys(r).filter(e=>e!=="__proto__"):[]}ue.allSchemaProperties=Wp;function n$(r,e){return Wp(e).filter(t=>!(0,gl.alwaysValidSchema)(r,e[t]))}ue.schemaProperties=n$;function i$({schemaCode:r,data:e,it:{gen:t,topSchemaRef:n,schemaPath:i,errorPath:s},it:o},a,c,l){let d=l?(0,ge._)`${r}, ${e}, ${n}${i}`:e,u=[[Fr.default.instancePath,(0,ge.strConcat)(Fr.default.instancePath,s)],[Fr.default.parentData,o.parentData],[Fr.default.parentDataProperty,o.parentDataProperty],[Fr.default.rootData,Fr.default.rootData]];o.opts.dynamicRef&&u.push([Fr.default.dynamicAnchors,Fr.default.dynamicAnchors]);let f=(0,ge._)`${d}, ${t.object(...u)}`;return c!==ge.nil?(0,ge._)`${a}.call(${c}, ${f})`:(0,ge._)`${a}(${f})`}ue.callValidateCode=i$;var s$=(0,ge._)`new RegExp`;function o$({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,ge._)`${i.code==="new RegExp"?s$:(0,Qv.useFunc)(r,i)}(${t}, ${n})`})}ue.usePattern=o$;function a$(r){let{gen:e,data:t,keyword:n,it:i}=r,s=e.name("valid");if(i.allErrors){let a=e.let("valid",!0);return o(()=>e.assign(a,!1)),a}return e.var(s,!0),o(()=>e.break()),s;function o(a){let c=e.const("len",(0,ge._)`${t}.length`);e.forRange("i",0,c,l=>{r.subschema({keyword:n,dataProp:l,dataPropType:gl.Type.Num},s),e.if((0,ge.not)(s),a)})}}ue.validateArray=a$;function c$(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,gl.alwaysValidSchema)(i,c))&&!i.opts.unevaluated)return;let o=e.let("valid",!1),a=e.name("_valid");e.block(()=>t.forEach((c,l)=>{let d=r.subschema({keyword:n,schemaProp:l,compositeRule:!0},a);e.assign(o,(0,ge._)`${o} || ${a}`),r.mergeValidEvaluated(d,a)||e.if((0,ge.not)(o))})),r.result(o,()=>r.reset(),()=>r.error(!0))}ue.validateUnion=c$});var Yp=A(Zt=>{"use strict";Object.defineProperty(Zt,"__esModule",{value:!0});Zt.validateKeywordUsage=Zt.validSchemaType=Zt.funcKeywordCode=Zt.macroKeywordCode=void 0;var Xe=H(),yn=$t(),l$=St(),d$=Yi();function u$(r,e){let{gen:t,keyword:n,schema:i,parentSchema:s,it:o}=r,a=e.macro.call(o.self,i,s,o),c=Jp(t,n,a);o.opts.validateSchema!==!1&&o.self.validateSchema(a,!0);let l=t.name("valid");r.subschema({schema:a,schemaPath:Xe.nil,errSchemaPath:`${o.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},l),r.pass(l,()=>r.error(!0))}Zt.macroKeywordCode=u$;function f$(r,e){var t;let{gen:n,keyword:i,schema:s,parentSchema:o,$data:a,it:c}=r;h$(c,e);let l=!a&&e.compile?e.compile.call(c.self,s,o,c):e.validate,d=Jp(n,i,l),u=n.let("valid");r.block$data(u,f),r.ok((t=e.valid)!==null&&t!==void 0?t:u);function f(){if(e.errors===!1)h(),e.modifying&&Gp(r),m(()=>r.error());else{let g=e.async?p():y();e.modifying&&Gp(r),m(()=>p$(r,g))}}function p(){let g=n.let("ruleErrs",null);return n.try(()=>h((0,Xe._)`await `),_=>n.assign(u,!1).if((0,Xe._)`${_} instanceof ${c.ValidationError}`,()=>n.assign(g,(0,Xe._)`${_}.errors`),()=>n.throw(_))),g}function y(){let g=(0,Xe._)`${d}.errors`;return n.assign(g,null),h(Xe.nil),g}function h(g=e.async?(0,Xe._)`await `:Xe.nil){let _=c.opts.passContext?yn.default.this:yn.default.self,w=!("compile"in e&&!a||e.schema===!1);n.assign(u,(0,Xe._)`${g}${(0,l$.callValidateCode)(r,d,_,w)}`,e.modifying)}function m(g){var _;n.if((0,Xe.not)((_=e.valid)!==null&&_!==void 0?_:u),g)}}Zt.funcKeywordCode=f$;function Gp(r){let{gen:e,data:t,it:n}=r;e.if(n.parentData,()=>e.assign(t,(0,Xe._)`${n.parentData}[${n.parentDataProperty}]`))}function p$(r,e){let{gen:t}=r;t.if((0,Xe._)`Array.isArray(${e})`,()=>{t.assign(yn.default.vErrors,(0,Xe._)`${yn.default.vErrors} === null ? ${e} : ${yn.default.vErrors}.concat(${e})`).assign(yn.default.errors,(0,Xe._)`${yn.default.vErrors}.length`),(0,d$.extendErrors)(r)},()=>r.error())}function h$({schemaEnv:r},e){if(e.async&&!r.$async)throw new Error("async keyword in sync schema")}function Jp(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,Xe.stringify)(t)})}function m$(r,e,t=!1){return!e.length||e.some(n=>n==="array"?Array.isArray(r):n==="object"?r&&typeof r=="object"&&!Array.isArray(r):typeof r==n||t&&typeof r=="undefined")}Zt.validSchemaType=m$;function y$({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!=null&&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)}}Zt.validateKeywordUsage=y$});var Qp=A(Ur=>{"use strict";Object.defineProperty(Ur,"__esModule",{value:!0});Ur.extendSubschemaMode=Ur.extendSubschemaData=Ur.getSubschema=void 0;var er=H(),Xp=Q();function g$(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,er._)`${r.schemaPath}${(0,er.getProperty)(e)}`,errSchemaPath:`${r.errSchemaPath}/${e}`}:{schema:a[t],schemaPath:(0,er._)`${r.schemaPath}${(0,er.getProperty)(e)}${(0,er.getProperty)(t)}`,errSchemaPath:`${r.errSchemaPath}/${e}/${(0,Xp.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')}Ur.getSubschema=g$;function _$(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:d,opts:u}=e,f=a.let("data",(0,er._)`${e.data}${(0,er.getProperty)(t)}`,!0);c(f),r.errorPath=(0,er.str)`${l}${(0,Xp.getErrorPath)(t,n,u.jsPropertySyntax)}`,r.parentDataProperty=(0,er._)`${t}`,r.dataPathArr=[...d,r.parentDataProperty]}if(i!==void 0){let l=i instanceof er.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]}}Ur.extendSubschemaData=_$;function b$(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}Ur.extendSubschemaMode=b$});var wl=A((XC,Zp)=>{"use strict";Zp.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 th=A((QC,eh)=>{"use strict";var Vr=eh.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(){};ko(e,n,i,r,"",r)};Vr.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Vr.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Vr.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Vr.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 ko(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 d in n){var u=n[d];if(Array.isArray(u)){if(d in Vr.arrayKeywords)for(var f=0;f{"use strict";Object.defineProperty(at,"__esModule",{value:!0});at.getSchemaRefs=at.resolveUrl=at.normalizeId=at._getFullPath=at.getFullPath=at.inlineRef=void 0;var v$=Q(),$$=wl(),S$=th(),E$=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function A$(r,e=!0){return typeof r=="boolean"?!0:e===!0?!vl(r):e?rh(r)<=e:!1}at.inlineRef=A$;var x$=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function vl(r){for(let e in r){if(x$.has(e))return!0;let t=r[e];if(Array.isArray(t)&&t.some(vl)||typeof t=="object"&&vl(t))return!0}return!1}function rh(r){let e=0;for(let t in r){if(t==="$ref")return 1/0;if(e++,!E$.has(t)&&(typeof r[t]=="object"&&(0,v$.eachItem)(r[t],n=>e+=rh(n)),e===1/0))return 1/0}return e}function nh(r,e="",t){t!==!1&&(e=zn(e));let n=r.parse(e);return ih(r,n)}at.getFullPath=nh;function ih(r,e){return r.serialize(e).split("#")[0]+"#"}at._getFullPath=ih;var k$=/#\/?$/;function zn(r){return r?r.replace(k$,""):""}at.normalizeId=zn;function P$(r,e,t){return t=zn(t),r.resolve(e,t)}at.resolveUrl=P$;var I$=/^[a-z_][-a-z0-9._]*$/i;function O$(r,e){if(typeof r=="boolean")return{};let{schemaId:t,uriResolver:n}=this.opts,i=zn(r[t]||e),s={"":i},o=nh(n,i,!1),a={},c=new Set;return S$(r,{allKeys:!0},(u,f,p,y)=>{if(y===void 0)return;let h=o+f,m=s[y];typeof u[t]=="string"&&(m=g.call(this,u[t])),_.call(this,u.$anchor),_.call(this,u.$dynamicAnchor),s[f]=m;function g(w){let k=this.opts.uriResolver.resolve;if(w=zn(m?k(m,w):w),c.has(w))throw d(w);c.add(w);let v=this.refs[w];return typeof v=="string"&&(v=this.refs[v]),typeof v=="object"?l(u,v.schema,w):w!==zn(h)&&(w[0]==="#"?(l(u,a[w],w),a[w]=u):this.refs[w]=h),w}function _(w){if(typeof w=="string"){if(!I$.test(w))throw new Error(`invalid anchor "${w}"`);g.call(this,`#${w}`)}}}),a;function l(u,f,p){if(f!==void 0&&!$$(u,f))throw d(p)}function d(u){return new Error(`reference "${u}" resolves to more than one schema`)}}at.getSchemaRefs=O$});var Hn=A(Br=>{"use strict";Object.defineProperty(Br,"__esModule",{value:!0});Br.getData=Br.KeywordCxt=Br.validateFunctionCode=void 0;var lh=Dp(),sh=Xi(),Sl=pl(),Po=Xi(),R$=Hp(),es=Yp(),$l=Qp(),F=H(),z=$t(),T$=Qi(),_r=Q(),Zi=Yi();function M$(r){if(fh(r)&&(ph(r),uh(r))){L$(r);return}dh(r,()=>(0,lh.topBoolOrEmptySchema)(r))}Br.validateFunctionCode=M$;function dh({gen:r,validateName:e,schema:t,schemaEnv:n,opts:i},s){i.code.es5?r.func(e,(0,F._)`${z.default.data}, ${z.default.valCxt}`,n.$async,()=>{r.code((0,F._)`"use strict"; ${oh(t,i)}`),N$(r,i),r.code(s)}):r.func(e,(0,F._)`${z.default.data}, ${C$(i)}`,n.$async,()=>r.code(oh(t,i)).code(s))}function C$(r){return(0,F._)`{${z.default.instancePath}="", ${z.default.parentData}, ${z.default.parentDataProperty}, ${z.default.rootData}=${z.default.data}${r.dynamicRef?(0,F._)`, ${z.default.dynamicAnchors}={}`:F.nil}}={}`}function N$(r,e){r.if(z.default.valCxt,()=>{r.var(z.default.instancePath,(0,F._)`${z.default.valCxt}.${z.default.instancePath}`),r.var(z.default.parentData,(0,F._)`${z.default.valCxt}.${z.default.parentData}`),r.var(z.default.parentDataProperty,(0,F._)`${z.default.valCxt}.${z.default.parentDataProperty}`),r.var(z.default.rootData,(0,F._)`${z.default.valCxt}.${z.default.rootData}`),e.dynamicRef&&r.var(z.default.dynamicAnchors,(0,F._)`${z.default.valCxt}.${z.default.dynamicAnchors}`)},()=>{r.var(z.default.instancePath,(0,F._)`""`),r.var(z.default.parentData,(0,F._)`undefined`),r.var(z.default.parentDataProperty,(0,F._)`undefined`),r.var(z.default.rootData,z.default.data),e.dynamicRef&&r.var(z.default.dynamicAnchors,(0,F._)`{}`)})}function L$(r){let{schema:e,opts:t,gen:n}=r;dh(r,()=>{t.$comment&&e.$comment&&mh(r),U$(r),n.let(z.default.vErrors,null),n.let(z.default.errors,0),t.unevaluated&&j$(r),hh(r),z$(r)})}function j$(r){let{gen:e,validateName:t}=r;r.evaluated=e.const("evaluated",(0,F._)`${t}.evaluated`),e.if((0,F._)`${r.evaluated}.dynamicProps`,()=>e.assign((0,F._)`${r.evaluated}.props`,(0,F._)`undefined`)),e.if((0,F._)`${r.evaluated}.dynamicItems`,()=>e.assign((0,F._)`${r.evaluated}.items`,(0,F._)`undefined`))}function oh(r,e){let t=typeof r=="object"&&r[e.schemaId];return t&&(e.code.source||e.code.process)?(0,F._)`/*# sourceURL=${t} */`:F.nil}function D$(r,e){if(fh(r)&&(ph(r),uh(r))){q$(r,e);return}(0,lh.boolOrEmptySchema)(r,e)}function uh({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 fh(r){return typeof r.schema!="boolean"}function q$(r,e){let{schema:t,gen:n,opts:i}=r;i.$comment&&t.$comment&&mh(r),V$(r),B$(r);let s=n.const("_errs",z.default.errors);hh(r,s),n.var(e,(0,F._)`${s} === ${z.default.errors}`)}function ph(r){(0,_r.checkUnknownRules)(r),F$(r)}function hh(r,e){if(r.opts.jtd)return ah(r,[],!1,e);let t=(0,sh.getSchemaTypes)(r.schema),n=(0,sh.coerceAndCheckDataType)(r,t);ah(r,t,!n,e)}function F$(r){let{schema:e,errSchemaPath:t,opts:n,self:i}=r;e.$ref&&n.ignoreKeywordsWithRef&&(0,_r.schemaHasRulesButRef)(e,i.RULES)&&i.logger.warn(`$ref: keywords ignored in schema at path "${t}"`)}function U$(r){let{schema:e,opts:t}=r;e.default!==void 0&&t.useDefaults&&t.strictSchema&&(0,_r.checkStrictMode)(r,"default is ignored in the schema root")}function V$(r){let e=r.schema[r.opts.schemaId];e&&(r.baseId=(0,T$.resolveUrl)(r.opts.uriResolver,r.baseId,e))}function B$(r){if(r.schema.$async&&!r.schemaEnv.$async)throw new Error("async schema in sync schema")}function mh({gen:r,schemaEnv:e,schema:t,errSchemaPath:n,opts:i}){let s=t.$comment;if(i.$comment===!0)r.code((0,F._)`${z.default.self}.logger.log(${s})`);else if(typeof i.$comment=="function"){let o=(0,F.str)`${n}/$comment`,a=r.scopeValue("root",{ref:e.root});r.code((0,F._)`${z.default.self}.opts.$comment(${s}, ${o}, ${a}.schema)`)}}function z$(r){let{gen:e,schemaEnv:t,validateName:n,ValidationError:i,opts:s}=r;t.$async?e.if((0,F._)`${z.default.errors} === 0`,()=>e.return(z.default.data),()=>e.throw((0,F._)`new ${i}(${z.default.vErrors})`)):(e.assign((0,F._)`${n}.errors`,z.default.vErrors),s.unevaluated&&H$(r),e.return((0,F._)`${z.default.errors} === 0`))}function H$({gen:r,evaluated:e,props:t,items:n}){t instanceof F.Name&&r.assign((0,F._)`${e}.props`,t),n instanceof F.Name&&r.assign((0,F._)`${e}.items`,n)}function ah(r,e,t,n){let{gen:i,schema:s,data:o,allErrors:a,opts:c,self:l}=r,{RULES:d}=l;if(s.$ref&&(c.ignoreKeywordsWithRef||!(0,_r.schemaHasRulesButRef)(s,d))){i.block(()=>gh(r,"$ref",d.all.$ref.definition));return}c.jtd||K$(r,e),i.block(()=>{for(let f of d.rules)u(f);u(d.post)});function u(f){(0,Sl.shouldUseGroup)(s,f)&&(f.type?(i.if((0,Po.checkDataType)(f.type,o,c.strictNumbers)),ch(r,f),e.length===1&&e[0]===f.type&&t&&(i.else(),(0,Po.reportTypeError)(r)),i.endIf()):ch(r,f),a||i.if((0,F._)`${z.default.errors} === ${n||0}`))}}function ch(r,e){let{gen:t,schema:n,opts:{useDefaults:i}}=r;i&&(0,R$.assignDefaults)(r,e.type),t.block(()=>{for(let s of e.rules)(0,Sl.shouldUseRule)(n,s)&&gh(r,s.keyword,s.definition,e.type)})}function K$(r,e){r.schemaEnv.meta||!r.opts.strictTypes||(W$(r,e),r.opts.allowUnionTypes||G$(r,e),J$(r,r.dataTypes))}function W$(r,e){if(e.length){if(!r.dataTypes.length){r.dataTypes=e;return}e.forEach(t=>{yh(r.dataTypes,t)||El(r,`type "${t}" not allowed by context "${r.dataTypes.join(",")}"`)}),X$(r,e)}}function G$(r,e){e.length>1&&!(e.length===2&&e.includes("null"))&&El(r,"use allowUnionTypes to allow union type keyword")}function J$(r,e){let t=r.self.RULES.all;for(let n in t){let i=t[n];if(typeof i=="object"&&(0,Sl.shouldUseRule)(r.schema,i)){let{type:s}=i.definition;s.length&&!s.some(o=>Y$(e,o))&&El(r,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function Y$(r,e){return r.includes(e)||e==="number"&&r.includes("integer")}function yh(r,e){return r.includes(e)||e==="integer"&&r.includes("number")}function X$(r,e){let t=[];for(let n of r.dataTypes)yh(e,n)?t.push(n):e.includes("integer")&&n==="number"&&t.push("integer");r.dataTypes=t}function El(r,e){let t=r.schemaEnv.baseId+r.errSchemaPath;e+=` at "${t}" (strictTypes)`,(0,_r.checkStrictMode)(r,e,r.opts.strictTypes)}var Io=class{constructor(e,t,n){if((0,es.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,_r.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",_h(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,es.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",z.default.errors))}result(e,t,n){this.failResult((0,F.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,F.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,F._)`${t} !== undefined && (${(0,F.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?Zi.reportExtraError:Zi.reportError)(this,this.def.error,t)}$dataError(){(0,Zi.reportError)(this,this.def.$dataError||Zi.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,Zi.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=F.nil){this.gen.block(()=>{this.check$data(e,n),t()})}check$data(e=F.nil,t=F.nil){if(!this.$data)return;let{gen:n,schemaCode:i,schemaType:s,def:o}=this;n.if((0,F.or)((0,F._)`${i} === undefined`,t)),e!==F.nil&&n.assign(e,!0),(s.length||o.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==F.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:t,schemaType:n,def:i,it:s}=this;return(0,F.or)(o(),a());function o(){if(n.length){if(!(t instanceof F.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,F._)`${(0,Po.checkDataTypes)(c,t,s.opts.strictNumbers,Po.DataType.Wrong)}`}return F.nil}function a(){if(i.validateSchema){let c=e.scopeValue("validate$data",{ref:i.validateSchema});return(0,F._)`!${c}(${t})`}return F.nil}}subschema(e,t){let n=(0,$l.getSubschema)(this.it,e);(0,$l.extendSubschemaData)(n,this.it,e),(0,$l.extendSubschemaMode)(n,e);let i={...this.it,...n,items:void 0,props:void 0};return D$(i,t),i}mergeEvaluated(e,t){let{it:n,gen:i}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=_r.mergeEvaluated.props(i,e.props,n.props,t)),n.items!==!0&&e.items!==void 0&&(n.items=_r.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,F.Name)),!0}};Br.KeywordCxt=Io;function gh(r,e,t,n){let i=new Io(r,t,e);"code"in t?t.code(i,n):i.$data&&t.validate?(0,es.funcKeywordCode)(i,t):"macro"in t?(0,es.macroKeywordCode)(i,t):(t.compile||t.validate)&&(0,es.funcKeywordCode)(i,t)}var Q$=/^\/(?:[^~]|~0|~1)*$/,Z$=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function _h(r,{dataLevel:e,dataNames:t,dataPathArr:n}){let i,s;if(r==="")return z.default.rootData;if(r[0]==="/"){if(!Q$.test(r))throw new Error(`Invalid JSON-pointer: ${r}`);i=r,s=z.default.rootData}else{let l=Z$.exec(r);if(!l)throw new Error(`Invalid JSON-pointer: ${r}`);let d=+l[1];if(i=l[2],i==="#"){if(d>=e)throw new Error(c("property/index",d));return n[e-d]}if(d>e)throw new Error(c("data",d));if(s=t[e-d],!i)return s}let o=s,a=i.split("/");for(let l of a)l&&(s=(0,F._)`${s}${(0,F.getProperty)((0,_r.unescapeJsonPointer)(l))}`,o=(0,F._)`${o} && ${s}`);return o;function c(l,d){return`Cannot access ${l} ${d} levels up, current level is ${e}`}}Br.getData=_h});var ts=A(xl=>{"use strict";Object.defineProperty(xl,"__esModule",{value:!0});var Al=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};xl.default=Al});var Kn=A(Il=>{"use strict";Object.defineProperty(Il,"__esModule",{value:!0});var kl=Qi(),Pl=class extends Error{constructor(e,t,n,i){super(i||`can't resolve reference ${n} from id ${t}`),this.missingRef=(0,kl.resolveUrl)(e,t,n),this.missingSchema=(0,kl.normalizeId)((0,kl.getFullPath)(e,this.missingRef))}};Il.default=Pl});var rs=A(Et=>{"use strict";Object.defineProperty(Et,"__esModule",{value:!0});Et.resolveSchema=Et.getCompilingSchema=Et.resolveRef=Et.compileSchema=Et.SchemaEnv=void 0;var Mt=H(),eS=ts(),gn=$t(),Ct=Qi(),bh=Q(),tS=Hn(),Wn=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,Ct.normalizeId)(n==null?void 0:n[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n==null?void 0:n.$async,this.refs={}}};Et.SchemaEnv=Wn;function Rl(r){let e=wh.call(this,r);if(e)return e;let t=(0,Ct.getFullPath)(this.opts.uriResolver,r.root.baseId),{es5:n,lines:i}=this.opts.code,{ownProperties:s}=this.opts,o=new Mt.CodeGen(this.scope,{es5:n,lines:i,ownProperties:s}),a;r.$async&&(a=o.scopeValue("Error",{ref:eS.default,code:(0,Mt._)`require("ajv/dist/runtime/validation_error").default`}));let c=o.scopeName("validate");r.validateName=c;let l={gen:o,allErrors:this.opts.allErrors,data:gn.default.data,parentData:gn.default.parentData,parentDataProperty:gn.default.parentDataProperty,dataNames:[gn.default.data],dataPathArr:[Mt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:o.scopeValue("schema",this.opts.code.source===!0?{ref:r.schema,code:(0,Mt.stringify)(r.schema)}:{ref:r.schema}),validateName:c,ValidationError:a,schema:r.schema,schemaEnv:r,rootId:t,baseId:r.baseId||t,schemaPath:Mt.nil,errSchemaPath:r.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Mt._)`""`,opts:this.opts,self:this},d;try{this._compilations.add(r),(0,tS.validateFunctionCode)(l),o.optimize(this.opts.code.optimize);let u=o.toString();d=`${o.scopeRefs(gn.default.scope)}return ${u}`,this.opts.code.process&&(d=this.opts.code.process(d,r));let p=new Function(`${gn.default.self}`,`${gn.default.scope}`,d)(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:u,scopeValues:o._values}),this.opts.unevaluated){let{props:y,items:h}=l;p.evaluated={props:y instanceof Mt.Name?void 0:y,items:h instanceof Mt.Name?void 0:h,dynamicProps:y instanceof Mt.Name,dynamicItems:h instanceof Mt.Name},p.source&&(p.source.evaluated=(0,Mt.stringify)(p.evaluated))}return r.validate=p,r}catch(u){throw delete r.validate,delete r.validateName,d&&this.logger.error("Error compiling schema, function code:",d),u}finally{this._compilations.delete(r)}}Et.compileSchema=Rl;function rS(r,e,t){var n;t=(0,Ct.resolveUrl)(this.opts.uriResolver,e,t);let i=r.refs[t];if(i)return i;let s=sS.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 Wn({schema:o,schemaId:a,root:r,baseId:e}))}if(s!==void 0)return r.refs[t]=nS.call(this,s)}Et.resolveRef=rS;function nS(r){return(0,Ct.inlineRef)(r.schema,this.opts.inlineRefs)?r.schema:r.validate?r:Rl.call(this,r)}function wh(r){for(let e of this._compilations)if(iS(e,r))return e}Et.getCompilingSchema=wh;function iS(r,e){return r.schema===e.schema&&r.root===e.root&&r.baseId===e.baseId}function sS(r,e){let t;for(;typeof(t=this.refs[e])=="string";)e=t;return t||this.schemas[e]||Oo.call(this,r,e)}function Oo(r,e){let t=this.opts.uriResolver.parse(e),n=(0,Ct._getFullPath)(this.opts.uriResolver,t),i=(0,Ct.getFullPath)(this.opts.uriResolver,r.baseId,void 0);if(Object.keys(r.schema).length>0&&n===i)return Ol.call(this,t,r);let s=(0,Ct.normalizeId)(n),o=this.refs[s]||this.schemas[s];if(typeof o=="string"){let a=Oo.call(this,r,o);return typeof(a==null?void 0:a.schema)!="object"?void 0:Ol.call(this,t,a)}if(typeof(o==null?void 0:o.schema)=="object"){if(o.validate||Rl.call(this,o),s===(0,Ct.normalizeId)(e)){let{schema:a}=o,{schemaId:c}=this.opts,l=a[c];return l&&(i=(0,Ct.resolveUrl)(this.opts.uriResolver,i,l)),new Wn({schema:a,schemaId:c,root:r,baseId:i})}return Ol.call(this,t,o)}}Et.resolveSchema=Oo;var oS=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Ol(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,bh.unescapeFragment)(a)];if(c===void 0)return;t=c;let l=typeof t=="object"&&t[this.opts.schemaId];!oS.has(a)&&l&&(e=(0,Ct.resolveUrl)(this.opts.uriResolver,e,l))}let s;if(typeof t!="boolean"&&t.$ref&&!(0,bh.schemaHasRulesButRef)(t,this.RULES)){let a=(0,Ct.resolveUrl)(this.opts.uriResolver,e,t.$ref);s=Oo.call(this,n,a)}let{schemaId:o}=this.opts;if(s=s||new Wn({schema:t,schemaId:o,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var vh=A((iN,aS)=>{aS.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 Cl=A((sN,kh)=>{"use strict";var cS=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Sh=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),Tl=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),Eh=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),lS=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function Ml(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 dS=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function $h(r){return r.length=0,!0}function uS(r,e,t){if(r.length){let n=Ml(r);if(n!=="")e.push(n);else return t.error=!0,!1;r.length=0}return!0}function fS(r){let e=0,t={error:!1,address:"",zone:""},n=[],i=[],s=!1,o=!1,a=uS;for(let c=0;c7){t.error=!0;break}c>0&&r[c-1]===":"&&(s=!0),n.push(":");continue}else if(l==="%"){if(!a(i,n,t))break;a=$h}else{i.push(l);continue}}return i.length&&(a===$h?t.zone=i.join(""):o?n.push(i.join("")):n.push(Ml(i))),t.address=n.join(""),t}function Ah(r){if(pS(r,":")<2)return{host:r,isIPV6:!1};let e=fS(r);if(e.error)return{host:r,isIPV6:!1};{let t=e.address,n=e.address;return e.zone&&(t+="%"+e.zone,n+="%25"+e.zone),{host:t,isIPV6:!0,escapedHost:n}}}function pS(r,e){let t=0;for(let n=0;nmS[n])}function _S(r,e=!1){if(r.indexOf("%")===-1)return r;let t="";for(let n=0;n{"use strict";var{isUUID:$S}=Cl(),SS=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,ES=["http","https","ws","wss","urn","urn:uuid"];function AS(r){return ES.indexOf(r)!==-1}function Nl(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 Ph(r){return r.host||(r.error=r.error||"HTTP URIs must have a host."),r}function Ih(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 xS(r){return r.secure=Nl(r),r.resourceName=(r.path||"/")+(r.query?"?"+r.query:""),r.path=void 0,r.query=void 0,r}function kS(r){if((r.port===(Nl(r)?443:80)||r.port==="")&&(r.port=void 0),typeof r.secure=="boolean"&&(r.scheme=r.secure?"wss":"ws",r.secure=void 0),r.resourceName){let[e,t]=r.resourceName.split("?");r.path=e&&e!=="/"?e:void 0,r.query=t,r.resourceName=void 0}return r.fragment=void 0,r}function PS(r,e){if(!r.path)return r.error="URN can not be parsed",r;let t=r.path.match(SS);if(t){let n=e.scheme||r.scheme||"urn";r.nid=t[1].toLowerCase(),r.nss=t[2];let i=`${n}:${e.nid||r.nid}`,s=Ll(i);r.path=void 0,s&&(r=s.parse(r,e))}else r.error=r.error||"URN can not be parsed.";return r}function IS(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=Ll(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 OS(r,e){let t=r;return t.uuid=t.nss,t.nss=void 0,!e.tolerant&&(!t.uuid||!$S(t.uuid))&&(t.error=t.error||"UUID is not valid."),t}function RS(r){let e=r;return e.nss=(r.uuid||"").toLowerCase(),e}var Oh={scheme:"http",domainHost:!0,parse:Ph,serialize:Ih},TS={scheme:"https",domainHost:Oh.domainHost,parse:Ph,serialize:Ih},Ro={scheme:"ws",domainHost:!0,parse:xS,serialize:kS},MS={scheme:"wss",domainHost:Ro.domainHost,parse:Ro.parse,serialize:Ro.serialize},CS={scheme:"urn",parse:PS,serialize:IS,skipNormalize:!0},NS={scheme:"urn:uuid",parse:OS,serialize:RS,skipNormalize:!0},To={http:Oh,https:TS,ws:Ro,wss:MS,urn:CS,"urn:uuid":NS};Object.setPrototypeOf(To,null);function Ll(r){return r&&(To[r]||To[r.toLowerCase()])||void 0}Rh.exports={wsIsSecure:Nl,SCHEMES:To,isValidSchemeName:AS,getSchemeHandler:Ll}});var jh=A((aN,No)=>{"use strict";var{normalizeIPv6:LS,removeDotSegments:ns,recomposeAuthority:jS,normalizePercentEncoding:DS,normalizePathEncoding:qS,escapePreservingEscapes:FS,reescapeHostDelimiters:US,isIPv4:VS,nonSimpleDomain:BS}=Cl(),{SCHEMES:zS,getSchemeHandler:Ch}=Th();function HS(r,e){return typeof r=="string"?r=QS(r,e):typeof r=="object"&&(r=Co(_n(r,e),e)),r}function KS(r,e,t){let n=t?Object.assign({scheme:"null"},t):{scheme:"null"},{parsed:i,malformedAuthorityOrPort:s}=Mo(r,n),{parsed:o,malformedAuthorityOrPort:a}=Mo(e,n);if(s||a)throw new Error(i.error||o.error||"URI is malformed.");let c=Nh(i,o,n,!0);return n.skipEscape=!0,_n(c,n)}function Nh(r,e,t,n){let i={};return n||(r=Co(_n(r,t),t),e=Co(_n(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=ns(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=ns(e.path||""),i.query=e.query):(e.path?(e.path[0]==="/"?i.path=ns(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=ns(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 WS(r,e,t){let n=Mh(r,t),i=Mh(e,t);return n!==void 0&&i!==void 0&&n.toLowerCase()===i.toLowerCase()}function _n(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=[],s=Ch(n.scheme||t.scheme);s&&s.serialize&&s.serialize(t,n),t.path!==void 0&&(n.skipEscape?t.path=DS(t.path):(t.path=FS(t.path),t.scheme!==void 0&&(t.path=t.path.split("%3A").join(":")))),n.reference!=="suffix"&&t.scheme&&i.push(t.scheme,":");let o=jS(t);if(o!==void 0&&(n.reference!=="suffix"&&i.push("//"),i.push(o),t.path&&t.path[0]!=="/"&&i.push("/")),t.path!==void 0){let a=t.path;!n.absolutePath&&(!s||!s.absolutePath)&&(a=ns(a)),o===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),i.push(a)}return t.query!==void 0&&i.push("?",t.query),t.fragment!==void 0&&i.push("#",t.fragment),i.join("")}var GS=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,JS=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,YS=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function XS(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 Mo(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;t.reference==="suffix"&&(t.scheme?r=t.scheme+":"+r:r="//"+r);let o=r.match(JS);o!==null&&o[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",i=!0);let a=r.match(YS);if(a!==null){let l=a[1],d=l.replace(/[\t\n\r]/g,"");d.length>=2&&(d.slice(0,2)!=="//"?(n.error=n.error||"URI authority must not contain a literal backslash.",i=!0):l.length!==d.length&&(n.error=n.error||"URI authority introducer must not contain whitespace.",i=!0))}let c=r.match(GS);if(c){n.scheme=c[1],n.userinfo=c[3],n.host=c[4],n.port=parseInt(c[5],10),n.path=c[6]||"",n.query=c[7],n.fragment=c[8],isNaN(n.port)&&(n.port=c[5]);let l=XS(n,c);if(l!==void 0&&(n.error=n.error||l,i=!0),n.host)if(VS(n.host)===!1){let f=LS(n.host);n.host=f.host.toLowerCase(),s=f.isIPV6}else s=!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 d=Ch(t.scheme||n.scheme);if(!t.unicodeSupport&&(!d||!d.unicodeSupport)&&n.host&&(t.domainHost||d&&d.domainHost)&&s===!1&&BS(n.host))try{n.host=new URL("http://"+n.host).hostname}catch(u){n.error=n.error||"Host's domain name can not be converted to ASCII: "+u}if((!d||d&&!d.skipNormalize)&&(r.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=US(unescape(n.host),s))),n.path&&(n.path=qS(n.path)),n.fragment))try{n.fragment=encodeURI(decodeURIComponent(n.fragment))}catch(u){n.error=n.error||"URI malformed"}d&&d.parse&&d.parse(n,t)}else n.error=n.error||"URI can not be parsed.";return{parsed:n,malformedAuthorityOrPort:i}}function Co(r,e){return Mo(r,e).parsed}function QS(r,e){return Lh(r,e).normalized}function Lh(r,e){let{parsed:t,malformedAuthorityOrPort:n}=Mo(r,e);return{normalized:n?r:_n(t,e),malformedAuthorityOrPort:n}}function Mh(r,e){if(typeof r=="string"){let{normalized:t,malformedAuthorityOrPort:n}=Lh(r,e);return n?void 0:t}if(typeof r=="object")return _n(r,e)}var jl={SCHEMES:zS,normalize:HS,resolve:KS,resolveComponent:Nh,equal:WS,serialize:_n,parse:Co};No.exports=jl;No.exports.default=jl;No.exports.fastUri=jl});var qh=A(Dl=>{"use strict";Object.defineProperty(Dl,"__esModule",{value:!0});var Dh=jh();Dh.code='require("ajv/dist/runtime/uri").default';Dl.default=Dh});var Ul=A(je=>{"use strict";Object.defineProperty(je,"__esModule",{value:!0});je.CodeGen=je.Name=je.nil=je.stringify=je.str=je._=je.KeywordCxt=void 0;var ZS=Hn();Object.defineProperty(je,"KeywordCxt",{enumerable:!0,get:function(){return ZS.KeywordCxt}});var Gn=H();Object.defineProperty(je,"_",{enumerable:!0,get:function(){return Gn._}});Object.defineProperty(je,"str",{enumerable:!0,get:function(){return Gn.str}});Object.defineProperty(je,"stringify",{enumerable:!0,get:function(){return Gn.stringify}});Object.defineProperty(je,"nil",{enumerable:!0,get:function(){return Gn.nil}});Object.defineProperty(je,"Name",{enumerable:!0,get:function(){return Gn.Name}});Object.defineProperty(je,"CodeGen",{enumerable:!0,get:function(){return Gn.CodeGen}});var eE=ts(),zh=Kn(),tE=fl(),is=rs(),rE=H(),ss=Qi(),Lo=Xi(),Fl=Q(),Fh=vh(),nE=qh(),Hh=(r,e)=>new RegExp(r,e);Hh.code="new RegExp";var iE=["removeAdditional","useDefaults","coerceTypes"],sE=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),oE={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."},aE={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Uh=200;function cE(r){var e,t,n,i,s,o,a,c,l,d,u,f,p,y,h,m,g,_,w,k,v,P,O,$,R;let S=r.strict,V=(e=r.code)===null||e===void 0?void 0:e.optimize,B=V===!0||V===void 0?1:V||0,T=(n=(t=r.code)===null||t===void 0?void 0:t.regExp)!==null&&n!==void 0?n:Hh,E=(i=r.uriResolver)!==null&&i!==void 0?i:nE.default;return{strictSchema:(o=(s=r.strictSchema)!==null&&s!==void 0?s:S)!==null&&o!==void 0?o:!0,strictNumbers:(c=(a=r.strictNumbers)!==null&&a!==void 0?a:S)!==null&&c!==void 0?c:!0,strictTypes:(d=(l=r.strictTypes)!==null&&l!==void 0?l:S)!==null&&d!==void 0?d:"log",strictTuples:(f=(u=r.strictTuples)!==null&&u!==void 0?u:S)!==null&&f!==void 0?f:"log",strictRequired:(y=(p=r.strictRequired)!==null&&p!==void 0?p:S)!==null&&y!==void 0?y:!1,code:r.code?{...r.code,optimize:B,regExp:T}:{optimize:B,regExp:T},loopRequired:(h=r.loopRequired)!==null&&h!==void 0?h:Uh,loopEnum:(m=r.loopEnum)!==null&&m!==void 0?m:Uh,meta:(g=r.meta)!==null&&g!==void 0?g:!0,messages:(_=r.messages)!==null&&_!==void 0?_:!0,inlineRefs:(w=r.inlineRefs)!==null&&w!==void 0?w:!0,schemaId:(k=r.schemaId)!==null&&k!==void 0?k:"$id",addUsedSchema:(v=r.addUsedSchema)!==null&&v!==void 0?v:!0,validateSchema:(P=r.validateSchema)!==null&&P!==void 0?P:!0,validateFormats:(O=r.validateFormats)!==null&&O!==void 0?O:!0,unicodeRegExp:($=r.unicodeRegExp)!==null&&$!==void 0?$:!0,int32range:(R=r.int32range)!==null&&R!==void 0?R:!0,uriResolver:E}}var os=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,...cE(e)};let{es5:t,lines:n}=this.opts.code;this.scope=new rE.ValueScope({scope:{},prefixes:sE,es5:t,lines:n}),this.logger=hE(e.logger);let i=e.validateFormats;e.validateFormats=!1,this.RULES=(0,tE.getRules)(),Vh.call(this,oE,e,"NOT SUPPORTED"),Vh.call(this,aE,e,"DEPRECATED","warn"),this._metaOpts=fE.call(this),e.formats&&dE.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&uE.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),lE.call(this),e.validateFormats=i}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:t,schemaId:n}=this.opts,i=Fh;n==="id"&&(i={...Fh},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(d,u){await s.call(this,d.$schema);let f=this._addSchema(d,u);return f.validate||o.call(this,f)}async function s(d){d&&!this.getSchema(d)&&await i.call(this,{$ref:d},!0)}async function o(d){try{return this._compileSchemaEnv(d)}catch(u){if(!(u instanceof zh.default))throw u;return a.call(this,u),await c.call(this,u.missingSchema),o.call(this,d)}}function a({missingSchema:d,missingRef:u}){if(this.refs[d])throw new Error(`AnySchema ${d} is loaded but ${u} cannot be resolved`)}async function c(d){let u=await l.call(this,d);this.refs[d]||await s.call(this,u.$schema),this.refs[d]||this.addSchema(u,d,t)}async function l(d){let u=this._loading[d];if(u)return u;try{return await(this._loading[d]=n(d))}finally{delete this._loading[d]}}}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,ss.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=Bh.call(this,e))=="string";)e=t;if(t===void 0){let{schemaId:n}=this.opts,i=new is.SchemaEnv({schema:{},schemaId:n});if(t=is.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=Bh.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,ss.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(yE.call(this,n,t),!t)return(0,Fl.eachItem)(n,s=>ql.call(this,s)),this;_E.call(this,t);let i={...t,type:(0,Lo.getJSONTypes)(t.type),schemaType:(0,Lo.getJSONTypes)(t.schemaType)};return(0,Fl.eachItem)(n,i.type.length===0?s=>ql.call(this,s,i):s=>i.type.forEach(o=>ql.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,d=o[a];l&&d&&(o[a]=Kh(d))}}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,ss.normalizeId)(o||n);let l=ss.getSchemaRefs.call(this,e,n);return c=new is.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):is.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{is.compileSchema.call(this,e)}finally{this.opts=t}}};os.ValidationError=eE.default;os.MissingRefError=zh.default;je.default=os;function Vh(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 Bh(r){return r=(0,ss.normalizeId)(r),this.schemas[r]||this.refs[r]}function lE(){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 dE(){for(let r in this.opts.formats){let e=this.opts.formats[r];e&&this.addFormat(r,e)}}function uE(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 fE(){let r={...this.opts};for(let e of iE)delete r[e];return r}var pE={log(){},warn(){},error(){}};function hE(r){if(r===!1)return pE;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 mE=/^[a-z_$][a-z0-9_$:-]*$/i;function yE(r,e){let{RULES:t}=this;if((0,Fl.eachItem)(r,n=>{if(t.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!mE.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 ql(r,e,t){var n;let i=e==null?void 0: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,Lo.getJSONTypes)(e.type),schemaType:(0,Lo.getJSONTypes)(e.schemaType)}};e.before?gE.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 gE(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 _E(r){let{metaSchema:e}=r;e!==void 0&&(r.$data&&this.opts.$data&&(e=Kh(e)),r.validateSchema=this.compile(e,!0))}var bE={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Kh(r){return{anyOf:[r,bE]}}});var Wh=A(Vl=>{"use strict";Object.defineProperty(Vl,"__esModule",{value:!0});var wE={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Vl.default=wE});var qo=A(bn=>{"use strict";Object.defineProperty(bn,"__esModule",{value:!0});bn.callRef=bn.getValidate=void 0;var vE=Kn(),Gh=St(),ct=H(),Jn=$t(),Jh=rs(),jo=Q(),$E={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 u();let d=Jh.resolveRef.call(c,l,i,t);if(d===void 0)throw new vE.default(n.opts.uriResolver,i,t);if(d instanceof Jh.SchemaEnv)return f(d);return p(d);function u(){if(s===l)return Do(r,o,s,s.$async);let y=e.scopeValue("root",{ref:l});return Do(r,(0,ct._)`${y}.validate`,l,l.$async)}function f(y){let h=Yh(r,y);Do(r,h,y,y.$async)}function p(y){let h=e.scopeValue("schema",a.code.source===!0?{ref:y,code:(0,ct.stringify)(y)}:{ref:y}),m=e.name("valid"),g=r.subschema({schema:y,dataTypes:[],schemaPath:ct.nil,topSchemaRef:h,errSchemaPath:t},m);r.mergeEvaluated(g),r.ok(m)}}};function Yh(r,e){let{gen:t}=r;return e.validate?t.scopeValue("validate",{ref:e.validate}):(0,ct._)`${t.scopeValue("wrapper",{ref:e})}.validate`}bn.getValidate=Yh;function Do(r,e,t,n){let{gen:i,it:s}=r,{allErrors:o,schemaEnv:a,opts:c}=s,l=c.passContext?Jn.default.this:ct.nil;n?d():u();function d(){if(!a.$async)throw new Error("async schema referenced by sync schema");let y=i.let("valid");i.try(()=>{i.code((0,ct._)`await ${(0,Gh.callValidateCode)(r,e,l)}`),p(e),o||i.assign(y,!0)},h=>{i.if((0,ct._)`!(${h} instanceof ${s.ValidationError})`,()=>i.throw(h)),f(h),o||i.assign(y,!1)}),r.ok(y)}function u(){r.result((0,Gh.callValidateCode)(r,e,l),()=>p(e),()=>f(e))}function f(y){let h=(0,ct._)`${y}.errors`;i.assign(Jn.default.vErrors,(0,ct._)`${Jn.default.vErrors} === null ? ${h} : ${Jn.default.vErrors}.concat(${h})`),i.assign(Jn.default.errors,(0,ct._)`${Jn.default.vErrors}.length`)}function p(y){var h;if(!s.opts.unevaluated)return;let m=(h=t==null?void 0:t.validate)===null||h===void 0?void 0:h.evaluated;if(s.props!==!0)if(m&&!m.dynamicProps)m.props!==void 0&&(s.props=jo.mergeEvaluated.props(i,m.props,s.props));else{let g=i.var("props",(0,ct._)`${y}.evaluated.props`);s.props=jo.mergeEvaluated.props(i,g,s.props,ct.Name)}if(s.items!==!0)if(m&&!m.dynamicItems)m.items!==void 0&&(s.items=jo.mergeEvaluated.items(i,m.items,s.items));else{let g=i.var("items",(0,ct._)`${y}.evaluated.items`);s.items=jo.mergeEvaluated.items(i,g,s.items,ct.Name)}}}bn.callRef=Do;bn.default=$E});var zl=A(Bl=>{"use strict";Object.defineProperty(Bl,"__esModule",{value:!0});var SE=Wh(),EE=qo(),AE=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",SE.default,EE.default];Bl.default=AE});var Xh=A(Hl=>{"use strict";Object.defineProperty(Hl,"__esModule",{value:!0});var Fo=H(),zr=Fo.operators,Uo={maximum:{okStr:"<=",ok:zr.LTE,fail:zr.GT},minimum:{okStr:">=",ok:zr.GTE,fail:zr.LT},exclusiveMaximum:{okStr:"<",ok:zr.LT,fail:zr.GTE},exclusiveMinimum:{okStr:">",ok:zr.GT,fail:zr.LTE}},xE={message:({keyword:r,schemaCode:e})=>(0,Fo.str)`must be ${Uo[r].okStr} ${e}`,params:({keyword:r,schemaCode:e})=>(0,Fo._)`{comparison: ${Uo[r].okStr}, limit: ${e}}`},kE={keyword:Object.keys(Uo),type:"number",schemaType:"number",$data:!0,error:xE,code(r){let{keyword:e,data:t,schemaCode:n}=r;r.fail$data((0,Fo._)`${t} ${Uo[e].fail} ${n} || isNaN(${t})`)}};Hl.default=kE});var Qh=A(Kl=>{"use strict";Object.defineProperty(Kl,"__esModule",{value:!0});var as=H(),PE={message:({schemaCode:r})=>(0,as.str)`must be multiple of ${r}`,params:({schemaCode:r})=>(0,as._)`{multipleOf: ${r}}`},IE={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:PE,code(r){let{gen:e,data:t,schemaCode:n,it:i}=r,s=i.opts.multipleOfPrecision,o=e.let("res"),a=s?(0,as._)`Math.abs(Math.round(${o}) - ${o}) > 1e-${s}`:(0,as._)`${o} !== parseInt(${o})`;r.fail$data((0,as._)`(${n} === 0 || (${o} = ${t}/${n}, ${a}))`)}};Kl.default=IE});var em=A(Wl=>{"use strict";Object.defineProperty(Wl,"__esModule",{value:!0});function Zh(r){let e=r.length,t=0,n=0,i;for(;n=55296&&i<=56319&&n{"use strict";Object.defineProperty(Gl,"__esModule",{value:!0});var wn=H(),OE=Q(),RE=em(),TE={message({keyword:r,schemaCode:e}){let t=r==="maxLength"?"more":"fewer";return(0,wn.str)`must NOT have ${t} than ${e} characters`},params:({schemaCode:r})=>(0,wn._)`{limit: ${r}}`},ME={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:TE,code(r){let{keyword:e,data:t,schemaCode:n,it:i}=r,s=e==="maxLength"?wn.operators.GT:wn.operators.LT,o=i.opts.unicode===!1?(0,wn._)`${t}.length`:(0,wn._)`${(0,OE.useFunc)(r.gen,RE.default)}(${t})`;r.fail$data((0,wn._)`${o} ${s} ${n}`)}};Gl.default=ME});var rm=A(Jl=>{"use strict";Object.defineProperty(Jl,"__esModule",{value:!0});var CE=St(),NE=Q(),Yn=H(),LE={message:({schemaCode:r})=>(0,Yn.str)`must match pattern "${r}"`,params:({schemaCode:r})=>(0,Yn._)`{pattern: ${r}}`},jE={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:LE,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,Yn._)`new RegExp`:(0,NE.useFunc)(e,c),d=e.let("valid");e.try(()=>e.assign(d,(0,Yn._)`${l}(${s}, ${a}).test(${t})`),()=>e.assign(d,!1)),r.fail$data((0,Yn._)`!${d}`)}else{let c=(0,CE.usePattern)(r,i);r.fail$data((0,Yn._)`!${c}.test(${t})`)}}};Jl.default=jE});var nm=A(Yl=>{"use strict";Object.defineProperty(Yl,"__esModule",{value:!0});var cs=H(),DE={message({keyword:r,schemaCode:e}){let t=r==="maxProperties"?"more":"fewer";return(0,cs.str)`must NOT have ${t} than ${e} properties`},params:({schemaCode:r})=>(0,cs._)`{limit: ${r}}`},qE={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:DE,code(r){let{keyword:e,data:t,schemaCode:n}=r,i=e==="maxProperties"?cs.operators.GT:cs.operators.LT;r.fail$data((0,cs._)`Object.keys(${t}).length ${i} ${n}`)}};Yl.default=qE});var im=A(Xl=>{"use strict";Object.defineProperty(Xl,"__esModule",{value:!0});var ls=St(),ds=H(),FE=Q(),UE={message:({params:{missingProperty:r}})=>(0,ds.str)`must have required property '${r}'`,params:({params:{missingProperty:r}})=>(0,ds._)`{missingProperty: ${r}}`},VE={keyword:"required",type:"object",schemaType:"array",$data:!0,error:UE,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():d(),a.strictRequired){let p=r.parentSchema.properties,{definedProperties:y}=r.it;for(let h of t)if((p==null?void 0:p[h])===void 0&&!y.has(h)){let m=o.schemaEnv.baseId+o.errSchemaPath,g=`required property "${h}" is not defined at "${m}" (strictRequired)`;(0,FE.checkStrictMode)(o,g,o.opts.strictRequired)}}function l(){if(c||s)r.block$data(ds.nil,u);else for(let p of t)(0,ls.checkReportMissingProp)(r,p)}function d(){let p=e.let("missing");if(c||s){let y=e.let("valid",!0);r.block$data(y,()=>f(p,y)),r.ok(y)}else e.if((0,ls.checkMissingProp)(r,t,p)),(0,ls.reportMissingProp)(r,p),e.else()}function u(){e.forOf("prop",n,p=>{r.setParams({missingProperty:p}),e.if((0,ls.noPropertyInData)(e,i,p,a.ownProperties),()=>r.error())})}function f(p,y){r.setParams({missingProperty:p}),e.forOf(p,n,()=>{e.assign(y,(0,ls.propertyInData)(e,i,p,a.ownProperties)),e.if((0,ds.not)(y),()=>{r.error(),e.break()})},ds.nil)}}};Xl.default=VE});var sm=A(Ql=>{"use strict";Object.defineProperty(Ql,"__esModule",{value:!0});var us=H(),BE={message({keyword:r,schemaCode:e}){let t=r==="maxItems"?"more":"fewer";return(0,us.str)`must NOT have ${t} than ${e} items`},params:({schemaCode:r})=>(0,us._)`{limit: ${r}}`},zE={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:BE,code(r){let{keyword:e,data:t,schemaCode:n}=r,i=e==="maxItems"?us.operators.GT:us.operators.LT;r.fail$data((0,us._)`${t}.length ${i} ${n}`)}};Ql.default=zE});var Vo=A(Zl=>{"use strict";Object.defineProperty(Zl,"__esModule",{value:!0});var om=wl();om.code='require("ajv/dist/runtime/equal").default';Zl.default=om});var am=A(td=>{"use strict";Object.defineProperty(td,"__esModule",{value:!0});var ed=Xi(),De=H(),HE=Q(),KE=Vo(),WE={message:({params:{i:r,j:e}})=>(0,De.str)`must NOT have duplicate items (items ## ${e} and ${r} are identical)`,params:({params:{i:r,j:e}})=>(0,De._)`{i: ${r}, j: ${e}}`},GE={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:WE,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,ed.getSchemaTypes)(s.items):[];r.block$data(c,d,(0,De._)`${o} === false`),r.ok(c);function d(){let y=e.let("i",(0,De._)`${t}.length`),h=e.let("j");r.setParams({i:y,j:h}),e.assign(c,!0),e.if((0,De._)`${y} > 1`,()=>(u()?f:p)(y,h))}function u(){return l.length>0&&!l.some(y=>y==="object"||y==="array")}function f(y,h){let m=e.name("item"),g=(0,ed.checkDataTypes)(l,m,a.opts.strictNumbers,ed.DataType.Wrong),_=e.const("indices",(0,De._)`{}`);e.for((0,De._)`;${y}--;`,()=>{e.let(m,(0,De._)`${t}[${y}]`),e.if(g,(0,De._)`continue`),l.length>1&&e.if((0,De._)`typeof ${m} == "string"`,(0,De._)`${m} += "_"`),e.if((0,De._)`typeof ${_}[${m}] == "number"`,()=>{e.assign(h,(0,De._)`${_}[${m}]`),r.error(),e.assign(c,!1).break()}).code((0,De._)`${_}[${m}] = ${y}`)})}function p(y,h){let m=(0,HE.useFunc)(e,KE.default),g=e.name("outer");e.label(g).for((0,De._)`;${y}--;`,()=>e.for((0,De._)`${h} = ${y}; ${h}--;`,()=>e.if((0,De._)`${m}(${t}[${y}], ${t}[${h}])`,()=>{r.error(),e.assign(c,!1).break(g)})))}}};td.default=GE});var cm=A(nd=>{"use strict";Object.defineProperty(nd,"__esModule",{value:!0});var rd=H(),JE=Q(),YE=Vo(),XE={message:"must be equal to constant",params:({schemaCode:r})=>(0,rd._)`{allowedValue: ${r}}`},QE={keyword:"const",$data:!0,error:XE,code(r){let{gen:e,data:t,$data:n,schemaCode:i,schema:s}=r;n||s&&typeof s=="object"?r.fail$data((0,rd._)`!${(0,JE.useFunc)(e,YE.default)}(${t}, ${i})`):r.fail((0,rd._)`${s} !== ${t}`)}};nd.default=QE});var lm=A(id=>{"use strict";Object.defineProperty(id,"__esModule",{value:!0});var fs=H(),ZE=Q(),eA=Vo(),tA={message:"must be equal to one of the allowed values",params:({schemaCode:r})=>(0,fs._)`{allowedValues: ${r}}`},rA={keyword:"enum",schemaType:"array",$data:!0,error:tA,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!=null?c:c=(0,ZE.useFunc)(e,eA.default),d;if(a||n)d=e.let("valid"),r.block$data(d,u);else{if(!Array.isArray(i))throw new Error("ajv implementation error");let p=e.const("vSchema",s);d=(0,fs.or)(...i.map((y,h)=>f(p,h)))}r.pass(d);function u(){e.assign(d,!1),e.forOf("v",s,p=>e.if((0,fs._)`${l()}(${t}, ${p})`,()=>e.assign(d,!0).break()))}function f(p,y){let h=i[y];return typeof h=="object"&&h!==null?(0,fs._)`${l()}(${t}, ${p}[${y}])`:(0,fs._)`${t} === ${h}`}}};id.default=rA});var od=A(sd=>{"use strict";Object.defineProperty(sd,"__esModule",{value:!0});var nA=Xh(),iA=Qh(),sA=tm(),oA=rm(),aA=nm(),cA=im(),lA=sm(),dA=am(),uA=cm(),fA=lm(),pA=[nA.default,iA.default,sA.default,oA.default,aA.default,cA.default,lA.default,dA.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},uA.default,fA.default];sd.default=pA});var cd=A(ps=>{"use strict";Object.defineProperty(ps,"__esModule",{value:!0});ps.validateAdditionalItems=void 0;var vn=H(),ad=Q(),hA={message:({params:{len:r}})=>(0,vn.str)`must NOT have more than ${r} items`,params:({params:{len:r}})=>(0,vn._)`{limit: ${r}}`},mA={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:hA,code(r){let{parentSchema:e,it:t}=r,{items:n}=e;if(!Array.isArray(n)){(0,ad.checkStrictMode)(t,'"additionalItems" is ignored when "items" is not an array of schemas');return}dm(r,n)}};function dm(r,e){let{gen:t,schema:n,data:i,keyword:s,it:o}=r;o.items=!0;let a=t.const("len",(0,vn._)`${i}.length`);if(n===!1)r.setParams({len:e.length}),r.pass((0,vn._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,ad.alwaysValidSchema)(o,n)){let l=t.var("valid",(0,vn._)`${a} <= ${e.length}`);t.if((0,vn.not)(l),()=>c(l)),r.ok(l)}function c(l){t.forRange("i",e.length,a,d=>{r.subschema({keyword:s,dataProp:d,dataPropType:ad.Type.Num},l),o.allErrors||t.if((0,vn.not)(l),()=>t.break())})}}ps.validateAdditionalItems=dm;ps.default=mA});var ld=A(hs=>{"use strict";Object.defineProperty(hs,"__esModule",{value:!0});hs.validateTuple=void 0;var um=H(),Bo=Q(),yA=St(),gA={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(r){let{schema:e,it:t}=r;if(Array.isArray(e))return fm(r,"additionalItems",e);t.items=!0,!(0,Bo.alwaysValidSchema)(t,e)&&r.ok((0,yA.validateArray)(r))}};function fm(r,e,t=r.schema){let{gen:n,parentSchema:i,data:s,keyword:o,it:a}=r;d(i),a.opts.unevaluated&&t.length&&a.items!==!0&&(a.items=Bo.mergeEvaluated.items(n,t.length,a.items));let c=n.name("valid"),l=n.const("len",(0,um._)`${s}.length`);t.forEach((u,f)=>{(0,Bo.alwaysValidSchema)(a,u)||(n.if((0,um._)`${l} > ${f}`,()=>r.subschema({keyword:o,schemaProp:f,dataProp:f},c)),r.ok(c))});function d(u){let{opts:f,errSchemaPath:p}=a,y=t.length,h=y===u.minItems&&(y===u.maxItems||u[e]===!1);if(f.strictTuples&&!h){let m=`"${o}" is ${y}-tuple, but minItems or maxItems/${e} are not specified or different at path "${p}"`;(0,Bo.checkStrictMode)(a,m,f.strictTuples)}}}hs.validateTuple=fm;hs.default=gA});var pm=A(dd=>{"use strict";Object.defineProperty(dd,"__esModule",{value:!0});var _A=ld(),bA={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:r=>(0,_A.validateTuple)(r,"items")};dd.default=bA});var mm=A(ud=>{"use strict";Object.defineProperty(ud,"__esModule",{value:!0});var hm=H(),wA=Q(),vA=St(),$A=cd(),SA={message:({params:{len:r}})=>(0,hm.str)`must NOT have more than ${r} items`,params:({params:{len:r}})=>(0,hm._)`{limit: ${r}}`},EA={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:SA,code(r){let{schema:e,parentSchema:t,it:n}=r,{prefixItems:i}=t;n.items=!0,!(0,wA.alwaysValidSchema)(n,e)&&(i?(0,$A.validateAdditionalItems)(r,i):r.ok((0,vA.validateArray)(r)))}};ud.default=EA});var ym=A(fd=>{"use strict";Object.defineProperty(fd,"__esModule",{value:!0});var At=H(),zo=Q(),AA={message:({params:{min:r,max:e}})=>e===void 0?(0,At.str)`must contain at least ${r} valid item(s)`:(0,At.str)`must contain at least ${r} and no more than ${e} valid item(s)`,params:({params:{min:r,max:e}})=>e===void 0?(0,At._)`{minContains: ${r}}`:(0,At._)`{minContains: ${r}, maxContains: ${e}}`},xA={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:AA,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 d=e.const("len",(0,At._)`${i}.length`);if(r.setParams({min:o,max:a}),a===void 0&&o===0){(0,zo.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&o>a){(0,zo.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),r.fail();return}if((0,zo.alwaysValidSchema)(s,t)){let h=(0,At._)`${d} >= ${o}`;a!==void 0&&(h=(0,At._)`${h} && ${d} <= ${a}`),r.pass(h);return}s.items=!0;let u=e.name("valid");a===void 0&&o===1?p(u,()=>e.if(u,()=>e.break())):o===0?(e.let(u,!0),a!==void 0&&e.if((0,At._)`${i}.length > 0`,f)):(e.let(u,!1),f()),r.result(u,()=>r.reset());function f(){let h=e.name("_valid"),m=e.let("count",0);p(h,()=>e.if(h,()=>y(m)))}function p(h,m){e.forRange("i",0,d,g=>{r.subschema({keyword:"contains",dataProp:g,dataPropType:zo.Type.Num,compositeRule:!0},h),m()})}function y(h){e.code((0,At._)`${h}++`),a===void 0?e.if((0,At._)`${h} >= ${o}`,()=>e.assign(u,!0).break()):(e.if((0,At._)`${h} > ${a}`,()=>e.assign(u,!1).break()),o===1?e.assign(u,!0):e.if((0,At._)`${h} >= ${o}`,()=>e.assign(u,!0)))}}};fd.default=xA});var Ho=A(tr=>{"use strict";Object.defineProperty(tr,"__esModule",{value:!0});tr.validateSchemaDeps=tr.validatePropertyDeps=tr.error=void 0;var pd=H(),kA=Q(),ms=St();tr.error={message:({params:{property:r,depsCount:e,deps:t}})=>{let n=e===1?"property":"properties";return(0,pd.str)`must have ${n} ${t} when property ${r} is present`},params:({params:{property:r,depsCount:e,deps:t,missingProperty:n}})=>(0,pd._)`{property: ${r}, + || ${o} === "boolean" || ${i} === null`).assign(a,(0,W._)`[${i}]`)}}}function Uv({gen:r,parentData:e,parentDataProperty:t},n){r.if((0,W._)`${e} !== undefined`,()=>r.assign((0,W._)`${e}[${t}]`,n))}function hl(r,e,t,n=zn.Correct){let i=n===zn.Correct?W.operators.EQ:W.operators.NEQ,s;switch(r){case"null":return(0,W._)`${e} ${i} null`;case"array":s=(0,W._)`Array.isArray(${e})`;break;case"object":s=(0,W._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=o((0,W._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=o();break;default:return(0,W._)`typeof ${e} ${i} ${r}`}return n===zn.Correct?s:(0,W.not)(s);function o(a=W.nil){return(0,W.and)((0,W._)`typeof ${e} == "number"`,a,t?(0,W._)`isFinite(${e})`:W.nil)}}ze.checkDataType=hl;function ml(r,e,t,n){if(r.length===1)return hl(r[0],e,t,n);let i,s=(0,Fp.toHash)(r);if(s.array&&s.object){let o=(0,W._)`typeof ${e} != "object"`;i=s.null?o:(0,W._)`!${e} || ${o}`,delete s.null,delete s.array,delete s.object}else i=W.nil;s.number&&delete s.integer;for(let o in s)i=(0,W.and)(i,hl(o,e,t,n));return i}ze.checkDataTypes=ml;var Bv={message:({schema:r})=>`must be ${r}`,params:({schema:r,schemaValue:e})=>typeof r=="string"?(0,W._)`{type: ${r}}`:(0,W._)`{type: ${e}}`};function yl(r){let e=zv(r);(0,jv.reportError)(e,Bv)}ze.reportTypeError=yl;function zv(r){let{gen:e,data:t,schema:n}=r,i=(0,Fp.schemaRefOrVal)(r,n,"type");return{gen:e,keyword:"type",data:t,schema:n.type,schemaCode:i,schemaValue:i,parentSchema:n,params:{},it:r}}});var zp=A(xo=>{"use strict";Object.defineProperty(xo,"__esModule",{value:!0});xo.assignDefaults=void 0;var Hn=H(),Hv=Q();function Kv(r,e){let{properties:t,items:n}=r.schema;if(e==="object"&&t)for(let i in t)Bp(r,i,t[i].default);else e==="array"&&Array.isArray(n)&&n.forEach((i,s)=>Bp(r,s,i.default))}xo.assignDefaults=Kv;function Bp(r,e,t){let{gen:n,compositeRule:i,data:s,opts:o}=r;if(t===void 0)return;let a=(0,Hn._)`${s}${(0,Hn.getProperty)(e)}`;if(i){(0,Hv.checkStrictMode)(r,`default is ignored for: ${a}`);return}let c=(0,Hn._)`${a} === undefined`;o.useDefaults==="empty"&&(c=(0,Hn._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,Hn._)`${a} = ${(0,Hn.stringify)(t)}`)}});var $t=A(ue=>{"use strict";Object.defineProperty(ue,"__esModule",{value:!0});ue.validateUnion=ue.validateArray=ue.usePattern=ue.callValidateCode=ue.schemaProperties=ue.allSchemaProperties=ue.noPropertyInData=ue.propertyInData=ue.isOwnProperty=ue.hasPropFunc=ue.reportMissingProp=ue.checkMissingProp=ue.checkReportMissingProp=void 0;var ge=H(),gl=Q(),Ur=vt(),Wv=Q();function Gv(r,e){let{gen:t,data:n,it:i}=r;t.if(bl(t,n,e,i.opts.ownProperties),()=>{r.setParams({missingProperty:(0,ge._)`${e}`},!0),r.error()})}ue.checkReportMissingProp=Gv;function Jv({gen:r,data:e,it:{opts:t}},n,i){return(0,ge.or)(...n.map(s=>(0,ge.and)(bl(r,e,s,t.ownProperties),(0,ge._)`${i} = ${s}`)))}ue.checkMissingProp=Jv;function Yv(r,e){r.setParams({missingProperty:e},!0),r.error()}ue.reportMissingProp=Yv;function Hp(r){return r.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,ge._)`Object.prototype.hasOwnProperty`})}ue.hasPropFunc=Hp;function _l(r,e,t){return(0,ge._)`${Hp(r)}.call(${e}, ${t})`}ue.isOwnProperty=_l;function Xv(r,e,t,n){let i=(0,ge._)`${e}${(0,ge.getProperty)(t)} !== undefined`;return n?(0,ge._)`${i} && ${_l(r,e,t)}`:i}ue.propertyInData=Xv;function bl(r,e,t,n){let i=(0,ge._)`${e}${(0,ge.getProperty)(t)} === undefined`;return n?(0,ge.or)(i,(0,ge.not)(_l(r,e,t))):i}ue.noPropertyInData=bl;function Kp(r){return r?Object.keys(r).filter(e=>e!=="__proto__"):[]}ue.allSchemaProperties=Kp;function Qv(r,e){return Kp(e).filter(t=>!(0,gl.alwaysValidSchema)(r,e[t]))}ue.schemaProperties=Qv;function Zv({schemaCode:r,data:e,it:{gen:t,topSchemaRef:n,schemaPath:i,errorPath:s},it:o},a,c,l){let d=l?(0,ge._)`${r}, ${e}, ${n}${i}`:e,u=[[Ur.default.instancePath,(0,ge.strConcat)(Ur.default.instancePath,s)],[Ur.default.parentData,o.parentData],[Ur.default.parentDataProperty,o.parentDataProperty],[Ur.default.rootData,Ur.default.rootData]];o.opts.dynamicRef&&u.push([Ur.default.dynamicAnchors,Ur.default.dynamicAnchors]);let f=(0,ge._)`${d}, ${t.object(...u)}`;return c!==ge.nil?(0,ge._)`${a}.call(${c}, ${f})`:(0,ge._)`${a}(${f})`}ue.callValidateCode=Zv;var e$=(0,ge._)`new RegExp`;function t$({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,ge._)`${i.code==="new RegExp"?e$:(0,Wv.useFunc)(r,i)}(${t}, ${n})`})}ue.usePattern=t$;function r$(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,ge._)`${t}.length`);e.forRange("i",0,c,l=>{r.subschema({keyword:n,dataProp:l,dataPropType:gl.Type.Num},s),e.if((0,ge.not)(s),a)})}}ue.validateArray=r$;function n$(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,gl.alwaysValidSchema)(i,c))&&!i.opts.unevaluated)return;let o=e.let("valid",!1),a=e.name("_valid");e.block(()=>t.forEach((c,l)=>{let d=r.subschema({keyword:n,schemaProp:l,compositeRule:!0},a);e.assign(o,(0,ge._)`${o} || ${a}`),r.mergeValidEvaluated(d,a)||e.if((0,ge.not)(o))})),r.result(o,()=>r.reset(),()=>r.error(!0))}ue.validateUnion=n$});var Jp=A(Qt=>{"use strict";Object.defineProperty(Qt,"__esModule",{value:!0});Qt.validateKeywordUsage=Qt.validSchemaType=Qt.funcKeywordCode=Qt.macroKeywordCode=void 0;var Ye=H(),_n=vt(),i$=$t(),s$=Xi();function o$(r,e){let{gen:t,keyword:n,schema:i,parentSchema:s,it:o}=r,a=e.macro.call(o.self,i,s,o),c=Gp(t,n,a);o.opts.validateSchema!==!1&&o.self.validateSchema(a,!0);let l=t.name("valid");r.subschema({schema:a,schemaPath:Ye.nil,errSchemaPath:`${o.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},l),r.pass(l,()=>r.error(!0))}Qt.macroKeywordCode=o$;function a$(r,e){var t;let{gen:n,keyword:i,schema:s,parentSchema:o,$data:a,it:c}=r;l$(c,e);let l=!a&&e.compile?e.compile.call(c.self,s,o,c):e.validate,d=Gp(n,i,l),u=n.let("valid");r.block$data(u,f),r.ok((t=e.valid)!==null&&t!==void 0?t:u);function f(){if(e.errors===!1)h(),e.modifying&&Wp(r),m(()=>r.error());else{let g=e.async?p():y();e.modifying&&Wp(r),m(()=>c$(r,g))}}function p(){let g=n.let("ruleErrs",null);return n.try(()=>h((0,Ye._)`await `),_=>n.assign(u,!1).if((0,Ye._)`${_} instanceof ${c.ValidationError}`,()=>n.assign(g,(0,Ye._)`${_}.errors`),()=>n.throw(_))),g}function y(){let g=(0,Ye._)`${d}.errors`;return n.assign(g,null),h(Ye.nil),g}function h(g=e.async?(0,Ye._)`await `:Ye.nil){let _=c.opts.passContext?_n.default.this:_n.default.self,w=!("compile"in e&&!a||e.schema===!1);n.assign(u,(0,Ye._)`${g}${(0,i$.callValidateCode)(r,d,_,w)}`,e.modifying)}function m(g){var _;n.if((0,Ye.not)((_=e.valid)!==null&&_!==void 0?_:u),g)}}Qt.funcKeywordCode=a$;function Wp(r){let{gen:e,data:t,it:n}=r;e.if(n.parentData,()=>e.assign(t,(0,Ye._)`${n.parentData}[${n.parentDataProperty}]`))}function c$(r,e){let{gen:t}=r;t.if((0,Ye._)`Array.isArray(${e})`,()=>{t.assign(_n.default.vErrors,(0,Ye._)`${_n.default.vErrors} === null ? ${e} : ${_n.default.vErrors}.concat(${e})`).assign(_n.default.errors,(0,Ye._)`${_n.default.vErrors}.length`),(0,s$.extendErrors)(r)},()=>r.error())}function l$({schemaEnv:r},e){if(e.async&&!r.$async)throw new Error("async keyword in sync schema")}function Gp(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,Ye.stringify)(t)})}function d$(r,e,t=!1){return!e.length||e.some(n=>n==="array"?Array.isArray(r):n==="object"?r&&typeof r=="object"&&!Array.isArray(r):typeof r==n||t&&typeof r=="undefined")}Qt.validSchemaType=d$;function u$({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!=null&&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)}}Qt.validateKeywordUsage=u$});var Xp=A(Br=>{"use strict";Object.defineProperty(Br,"__esModule",{value:!0});Br.extendSubschemaMode=Br.extendSubschemaData=Br.getSubschema=void 0;var Zt=H(),Yp=Q();function f$(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,Zt._)`${r.schemaPath}${(0,Zt.getProperty)(e)}`,errSchemaPath:`${r.errSchemaPath}/${e}`}:{schema:a[t],schemaPath:(0,Zt._)`${r.schemaPath}${(0,Zt.getProperty)(e)}${(0,Zt.getProperty)(t)}`,errSchemaPath:`${r.errSchemaPath}/${e}/${(0,Yp.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')}Br.getSubschema=f$;function p$(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:d,opts:u}=e,f=a.let("data",(0,Zt._)`${e.data}${(0,Zt.getProperty)(t)}`,!0);c(f),r.errorPath=(0,Zt.str)`${l}${(0,Yp.getErrorPath)(t,n,u.jsPropertySyntax)}`,r.parentDataProperty=(0,Zt._)`${t}`,r.dataPathArr=[...d,r.parentDataProperty]}if(i!==void 0){let l=i instanceof Zt.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]}}Br.extendSubschemaData=p$;function h$(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}Br.extendSubschemaMode=h$});var wl=A((zM,Qp)=>{"use strict";Qp.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 eh=A((HM,Zp)=>{"use strict";var zr=Zp.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(){};Po(e,n,i,r,"",r)};zr.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};zr.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};zr.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};zr.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 Po(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 d in n){var u=n[d];if(Array.isArray(u)){if(d in zr.arrayKeywords)for(var f=0;f{"use strict";Object.defineProperty(ot,"__esModule",{value:!0});ot.getSchemaRefs=ot.resolveUrl=ot.normalizeId=ot._getFullPath=ot.getFullPath=ot.inlineRef=void 0;var y$=Q(),g$=wl(),_$=eh(),b$=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function w$(r,e=!0){return typeof r=="boolean"?!0:e===!0?!vl(r):e?th(r)<=e:!1}ot.inlineRef=w$;var v$=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function vl(r){for(let e in r){if(v$.has(e))return!0;let t=r[e];if(Array.isArray(t)&&t.some(vl)||typeof t=="object"&&vl(t))return!0}return!1}function th(r){let e=0;for(let t in r){if(t==="$ref")return 1/0;if(e++,!b$.has(t)&&(typeof r[t]=="object"&&(0,y$.eachItem)(r[t],n=>e+=th(n)),e===1/0))return 1/0}return e}function rh(r,e="",t){t!==!1&&(e=Kn(e));let n=r.parse(e);return nh(r,n)}ot.getFullPath=rh;function nh(r,e){return r.serialize(e).split("#")[0]+"#"}ot._getFullPath=nh;var $$=/#\/?$/;function Kn(r){return r?r.replace($$,""):""}ot.normalizeId=Kn;function S$(r,e,t){return t=Kn(t),r.resolve(e,t)}ot.resolveUrl=S$;var E$=/^[a-z_][-a-z0-9._]*$/i;function A$(r,e){if(typeof r=="boolean")return{};let{schemaId:t,uriResolver:n}=this.opts,i=Kn(r[t]||e),s={"":i},o=rh(n,i,!1),a={},c=new Set;return _$(r,{allKeys:!0},(u,f,p,y)=>{if(y===void 0)return;let h=o+f,m=s[y];typeof u[t]=="string"&&(m=g.call(this,u[t])),_.call(this,u.$anchor),_.call(this,u.$dynamicAnchor),s[f]=m;function g(w){let x=this.opts.uriResolver.resolve;if(w=Kn(m?x(m,w):w),c.has(w))throw d(w);c.add(w);let v=this.refs[w];return typeof v=="string"&&(v=this.refs[v]),typeof v=="object"?l(u,v.schema,w):w!==Kn(h)&&(w[0]==="#"?(l(u,a[w],w),a[w]=u):this.refs[w]=h),w}function _(w){if(typeof w=="string"){if(!E$.test(w))throw new Error(`invalid anchor "${w}"`);g.call(this,`#${w}`)}}}),a;function l(u,f,p){if(f!==void 0&&!g$(u,f))throw d(p)}function d(u){return new Error(`reference "${u}" resolves to more than one schema`)}}ot.getSchemaRefs=A$});var Wn=A(Hr=>{"use strict";Object.defineProperty(Hr,"__esModule",{value:!0});Hr.getData=Hr.KeywordCxt=Hr.validateFunctionCode=void 0;var ch=jp(),ih=Qi(),Sl=pl(),Io=Qi(),k$=zp(),ts=Jp(),$l=Xp(),F=H(),z=vt(),x$=Zi(),_r=Q(),es=Xi();function P$(r){if(uh(r)&&(fh(r),dh(r))){R$(r);return}lh(r,()=>(0,ch.topBoolOrEmptySchema)(r))}Hr.validateFunctionCode=P$;function lh({gen:r,validateName:e,schema:t,schemaEnv:n,opts:i},s){i.code.es5?r.func(e,(0,F._)`${z.default.data}, ${z.default.valCxt}`,n.$async,()=>{r.code((0,F._)`"use strict"; ${sh(t,i)}`),O$(r,i),r.code(s)}):r.func(e,(0,F._)`${z.default.data}, ${I$(i)}`,n.$async,()=>r.code(sh(t,i)).code(s))}function I$(r){return(0,F._)`{${z.default.instancePath}="", ${z.default.parentData}, ${z.default.parentDataProperty}, ${z.default.rootData}=${z.default.data}${r.dynamicRef?(0,F._)`, ${z.default.dynamicAnchors}={}`:F.nil}}={}`}function O$(r,e){r.if(z.default.valCxt,()=>{r.var(z.default.instancePath,(0,F._)`${z.default.valCxt}.${z.default.instancePath}`),r.var(z.default.parentData,(0,F._)`${z.default.valCxt}.${z.default.parentData}`),r.var(z.default.parentDataProperty,(0,F._)`${z.default.valCxt}.${z.default.parentDataProperty}`),r.var(z.default.rootData,(0,F._)`${z.default.valCxt}.${z.default.rootData}`),e.dynamicRef&&r.var(z.default.dynamicAnchors,(0,F._)`${z.default.valCxt}.${z.default.dynamicAnchors}`)},()=>{r.var(z.default.instancePath,(0,F._)`""`),r.var(z.default.parentData,(0,F._)`undefined`),r.var(z.default.parentDataProperty,(0,F._)`undefined`),r.var(z.default.rootData,z.default.data),e.dynamicRef&&r.var(z.default.dynamicAnchors,(0,F._)`{}`)})}function R$(r){let{schema:e,opts:t,gen:n}=r;lh(r,()=>{t.$comment&&e.$comment&&hh(r),L$(r),n.let(z.default.vErrors,null),n.let(z.default.errors,0),t.unevaluated&&T$(r),ph(r),q$(r)})}function T$(r){let{gen:e,validateName:t}=r;r.evaluated=e.const("evaluated",(0,F._)`${t}.evaluated`),e.if((0,F._)`${r.evaluated}.dynamicProps`,()=>e.assign((0,F._)`${r.evaluated}.props`,(0,F._)`undefined`)),e.if((0,F._)`${r.evaluated}.dynamicItems`,()=>e.assign((0,F._)`${r.evaluated}.items`,(0,F._)`undefined`))}function sh(r,e){let t=typeof r=="object"&&r[e.schemaId];return t&&(e.code.source||e.code.process)?(0,F._)`/*# sourceURL=${t} */`:F.nil}function C$(r,e){if(uh(r)&&(fh(r),dh(r))){M$(r,e);return}(0,ch.boolOrEmptySchema)(r,e)}function dh({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 uh(r){return typeof r.schema!="boolean"}function M$(r,e){let{schema:t,gen:n,opts:i}=r;i.$comment&&t.$comment&&hh(r),j$(r),D$(r);let s=n.const("_errs",z.default.errors);ph(r,s),n.var(e,(0,F._)`${s} === ${z.default.errors}`)}function fh(r){(0,_r.checkUnknownRules)(r),N$(r)}function ph(r,e){if(r.opts.jtd)return oh(r,[],!1,e);let t=(0,ih.getSchemaTypes)(r.schema),n=(0,ih.coerceAndCheckDataType)(r,t);oh(r,t,!n,e)}function N$(r){let{schema:e,errSchemaPath:t,opts:n,self:i}=r;e.$ref&&n.ignoreKeywordsWithRef&&(0,_r.schemaHasRulesButRef)(e,i.RULES)&&i.logger.warn(`$ref: keywords ignored in schema at path "${t}"`)}function L$(r){let{schema:e,opts:t}=r;e.default!==void 0&&t.useDefaults&&t.strictSchema&&(0,_r.checkStrictMode)(r,"default is ignored in the schema root")}function j$(r){let e=r.schema[r.opts.schemaId];e&&(r.baseId=(0,x$.resolveUrl)(r.opts.uriResolver,r.baseId,e))}function D$(r){if(r.schema.$async&&!r.schemaEnv.$async)throw new Error("async schema in sync schema")}function hh({gen:r,schemaEnv:e,schema:t,errSchemaPath:n,opts:i}){let s=t.$comment;if(i.$comment===!0)r.code((0,F._)`${z.default.self}.logger.log(${s})`);else if(typeof i.$comment=="function"){let o=(0,F.str)`${n}/$comment`,a=r.scopeValue("root",{ref:e.root});r.code((0,F._)`${z.default.self}.opts.$comment(${s}, ${o}, ${a}.schema)`)}}function q$(r){let{gen:e,schemaEnv:t,validateName:n,ValidationError:i,opts:s}=r;t.$async?e.if((0,F._)`${z.default.errors} === 0`,()=>e.return(z.default.data),()=>e.throw((0,F._)`new ${i}(${z.default.vErrors})`)):(e.assign((0,F._)`${n}.errors`,z.default.vErrors),s.unevaluated&&F$(r),e.return((0,F._)`${z.default.errors} === 0`))}function F$({gen:r,evaluated:e,props:t,items:n}){t instanceof F.Name&&r.assign((0,F._)`${e}.props`,t),n instanceof F.Name&&r.assign((0,F._)`${e}.items`,n)}function oh(r,e,t,n){let{gen:i,schema:s,data:o,allErrors:a,opts:c,self:l}=r,{RULES:d}=l;if(s.$ref&&(c.ignoreKeywordsWithRef||!(0,_r.schemaHasRulesButRef)(s,d))){i.block(()=>yh(r,"$ref",d.all.$ref.definition));return}c.jtd||V$(r,e),i.block(()=>{for(let f of d.rules)u(f);u(d.post)});function u(f){(0,Sl.shouldUseGroup)(s,f)&&(f.type?(i.if((0,Io.checkDataType)(f.type,o,c.strictNumbers)),ah(r,f),e.length===1&&e[0]===f.type&&t&&(i.else(),(0,Io.reportTypeError)(r)),i.endIf()):ah(r,f),a||i.if((0,F._)`${z.default.errors} === ${n||0}`))}}function ah(r,e){let{gen:t,schema:n,opts:{useDefaults:i}}=r;i&&(0,k$.assignDefaults)(r,e.type),t.block(()=>{for(let s of e.rules)(0,Sl.shouldUseRule)(n,s)&&yh(r,s.keyword,s.definition,e.type)})}function V$(r,e){r.schemaEnv.meta||!r.opts.strictTypes||(U$(r,e),r.opts.allowUnionTypes||B$(r,e),z$(r,r.dataTypes))}function U$(r,e){if(e.length){if(!r.dataTypes.length){r.dataTypes=e;return}e.forEach(t=>{mh(r.dataTypes,t)||El(r,`type "${t}" not allowed by context "${r.dataTypes.join(",")}"`)}),K$(r,e)}}function B$(r,e){e.length>1&&!(e.length===2&&e.includes("null"))&&El(r,"use allowUnionTypes to allow union type keyword")}function z$(r,e){let t=r.self.RULES.all;for(let n in t){let i=t[n];if(typeof i=="object"&&(0,Sl.shouldUseRule)(r.schema,i)){let{type:s}=i.definition;s.length&&!s.some(o=>H$(e,o))&&El(r,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function H$(r,e){return r.includes(e)||e==="number"&&r.includes("integer")}function mh(r,e){return r.includes(e)||e==="integer"&&r.includes("number")}function K$(r,e){let t=[];for(let n of r.dataTypes)mh(e,n)?t.push(n):e.includes("integer")&&n==="number"&&t.push("integer");r.dataTypes=t}function El(r,e){let t=r.schemaEnv.baseId+r.errSchemaPath;e+=` at "${t}" (strictTypes)`,(0,_r.checkStrictMode)(r,e,r.opts.strictTypes)}var Oo=class{constructor(e,t,n){if((0,ts.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,_r.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",gh(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,ts.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",z.default.errors))}result(e,t,n){this.failResult((0,F.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,F.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,F._)`${t} !== undefined && (${(0,F.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?es.reportExtraError:es.reportError)(this,this.def.error,t)}$dataError(){(0,es.reportError)(this,this.def.$dataError||es.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,es.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=F.nil){this.gen.block(()=>{this.check$data(e,n),t()})}check$data(e=F.nil,t=F.nil){if(!this.$data)return;let{gen:n,schemaCode:i,schemaType:s,def:o}=this;n.if((0,F.or)((0,F._)`${i} === undefined`,t)),e!==F.nil&&n.assign(e,!0),(s.length||o.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==F.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:t,schemaType:n,def:i,it:s}=this;return(0,F.or)(o(),a());function o(){if(n.length){if(!(t instanceof F.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,F._)`${(0,Io.checkDataTypes)(c,t,s.opts.strictNumbers,Io.DataType.Wrong)}`}return F.nil}function a(){if(i.validateSchema){let c=e.scopeValue("validate$data",{ref:i.validateSchema});return(0,F._)`!${c}(${t})`}return F.nil}}subschema(e,t){let n=(0,$l.getSubschema)(this.it,e);(0,$l.extendSubschemaData)(n,this.it,e),(0,$l.extendSubschemaMode)(n,e);let i={...this.it,...n,items:void 0,props:void 0};return C$(i,t),i}mergeEvaluated(e,t){let{it:n,gen:i}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=_r.mergeEvaluated.props(i,e.props,n.props,t)),n.items!==!0&&e.items!==void 0&&(n.items=_r.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,F.Name)),!0}};Hr.KeywordCxt=Oo;function yh(r,e,t,n){let i=new Oo(r,t,e);"code"in t?t.code(i,n):i.$data&&t.validate?(0,ts.funcKeywordCode)(i,t):"macro"in t?(0,ts.macroKeywordCode)(i,t):(t.compile||t.validate)&&(0,ts.funcKeywordCode)(i,t)}var W$=/^\/(?:[^~]|~0|~1)*$/,G$=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function gh(r,{dataLevel:e,dataNames:t,dataPathArr:n}){let i,s;if(r==="")return z.default.rootData;if(r[0]==="/"){if(!W$.test(r))throw new Error(`Invalid JSON-pointer: ${r}`);i=r,s=z.default.rootData}else{let l=G$.exec(r);if(!l)throw new Error(`Invalid JSON-pointer: ${r}`);let d=+l[1];if(i=l[2],i==="#"){if(d>=e)throw new Error(c("property/index",d));return n[e-d]}if(d>e)throw new Error(c("data",d));if(s=t[e-d],!i)return s}let o=s,a=i.split("/");for(let l of a)l&&(s=(0,F._)`${s}${(0,F.getProperty)((0,_r.unescapeJsonPointer)(l))}`,o=(0,F._)`${o} && ${s}`);return o;function c(l,d){return`Cannot access ${l} ${d} levels up, current level is ${e}`}}Hr.getData=gh});var rs=A(kl=>{"use strict";Object.defineProperty(kl,"__esModule",{value:!0});var Al=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};kl.default=Al});var Gn=A(Il=>{"use strict";Object.defineProperty(Il,"__esModule",{value:!0});var xl=Zi(),Pl=class extends Error{constructor(e,t,n,i){super(i||`can't resolve reference ${n} from id ${t}`),this.missingRef=(0,xl.resolveUrl)(e,t,n),this.missingSchema=(0,xl.normalizeId)((0,xl.getFullPath)(e,this.missingRef))}};Il.default=Pl});var ns=A(St=>{"use strict";Object.defineProperty(St,"__esModule",{value:!0});St.resolveSchema=St.getCompilingSchema=St.resolveRef=St.compileSchema=St.SchemaEnv=void 0;var Tt=H(),J$=rs(),bn=vt(),Ct=Zi(),_h=Q(),Y$=Wn(),Jn=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,Ct.normalizeId)(n==null?void 0:n[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n==null?void 0:n.$async,this.refs={}}};St.SchemaEnv=Jn;function Rl(r){let e=bh.call(this,r);if(e)return e;let t=(0,Ct.getFullPath)(this.opts.uriResolver,r.root.baseId),{es5:n,lines:i}=this.opts.code,{ownProperties:s}=this.opts,o=new Tt.CodeGen(this.scope,{es5:n,lines:i,ownProperties:s}),a;r.$async&&(a=o.scopeValue("Error",{ref:J$.default,code:(0,Tt._)`require("ajv/dist/runtime/validation_error").default`}));let c=o.scopeName("validate");r.validateName=c;let l={gen:o,allErrors:this.opts.allErrors,data:bn.default.data,parentData:bn.default.parentData,parentDataProperty:bn.default.parentDataProperty,dataNames:[bn.default.data],dataPathArr:[Tt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:o.scopeValue("schema",this.opts.code.source===!0?{ref:r.schema,code:(0,Tt.stringify)(r.schema)}:{ref:r.schema}),validateName:c,ValidationError:a,schema:r.schema,schemaEnv:r,rootId:t,baseId:r.baseId||t,schemaPath:Tt.nil,errSchemaPath:r.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Tt._)`""`,opts:this.opts,self:this},d;try{this._compilations.add(r),(0,Y$.validateFunctionCode)(l),o.optimize(this.opts.code.optimize);let u=o.toString();d=`${o.scopeRefs(bn.default.scope)}return ${u}`,this.opts.code.process&&(d=this.opts.code.process(d,r));let p=new Function(`${bn.default.self}`,`${bn.default.scope}`,d)(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:u,scopeValues:o._values}),this.opts.unevaluated){let{props:y,items:h}=l;p.evaluated={props:y instanceof Tt.Name?void 0:y,items:h instanceof Tt.Name?void 0:h,dynamicProps:y instanceof Tt.Name,dynamicItems:h instanceof Tt.Name},p.source&&(p.source.evaluated=(0,Tt.stringify)(p.evaluated))}return r.validate=p,r}catch(u){throw delete r.validate,delete r.validateName,d&&this.logger.error("Error compiling schema, function code:",d),u}finally{this._compilations.delete(r)}}St.compileSchema=Rl;function X$(r,e,t){var n;t=(0,Ct.resolveUrl)(this.opts.uriResolver,e,t);let i=r.refs[t];if(i)return i;let s=eS.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 Jn({schema:o,schemaId:a,root:r,baseId:e}))}if(s!==void 0)return r.refs[t]=Q$.call(this,s)}St.resolveRef=X$;function Q$(r){return(0,Ct.inlineRef)(r.schema,this.opts.inlineRefs)?r.schema:r.validate?r:Rl.call(this,r)}function bh(r){for(let e of this._compilations)if(Z$(e,r))return e}St.getCompilingSchema=bh;function Z$(r,e){return r.schema===e.schema&&r.root===e.root&&r.baseId===e.baseId}function eS(r,e){let t;for(;typeof(t=this.refs[e])=="string";)e=t;return t||this.schemas[e]||Ro.call(this,r,e)}function Ro(r,e){let t=this.opts.uriResolver.parse(e),n=(0,Ct._getFullPath)(this.opts.uriResolver,t),i=(0,Ct.getFullPath)(this.opts.uriResolver,r.baseId,void 0);if(Object.keys(r.schema).length>0&&n===i)return Ol.call(this,t,r);let s=(0,Ct.normalizeId)(n),o=this.refs[s]||this.schemas[s];if(typeof o=="string"){let a=Ro.call(this,r,o);return typeof(a==null?void 0:a.schema)!="object"?void 0:Ol.call(this,t,a)}if(typeof(o==null?void 0:o.schema)=="object"){if(o.validate||Rl.call(this,o),s===(0,Ct.normalizeId)(e)){let{schema:a}=o,{schemaId:c}=this.opts,l=a[c];return l&&(i=(0,Ct.resolveUrl)(this.opts.uriResolver,i,l)),new Jn({schema:a,schemaId:c,root:r,baseId:i})}return Ol.call(this,t,o)}}St.resolveSchema=Ro;var tS=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Ol(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,_h.unescapeFragment)(a)];if(c===void 0)return;t=c;let l=typeof t=="object"&&t[this.opts.schemaId];!tS.has(a)&&l&&(e=(0,Ct.resolveUrl)(this.opts.uriResolver,e,l))}let s;if(typeof t!="boolean"&&t.$ref&&!(0,_h.schemaHasRulesButRef)(t,this.RULES)){let a=(0,Ct.resolveUrl)(this.opts.uriResolver,e,t.$ref);s=Ro.call(this,n,a)}let{schemaId:o}=this.opts;if(s=s||new Jn({schema:t,schemaId:o,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var wh=A((XM,rS)=>{rS.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 Ml=A((QM,kh)=>{"use strict";var nS=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),$h=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),Tl=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),Sh=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),iS=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function Cl(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 sS=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function vh(r){return r.length=0,!0}function oS(r,e,t){if(r.length){let n=Cl(r);if(n!=="")e.push(n);else return t.error=!0,!1;r.length=0}return!0}function aS(r){let e=0,t={error:!1,address:"",zone:""},n=[],i=[],s=!1,o=!1,a=oS;for(let c=0;c7){t.error=!0;break}c>0&&r[c-1]===":"&&(s=!0),n.push(":");continue}else if(l==="%"){if(!a(i,n,t))break;a=vh}else{i.push(l);continue}}return i.length&&(a===vh?t.zone=i.join(""):o?n.push(i.join("")):n.push(Cl(i))),t.address=n.join(""),t}function Eh(r){if(cS(r,":")<2)return{host:r,isIPV6:!1};let e=aS(r);if(e.error)return{host:r,isIPV6:!1};{let t=e.address,n=e.address;return e.zone&&(t+="%"+e.zone,n+="%25"+e.zone),{host:t,isIPV6:!0,escapedHost:n}}}function cS(r,e){let t=0;for(let n=0;ndS[n])}function pS(r,e=!1){if(r.indexOf("%")===-1)return r;let t="";for(let n=0;n{"use strict";var{isUUID:gS}=Ml(),_S=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,bS=["http","https","ws","wss","urn","urn:uuid"];function wS(r){return bS.indexOf(r)!==-1}function Nl(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 xh(r){return r.host||(r.error=r.error||"HTTP URIs must have a host."),r}function Ph(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 vS(r){return r.secure=Nl(r),r.resourceName=(r.path||"/")+(r.query?"?"+r.query:""),r.path=void 0,r.query=void 0,r}function $S(r){if((r.port===(Nl(r)?443:80)||r.port==="")&&(r.port=void 0),typeof r.secure=="boolean"&&(r.scheme=r.secure?"wss":"ws",r.secure=void 0),r.resourceName){let[e,t]=r.resourceName.split("?");r.path=e&&e!=="/"?e:void 0,r.query=t,r.resourceName=void 0}return r.fragment=void 0,r}function SS(r,e){if(!r.path)return r.error="URN can not be parsed",r;let t=r.path.match(_S);if(t){let n=e.scheme||r.scheme||"urn";r.nid=t[1].toLowerCase(),r.nss=t[2];let i=`${n}:${e.nid||r.nid}`,s=Ll(i);r.path=void 0,s&&(r=s.parse(r,e))}else r.error=r.error||"URN can not be parsed.";return r}function ES(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=Ll(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 AS(r,e){let t=r;return t.uuid=t.nss,t.nss=void 0,!e.tolerant&&(!t.uuid||!gS(t.uuid))&&(t.error=t.error||"UUID is not valid."),t}function kS(r){let e=r;return e.nss=(r.uuid||"").toLowerCase(),e}var Ih={scheme:"http",domainHost:!0,parse:xh,serialize:Ph},xS={scheme:"https",domainHost:Ih.domainHost,parse:xh,serialize:Ph},To={scheme:"ws",domainHost:!0,parse:vS,serialize:$S},PS={scheme:"wss",domainHost:To.domainHost,parse:To.parse,serialize:To.serialize},IS={scheme:"urn",parse:SS,serialize:ES,skipNormalize:!0},OS={scheme:"urn:uuid",parse:AS,serialize:kS,skipNormalize:!0},Co={http:Ih,https:xS,ws:To,wss:PS,urn:IS,"urn:uuid":OS};Object.setPrototypeOf(Co,null);function Ll(r){return r&&(Co[r]||Co[r.toLowerCase()])||void 0}Oh.exports={wsIsSecure:Nl,SCHEMES:Co,isValidSchemeName:wS,getSchemeHandler:Ll}});var Lh=A((eN,Lo)=>{"use strict";var{normalizeIPv6:RS,removeDotSegments:is,recomposeAuthority:TS,normalizePercentEncoding:CS,normalizePathEncoding:MS,escapePreservingEscapes:NS,reescapeHostDelimiters:LS,isIPv4:jS,nonSimpleDomain:DS}=Ml(),{SCHEMES:qS,getSchemeHandler:Ch}=Rh();function FS(r,e){return typeof r=="string"?r=WS(r,e):typeof r=="object"&&(r=No(wn(r,e),e)),r}function VS(r,e,t){let n=t?Object.assign({scheme:"null"},t):{scheme:"null"},{parsed:i,malformedAuthorityOrPort:s}=Mo(r,n),{parsed:o,malformedAuthorityOrPort:a}=Mo(e,n);if(s||a)throw new Error(i.error||o.error||"URI is malformed.");let c=Mh(i,o,n,!0);return n.skipEscape=!0,wn(c,n)}function Mh(r,e,t,n){let i={};return n||(r=No(wn(r,t),t),e=No(wn(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=is(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=is(e.path||""),i.query=e.query):(e.path?(e.path[0]==="/"?i.path=is(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=is(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 US(r,e,t){let n=Th(r,t),i=Th(e,t);return n!==void 0&&i!==void 0&&n.toLowerCase()===i.toLowerCase()}function wn(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=[],s=Ch(n.scheme||t.scheme);s&&s.serialize&&s.serialize(t,n),t.path!==void 0&&(n.skipEscape?t.path=CS(t.path):(t.path=NS(t.path),t.scheme!==void 0&&(t.path=t.path.split("%3A").join(":")))),n.reference!=="suffix"&&t.scheme&&i.push(t.scheme,":");let o=TS(t);if(o!==void 0&&(n.reference!=="suffix"&&i.push("//"),i.push(o),t.path&&t.path[0]!=="/"&&i.push("/")),t.path!==void 0){let a=t.path;!n.absolutePath&&(!s||!s.absolutePath)&&(a=is(a)),o===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),i.push(a)}return t.query!==void 0&&i.push("?",t.query),t.fragment!==void 0&&i.push("#",t.fragment),i.join("")}var BS=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,zS=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,HS=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function KS(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 Mo(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;t.reference==="suffix"&&(t.scheme?r=t.scheme+":"+r:r="//"+r);let o=r.match(zS);o!==null&&o[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",i=!0);let a=r.match(HS);if(a!==null){let l=a[1],d=l.replace(/[\t\n\r]/g,"");d.length>=2&&(d.slice(0,2)!=="//"?(n.error=n.error||"URI authority must not contain a literal backslash.",i=!0):l.length!==d.length&&(n.error=n.error||"URI authority introducer must not contain whitespace.",i=!0))}let c=r.match(BS);if(c){n.scheme=c[1],n.userinfo=c[3],n.host=c[4],n.port=parseInt(c[5],10),n.path=c[6]||"",n.query=c[7],n.fragment=c[8],isNaN(n.port)&&(n.port=c[5]);let l=KS(n,c);if(l!==void 0&&(n.error=n.error||l,i=!0),n.host)if(jS(n.host)===!1){let f=RS(n.host);n.host=f.host.toLowerCase(),s=f.isIPV6}else s=!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 d=Ch(t.scheme||n.scheme);if(!t.unicodeSupport&&(!d||!d.unicodeSupport)&&n.host&&(t.domainHost||d&&d.domainHost)&&s===!1&&DS(n.host))try{n.host=new URL("http://"+n.host).hostname}catch(u){n.error=n.error||"Host's domain name can not be converted to ASCII: "+u}if((!d||d&&!d.skipNormalize)&&(r.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=LS(unescape(n.host),s))),n.path&&(n.path=MS(n.path)),n.fragment))try{n.fragment=encodeURI(decodeURIComponent(n.fragment))}catch(u){n.error=n.error||"URI malformed"}d&&d.parse&&d.parse(n,t)}else n.error=n.error||"URI can not be parsed.";return{parsed:n,malformedAuthorityOrPort:i}}function No(r,e){return Mo(r,e).parsed}function WS(r,e){return Nh(r,e).normalized}function Nh(r,e){let{parsed:t,malformedAuthorityOrPort:n}=Mo(r,e);return{normalized:n?r:wn(t,e),malformedAuthorityOrPort:n}}function Th(r,e){if(typeof r=="string"){let{normalized:t,malformedAuthorityOrPort:n}=Nh(r,e);return n?void 0:t}if(typeof r=="object")return wn(r,e)}var jl={SCHEMES:qS,normalize:FS,resolve:VS,resolveComponent:Mh,equal:US,serialize:wn,parse:No};Lo.exports=jl;Lo.exports.default=jl;Lo.exports.fastUri=jl});var Dh=A(Dl=>{"use strict";Object.defineProperty(Dl,"__esModule",{value:!0});var jh=Lh();jh.code='require("ajv/dist/runtime/uri").default';Dl.default=jh});var Vl=A(Le=>{"use strict";Object.defineProperty(Le,"__esModule",{value:!0});Le.CodeGen=Le.Name=Le.nil=Le.stringify=Le.str=Le._=Le.KeywordCxt=void 0;var GS=Wn();Object.defineProperty(Le,"KeywordCxt",{enumerable:!0,get:function(){return GS.KeywordCxt}});var Yn=H();Object.defineProperty(Le,"_",{enumerable:!0,get:function(){return Yn._}});Object.defineProperty(Le,"str",{enumerable:!0,get:function(){return Yn.str}});Object.defineProperty(Le,"stringify",{enumerable:!0,get:function(){return Yn.stringify}});Object.defineProperty(Le,"nil",{enumerable:!0,get:function(){return Yn.nil}});Object.defineProperty(Le,"Name",{enumerable:!0,get:function(){return Yn.Name}});Object.defineProperty(Le,"CodeGen",{enumerable:!0,get:function(){return Yn.CodeGen}});var JS=rs(),Bh=Gn(),YS=fl(),ss=ns(),XS=H(),os=Zi(),jo=Qi(),Fl=Q(),qh=wh(),QS=Dh(),zh=(r,e)=>new RegExp(r,e);zh.code="new RegExp";var ZS=["removeAdditional","useDefaults","coerceTypes"],eE=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),tE={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."},rE={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Fh=200;function nE(r){var e,t,n,i,s,o,a,c,l,d,u,f,p,y,h,m,g,_,w,x,v,P,O,$,R;let S=r.strict,U=(e=r.code)===null||e===void 0?void 0:e.optimize,B=U===!0||U===void 0?1:U||0,T=(n=(t=r.code)===null||t===void 0?void 0:t.regExp)!==null&&n!==void 0?n:zh,E=(i=r.uriResolver)!==null&&i!==void 0?i:QS.default;return{strictSchema:(o=(s=r.strictSchema)!==null&&s!==void 0?s:S)!==null&&o!==void 0?o:!0,strictNumbers:(c=(a=r.strictNumbers)!==null&&a!==void 0?a:S)!==null&&c!==void 0?c:!0,strictTypes:(d=(l=r.strictTypes)!==null&&l!==void 0?l:S)!==null&&d!==void 0?d:"log",strictTuples:(f=(u=r.strictTuples)!==null&&u!==void 0?u:S)!==null&&f!==void 0?f:"log",strictRequired:(y=(p=r.strictRequired)!==null&&p!==void 0?p:S)!==null&&y!==void 0?y:!1,code:r.code?{...r.code,optimize:B,regExp:T}:{optimize:B,regExp:T},loopRequired:(h=r.loopRequired)!==null&&h!==void 0?h:Fh,loopEnum:(m=r.loopEnum)!==null&&m!==void 0?m:Fh,meta:(g=r.meta)!==null&&g!==void 0?g:!0,messages:(_=r.messages)!==null&&_!==void 0?_:!0,inlineRefs:(w=r.inlineRefs)!==null&&w!==void 0?w:!0,schemaId:(x=r.schemaId)!==null&&x!==void 0?x:"$id",addUsedSchema:(v=r.addUsedSchema)!==null&&v!==void 0?v:!0,validateSchema:(P=r.validateSchema)!==null&&P!==void 0?P:!0,validateFormats:(O=r.validateFormats)!==null&&O!==void 0?O:!0,unicodeRegExp:($=r.unicodeRegExp)!==null&&$!==void 0?$:!0,int32range:(R=r.int32range)!==null&&R!==void 0?R:!0,uriResolver:E}}var as=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,...nE(e)};let{es5:t,lines:n}=this.opts.code;this.scope=new XS.ValueScope({scope:{},prefixes:eE,es5:t,lines:n}),this.logger=lE(e.logger);let i=e.validateFormats;e.validateFormats=!1,this.RULES=(0,YS.getRules)(),Vh.call(this,tE,e,"NOT SUPPORTED"),Vh.call(this,rE,e,"DEPRECATED","warn"),this._metaOpts=aE.call(this),e.formats&&sE.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&oE.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),iE.call(this),e.validateFormats=i}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:t,schemaId:n}=this.opts,i=qh;n==="id"&&(i={...qh},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(d,u){await s.call(this,d.$schema);let f=this._addSchema(d,u);return f.validate||o.call(this,f)}async function s(d){d&&!this.getSchema(d)&&await i.call(this,{$ref:d},!0)}async function o(d){try{return this._compileSchemaEnv(d)}catch(u){if(!(u instanceof Bh.default))throw u;return a.call(this,u),await c.call(this,u.missingSchema),o.call(this,d)}}function a({missingSchema:d,missingRef:u}){if(this.refs[d])throw new Error(`AnySchema ${d} is loaded but ${u} cannot be resolved`)}async function c(d){let u=await l.call(this,d);this.refs[d]||await s.call(this,u.$schema),this.refs[d]||this.addSchema(u,d,t)}async function l(d){let u=this._loading[d];if(u)return u;try{return await(this._loading[d]=n(d))}finally{delete this._loading[d]}}}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,os.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=Uh.call(this,e))=="string";)e=t;if(t===void 0){let{schemaId:n}=this.opts,i=new ss.SchemaEnv({schema:{},schemaId:n});if(t=ss.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=Uh.call(this,e);return typeof t=="object"&&this._cache.delete(t.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let t=e;this._cache.delete(t);let n=e[this.opts.schemaId];return n&&(n=(0,os.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let t of e)this.addKeyword(t);return this}addKeyword(e,t){let n;if(typeof e=="string")n=e,typeof t=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),t.keyword=n);else if(typeof e=="object"&&t===void 0){if(t=e,n=t.keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(uE.call(this,n,t),!t)return(0,Fl.eachItem)(n,s=>ql.call(this,s)),this;pE.call(this,t);let i={...t,type:(0,jo.getJSONTypes)(t.type),schemaType:(0,jo.getJSONTypes)(t.schemaType)};return(0,Fl.eachItem)(n,i.type.length===0?s=>ql.call(this,s,i):s=>i.type.forEach(o=>ql.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,d=o[a];l&&d&&(o[a]=Hh(d))}}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,os.normalizeId)(o||n);let l=os.getSchemaRefs.call(this,e,n);return c=new ss.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):ss.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{ss.compileSchema.call(this,e)}finally{this.opts=t}}};as.ValidationError=JS.default;as.MissingRefError=Bh.default;Le.default=as;function Vh(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 Uh(r){return r=(0,os.normalizeId)(r),this.schemas[r]||this.refs[r]}function iE(){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 sE(){for(let r in this.opts.formats){let e=this.opts.formats[r];e&&this.addFormat(r,e)}}function oE(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 aE(){let r={...this.opts};for(let e of ZS)delete r[e];return r}var cE={log(){},warn(){},error(){}};function lE(r){if(r===!1)return cE;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 dE=/^[a-z_$][a-z0-9_$:-]*$/i;function uE(r,e){let{RULES:t}=this;if((0,Fl.eachItem)(r,n=>{if(t.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!dE.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 ql(r,e,t){var n;let i=e==null?void 0: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,jo.getJSONTypes)(e.type),schemaType:(0,jo.getJSONTypes)(e.schemaType)}};e.before?fE.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 fE(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 pE(r){let{metaSchema:e}=r;e!==void 0&&(r.$data&&this.opts.$data&&(e=Hh(e)),r.validateSchema=this.compile(e,!0))}var hE={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Hh(r){return{anyOf:[r,hE]}}});var Kh=A(Ul=>{"use strict";Object.defineProperty(Ul,"__esModule",{value:!0});var mE={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Ul.default=mE});var Fo=A(vn=>{"use strict";Object.defineProperty(vn,"__esModule",{value:!0});vn.callRef=vn.getValidate=void 0;var yE=Gn(),Wh=$t(),at=H(),Xn=vt(),Gh=ns(),Do=Q(),gE={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 u();let d=Gh.resolveRef.call(c,l,i,t);if(d===void 0)throw new yE.default(n.opts.uriResolver,i,t);if(d instanceof Gh.SchemaEnv)return f(d);return p(d);function u(){if(s===l)return qo(r,o,s,s.$async);let y=e.scopeValue("root",{ref:l});return qo(r,(0,at._)`${y}.validate`,l,l.$async)}function f(y){let h=Jh(r,y);qo(r,h,y,y.$async)}function p(y){let h=e.scopeValue("schema",a.code.source===!0?{ref:y,code:(0,at.stringify)(y)}:{ref:y}),m=e.name("valid"),g=r.subschema({schema:y,dataTypes:[],schemaPath:at.nil,topSchemaRef:h,errSchemaPath:t},m);r.mergeEvaluated(g),r.ok(m)}}};function Jh(r,e){let{gen:t}=r;return e.validate?t.scopeValue("validate",{ref:e.validate}):(0,at._)`${t.scopeValue("wrapper",{ref:e})}.validate`}vn.getValidate=Jh;function qo(r,e,t,n){let{gen:i,it:s}=r,{allErrors:o,schemaEnv:a,opts:c}=s,l=c.passContext?Xn.default.this:at.nil;n?d():u();function d(){if(!a.$async)throw new Error("async schema referenced by sync schema");let y=i.let("valid");i.try(()=>{i.code((0,at._)`await ${(0,Wh.callValidateCode)(r,e,l)}`),p(e),o||i.assign(y,!0)},h=>{i.if((0,at._)`!(${h} instanceof ${s.ValidationError})`,()=>i.throw(h)),f(h),o||i.assign(y,!1)}),r.ok(y)}function u(){r.result((0,Wh.callValidateCode)(r,e,l),()=>p(e),()=>f(e))}function f(y){let h=(0,at._)`${y}.errors`;i.assign(Xn.default.vErrors,(0,at._)`${Xn.default.vErrors} === null ? ${h} : ${Xn.default.vErrors}.concat(${h})`),i.assign(Xn.default.errors,(0,at._)`${Xn.default.vErrors}.length`)}function p(y){var h;if(!s.opts.unevaluated)return;let m=(h=t==null?void 0:t.validate)===null||h===void 0?void 0:h.evaluated;if(s.props!==!0)if(m&&!m.dynamicProps)m.props!==void 0&&(s.props=Do.mergeEvaluated.props(i,m.props,s.props));else{let g=i.var("props",(0,at._)`${y}.evaluated.props`);s.props=Do.mergeEvaluated.props(i,g,s.props,at.Name)}if(s.items!==!0)if(m&&!m.dynamicItems)m.items!==void 0&&(s.items=Do.mergeEvaluated.items(i,m.items,s.items));else{let g=i.var("items",(0,at._)`${y}.evaluated.items`);s.items=Do.mergeEvaluated.items(i,g,s.items,at.Name)}}}vn.callRef=qo;vn.default=gE});var zl=A(Bl=>{"use strict";Object.defineProperty(Bl,"__esModule",{value:!0});var _E=Kh(),bE=Fo(),wE=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",_E.default,bE.default];Bl.default=wE});var Yh=A(Hl=>{"use strict";Object.defineProperty(Hl,"__esModule",{value:!0});var Vo=H(),Kr=Vo.operators,Uo={maximum:{okStr:"<=",ok:Kr.LTE,fail:Kr.GT},minimum:{okStr:">=",ok:Kr.GTE,fail:Kr.LT},exclusiveMaximum:{okStr:"<",ok:Kr.LT,fail:Kr.GTE},exclusiveMinimum:{okStr:">",ok:Kr.GT,fail:Kr.LTE}},vE={message:({keyword:r,schemaCode:e})=>(0,Vo.str)`must be ${Uo[r].okStr} ${e}`,params:({keyword:r,schemaCode:e})=>(0,Vo._)`{comparison: ${Uo[r].okStr}, limit: ${e}}`},$E={keyword:Object.keys(Uo),type:"number",schemaType:"number",$data:!0,error:vE,code(r){let{keyword:e,data:t,schemaCode:n}=r;r.fail$data((0,Vo._)`${t} ${Uo[e].fail} ${n} || isNaN(${t})`)}};Hl.default=$E});var Xh=A(Kl=>{"use strict";Object.defineProperty(Kl,"__esModule",{value:!0});var cs=H(),SE={message:({schemaCode:r})=>(0,cs.str)`must be multiple of ${r}`,params:({schemaCode:r})=>(0,cs._)`{multipleOf: ${r}}`},EE={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:SE,code(r){let{gen:e,data:t,schemaCode:n,it:i}=r,s=i.opts.multipleOfPrecision,o=e.let("res"),a=s?(0,cs._)`Math.abs(Math.round(${o}) - ${o}) > 1e-${s}`:(0,cs._)`${o} !== parseInt(${o})`;r.fail$data((0,cs._)`(${n} === 0 || (${o} = ${t}/${n}, ${a}))`)}};Kl.default=EE});var Zh=A(Wl=>{"use strict";Object.defineProperty(Wl,"__esModule",{value:!0});function Qh(r){let e=r.length,t=0,n=0,i;for(;n=55296&&i<=56319&&n{"use strict";Object.defineProperty(Gl,"__esModule",{value:!0});var $n=H(),AE=Q(),kE=Zh(),xE={message({keyword:r,schemaCode:e}){let t=r==="maxLength"?"more":"fewer";return(0,$n.str)`must NOT have ${t} than ${e} characters`},params:({schemaCode:r})=>(0,$n._)`{limit: ${r}}`},PE={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:xE,code(r){let{keyword:e,data:t,schemaCode:n,it:i}=r,s=e==="maxLength"?$n.operators.GT:$n.operators.LT,o=i.opts.unicode===!1?(0,$n._)`${t}.length`:(0,$n._)`${(0,AE.useFunc)(r.gen,kE.default)}(${t})`;r.fail$data((0,$n._)`${o} ${s} ${n}`)}};Gl.default=PE});var tm=A(Jl=>{"use strict";Object.defineProperty(Jl,"__esModule",{value:!0});var IE=$t(),OE=Q(),Qn=H(),RE={message:({schemaCode:r})=>(0,Qn.str)`must match pattern "${r}"`,params:({schemaCode:r})=>(0,Qn._)`{pattern: ${r}}`},TE={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:RE,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,Qn._)`new RegExp`:(0,OE.useFunc)(e,c),d=e.let("valid");e.try(()=>e.assign(d,(0,Qn._)`${l}(${s}, ${a}).test(${t})`),()=>e.assign(d,!1)),r.fail$data((0,Qn._)`!${d}`)}else{let c=(0,IE.usePattern)(r,i);r.fail$data((0,Qn._)`!${c}.test(${t})`)}}};Jl.default=TE});var rm=A(Yl=>{"use strict";Object.defineProperty(Yl,"__esModule",{value:!0});var ls=H(),CE={message({keyword:r,schemaCode:e}){let t=r==="maxProperties"?"more":"fewer";return(0,ls.str)`must NOT have ${t} than ${e} properties`},params:({schemaCode:r})=>(0,ls._)`{limit: ${r}}`},ME={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:CE,code(r){let{keyword:e,data:t,schemaCode:n}=r,i=e==="maxProperties"?ls.operators.GT:ls.operators.LT;r.fail$data((0,ls._)`Object.keys(${t}).length ${i} ${n}`)}};Yl.default=ME});var nm=A(Xl=>{"use strict";Object.defineProperty(Xl,"__esModule",{value:!0});var ds=$t(),us=H(),NE=Q(),LE={message:({params:{missingProperty:r}})=>(0,us.str)`must have required property '${r}'`,params:({params:{missingProperty:r}})=>(0,us._)`{missingProperty: ${r}}`},jE={keyword:"required",type:"object",schemaType:"array",$data:!0,error:LE,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():d(),a.strictRequired){let p=r.parentSchema.properties,{definedProperties:y}=r.it;for(let h of t)if((p==null?void 0:p[h])===void 0&&!y.has(h)){let m=o.schemaEnv.baseId+o.errSchemaPath,g=`required property "${h}" is not defined at "${m}" (strictRequired)`;(0,NE.checkStrictMode)(o,g,o.opts.strictRequired)}}function l(){if(c||s)r.block$data(us.nil,u);else for(let p of t)(0,ds.checkReportMissingProp)(r,p)}function d(){let p=e.let("missing");if(c||s){let y=e.let("valid",!0);r.block$data(y,()=>f(p,y)),r.ok(y)}else e.if((0,ds.checkMissingProp)(r,t,p)),(0,ds.reportMissingProp)(r,p),e.else()}function u(){e.forOf("prop",n,p=>{r.setParams({missingProperty:p}),e.if((0,ds.noPropertyInData)(e,i,p,a.ownProperties),()=>r.error())})}function f(p,y){r.setParams({missingProperty:p}),e.forOf(p,n,()=>{e.assign(y,(0,ds.propertyInData)(e,i,p,a.ownProperties)),e.if((0,us.not)(y),()=>{r.error(),e.break()})},us.nil)}}};Xl.default=jE});var im=A(Ql=>{"use strict";Object.defineProperty(Ql,"__esModule",{value:!0});var fs=H(),DE={message({keyword:r,schemaCode:e}){let t=r==="maxItems"?"more":"fewer";return(0,fs.str)`must NOT have ${t} than ${e} items`},params:({schemaCode:r})=>(0,fs._)`{limit: ${r}}`},qE={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:DE,code(r){let{keyword:e,data:t,schemaCode:n}=r,i=e==="maxItems"?fs.operators.GT:fs.operators.LT;r.fail$data((0,fs._)`${t}.length ${i} ${n}`)}};Ql.default=qE});var Bo=A(Zl=>{"use strict";Object.defineProperty(Zl,"__esModule",{value:!0});var sm=wl();sm.code='require("ajv/dist/runtime/equal").default';Zl.default=sm});var om=A(td=>{"use strict";Object.defineProperty(td,"__esModule",{value:!0});var ed=Qi(),je=H(),FE=Q(),VE=Bo(),UE={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}}`},BE={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:UE,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,ed.getSchemaTypes)(s.items):[];r.block$data(c,d,(0,je._)`${o} === false`),r.ok(c);function d(){let y=e.let("i",(0,je._)`${t}.length`),h=e.let("j");r.setParams({i:y,j:h}),e.assign(c,!0),e.if((0,je._)`${y} > 1`,()=>(u()?f:p)(y,h))}function u(){return l.length>0&&!l.some(y=>y==="object"||y==="array")}function f(y,h){let m=e.name("item"),g=(0,ed.checkDataTypes)(l,m,a.opts.strictNumbers,ed.DataType.Wrong),_=e.const("indices",(0,je._)`{}`);e.for((0,je._)`;${y}--;`,()=>{e.let(m,(0,je._)`${t}[${y}]`),e.if(g,(0,je._)`continue`),l.length>1&&e.if((0,je._)`typeof ${m} == "string"`,(0,je._)`${m} += "_"`),e.if((0,je._)`typeof ${_}[${m}] == "number"`,()=>{e.assign(h,(0,je._)`${_}[${m}]`),r.error(),e.assign(c,!1).break()}).code((0,je._)`${_}[${m}] = ${y}`)})}function p(y,h){let m=(0,FE.useFunc)(e,VE.default),g=e.name("outer");e.label(g).for((0,je._)`;${y}--;`,()=>e.for((0,je._)`${h} = ${y}; ${h}--;`,()=>e.if((0,je._)`${m}(${t}[${y}], ${t}[${h}])`,()=>{r.error(),e.assign(c,!1).break(g)})))}}};td.default=BE});var am=A(nd=>{"use strict";Object.defineProperty(nd,"__esModule",{value:!0});var rd=H(),zE=Q(),HE=Bo(),KE={message:"must be equal to constant",params:({schemaCode:r})=>(0,rd._)`{allowedValue: ${r}}`},WE={keyword:"const",$data:!0,error:KE,code(r){let{gen:e,data:t,$data:n,schemaCode:i,schema:s}=r;n||s&&typeof s=="object"?r.fail$data((0,rd._)`!${(0,zE.useFunc)(e,HE.default)}(${t}, ${i})`):r.fail((0,rd._)`${s} !== ${t}`)}};nd.default=WE});var cm=A(id=>{"use strict";Object.defineProperty(id,"__esModule",{value:!0});var ps=H(),GE=Q(),JE=Bo(),YE={message:"must be equal to one of the allowed values",params:({schemaCode:r})=>(0,ps._)`{allowedValues: ${r}}`},XE={keyword:"enum",schemaType:"array",$data:!0,error:YE,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!=null?c:c=(0,GE.useFunc)(e,JE.default),d;if(a||n)d=e.let("valid"),r.block$data(d,u);else{if(!Array.isArray(i))throw new Error("ajv implementation error");let p=e.const("vSchema",s);d=(0,ps.or)(...i.map((y,h)=>f(p,h)))}r.pass(d);function u(){e.assign(d,!1),e.forOf("v",s,p=>e.if((0,ps._)`${l()}(${t}, ${p})`,()=>e.assign(d,!0).break()))}function f(p,y){let h=i[y];return typeof h=="object"&&h!==null?(0,ps._)`${l()}(${t}, ${p}[${y}])`:(0,ps._)`${t} === ${h}`}}};id.default=XE});var od=A(sd=>{"use strict";Object.defineProperty(sd,"__esModule",{value:!0});var QE=Yh(),ZE=Xh(),eA=em(),tA=tm(),rA=rm(),nA=nm(),iA=im(),sA=om(),oA=am(),aA=cm(),cA=[QE.default,ZE.default,eA.default,tA.default,rA.default,nA.default,iA.default,sA.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},oA.default,aA.default];sd.default=cA});var cd=A(hs=>{"use strict";Object.defineProperty(hs,"__esModule",{value:!0});hs.validateAdditionalItems=void 0;var Sn=H(),ad=Q(),lA={message:({params:{len:r}})=>(0,Sn.str)`must NOT have more than ${r} items`,params:({params:{len:r}})=>(0,Sn._)`{limit: ${r}}`},dA={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:lA,code(r){let{parentSchema:e,it:t}=r,{items:n}=e;if(!Array.isArray(n)){(0,ad.checkStrictMode)(t,'"additionalItems" is ignored when "items" is not an array of schemas');return}lm(r,n)}};function lm(r,e){let{gen:t,schema:n,data:i,keyword:s,it:o}=r;o.items=!0;let a=t.const("len",(0,Sn._)`${i}.length`);if(n===!1)r.setParams({len:e.length}),r.pass((0,Sn._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,ad.alwaysValidSchema)(o,n)){let l=t.var("valid",(0,Sn._)`${a} <= ${e.length}`);t.if((0,Sn.not)(l),()=>c(l)),r.ok(l)}function c(l){t.forRange("i",e.length,a,d=>{r.subschema({keyword:s,dataProp:d,dataPropType:ad.Type.Num},l),o.allErrors||t.if((0,Sn.not)(l),()=>t.break())})}}hs.validateAdditionalItems=lm;hs.default=dA});var ld=A(ms=>{"use strict";Object.defineProperty(ms,"__esModule",{value:!0});ms.validateTuple=void 0;var dm=H(),zo=Q(),uA=$t(),fA={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(r){let{schema:e,it:t}=r;if(Array.isArray(e))return um(r,"additionalItems",e);t.items=!0,!(0,zo.alwaysValidSchema)(t,e)&&r.ok((0,uA.validateArray)(r))}};function um(r,e,t=r.schema){let{gen:n,parentSchema:i,data:s,keyword:o,it:a}=r;d(i),a.opts.unevaluated&&t.length&&a.items!==!0&&(a.items=zo.mergeEvaluated.items(n,t.length,a.items));let c=n.name("valid"),l=n.const("len",(0,dm._)`${s}.length`);t.forEach((u,f)=>{(0,zo.alwaysValidSchema)(a,u)||(n.if((0,dm._)`${l} > ${f}`,()=>r.subschema({keyword:o,schemaProp:f,dataProp:f},c)),r.ok(c))});function d(u){let{opts:f,errSchemaPath:p}=a,y=t.length,h=y===u.minItems&&(y===u.maxItems||u[e]===!1);if(f.strictTuples&&!h){let m=`"${o}" is ${y}-tuple, but minItems or maxItems/${e} are not specified or different at path "${p}"`;(0,zo.checkStrictMode)(a,m,f.strictTuples)}}}ms.validateTuple=um;ms.default=fA});var fm=A(dd=>{"use strict";Object.defineProperty(dd,"__esModule",{value:!0});var pA=ld(),hA={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:r=>(0,pA.validateTuple)(r,"items")};dd.default=hA});var hm=A(ud=>{"use strict";Object.defineProperty(ud,"__esModule",{value:!0});var pm=H(),mA=Q(),yA=$t(),gA=cd(),_A={message:({params:{len:r}})=>(0,pm.str)`must NOT have more than ${r} items`,params:({params:{len:r}})=>(0,pm._)`{limit: ${r}}`},bA={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:_A,code(r){let{schema:e,parentSchema:t,it:n}=r,{prefixItems:i}=t;n.items=!0,!(0,mA.alwaysValidSchema)(n,e)&&(i?(0,gA.validateAdditionalItems)(r,i):r.ok((0,yA.validateArray)(r)))}};ud.default=bA});var mm=A(fd=>{"use strict";Object.defineProperty(fd,"__esModule",{value:!0});var Et=H(),Ho=Q(),wA={message:({params:{min:r,max:e}})=>e===void 0?(0,Et.str)`must contain at least ${r} valid item(s)`:(0,Et.str)`must contain at least ${r} and no more than ${e} valid item(s)`,params:({params:{min:r,max:e}})=>e===void 0?(0,Et._)`{minContains: ${r}}`:(0,Et._)`{minContains: ${r}, maxContains: ${e}}`},vA={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:wA,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 d=e.const("len",(0,Et._)`${i}.length`);if(r.setParams({min:o,max:a}),a===void 0&&o===0){(0,Ho.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&o>a){(0,Ho.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),r.fail();return}if((0,Ho.alwaysValidSchema)(s,t)){let h=(0,Et._)`${d} >= ${o}`;a!==void 0&&(h=(0,Et._)`${h} && ${d} <= ${a}`),r.pass(h);return}s.items=!0;let u=e.name("valid");a===void 0&&o===1?p(u,()=>e.if(u,()=>e.break())):o===0?(e.let(u,!0),a!==void 0&&e.if((0,Et._)`${i}.length > 0`,f)):(e.let(u,!1),f()),r.result(u,()=>r.reset());function f(){let h=e.name("_valid"),m=e.let("count",0);p(h,()=>e.if(h,()=>y(m)))}function p(h,m){e.forRange("i",0,d,g=>{r.subschema({keyword:"contains",dataProp:g,dataPropType:Ho.Type.Num,compositeRule:!0},h),m()})}function y(h){e.code((0,Et._)`${h}++`),a===void 0?e.if((0,Et._)`${h} >= ${o}`,()=>e.assign(u,!0).break()):(e.if((0,Et._)`${h} > ${a}`,()=>e.assign(u,!1).break()),o===1?e.assign(u,!0):e.if((0,Et._)`${h} >= ${o}`,()=>e.assign(u,!0)))}}};fd.default=vA});var Ko=A(er=>{"use strict";Object.defineProperty(er,"__esModule",{value:!0});er.validateSchemaDeps=er.validatePropertyDeps=er.error=void 0;var pd=H(),$A=Q(),ys=$t();er.error={message:({params:{property:r,depsCount:e,deps:t}})=>{let n=e===1?"property":"properties";return(0,pd.str)`must have ${n} ${t} when property ${r} is present`},params:({params:{property:r,depsCount:e,deps:t,missingProperty:n}})=>(0,pd._)`{property: ${r}, missingProperty: ${n}, depsCount: ${e}, - deps: ${t}}`};var PA={keyword:"dependencies",type:"object",schemaType:"object",error:tr.error,code(r){let[e,t]=IA(r);gm(r,e),_m(r,t)}};function IA({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 gm(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,ms.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,ms.checkReportMissingProp)(r,l)}):(t.if((0,pd._)`${c} && (${(0,ms.checkMissingProp)(r,a,s)})`),(0,ms.reportMissingProp)(r,s),t.else())}}tr.validatePropertyDeps=gm;function _m(r,e=r.schema){let{gen:t,data:n,keyword:i,it:s}=r,o=t.name("valid");for(let a in e)(0,kA.alwaysValidSchema)(s,e[a])||(t.if((0,ms.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))}tr.validateSchemaDeps=_m;tr.default=PA});var wm=A(hd=>{"use strict";Object.defineProperty(hd,"__esModule",{value:!0});var bm=H(),OA=Q(),RA={message:"property name must be valid",params:({params:r})=>(0,bm._)`{propertyName: ${r.propertyName}}`},TA={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:RA,code(r){let{gen:e,schema:t,data:n,it:i}=r;if((0,OA.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,bm.not)(s),()=>{r.error(!0),i.allErrors||e.break()})}),r.ok(s)}};hd.default=TA});var yd=A(md=>{"use strict";Object.defineProperty(md,"__esModule",{value:!0});var Ko=St(),Nt=H(),MA=$t(),Wo=Q(),CA={message:"must NOT have additional properties",params:({params:r})=>(0,Nt._)`{additionalProperty: ${r.additionalProperty}}`},NA={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:CA,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,Wo.alwaysValidSchema)(o,t))return;let l=(0,Ko.allSchemaProperties)(n.properties),d=(0,Ko.allSchemaProperties)(n.patternProperties);u(),r.ok((0,Nt._)`${s} === ${MA.default.errors}`);function u(){e.forIn("key",i,m=>{!l.length&&!d.length?y(m):e.if(f(m),()=>y(m))})}function f(m){let g;if(l.length>8){let _=(0,Wo.schemaRefOrVal)(o,n.properties,"properties");g=(0,Ko.isOwnProperty)(e,_,m)}else l.length?g=(0,Nt.or)(...l.map(_=>(0,Nt._)`${m} === ${_}`)):g=Nt.nil;return d.length&&(g=(0,Nt.or)(g,...d.map(_=>(0,Nt._)`${(0,Ko.usePattern)(r,_)}.test(${m})`))),(0,Nt.not)(g)}function p(m){e.code((0,Nt._)`delete ${i}[${m}]`)}function y(m){if(c.removeAdditional==="all"||c.removeAdditional&&t===!1){p(m);return}if(t===!1){r.setParams({additionalProperty:m}),r.error(),a||e.break();return}if(typeof t=="object"&&!(0,Wo.alwaysValidSchema)(o,t)){let g=e.name("valid");c.removeAdditional==="failing"?(h(m,g,!1),e.if((0,Nt.not)(g),()=>{r.reset(),p(m)})):(h(m,g),a||e.if((0,Nt.not)(g),()=>e.break()))}}function h(m,g,_){let w={keyword:"additionalProperties",dataProp:m,dataPropType:Wo.Type.Str};_===!1&&Object.assign(w,{compositeRule:!0,createErrors:!1,allErrors:!1}),r.subschema(w,g)}}};md.default=NA});var Sm=A(_d=>{"use strict";Object.defineProperty(_d,"__esModule",{value:!0});var LA=Hn(),vm=St(),gd=Q(),$m=yd(),jA={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&&$m.default.code(new LA.KeywordCxt(s,$m.default,"additionalProperties"));let o=(0,vm.allSchemaProperties)(t);for(let u of o)s.definedProperties.add(u);s.opts.unevaluated&&o.length&&s.props!==!0&&(s.props=gd.mergeEvaluated.props(e,(0,gd.toHash)(o),s.props));let a=o.filter(u=>!(0,gd.alwaysValidSchema)(s,t[u]));if(a.length===0)return;let c=e.name("valid");for(let u of a)l(u)?d(u):(e.if((0,vm.propertyInData)(e,i,u,s.opts.ownProperties)),d(u),s.allErrors||e.else().var(c,!0),e.endIf()),r.it.definedProperties.add(u),r.ok(c);function l(u){return s.opts.useDefaults&&!s.compositeRule&&t[u].default!==void 0}function d(u){r.subschema({keyword:"properties",schemaProp:u,dataProp:u},c)}}};_d.default=jA});var km=A(bd=>{"use strict";Object.defineProperty(bd,"__esModule",{value:!0});var Em=St(),Go=H(),Am=Q(),xm=Q(),DA={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,Em.allSchemaProperties)(t),c=a.filter(h=>(0,Am.alwaysValidSchema)(s,t[h]));if(a.length===0||c.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let l=o.strictSchema&&!o.allowMatchingProperties&&i.properties,d=e.name("valid");s.props!==!0&&!(s.props instanceof Go.Name)&&(s.props=(0,xm.evaluatedPropsToName)(e,s.props));let{props:u}=s;f();function f(){for(let h of a)l&&p(h),s.allErrors?y(h):(e.var(d,!0),y(h),e.if(d))}function p(h){for(let m in l)new RegExp(h).test(m)&&(0,Am.checkStrictMode)(s,`property ${m} matches pattern ${h} (use allowMatchingProperties)`)}function y(h){e.forIn("key",n,m=>{e.if((0,Go._)`${(0,Em.usePattern)(r,h)}.test(${m})`,()=>{let g=c.includes(h);g||r.subschema({keyword:"patternProperties",schemaProp:h,dataProp:m,dataPropType:xm.Type.Str},d),s.opts.unevaluated&&u!==!0?e.assign((0,Go._)`${u}[${m}]`,!0):!g&&!s.allErrors&&e.if((0,Go.not)(d),()=>e.break())})})}}};bd.default=DA});var Pm=A(wd=>{"use strict";Object.defineProperty(wd,"__esModule",{value:!0});var qA=Q(),FA={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(r){let{gen:e,schema:t,it:n}=r;if((0,qA.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"}};wd.default=FA});var Im=A(vd=>{"use strict";Object.defineProperty(vd,"__esModule",{value:!0});var UA=St(),VA={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:UA.validateUnion,error:{message:"must match a schema in anyOf"}};vd.default=VA});var Om=A($d=>{"use strict";Object.defineProperty($d,"__esModule",{value:!0});var Jo=H(),BA=Q(),zA={message:"must match exactly one schema in oneOf",params:({params:r})=>(0,Jo._)`{passingSchemas: ${r.passing}}`},HA={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:zA,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((d,u)=>{let f;(0,BA.alwaysValidSchema)(i,d)?e.var(c,!0):f=r.subschema({keyword:"oneOf",schemaProp:u,compositeRule:!0},c),u>0&&e.if((0,Jo._)`${c} && ${o}`).assign(o,!1).assign(a,(0,Jo._)`[${a}, ${u}]`).else(),e.if(c,()=>{e.assign(o,!0),e.assign(a,u),f&&r.mergeEvaluated(f,Jo.Name)})})}}};$d.default=HA});var Rm=A(Sd=>{"use strict";Object.defineProperty(Sd,"__esModule",{value:!0});var KA=Q(),WA={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,KA.alwaysValidSchema)(n,s))return;let a=r.subschema({keyword:"allOf",schemaProp:o},i);r.ok(i),r.mergeEvaluated(a)})}};Sd.default=WA});var Cm=A(Ed=>{"use strict";Object.defineProperty(Ed,"__esModule",{value:!0});var Yo=H(),Mm=Q(),GA={message:({params:r})=>(0,Yo.str)`must match "${r.ifClause}" schema`,params:({params:r})=>(0,Yo._)`{failingKeyword: ${r.ifClause}}`},JA={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:GA,code(r){let{gen:e,parentSchema:t,it:n}=r;t.then===void 0&&t.else===void 0&&(0,Mm.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let i=Tm(n,"then"),s=Tm(n,"else");if(!i&&!s)return;let o=e.let("valid",!0),a=e.name("_valid");if(c(),r.reset(),i&&s){let d=e.let("ifClause");r.setParams({ifClause:d}),e.if(a,l("then",d),l("else",d))}else i?e.if(a,l("then")):e.if((0,Yo.not)(a),l("else"));r.pass(o,()=>r.error(!0));function c(){let d=r.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);r.mergeEvaluated(d)}function l(d,u){return()=>{let f=r.subschema({keyword:d},a);e.assign(o,a),r.mergeValidEvaluated(f,o),u?e.assign(u,(0,Yo._)`${d}`):r.setParams({ifClause:d})}}}};function Tm(r,e){let t=r.schema[e];return t!==void 0&&!(0,Mm.alwaysValidSchema)(r,t)}Ed.default=JA});var Nm=A(Ad=>{"use strict";Object.defineProperty(Ad,"__esModule",{value:!0});var YA=Q(),XA={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:r,parentSchema:e,it:t}){e.if===void 0&&(0,YA.checkStrictMode)(t,`"${r}" without "if" is ignored`)}};Ad.default=XA});var kd=A(xd=>{"use strict";Object.defineProperty(xd,"__esModule",{value:!0});var QA=cd(),ZA=pm(),ex=ld(),tx=mm(),rx=ym(),nx=Ho(),ix=wm(),sx=yd(),ox=Sm(),ax=km(),cx=Pm(),lx=Im(),dx=Om(),ux=Rm(),fx=Cm(),px=Nm();function hx(r=!1){let e=[cx.default,lx.default,dx.default,ux.default,fx.default,px.default,ix.default,sx.default,nx.default,ox.default,ax.default];return r?e.push(ZA.default,tx.default):e.push(QA.default,ex.default),e.push(rx.default),e}xd.default=hx});var Id=A(ys=>{"use strict";Object.defineProperty(ys,"__esModule",{value:!0});ys.dynamicAnchor=void 0;var Pd=H(),mx=$t(),Lm=rs(),yx=qo(),gx={keyword:"$dynamicAnchor",schemaType:"string",code:r=>jm(r,r.schema)};function jm(r,e){let{gen:t,it:n}=r;n.schemaEnv.root.dynamicAnchors[e]=!0;let i=(0,Pd._)`${mx.default.dynamicAnchors}${(0,Pd.getProperty)(e)}`,s=n.errSchemaPath==="#"?n.validateName:_x(r);t.if((0,Pd._)`!${i}`,()=>t.assign(i,s))}ys.dynamicAnchor=jm;function _x(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 Lm.SchemaEnv({schema:t,schemaId:c,root:i,baseId:s,localRefs:o,meta:a});return Lm.compileSchema.call(n,l),(0,yx.getValidate)(r,l)}ys.default=gx});var Od=A(gs=>{"use strict";Object.defineProperty(gs,"__esModule",{value:!0});gs.dynamicRef=void 0;var Dm=H(),bx=$t(),qm=qo(),wx={keyword:"$dynamicRef",schemaType:"string",code:r=>Fm(r,r.schema)};function Fm(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,Dm._)`${bx.default.dynamicAnchors}${(0,Dm.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,qm.callRef)(r,c),t.let(l,!0)}):()=>(0,qm.callRef)(r,c)}}gs.dynamicRef=Fm;gs.default=wx});var Um=A(Rd=>{"use strict";Object.defineProperty(Rd,"__esModule",{value:!0});var vx=Id(),$x=Q(),Sx={keyword:"$recursiveAnchor",schemaType:"boolean",code(r){r.schema?(0,vx.dynamicAnchor)(r,""):(0,$x.checkStrictMode)(r.it,"$recursiveAnchor: false is ignored")}};Rd.default=Sx});var Vm=A(Td=>{"use strict";Object.defineProperty(Td,"__esModule",{value:!0});var Ex=Od(),Ax={keyword:"$recursiveRef",schemaType:"string",code:r=>(0,Ex.dynamicRef)(r,r.schema)};Td.default=Ax});var Bm=A(Md=>{"use strict";Object.defineProperty(Md,"__esModule",{value:!0});var xx=Id(),kx=Od(),Px=Um(),Ix=Vm(),Ox=[xx.default,kx.default,Px.default,Ix.default];Md.default=Ox});var Hm=A(Cd=>{"use strict";Object.defineProperty(Cd,"__esModule",{value:!0});var zm=Ho(),Rx={keyword:"dependentRequired",type:"object",schemaType:"object",error:zm.error,code:r=>(0,zm.validatePropertyDeps)(r)};Cd.default=Rx});var Km=A(Nd=>{"use strict";Object.defineProperty(Nd,"__esModule",{value:!0});var Tx=Ho(),Mx={keyword:"dependentSchemas",type:"object",schemaType:"object",code:r=>(0,Tx.validateSchemaDeps)(r)};Nd.default=Mx});var Wm=A(Ld=>{"use strict";Object.defineProperty(Ld,"__esModule",{value:!0});var Cx=Q(),Nx={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword:r,parentSchema:e,it:t}){e.contains===void 0&&(0,Cx.checkStrictMode)(t,`"${r}" without "contains" is ignored`)}};Ld.default=Nx});var Gm=A(jd=>{"use strict";Object.defineProperty(jd,"__esModule",{value:!0});var Lx=Hm(),jx=Km(),Dx=Wm(),qx=[Lx.default,jx.default,Dx.default];jd.default=qx});var Ym=A(Dd=>{"use strict";Object.defineProperty(Dd,"__esModule",{value:!0});var Hr=H(),Jm=Q(),Fx=$t(),Ux={message:"must NOT have unevaluated properties",params:({params:r})=>(0,Hr._)`{unevaluatedProperty: ${r.unevaluatedProperty}}`},Vx={keyword:"unevaluatedProperties",type:"object",schemaType:["boolean","object"],trackErrors:!0,error:Ux,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 Hr.Name?e.if((0,Hr._)`${a} !== true`,()=>e.forIn("key",n,u=>e.if(l(a,u),()=>c(u)))):a!==!0&&e.forIn("key",n,u=>a===void 0?c(u):e.if(d(a,u),()=>c(u))),s.props=!0,r.ok((0,Hr._)`${i} === ${Fx.default.errors}`);function c(u){if(t===!1){r.setParams({unevaluatedProperty:u}),r.error(),o||e.break();return}if(!(0,Jm.alwaysValidSchema)(s,t)){let f=e.name("valid");r.subschema({keyword:"unevaluatedProperties",dataProp:u,dataPropType:Jm.Type.Str},f),o||e.if((0,Hr.not)(f),()=>e.break())}}function l(u,f){return(0,Hr._)`!${u} || !${u}[${f}]`}function d(u,f){let p=[];for(let y in u)u[y]===!0&&p.push((0,Hr._)`${f} !== ${y}`);return(0,Hr.and)(...p)}}};Dd.default=Vx});var Qm=A(qd=>{"use strict";Object.defineProperty(qd,"__esModule",{value:!0});var $n=H(),Xm=Q(),Bx={message:({params:{len:r}})=>(0,$n.str)`must NOT have more than ${r} items`,params:({params:{len:r}})=>(0,$n._)`{limit: ${r}}`},zx={keyword:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error:Bx,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,$n._)`${n}.length`);if(t===!1)r.setParams({len:s}),r.fail((0,$n._)`${o} > ${s}`);else if(typeof t=="object"&&!(0,Xm.alwaysValidSchema)(i,t)){let c=e.var("valid",(0,$n._)`${o} <= ${s}`);e.if((0,$n.not)(c),()=>a(c,s)),r.ok(c)}i.items=!0;function a(c,l){e.forRange("i",l,o,d=>{r.subschema({keyword:"unevaluatedItems",dataProp:d,dataPropType:Xm.Type.Num},c),i.allErrors||e.if((0,$n.not)(c),()=>e.break())})}}};qd.default=zx});var Zm=A(Fd=>{"use strict";Object.defineProperty(Fd,"__esModule",{value:!0});var Hx=Ym(),Kx=Qm(),Wx=[Hx.default,Kx.default];Fd.default=Wx});var ey=A(Ud=>{"use strict";Object.defineProperty(Ud,"__esModule",{value:!0});var xe=H(),Gx={message:({schemaCode:r})=>(0,xe.str)`must match format "${r}"`,params:({schemaCode:r})=>(0,xe._)`{format: ${r}}`},Jx={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:Gx,code(r,e){let{gen:t,data:n,$data:i,schema:s,schemaCode:o,it:a}=r,{opts:c,errSchemaPath:l,schemaEnv:d,self:u}=a;if(!c.validateFormats)return;i?f():p();function f(){let y=t.scopeValue("formats",{ref:u.formats,code:c.code.formats}),h=t.const("fDef",(0,xe._)`${y}[${o}]`),m=t.let("fType"),g=t.let("format");t.if((0,xe._)`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>t.assign(m,(0,xe._)`${h}.type || "string"`).assign(g,(0,xe._)`${h}.validate`),()=>t.assign(m,(0,xe._)`"string"`).assign(g,h)),r.fail$data((0,xe.or)(_(),w()));function _(){return c.strictSchema===!1?xe.nil:(0,xe._)`${o} && !${g}`}function w(){let k=d.$async?(0,xe._)`(${h}.async ? await ${g}(${n}) : ${g}(${n}))`:(0,xe._)`${g}(${n})`,v=(0,xe._)`(typeof ${g} == "function" ? ${k} : ${g}.test(${n}))`;return(0,xe._)`${g} && ${g} !== true && ${m} === ${e} && !${v}`}}function p(){let y=u.formats[s];if(!y){_();return}if(y===!0)return;let[h,m,g]=w(y);h===e&&r.pass(k());function _(){if(c.strictSchema===!1){u.logger.warn(v());return}throw new Error(v());function v(){return`unknown format "${s}" ignored in schema at path "${l}"`}}function w(v){let P=v instanceof RegExp?(0,xe.regexpCode)(v):c.code.formats?(0,xe._)`${c.code.formats}${(0,xe.getProperty)(s)}`:void 0,O=t.scopeValue("formats",{key:s,ref:v,code:P});return typeof v=="object"&&!(v instanceof RegExp)?[v.type||"string",v.validate,(0,xe._)`${O}.validate`]:["string",v,O]}function k(){if(typeof y=="object"&&!(y instanceof RegExp)&&y.async){if(!d.$async)throw new Error("async format in sync schema");return(0,xe._)`await ${g}(${n})`}return typeof m=="function"?(0,xe._)`${g}(${n})`:(0,xe._)`${g}.test(${n})`}}}};Ud.default=Jx});var Bd=A(Vd=>{"use strict";Object.defineProperty(Vd,"__esModule",{value:!0});var Yx=ey(),Xx=[Yx.default];Vd.default=Xx});var zd=A(Xn=>{"use strict";Object.defineProperty(Xn,"__esModule",{value:!0});Xn.contentVocabulary=Xn.metadataVocabulary=void 0;Xn.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Xn.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var ry=A(Hd=>{"use strict";Object.defineProperty(Hd,"__esModule",{value:!0});var Qx=zl(),Zx=od(),e1=kd(),t1=Bm(),r1=Gm(),n1=Zm(),i1=Bd(),ty=zd(),s1=[t1.default,Qx.default,Zx.default,(0,e1.default)(!0),i1.default,ty.metadataVocabulary,ty.contentVocabulary,r1.default,n1.default];Hd.default=s1});var iy=A(Xo=>{"use strict";Object.defineProperty(Xo,"__esModule",{value:!0});Xo.DiscrError=void 0;var ny;(function(r){r.Tag="tag",r.Mapping="mapping"})(ny||(Xo.DiscrError=ny={}))});var Gd=A(Wd=>{"use strict";Object.defineProperty(Wd,"__esModule",{value:!0});var Qn=H(),Kd=iy(),sy=rs(),o1=Kn(),a1=Q(),c1={message:({params:{discrError:r,tagName:e}})=>r===Kd.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:r,tag:e,tagName:t}})=>(0,Qn._)`{error: ${r}, tag: ${t}, tagValue: ${e}}`},l1={keyword:"discriminator",type:"object",schemaType:"object",error:c1,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,Qn._)`${t}${(0,Qn.getProperty)(a)}`);e.if((0,Qn._)`typeof ${l} == "string"`,()=>d(),()=>r.error(!1,{discrError:Kd.DiscrError.Tag,tag:l,tagName:a})),r.ok(c);function d(){let p=f();e.if(!1);for(let y in p)e.elseIf((0,Qn._)`${l} === ${y}`),e.assign(c,u(p[y]));e.else(),r.error(!1,{discrError:Kd.DiscrError.Mapping,tag:l,tagName:a}),e.endIf()}function u(p){let y=e.name("valid"),h=r.subschema({keyword:"oneOf",schemaProp:p},y);return r.mergeEvaluated(h,Qn.Name),y}function f(){var p;let y={},h=g(i),m=!0;for(let k=0;k{d1.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 ay=A((c2,u1)=>{u1.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 cy=A((l2,f1)=>{f1.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 ly=A((d2,p1)=>{p1.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 dy=A((u2,h1)=>{h1.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 uy=A((f2,m1)=>{m1.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 fy=A((p2,y1)=>{y1.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 py=A((h2,g1)=>{g1.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 hy=A(Jd=>{"use strict";Object.defineProperty(Jd,"__esModule",{value:!0});var _1=oy(),b1=ay(),w1=cy(),v1=ly(),$1=dy(),S1=uy(),E1=fy(),A1=py(),x1=["/properties"];function k1(r){return[_1,b1,w1,v1,$1,e(this,S1),E1,e(this,A1)].forEach(t=>this.addMetaSchema(t,void 0,!1)),this;function e(t,n){return r?t.$dataMetaSchema(n,x1):n}}Jd.default=k1});var Qd=A((_e,Xd)=>{"use strict";Object.defineProperty(_e,"__esModule",{value:!0});_e.MissingRefError=_e.ValidationError=_e.CodeGen=_e.Name=_e.nil=_e.stringify=_e.str=_e._=_e.KeywordCxt=_e.Ajv2020=void 0;var P1=Ul(),I1=ry(),O1=Gd(),R1=hy(),Yd="https://json-schema.org/draft/2020-12/schema",Zn=class extends P1.default{constructor(e={}){super({...e,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){super._addVocabularies(),I1.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(O1.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data:e,meta:t}=this.opts;t&&(R1.default.call(this,e),this.refs["http://json-schema.org/schema"]=Yd)}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Yd)?Yd:void 0)}};_e.Ajv2020=Zn;Xd.exports=_e=Zn;Xd.exports.Ajv2020=Zn;Object.defineProperty(_e,"__esModule",{value:!0});_e.default=Zn;var T1=Hn();Object.defineProperty(_e,"KeywordCxt",{enumerable:!0,get:function(){return T1.KeywordCxt}});var ei=H();Object.defineProperty(_e,"_",{enumerable:!0,get:function(){return ei._}});Object.defineProperty(_e,"str",{enumerable:!0,get:function(){return ei.str}});Object.defineProperty(_e,"stringify",{enumerable:!0,get:function(){return ei.stringify}});Object.defineProperty(_e,"nil",{enumerable:!0,get:function(){return ei.nil}});Object.defineProperty(_e,"Name",{enumerable:!0,get:function(){return ei.Name}});Object.defineProperty(_e,"CodeGen",{enumerable:!0,get:function(){return ei.CodeGen}});var M1=ts();Object.defineProperty(_e,"ValidationError",{enumerable:!0,get:function(){return M1.default}});var C1=Kn();Object.defineProperty(_e,"MissingRefError",{enumerable:!0,get:function(){return C1.default}})});var $y=A(nr=>{"use strict";Object.defineProperty(nr,"__esModule",{value:!0});nr.formatNames=nr.fastFormats=nr.fullFormats=void 0;function rr(r,e){return{validate:r,compare:e}}nr.fullFormats={date:rr(_y,ru),time:rr(eu(!0),nu),"date-time":rr(my(!0),wy),"iso-time":rr(eu(),by),"iso-date-time":rr(my(),vy),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:F1,"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:W1,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:U1,int32:{type:"number",validate:z1},int64:{type:"number",validate:H1},float:{type:"number",validate:gy},double:{type:"number",validate:gy},password:!0,binary:!0};nr.fastFormats={...nr.fullFormats,date:rr(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,ru),time:rr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,nu),"date-time":rr(/^\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,wy),"iso-time":rr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,by),"iso-date-time":rr(/^\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,vy),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};nr.formatNames=Object.keys(nr.fullFormats);function N1(r){return r%4===0&&(r%100!==0||r%400===0)}var L1=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,j1=[0,31,28,31,30,31,30,31,31,30,31,30,31];function _y(r){let e=L1.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&&N1(t)?29:j1[n])}function ru(r,e){if(r&&e)return r>e?1:r23||d>59||r&&!a)return!1;if(i<=23&&s<=59&&o<60)return!0;let u=s-d*c,f=i-l*c-(u<0?1:0);return(f===23||f===-1)&&(u===59||u===-1)&&o<61}}function nu(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 by(r,e){if(!(r&&e))return;let t=Zd.exec(r),n=Zd.exec(e);if(t&&n)return r=t[1]+t[2]+t[3],e=n[1]+n[2]+n[3],r>e?1:r=V1}function H1(r){return Number.isInteger(r)}function gy(){return!0}var K1=/[^\\]\\Z/;function W1(r){if(K1.test(r))return!1;try{return new RegExp(r),!0}catch(e){return!1}}});var Ey=A(iu=>{"use strict";Object.defineProperty(iu,"__esModule",{value:!0});var G1=zl(),J1=od(),Y1=kd(),X1=Bd(),Sy=zd(),Q1=[G1.default,J1.default,(0,Y1.default)(),X1.default,Sy.metadataVocabulary,Sy.contentVocabulary];iu.default=Q1});var Ay=A((_2,Z1)=>{Z1.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 ky=A((be,su)=>{"use strict";Object.defineProperty(be,"__esModule",{value:!0});be.MissingRefError=be.ValidationError=be.CodeGen=be.Name=be.nil=be.stringify=be.str=be._=be.KeywordCxt=be.Ajv=void 0;var ek=Ul(),tk=Ey(),rk=Gd(),xy=Ay(),nk=["/properties"],Qo="http://json-schema.org/draft-07/schema",ti=class extends ek.default{_addVocabularies(){super._addVocabularies(),tk.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(rk.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(xy,nk):xy;this.addMetaSchema(e,Qo,!1),this.refs["http://json-schema.org/schema"]=Qo}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Qo)?Qo:void 0)}};be.Ajv=ti;su.exports=be=ti;su.exports.Ajv=ti;Object.defineProperty(be,"__esModule",{value:!0});be.default=ti;var ik=Hn();Object.defineProperty(be,"KeywordCxt",{enumerable:!0,get:function(){return ik.KeywordCxt}});var ri=H();Object.defineProperty(be,"_",{enumerable:!0,get:function(){return ri._}});Object.defineProperty(be,"str",{enumerable:!0,get:function(){return ri.str}});Object.defineProperty(be,"stringify",{enumerable:!0,get:function(){return ri.stringify}});Object.defineProperty(be,"nil",{enumerable:!0,get:function(){return ri.nil}});Object.defineProperty(be,"Name",{enumerable:!0,get:function(){return ri.Name}});Object.defineProperty(be,"CodeGen",{enumerable:!0,get:function(){return ri.CodeGen}});var sk=ts();Object.defineProperty(be,"ValidationError",{enumerable:!0,get:function(){return sk.default}});var ok=Kn();Object.defineProperty(be,"MissingRefError",{enumerable:!0,get:function(){return ok.default}})});var Py=A(ni=>{"use strict";Object.defineProperty(ni,"__esModule",{value:!0});ni.formatLimitDefinition=void 0;var ak=ky(),Lt=H(),Kr=Lt.operators,Zo={formatMaximum:{okStr:"<=",ok:Kr.LTE,fail:Kr.GT},formatMinimum:{okStr:">=",ok:Kr.GTE,fail:Kr.LT},formatExclusiveMaximum:{okStr:"<",ok:Kr.LT,fail:Kr.GTE},formatExclusiveMinimum:{okStr:">",ok:Kr.GT,fail:Kr.LTE}},ck={message:({keyword:r,schemaCode:e})=>(0,Lt.str)`should be ${Zo[r].okStr} ${e}`,params:({keyword:r,schemaCode:e})=>(0,Lt._)`{comparison: ${Zo[r].okStr}, limit: ${e}}`};ni.formatLimitDefinition={keyword:Object.keys(Zo),type:"string",schemaType:"string",$data:!0,error:ck,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 ak.KeywordCxt(s,a.RULES.all.format.definition,"format");c.$data?l():d();function l(){let f=e.scopeValue("formats",{ref:a.formats,code:o.code.formats}),p=e.const("fmt",(0,Lt._)`${f}[${c.schemaCode}]`);r.fail$data((0,Lt.or)((0,Lt._)`typeof ${p} != "object"`,(0,Lt._)`${p} instanceof RegExp`,(0,Lt._)`typeof ${p}.compare != "function"`,u(p)))}function d(){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 y=e.scopeValue("formats",{key:f,ref:p,code:o.code.formats?(0,Lt._)`${o.code.formats}${(0,Lt.getProperty)(f)}`:void 0});r.fail$data(u(y))}function u(f){return(0,Lt._)`${f}.compare(${t}, ${n}) ${Zo[i].fail} 0`}},dependencies:["format"]};var lk=r=>(r.addKeyword(ni.formatLimitDefinition),r);ni.default=lk});var cu=A((_s,Ry)=>{"use strict";Object.defineProperty(_s,"__esModule",{value:!0});var ii=$y(),dk=Py(),ou=H(),Iy=new ou.Name("fullFormats"),uk=new ou.Name("fastFormats"),au=(r,e={keywords:!0})=>{if(Array.isArray(e))return Oy(r,e,ii.fullFormats,Iy),r;let[t,n]=e.mode==="fast"?[ii.fastFormats,uk]:[ii.fullFormats,Iy],i=e.formats||ii.formatNames;return Oy(r,i,t,n),e.keywords&&(0,dk.default)(r),r};au.get=(r,e="full")=>{let n=(e==="fast"?ii.fastFormats:ii.fullFormats)[r];if(!n)throw new Error(`Unknown format "${r}"`);return n};function Oy(r,e,t,n){var i,s;(i=(s=r.opts.code).formats)!==null&&i!==void 0||(s.formats=(0,ou._)`require("ajv-formats/dist/formats").${n}`);for(let o of e)r.addFormat(o,t[o])}Ry.exports=_s=au;Object.defineProperty(_s,"__esModule",{value:!0});_s.default=au});var ai=A((x2,Dy)=>{"use strict";var hk="2.0.0",mk=Number.MAX_SAFE_INTEGER||9007199254740991,yk=16,gk=250,_k=["major","premajor","minor","preminor","patch","prepatch","prerelease"];Dy.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:yk,MAX_SAFE_BUILD_LENGTH:gk,MAX_SAFE_INTEGER:mk,RELEASE_TYPES:_k,SEMVER_SPEC_VERSION:hk,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var bs=A((k2,qy)=>{"use strict";var bk=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...r)=>console.error("SEMVER",...r):()=>{};qy.exports=bk});var ci=A((sr,Fy)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:fu,MAX_SAFE_BUILD_LENGTH:wk,MAX_LENGTH:vk}=ai(),$k=bs();sr=Fy.exports={};var Sk=sr.re=[],Ek=sr.safeRe=[],j=sr.src=[],Ak=sr.safeSrc=[],D=sr.t={},xk=0,pu="[a-zA-Z0-9-]",kk=[["\\s",1],["\\d",vk],[pu,wk]],Pk=r=>{for(let[e,t]of kk)r=r.split(`${e}*`).join(`${e}{0,${t}}`).split(`${e}+`).join(`${e}{1,${t}}`);return r},K=(r,e,t)=>{let n=Pk(e),i=xk++;$k(r,i,e),D[r]=i,j[i]=e,Ak[i]=n,Sk[i]=new RegExp(e,t?"g":void 0),Ek[i]=new RegExp(n,t?"g":void 0)};K("NUMERICIDENTIFIER","0|[1-9]\\d*");K("NUMERICIDENTIFIERLOOSE","\\d+");K("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${pu}*`);K("MAINVERSION",`(${j[D.NUMERICIDENTIFIER]})\\.(${j[D.NUMERICIDENTIFIER]})\\.(${j[D.NUMERICIDENTIFIER]})`);K("MAINVERSIONLOOSE",`(${j[D.NUMERICIDENTIFIERLOOSE]})\\.(${j[D.NUMERICIDENTIFIERLOOSE]})\\.(${j[D.NUMERICIDENTIFIERLOOSE]})`);K("PRERELEASEIDENTIFIER",`(?:${j[D.NONNUMERICIDENTIFIER]}|${j[D.NUMERICIDENTIFIER]})`);K("PRERELEASEIDENTIFIERLOOSE",`(?:${j[D.NONNUMERICIDENTIFIER]}|${j[D.NUMERICIDENTIFIERLOOSE]})`);K("PRERELEASE",`(?:-(${j[D.PRERELEASEIDENTIFIER]}(?:\\.${j[D.PRERELEASEIDENTIFIER]})*))`);K("PRERELEASELOOSE",`(?:-?(${j[D.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${j[D.PRERELEASEIDENTIFIERLOOSE]})*))`);K("BUILDIDENTIFIER",`${pu}+`);K("BUILD",`(?:\\+(${j[D.BUILDIDENTIFIER]}(?:\\.${j[D.BUILDIDENTIFIER]})*))`);K("FULLPLAIN",`v?${j[D.MAINVERSION]}${j[D.PRERELEASE]}?${j[D.BUILD]}?`);K("FULL",`^${j[D.FULLPLAIN]}$`);K("LOOSEPLAIN",`[v=\\s]*${j[D.MAINVERSIONLOOSE]}${j[D.PRERELEASELOOSE]}?${j[D.BUILD]}?`);K("LOOSE",`^${j[D.LOOSEPLAIN]}$`);K("GTLT","((?:<|>)?=?)");K("XRANGEIDENTIFIERLOOSE",`${j[D.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);K("XRANGEIDENTIFIER",`${j[D.NUMERICIDENTIFIER]}|x|X|\\*`);K("XRANGEPLAIN",`[v=\\s]*(${j[D.XRANGEIDENTIFIER]})(?:\\.(${j[D.XRANGEIDENTIFIER]})(?:\\.(${j[D.XRANGEIDENTIFIER]})(?:${j[D.PRERELEASE]})?${j[D.BUILD]}?)?)?`);K("XRANGEPLAINLOOSE",`[v=\\s]*(${j[D.XRANGEIDENTIFIERLOOSE]})(?:\\.(${j[D.XRANGEIDENTIFIERLOOSE]})(?:\\.(${j[D.XRANGEIDENTIFIERLOOSE]})(?:${j[D.PRERELEASELOOSE]})?${j[D.BUILD]}?)?)?`);K("XRANGE",`^${j[D.GTLT]}\\s*${j[D.XRANGEPLAIN]}$`);K("XRANGELOOSE",`^${j[D.GTLT]}\\s*${j[D.XRANGEPLAINLOOSE]}$`);K("COERCEPLAIN",`(^|[^\\d])(\\d{1,${fu}})(?:\\.(\\d{1,${fu}}))?(?:\\.(\\d{1,${fu}}))?`);K("COERCE",`${j[D.COERCEPLAIN]}(?:$|[^\\d])`);K("COERCEFULL",j[D.COERCEPLAIN]+`(?:${j[D.PRERELEASE]})?(?:${j[D.BUILD]})?(?:$|[^\\d])`);K("COERCERTL",j[D.COERCE],!0);K("COERCERTLFULL",j[D.COERCEFULL],!0);K("LONETILDE","(?:~>?)");K("TILDETRIM",`(\\s*)${j[D.LONETILDE]}\\s+`,!0);sr.tildeTrimReplace="$1~";K("TILDE",`^${j[D.LONETILDE]}${j[D.XRANGEPLAIN]}$`);K("TILDELOOSE",`^${j[D.LONETILDE]}${j[D.XRANGEPLAINLOOSE]}$`);K("LONECARET","(?:\\^)");K("CARETTRIM",`(\\s*)${j[D.LONECARET]}\\s+`,!0);sr.caretTrimReplace="$1^";K("CARET",`^${j[D.LONECARET]}${j[D.XRANGEPLAIN]}$`);K("CARETLOOSE",`^${j[D.LONECARET]}${j[D.XRANGEPLAINLOOSE]}$`);K("COMPARATORLOOSE",`^${j[D.GTLT]}\\s*(${j[D.LOOSEPLAIN]})$|^$`);K("COMPARATOR",`^${j[D.GTLT]}\\s*(${j[D.FULLPLAIN]})$|^$`);K("COMPARATORTRIM",`(\\s*)${j[D.GTLT]}\\s*(${j[D.LOOSEPLAIN]}|${j[D.XRANGEPLAIN]})`,!0);sr.comparatorTrimReplace="$1$2$3";K("HYPHENRANGE",`^\\s*(${j[D.XRANGEPLAIN]})\\s+-\\s+(${j[D.XRANGEPLAIN]})\\s*$`);K("HYPHENRANGELOOSE",`^\\s*(${j[D.XRANGEPLAINLOOSE]})\\s+-\\s+(${j[D.XRANGEPLAINLOOSE]})\\s*$`);K("STAR","(<|>)?=?\\s*\\*");K("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");K("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")});var ra=A((P2,Uy)=>{"use strict";var Ik=Object.freeze({loose:!0}),Ok=Object.freeze({}),Rk=r=>r?typeof r!="object"?Ik:r:Ok;Uy.exports=Rk});var hu=A((I2,zy)=>{"use strict";var Vy=/^[0-9]+$/,By=(r,e)=>{if(typeof r=="number"&&typeof e=="number")return r===e?0:rBy(e,r);zy.exports={compareIdentifiers:By,rcompareIdentifiers:Tk}});var qe=A((O2,Ky)=>{"use strict";var na=bs(),{MAX_LENGTH:Hy,MAX_SAFE_INTEGER:ia}=ai(),{safeRe:sa,t:oa}=ci(),Mk=ra(),{compareIdentifiers:mu}=hu(),Ck=(r,e)=>{let t=e.split(".");if(t.length>r.length)return!1;for(let n=0;nHy)throw new TypeError(`version is longer than ${Hy} characters`);na("SemVer",e,t),this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease;let n=e.trim().match(t.loose?sa[oa.LOOSE]:sa[oa.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>ia||this.major<0)throw new TypeError("Invalid major version");if(this.minor>ia||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>ia||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(na("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 mu(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(na("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 mu(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?sa[oa.PRERELEASELOOSE]:sa[oa.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]),Ck(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}};Ky.exports=yu});var Gr=A((R2,Gy)=>{"use strict";var Wy=qe(),Nk=(r,e,t=!1)=>{if(r instanceof Wy)return r;try{return new Wy(r,e)}catch(n){if(!t)return null;throw n}};Gy.exports=Nk});var Yy=A((T2,Jy)=>{"use strict";var Lk=Gr(),jk=(r,e)=>{let t=Lk(r,e);return t?t.version:null};Jy.exports=jk});var Qy=A((M2,Xy)=>{"use strict";var Dk=Gr(),qk=(r,e)=>{let t=Dk(r.trim().replace(/^[=v]+/,""),e);return t?t.version:null};Xy.exports=qk});var tg=A((C2,eg)=>{"use strict";var Zy=qe(),Fk=(r,e,t,n,i)=>{typeof t=="string"&&(i=n,n=t,t=void 0);try{return new Zy(r instanceof Zy?r.version:r,t).inc(e,n,i).version}catch(s){return null}};eg.exports=Fk});var ig=A((N2,ng)=>{"use strict";var rg=Gr(),Uk=(r,e)=>{let t=rg(r,null,!0),n=rg(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 d=c?"pre":"";return t.major!==n.major?d+"major":t.minor!==n.minor?d+"minor":t.patch!==n.patch?d+"patch":"prerelease"};ng.exports=Uk});var og=A((L2,sg)=>{"use strict";var Vk=qe(),Bk=(r,e)=>new Vk(r,e).major;sg.exports=Bk});var cg=A((j2,ag)=>{"use strict";var zk=qe(),Hk=(r,e)=>new zk(r,e).minor;ag.exports=Hk});var dg=A((D2,lg)=>{"use strict";var Kk=qe(),Wk=(r,e)=>new Kk(r,e).patch;lg.exports=Wk});var fg=A((q2,ug)=>{"use strict";var Gk=Gr(),Jk=(r,e)=>{let t=Gk(r,e);return t&&t.prerelease.length?t.prerelease:null};ug.exports=Jk});var xt=A((F2,hg)=>{"use strict";var pg=qe(),Yk=(r,e,t)=>new pg(r,t).compare(new pg(e,t));hg.exports=Yk});var yg=A((U2,mg)=>{"use strict";var Xk=xt(),Qk=(r,e,t)=>Xk(e,r,t);mg.exports=Qk});var _g=A((V2,gg)=>{"use strict";var Zk=xt(),eP=(r,e)=>Zk(r,e,!0);gg.exports=eP});var aa=A((B2,wg)=>{"use strict";var bg=qe(),tP=(r,e,t)=>{let n=new bg(r,t),i=new bg(e,t);return n.compare(i)||n.compareBuild(i)};wg.exports=tP});var $g=A((z2,vg)=>{"use strict";var rP=aa(),nP=(r,e)=>r.sort((t,n)=>rP(t,n,e));vg.exports=nP});var Eg=A((H2,Sg)=>{"use strict";var iP=aa(),sP=(r,e)=>r.sort((t,n)=>iP(n,t,e));Sg.exports=sP});var ws=A((K2,Ag)=>{"use strict";var oP=xt(),aP=(r,e,t)=>oP(r,e,t)>0;Ag.exports=aP});var ca=A((W2,xg)=>{"use strict";var cP=xt(),lP=(r,e,t)=>cP(r,e,t)<0;xg.exports=lP});var gu=A((G2,kg)=>{"use strict";var dP=xt(),uP=(r,e,t)=>dP(r,e,t)===0;kg.exports=uP});var _u=A((J2,Pg)=>{"use strict";var fP=xt(),pP=(r,e,t)=>fP(r,e,t)!==0;Pg.exports=pP});var la=A((Y2,Ig)=>{"use strict";var hP=xt(),mP=(r,e,t)=>hP(r,e,t)>=0;Ig.exports=mP});var da=A((X2,Og)=>{"use strict";var yP=xt(),gP=(r,e,t)=>yP(r,e,t)<=0;Og.exports=gP});var bu=A((Q2,Rg)=>{"use strict";var _P=gu(),bP=_u(),wP=ws(),vP=la(),$P=ca(),SP=da(),EP=(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 _P(r,t,n);case"!=":return bP(r,t,n);case">":return wP(r,t,n);case">=":return vP(r,t,n);case"<":return $P(r,t,n);case"<=":return SP(r,t,n);default:throw new TypeError(`Invalid operator: ${e}`)}};Rg.exports=EP});var Mg=A((Z2,Tg)=>{"use strict";var AP=qe(),xP=Gr(),{safeRe:ua,t:fa}=ci(),kP=(r,e)=>{if(r instanceof AP)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?ua[fa.COERCEFULL]:ua[fa.COERCE]);else{let c=e.includePrerelease?ua[fa.COERCERTLFULL]:ua[fa.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 xP(`${n}.${i}.${s}${o}${a}`,e)};Tg.exports=kP});var Ng=A((eL,Cg)=>{"use strict";var PP=Gr(),IP=ai(),OP=qe(),RP=(r,e,t)=>{if(!IP.RELEASE_TYPES.includes(e))return null;let n=TP(r,t);return n&&MP(n,e)},TP=(r,e)=>{let t=r instanceof OP?r.version:r;return PP(t,e)},MP=(r,e)=>{if(CP(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()},CP=r=>r.startsWith("pre");Cg.exports=RP});var jg=A((tL,Lg)=>{"use strict";var wu=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}};Lg.exports=wu});var kt=A((rL,Ug)=>{"use strict";var NP=/\s+/g,vu=class r{constructor(e,t){if(t=jP(t),e instanceof r)return e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease?e:new r(e.raw,t);if(e instanceof $u)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(NP," "),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=>!qg(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&&KP(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(HP,"");let n=((this.options.includePrerelease&&BP)|(this.options.loose&&zP))+":"+e,i=Dg.get(n);if(i)return i;let s=this.options.loose,o=s?Qe[Fe.HYPHENRANGELOOSE]:Qe[Fe.HYPHENRANGE];e=e.replace(o,nI(this.options.includePrerelease)),we("hyphen replace",e),e=e.replace(Qe[Fe.COMPARATORTRIM],FP),we("comparator trim",e),e=e.replace(Qe[Fe.TILDETRIM],UP),we("tilde trim",e),e=e.replace(Qe[Fe.CARETTRIM],VP),we("caret trim",e);let a=e.split(" ").map(u=>WP(u,this.options)).join(" ").split(/\s+/).map(u=>rI(u,this.options));s&&(a=a.filter(u=>(we("loose invalid filter",u,this.options),!!u.match(Qe[Fe.COMPARATORLOOSE])))),we("range list",a);let c=new Map,l=a.map(u=>new $u(u,this.options));for(let u of l){if(qg(u))return[u];c.set(u.value,u)}c.size>1&&c.has("")&&c.delete("");let d=[...c.values()];return Dg.set(n,d),d}intersects(e,t){if(!(e instanceof r))throw new TypeError("a Range is required");return this.set.some(n=>Fg(n,t)&&e.set.some(i=>Fg(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 DP(e,this.options)}catch(t){return!1}for(let t=0;tr.value==="<0.0.0-0",KP=r=>r.value==="",Fg=(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},WP=(r,e)=>(r=r.replace(Qe[Fe.BUILD],""),we("comp",r,e),r=XP(r,e),we("caret",r),r=JP(r,e),we("tildes",r),r=ZP(r,e),we("xrange",r),r=tI(r,e),we("stars",r),r),Re=r=>!r||r.toLowerCase()==="x"||r==="*",GP=(r,e,t)=>Re(r)&&!Re(e)||Re(e)&&t&&!Re(t),JP=(r,e)=>r.trim().split(/\s+/).map(t=>YP(t,e)).join(" "),YP=(r,e)=>{let t=e.loose?Qe[Fe.TILDELOOSE]:Qe[Fe.TILDE],n=e.includePrerelease?"-0":"";return r.replace(t,(i,s,o,a,c)=>{we("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?(we("replaceTilde pr",c),l=`>=${s}.${o}.${a}-${c} <${s}.${+o+1}.0-0`):l=`>=${s}.${o}.${a} <${s}.${+o+1}.0-0`,we("tilde return",l),l})},XP=(r,e)=>r.trim().split(/\s+/).map(t=>QP(t,e)).join(" "),QP=(r,e)=>{we("caret",r,e);let t=e.loose?Qe[Fe.CARETLOOSE]:Qe[Fe.CARET],n=e.includePrerelease?"-0":"";return r.replace(t,(i,s,o,a,c)=>{we("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?(we("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`):(we("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`),we("caret return",l),l})},ZP=(r,e)=>(we("replaceXRanges",r,e),r.split(/\s+/).map(t=>eI(t,e)).join(" ")),eI=(r,e)=>{r=r.trim();let t=e.loose?Qe[Fe.XRANGELOOSE]:Qe[Fe.XRANGE];return r.replace(t,(n,i,s,o,a,c)=>{if(we("xRange",r,n,i,s,o,a,c),GP(s,o,a))return r;let l=Re(s),d=l||Re(o),u=d||Re(a),f=u;return i==="="&&f&&(i=""),c=e.includePrerelease?"-0":"",l?i===">"||i==="<"?n="<0.0.0-0":n="*":i&&f?(d&&(o=0),a=0,i===">"?(i=">=",d?(s=+s+1,o=0,a=0):(o=+o+1,a=0)):i==="<="&&(i="<",d?s=+s+1:o=+o+1),i==="<"&&(c="-0"),n=`${i+s}.${o}.${a}${c}`):d?n=`>=${s}.0.0${c} <${+s+1}.0.0-0`:u&&(n=`>=${s}.${o}.0${c} <${s}.${+o+1}.0-0`),we("xRange return",n),n})},tI=(r,e)=>(we("replaceStars",r,e),r.trim().replace(Qe[Fe.STAR],"")),rI=(r,e)=>(we("replaceGTE0",r,e),r.trim().replace(Qe[e.includePrerelease?Fe.GTE0PRE:Fe.GTE0],"")),nI=r=>(e,t,n,i,s,o,a,c,l,d,u,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(d)?c=`<${+l+1}.0.0-0`:Re(u)?c=`<${l}.${+d+1}.0-0`:f?c=`<=${l}.${d}.${u}-${f}`:r?c=`<${l}.${d}.${+u+1}-0`:c=`<=${c}`,`${t} ${c}`.trim()),iI=(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 vs=A((nL,Wg)=>{"use strict";var $s=Symbol("SemVer ANY"),Au=class r{static get ANY(){return $s}constructor(e,t){if(t=Vg(t),e instanceof r){if(e.loose===!!t.loose)return e;e=e.value}e=e.trim().split(/\s+/).join(" "),Eu("comparator",e,t),this.options=t,this.loose=!!t.loose,this.parse(e),this.semver===$s?this.value="":this.value=this.operator+this.semver.version,Eu("comp",this)}parse(e){let t=this.options.loose?Bg[zg.COMPARATORLOOSE]:Bg[zg.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 Hg(n[2],this.options.loose):this.semver=$s}toString(){return this.value}test(e){if(Eu("Comparator.test",e,this.options.loose),this.semver===$s||e===$s)return!0;if(typeof e=="string")try{e=new Hg(e,this.options)}catch(t){return!1}return Su(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 Kg(e.value,t).test(this.value):e.operator===""?e.value===""?!0:new Kg(this.value,t).test(e.semver):(t=Vg(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("=")||Su(this.semver,"<",e.semver,t)&&this.operator.startsWith(">")&&e.operator.startsWith("<")||Su(this.semver,">",e.semver,t)&&this.operator.startsWith("<")&&e.operator.startsWith(">")))}};Wg.exports=Au;var Vg=ra(),{safeRe:Bg,t:zg}=ci(),Su=bu(),Eu=bs(),Hg=qe(),Kg=kt()});var Ss=A((iL,Gg)=>{"use strict";var sI=kt(),oI=(r,e,t)=>{try{e=new sI(e,t)}catch(n){return!1}return e.test(r)};Gg.exports=oI});var Yg=A((sL,Jg)=>{"use strict";var aI=kt(),cI=(r,e)=>new aI(r,e).set.map(t=>t.map(n=>n.value).join(" ").trim().split(" "));Jg.exports=cI});var Qg=A((oL,Xg)=>{"use strict";var lI=qe(),dI=kt(),uI=(r,e,t)=>{let n=null,i=null,s=null;try{s=new dI(e,t)}catch(o){return null}return r.forEach(o=>{s.test(o)&&(!n||i.compare(o)===-1)&&(n=o,i=new lI(n,t))}),n};Xg.exports=uI});var e_=A((aL,Zg)=>{"use strict";var fI=qe(),pI=kt(),hI=(r,e,t)=>{let n=null,i=null,s=null;try{s=new pI(e,t)}catch(o){return null}return r.forEach(o=>{s.test(o)&&(!n||i.compare(o)===1)&&(n=o,i=new fI(n,t))}),n};Zg.exports=hI});var n_=A((cL,r_)=>{"use strict";var xu=qe(),mI=kt(),t_=ws(),yI=(r,e)=>{r=new mI(r,e);let t=new xu("0.0.0");if(r.test(t)||(t=new xu("0.0.0-0"),r.test(t)))return t;t=null;for(let n=0;n{let a=new xu(o.semver.version);switch(o.operator){case">":a.prerelease.length===0?a.patch++:a.prerelease.push(0),a.raw=a.format();case"":case">=":(!s||t_(a,s))&&(s=a);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${o.operator}`)}}),s&&(!t||t_(t,s))&&(t=s)}return t&&r.test(t)?t:null};r_.exports=yI});var s_=A((lL,i_)=>{"use strict";var gI=kt(),_I=(r,e)=>{try{return new gI(r,e).range||"*"}catch(t){return null}};i_.exports=_I});var pa=A((dL,l_)=>{"use strict";var bI=qe(),c_=vs(),{ANY:wI}=c_,vI=kt(),$I=Ss(),o_=ws(),a_=ca(),SI=da(),EI=la(),AI=(r,e,t,n)=>{r=new bI(r,n),e=new vI(e,n);let i,s,o,a,c;switch(t){case">":i=o_,s=SI,o=a_,a=">",c=">=";break;case"<":i=a_,s=EI,o=o_,a="<",c="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if($I(r,e,n))return!1;for(let l=0;l{p.semver===wI&&(p=new c_(">=0.0.0")),u=u||p,f=f||p,i(p.semver,u.semver,n)?u=p:o(p.semver,f.semver,n)&&(f=p)}),u.operator===a||u.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};l_.exports=AI});var u_=A((uL,d_)=>{"use strict";var xI=pa(),kI=(r,e,t)=>xI(r,e,">",t);d_.exports=kI});var p_=A((fL,f_)=>{"use strict";var PI=pa(),II=(r,e,t)=>PI(r,e,"<",t);f_.exports=II});var y_=A((pL,m_)=>{"use strict";var h_=kt(),OI=(r,e,t)=>(r=new h_(r,t),e=new h_(e,t),r.intersects(e,t));m_.exports=OI});var __=A((hL,g_)=>{"use strict";var RI=Ss(),TI=xt();g_.exports=(r,e,t)=>{let n=[],i=null,s=null,o=r.sort((d,u)=>TI(d,u,t));for(let d of o)RI(d,e,t)?(s=d,i||(i=d)):(s&&n.push([i,s]),s=null,i=null);i&&n.push([i,null]);let a=[];for(let[d,u]of n)d===u?a.push(d):!u&&d===o[0]?a.push("*"):u?d===o[0]?a.push(`<=${u}`):a.push(`${d} - ${u}`):a.push(`>=${d}`);let c=a.join(" || "),l=typeof e.raw=="string"?e.raw:String(e);return c.length{"use strict";var b_=kt(),Iu=vs(),{ANY:ku}=Iu,Pu=Ss(),Ou=xt(),MI=(r,e,t={})=>{if(r===e)return!0;r=new b_(r,t),e=new b_(e,t);let n=!1;e:for(let i of r.set){for(let s of e.set){let o=NI(i,s,t);if(n=n||o!==null,o)continue e}if(n)return!1}return!0},CI=[new Iu(">=0.0.0-0")],w_=[new Iu(">=0.0.0")],NI=(r,e,t)=>{if(r===e)return!0;if(r.length===1&&r[0].semver===ku){if(e.length===1&&e[0].semver===ku)return!0;t.includePrerelease?r=CI:r=w_}if(e.length===1&&e[0].semver===ku){if(t.includePrerelease)return!0;e=w_}let n=new Set,i,s;for(let p of r)p.operator===">"||p.operator===">="?i=v_(i,p,t):p.operator==="<"||p.operator==="<="?s=$_(s,p,t):n.add(p.semver);if(n.size>1)return null;let o;if(i&&s){if(o=Ou(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&&!Pu(p,String(i),t)||s&&!Pu(p,String(s),t))return null;for(let y of e)if(!Pu(p,String(y),t))return!1;return!0}let a,c,l,d,u=s&&!t.includePrerelease&&s.semver.prerelease.length?s.semver:!1,f=i&&!t.includePrerelease&&i.semver.prerelease.length?i.semver:!1;u&&u.prerelease.length===1&&s.operator==="<"&&u.prerelease[0]===0&&(u=!1);for(let p of e){if(d=d||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=v_(i,p,t),a===p&&a!==i)return!1}else if(i.operator===">="&&!p.test(i.semver))return!1}if(s){if(u&&p.semver.prerelease&&p.semver.prerelease.length&&p.semver.major===u.major&&p.semver.minor===u.minor&&p.semver.patch===u.patch&&(u=!1),p.operator==="<"||p.operator==="<="){if(c=$_(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&&d&&!i&&o!==0||f||u)},v_=(r,e,t)=>{if(!r)return e;let n=Ou(r.semver,e.semver,t);return n>0?r:n<0||e.operator===">"&&r.operator===">="?e:r},$_=(r,e,t)=>{if(!r)return e;let n=Ou(r.semver,e.semver,t);return n<0?r:n>0||e.operator==="<"&&r.operator==="<="?e:r};S_.exports=MI});var P_=A((yL,k_)=>{"use strict";var Ru=ci(),A_=ai(),LI=qe(),x_=hu(),jI=Gr(),DI=Yy(),qI=Qy(),FI=tg(),UI=ig(),VI=og(),BI=cg(),zI=dg(),HI=fg(),KI=xt(),WI=yg(),GI=_g(),JI=aa(),YI=$g(),XI=Eg(),QI=ws(),ZI=ca(),eO=gu(),tO=_u(),rO=la(),nO=da(),iO=bu(),sO=Mg(),oO=Ng(),aO=vs(),cO=kt(),lO=Ss(),dO=Yg(),uO=Qg(),fO=e_(),pO=n_(),hO=s_(),mO=pa(),yO=u_(),gO=p_(),_O=y_(),bO=__(),wO=E_();k_.exports={parse:jI,valid:DI,clean:qI,inc:FI,diff:UI,major:VI,minor:BI,patch:zI,prerelease:HI,compare:KI,rcompare:WI,compareLoose:GI,compareBuild:JI,sort:YI,rsort:XI,gt:QI,lt:ZI,eq:eO,neq:tO,gte:rO,lte:nO,cmp:iO,coerce:sO,truncate:oO,Comparator:aO,Range:cO,satisfies:lO,toComparators:dO,maxSatisfying:uO,minSatisfying:fO,minVersion:pO,validRange:hO,outside:mO,gtr:yO,ltr:gO,intersects:_O,simplifyRange:bO,subset:wO,SemVer:LI,re:Ru.re,src:Ru.src,tokens:Ru.t,SEMVER_SPEC_VERSION:A_.SEMVER_SPEC_VERSION,RELEASE_TYPES:A_.RELEASE_TYPES,compareIdentifiers:x_.compareIdentifiers,rcompareIdentifiers:x_.rcompareIdentifiers}});var As=A((CL,D_)=>{"use strict";var C_="[^\\\\/]",IO="(?=.)",N_="[^/]",Lu="(?:\\/|$)",L_="(?:^|\\/)",ju=`\\.{1,2}${Lu}`,OO="(?!\\.)",RO=`(?!${L_}${ju})`,TO=`(?!\\.{0,1}${Lu})`,MO=`(?!${ju})`,CO="[^.\\/]",NO=`${N_}*?`,LO="/",j_={DOT_LITERAL:"\\.",PLUS_LITERAL:"\\+",QMARK_LITERAL:"\\?",SLASH_LITERAL:"\\/",ONE_CHAR:IO,QMARK:N_,END_ANCHOR:Lu,DOTS_SLASH:ju,NO_DOT:OO,NO_DOTS:RO,NO_DOT_SLASH:TO,NO_DOTS_SLASH:MO,QMARK_NO_DOT:CO,STAR:NO,START_ANCHOR:L_,SEP:LO},jO={...j_,SLASH_LITERAL:"[\\\\/]",QMARK:C_,STAR:`${C_}*?`,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:"\\"},DO={__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"};D_.exports={DEFAULT_MAX_EXTGLOB_RECURSION:0,MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:DO,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?jO:j_}}});var xs=A(lt=>{"use strict";var{REGEX_BACKSLASH:qO,REGEX_REMOVE_BACKSLASH:FO,REGEX_SPECIAL_CHARS:UO,REGEX_SPECIAL_CHARS_GLOBAL:VO}=As();lt.isObject=r=>r!==null&&typeof r=="object"&&!Array.isArray(r);lt.hasRegexChars=r=>UO.test(r);lt.isRegexChar=r=>r.length===1&<.hasRegexChars(r);lt.escapeRegex=r=>r.replace(VO,"\\$1");lt.toPosixSlashes=r=>r.replace(qO,"/");lt.isWindows=()=>{if(typeof navigator!="undefined"&&navigator.platform){let r=navigator.platform.toLowerCase();return r==="win32"||r==="windows"}return typeof process!="undefined"&&process.platform?process.platform==="win32":!1};lt.removeBackslashes=r=>r.replace(FO,e=>e==="\\"?"":e);lt.escapeLast=(r,e,t)=>{let n=r.lastIndexOf(e,t);return n===-1?r:r[n-1]==="\\"?lt.escapeLast(r,e,n-1):`${r.slice(0,n)}\\${r.slice(n)}`};lt.removePrefix=(r,e={})=>{let t=r;return t.startsWith("./")&&(t=t.slice(2),e.prefix="./"),t};lt.wrapOutput=(r,e={},t={})=>{let n=t.contains?"":"^",i=t.contains?"":"$",s=`${n}(?:${r})${i}`;return e.negated===!0&&(s=`(?:^(?!${s}).*$)`),s};lt.basename=(r,{windows:e}={})=>{let t=r.split(e?/[\\/]/:"/"),n=t[t.length-1];return n===""?t[t.length-2]:n}});var K_=A((LL,H_)=>{"use strict";var q_=xs(),{CHAR_ASTERISK:Du,CHAR_AT:BO,CHAR_BACKWARD_SLASH:ks,CHAR_COMMA:zO,CHAR_DOT:qu,CHAR_EXCLAMATION_MARK:Fu,CHAR_FORWARD_SLASH:z_,CHAR_LEFT_CURLY_BRACE:Uu,CHAR_LEFT_PARENTHESES:Vu,CHAR_LEFT_SQUARE_BRACKET:HO,CHAR_PLUS:KO,CHAR_QUESTION_MARK:F_,CHAR_RIGHT_CURLY_BRACE:WO,CHAR_RIGHT_PARENTHESES:U_,CHAR_RIGHT_SQUARE_BRACKET:GO}=As(),V_=r=>r===z_||r===ks,B_=r=>{r.isPrefix!==!0&&(r.depth=r.isGlobstar?1/0:1)},JO=(r,e)=>{let t=e||{},n=r.length-1,i=t.parts===!0||t.scanToEnd===!0,s=[],o=[],a=[],c=r,l=-1,d=0,u=0,f=!1,p=!1,y=!1,h=!1,m=!1,g=!1,_=!1,w=!1,k=!1,v=!1,P=0,O,$,R={value:"",depth:0,isGlob:!1},S=()=>l>=n,V=()=>c.charCodeAt(l+1),B=()=>(O=$,c.charCodeAt(++l));for(;l0&&(E=c.slice(0,d),c=c.slice(d),u-=d),T&&y===!0&&u>0?(T=c.slice(0,u),x=c.slice(u)):y===!0?(T="",x=c):T=c,T&&T!==""&&T!=="/"&&T!==c&&V_(T.charCodeAt(T.length-1))&&(T=T.slice(0,-1)),t.unescape===!0&&(x&&(x=q_.removeBackslashes(x)),T&&_===!0&&(T=q_.removeBackslashes(T)));let de={prefix:E,input:r,start:d,base:T,glob:x,isBrace:f,isBracket:p,isGlob:y,isExtglob:h,isGlobstar:m,negated:w,negatedExtglob:k};if(t.tokens===!0&&(de.maxDepth=0,V_($)||o.push(R),de.tokens=o),t.parts===!0||t.tokens===!0){let Z;for(let U=0;U{"use strict";var Ps=As(),mt=xs(),{MAX_LENGTH:ga,POSIX_REGEX_SOURCE:YO,REGEX_NON_SPECIAL_CHARS:XO,REGEX_SPECIAL_CHARS_BACKREF:QO,REPLACEMENTS:W_}=Ps,ZO=(r,e)=>{if(typeof e.expandRange=="function")return e.expandRange(...r,e);r.sort();let t=`[${r.join("-")}]`;try{new RegExp(t)}catch(n){return r.map(i=>mt.escapeRegex(i)).join("..")}return t},li=(r,e)=>`Missing ${r}: "${e}" - use "\\\\${e}" to match literal characters`,G_=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},eR=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},zu=r=>{let e=r.trim(),t=!0;for(;t===!0;)t=!1,/^@\([^\\()[\]{}|]+\)$/.test(e)&&(e=e.slice(2,-1),t=!0);if(eR(e))return e.replace(/\\(.)/g,"$1")},tR=r=>{let e=r.map(zu).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}}}}},rR=r=>`${r.length===1?mt.escapeRegex(r[0]):`[${r.map(t=>mt.escapeRegex(t)).join("")}]`}*`,nR=r=>{let e=0,t=[];for(;eo.trim());if(i.length!==1)return;let s=zu(i[0]);if(!s||s.length!==1)return;t.push(s),e+=n.end+1}if(!(t.length<1))return t},iR=r=>{let e=0,t=r.trim(),n=Bu(t);for(;n;)e++,t=n.body.trim(),n=Bu(t);return e},sR=(r,e)=>{if(e.maxExtglobRecursion===!1)return{risky:!1};let t=typeof e.maxExtglobRecursion=="number"?e.maxExtglobRecursion:Ps.DEFAULT_MAX_EXTGLOB_RECURSION,n=G_(r).map(a=>a.trim());if(n.length>1&&(n.some(a=>a==="")||n.some(a=>/^[*?]+$/.test(a))||tR(n)))return{risky:!0};let i=[],s=!1,o=!0;for(let a of n){let c=nR(a);if(c){s=!0,i.push(...c);continue}let l=zu(a);if(l&&l.length===1){i.push(l);continue}if(o=!1,iR(a)>t)return{risky:!0}}return s?o?{risky:!0,safeOutput:rR([...new Set(i)])}:{risky:!0}:{risky:!1}},Hu=(r,e)=>{if(typeof r!="string")throw new TypeError("Expected a string");r=W_[r]||r;let t={...e},n=typeof t.maxLength=="number"?Math.min(ga,t.maxLength):ga,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=Ps.globChars(t.windows),l=Ps.extglobChars(c),{DOT_LITERAL:d,PLUS_LITERAL:u,SLASH_LITERAL:f,ONE_CHAR:p,DOTS_SLASH:y,NO_DOT:h,NO_DOT_SLASH:m,NO_DOTS_SLASH:g,QMARK:_,QMARK_NO_DOT:w,STAR:k,START_ANCHOR:v}=c,P=C=>`(${a}(?:(?!${v}${C.dot?y:d}).)*?)`,O=t.dot?"":h,$=t.dot?_:w,R=t.bash===!0?P(t):k;t.capture&&(R=`(${R})`),typeof t.noext=="boolean"&&(t.noextglob=t.noext);let S={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=mt.removePrefix(r,S),i=r.length;let V=[],B=[],T=[],E=s,x,de=()=>S.index===i-1,Z=S.peek=(C=1)=>r[S.index+C],U=S.advance=()=>r[++S.index]||"",fe=()=>r.slice(S.index+1),Ve=(C="",$e=0)=>{S.consumed+=C,S.index+=$e},Yt=C=>{S.output+=C.output!=null?C.output:C.value,Ve(C.value)},Lr=()=>{let C=1;for(;Z()==="!"&&(Z(2)!=="("||Z(3)==="?");)U(),S.start++,C++;return C%2===0?!1:(S.negated=!0,S.start++,!0)},ln=C=>{S[C]++,T.push(C)},jr=C=>{S[C]--,T.pop()},ee=C=>{if(E.type==="globstar"){let $e=S.braces>0&&(C.type==="comma"||C.type==="brace"),M=C.extglob===!0||V.length&&(C.type==="pipe"||C.type==="paren");C.type!=="slash"&&C.type!=="paren"&&!$e&&!M&&(S.output=S.output.slice(0,-E.output.length),E.type="star",E.value="*",E.output=R,S.output+=E.output)}if(V.length&&C.type!=="paren"&&(V[V.length-1].inner+=C.value),(C.value||C.output)&&Yt(C),E&&E.type==="text"&&C.type==="text"){E.output=(E.output||E.value)+C.value,E.value+=C.value;return}C.prev=E,o.push(C),E=C},go=(C,$e)=>{let M={...l[$e],conditions:1,inner:""};M.prev=E,M.parens=S.parens,M.output=S.output,M.startIndex=S.index,M.tokensIndex=o.length;let te=(t.capture?"(":"")+M.open;ln("parens"),ee({type:C,value:$e,output:S.output?"":p}),ee({type:"paren",extglob:!0,value:U(),output:te}),V.push(M)},U0=C=>{let $e=r.slice(C.startIndex,S.index+1),M=r.slice(C.startIndex+2,S.index),te=sR(M,t);if((C.type==="plus"||C.type==="star")&&te.risky){let he=te.safeOutput?(C.output?"":p)+(t.capture?`(${te.safeOutput})`:te.safeOutput):void 0,Xt=o[C.tokensIndex];Xt.type="text",Xt.value=$e,Xt.output=he||mt.escapeRegex($e);for(let Qt=C.tokensIndex+1;Qt1&&C.inner.includes("/")&&(he=P(t)),(he!==R||de()||/^\)+$/.test(fe()))&&(ye=C.close=`)$))${he}`),C.inner.includes("*")&&(Oe=fe())&&/^\.[^\\/.]+$/.test(Oe)){let Xt=Hu(Oe,{...e,fastpaths:!1}).output;ye=C.close=`)${Xt})${he})`}C.prev.type==="bos"&&(S.negatedExtglob=!0)}ee({type:"paren",extglob:!0,value:x,output:ye}),jr("parens")};if(t.fastpaths!==!1&&!/(^[*!]|[/()[\]{}"])/.test(r)){let C=!1,$e=r.replace(QO,(M,te,ye,Oe,he,Xt)=>Oe==="\\"?(C=!0,M):Oe==="?"?te?te+Oe+(he?_.repeat(he.length):""):Xt===0?$+(he?_.repeat(he.length):""):_.repeat(ye.length):Oe==="."?d.repeat(ye.length):Oe==="*"?te?te+Oe+(he?R:""):R:te?M:`\\${M}`);return C===!0&&(t.unescape===!0?$e=$e.replace(/\\/g,""):$e=$e.replace(/\\+/g,M=>M.length%2===0?"\\\\":M?"\\":"")),$e===r&&t.contains===!0?(S.output=r,S):(S.output=mt.wrapOutput($e,S,e),S)}for(;!de();){if(x=U(),x==="\0")continue;if(x==="\\"){let M=Z();if(M==="/"&&t.bash!==!0||M==="."||M===";")continue;if(!M){x+="\\",ee({type:"text",value:x});continue}let te=/^\\+/.exec(fe()),ye=0;if(te&&te[0].length>2&&(ye=te[0].length,S.index+=ye,ye%2!==0&&(x+="\\")),t.unescape===!0?x=U():x+=U(),S.brackets===0){ee({type:"text",value:x});continue}}if(S.brackets>0&&(x!=="]"||E.value==="["||E.value==="[^")){if(t.posix!==!1&&x===":"){let M=E.value.slice(1);if(M.includes("[")&&(E.posix=!0,M.includes(":"))){let te=E.value.lastIndexOf("["),ye=E.value.slice(0,te),Oe=E.value.slice(te+2),he=YO[Oe];if(he){E.value=ye+he,S.backtrack=!0,U(),!s.output&&o.indexOf(E)===1&&(s.output=p);continue}}}(x==="["&&Z()!==":"||x==="-"&&Z()==="]")&&(x=`\\${x}`),x==="]"&&(E.value==="["||E.value==="[^")&&(x=`\\${x}`),t.posix===!0&&x==="!"&&E.value==="["&&(x="^"),E.value+=x,Yt({value:x});continue}if(S.quotes===1&&x!=='"'){x=mt.escapeRegex(x),E.value+=x,Yt({value:x});continue}if(x==='"'){S.quotes=S.quotes===1?0:1,t.keepQuotes===!0&&ee({type:"text",value:x});continue}if(x==="("){ln("parens"),ee({type:"paren",value:x});continue}if(x===")"){if(S.parens===0&&t.strictBrackets===!0)throw new SyntaxError(li("opening","("));let M=V[V.length-1];if(M&&S.parens===M.parens+1){U0(V.pop());continue}ee({type:"paren",value:x,output:S.parens?")":"\\)"}),jr("parens");continue}if(x==="["){if(t.nobracket===!0||!fe().includes("]")){if(t.nobracket!==!0&&t.strictBrackets===!0)throw new SyntaxError(li("closing","]"));x=`\\${x}`}else ln("brackets");ee({type:"bracket",value:x});continue}if(x==="]"){if(t.nobracket===!0||E&&E.type==="bracket"&&E.value.length===1){ee({type:"text",value:x,output:`\\${x}`});continue}if(S.brackets===0){if(t.strictBrackets===!0)throw new SyntaxError(li("opening","["));ee({type:"text",value:x,output:`\\${x}`});continue}jr("brackets");let M=E.value.slice(1);if(E.posix!==!0&&M[0]==="^"&&!M.includes("/")&&(x=`/${x}`),E.value+=x,Yt({value:x}),t.literalBrackets===!1||mt.hasRegexChars(M))continue;let te=mt.escapeRegex(E.value);if(S.output=S.output.slice(0,-E.value.length),t.literalBrackets===!0){S.output+=te,E.value=te;continue}E.value=`(${a}${te}|${E.value})`,S.output+=E.value;continue}if(x==="{"&&t.nobrace!==!0){ln("braces");let M={type:"brace",value:x,output:"(",outputIndex:S.output.length,tokensIndex:S.tokens.length};B.push(M),ee(M);continue}if(x==="}"){let M=B[B.length-1];if(t.nobrace===!0||!M){ee({type:"text",value:x,output:x});continue}let te=")";if(M.dots===!0){let ye=o.slice(),Oe=[];for(let he=ye.length-1;he>=0&&(o.pop(),ye[he].type!=="brace");he--)ye[he].type!=="dots"&&Oe.unshift(ye[he].value);te=ZO(Oe,t),S.backtrack=!0}if(M.comma!==!0&&M.dots!==!0){let ye=S.output.slice(0,M.outputIndex),Oe=S.tokens.slice(M.tokensIndex);M.value=M.output="\\{",x=te="\\}",S.output=ye;for(let he of Oe)S.output+=he.output||he.value}ee({type:"brace",value:x,output:te}),jr("braces"),B.pop();continue}if(x==="|"){V.length>0&&V[V.length-1].conditions++,ee({type:"text",value:x});continue}if(x===","){let M=x,te=B[B.length-1];te&&T[T.length-1]==="braces"&&(te.comma=!0,M="|"),ee({type:"comma",value:x,output:M});continue}if(x==="/"){if(E.type==="dot"&&S.index===S.start+1){S.start=S.index+1,S.consumed="",S.output="",o.pop(),E=s;continue}ee({type:"slash",value:x,output:f});continue}if(x==="."){if(S.braces>0&&E.type==="dot"){E.value==="."&&(E.output=d);let M=B[B.length-1];E.type="dots",E.output+=x,E.value+=x,M.dots=!0;continue}if(S.braces+S.parens===0&&E.type!=="bos"&&E.type!=="slash"){ee({type:"text",value:x,output:d});continue}ee({type:"dot",value:x,output:d});continue}if(x==="?"){if(!(E&&E.value==="(")&&t.noextglob!==!0&&Z()==="("&&Z(2)!=="?"){go("qmark",x);continue}if(E&&E.type==="paren"){let te=Z(),ye=x;(E.value==="("&&!/[!=<:]/.test(te)||te==="<"&&!/<([!=]|\w+>)/.test(fe()))&&(ye=`\\${x}`),ee({type:"text",value:x,output:ye});continue}if(t.dot!==!0&&(E.type==="slash"||E.type==="bos")){ee({type:"qmark",value:x,output:w});continue}ee({type:"qmark",value:x,output:_});continue}if(x==="!"){if(t.noextglob!==!0&&Z()==="("&&(Z(2)!=="?"||!/[!=<:]/.test(Z(3)))){go("negate",x);continue}if(t.nonegate!==!0&&S.index===0){Lr();continue}}if(x==="+"){if(t.noextglob!==!0&&Z()==="("&&Z(2)!=="?"){go("plus",x);continue}if(E&&E.value==="("||t.regex===!1){ee({type:"plus",value:x,output:u});continue}if(E&&(E.type==="bracket"||E.type==="paren"||E.type==="brace")||S.parens>0){ee({type:"plus",value:x});continue}ee({type:"plus",value:u});continue}if(x==="@"){if(t.noextglob!==!0&&Z()==="("&&Z(2)!=="?"){ee({type:"at",extglob:!0,value:x,output:""});continue}ee({type:"text",value:x});continue}if(x!=="*"){(x==="$"||x==="^")&&(x=`\\${x}`);let M=XO.exec(fe());M&&(x+=M[0],S.index+=M[0].length),ee({type:"text",value:x});continue}if(E&&(E.type==="globstar"||E.star===!0)){E.type="star",E.star=!0,E.value+=x,E.output=R,S.backtrack=!0,S.globstar=!0,Ve(x);continue}let C=fe();if(t.noextglob!==!0&&/^\([^?]/.test(C)){go("star",x);continue}if(E.type==="star"){if(t.noglobstar===!0){Ve(x);continue}let M=E.prev,te=M.prev,ye=M.type==="slash"||M.type==="bos",Oe=te&&(te.type==="star"||te.type==="globstar");if(t.bash===!0&&(!ye||C[0]&&C[0]!=="/")){ee({type:"star",value:x,output:""});continue}let he=S.braces>0&&(M.type==="comma"||M.type==="brace"),Xt=V.length&&(M.type==="pipe"||M.type==="paren");if(!ye&&M.type!=="paren"&&!he&&!Xt){ee({type:"star",value:x,output:""});continue}for(;C.slice(0,3)==="/**";){let Qt=r[S.index+4];if(Qt&&Qt!=="/")break;C=C.slice(3),Ve("/**",3)}if(M.type==="bos"&&de()){E.type="globstar",E.value+=x,E.output=P(t),S.output=E.output,S.globstar=!0,Ve(x);continue}if(M.type==="slash"&&M.prev.type!=="bos"&&!Oe&&de()){S.output=S.output.slice(0,-(M.output+E.output).length),M.output=`(?:${M.output}`,E.type="globstar",E.output=P(t)+(t.strictSlashes?")":"|$)"),E.value+=x,S.globstar=!0,S.output+=M.output+E.output,Ve(x);continue}if(M.type==="slash"&&M.prev.type!=="bos"&&C[0]==="/"){let Qt=C[1]!==void 0?"|$":"";S.output=S.output.slice(0,-(M.output+E.output).length),M.output=`(?:${M.output}`,E.type="globstar",E.output=`${P(t)}${f}|${f}${Qt})`,E.value+=x,S.output+=M.output+E.output,S.globstar=!0,Ve(x+U()),ee({type:"slash",value:"/",output:""});continue}if(M.type==="bos"&&C[0]==="/"){E.type="globstar",E.value+=x,E.output=`(?:^|${f}|${P(t)}${f})`,S.output=E.output,S.globstar=!0,Ve(x+U()),ee({type:"slash",value:"/",output:""});continue}S.output=S.output.slice(0,-E.output.length),E.type="globstar",E.output=P(t),E.value+=x,S.output+=E.output,S.globstar=!0,Ve(x);continue}let $e={type:"star",value:x,output:R};if(t.bash===!0){$e.output=".*?",(E.type==="bos"||E.type==="slash")&&($e.output=O+$e.output),ee($e);continue}if(E&&(E.type==="bracket"||E.type==="paren")&&t.regex===!0){$e.output=x,ee($e);continue}(S.index===S.start||E.type==="slash"||E.type==="dot")&&(E.type==="dot"?(S.output+=m,E.output+=m):t.dot===!0?(S.output+=g,E.output+=g):(S.output+=O,E.output+=O),Z()!=="*"&&(S.output+=p,E.output+=p)),ee($e)}for(;S.brackets>0;){if(t.strictBrackets===!0)throw new SyntaxError(li("closing","]"));S.output=mt.escapeLast(S.output,"["),jr("brackets")}for(;S.parens>0;){if(t.strictBrackets===!0)throw new SyntaxError(li("closing",")"));S.output=mt.escapeLast(S.output,"("),jr("parens")}for(;S.braces>0;){if(t.strictBrackets===!0)throw new SyntaxError(li("closing","}"));S.output=mt.escapeLast(S.output,"{"),jr("braces")}if(t.strictSlashes!==!0&&(E.type==="star"||E.type==="bracket")&&ee({type:"maybe_slash",value:"",output:`${f}?`}),S.backtrack===!0){S.output="";for(let C of S.tokens)S.output+=C.output!=null?C.output:C.value,C.suffix&&(S.output+=C.suffix)}return S};Hu.fastpaths=(r,e)=>{let t={...e},n=typeof t.maxLength=="number"?Math.min(ga,t.maxLength):ga,i=r.length;if(i>n)throw new SyntaxError(`Input length: ${i}, exceeds maximum allowed length: ${n}`);r=W_[r]||r;let{DOT_LITERAL:s,SLASH_LITERAL:o,ONE_CHAR:a,DOTS_SLASH:c,NO_DOT:l,NO_DOTS:d,NO_DOTS_SLASH:u,STAR:f,START_ANCHOR:p}=Ps.globChars(t.windows),y=t.dot?d:l,h=t.dot?u:l,m=t.capture?"":"?:",g={negated:!1,prefix:""},_=t.bash===!0?".*?":f;t.capture&&(_=`(${_})`);let w=O=>O.noglobstar===!0?_:`(${m}(?:(?!${p}${O.dot?c:s}).)*?)`,k=O=>{switch(O){case"*":return`${y}${a}${_}`;case".*":return`${s}${a}${_}`;case"*.*":return`${y}${_}${s}${a}${_}`;case"*/*":return`${y}${_}${o}${a}${h}${_}`;case"**":return y+w(t);case"**/*":return`(?:${y}${w(t)}${o})?${h}${a}${_}`;case"**/*.*":return`(?:${y}${w(t)}${o})?${h}${_}${s}${a}${_}`;case"**/.*":return`(?:${y}${w(t)}${o})?${s}${a}${_}`;default:{let $=/^(.*?)\.(\w+)$/.exec(O);if(!$)return;let R=k($[1]);return R?R+s+$[2]:void 0}}},v=mt.removePrefix(r,g),P=k(v);return P&&t.strictSlashes!==!0&&(P+=`${o}?`),P};J_.exports=Hu});var Z_=A((DL,Q_)=>{"use strict";var oR=K_(),Ku=Y_(),X_=xs(),aR=As(),cR=r=>r&&typeof r=="object"&&!Array.isArray(r),ke=(r,e,t=!1)=>{if(Array.isArray(r)){let d=r.map(f=>ke(f,e,t));return f=>{for(let p of d){let y=p(f);if(y)return y}return!1}}let n=cR(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?ke.compileRe(r,e):ke.makeRe(r,e,!1,!0),a=o.state;delete o.state;let c=()=>!1;if(i.ignore){let d={...e,ignore:null,onMatch:null,onResult:null};c=ke(i.ignore,d,t)}let l=(d,u=!1)=>{let{isMatch:f,match:p,output:y}=ke.test(d,o,e,{glob:r,posix:s}),h={glob:r,state:a,regex:o,posix:s,input:d,output:y,match:p,isMatch:f};return typeof i.onResult=="function"&&i.onResult(h),f===!1?(h.isMatch=!1,u?h:!1):c(d)?(typeof i.onIgnore=="function"&&i.onIgnore(h),h.isMatch=!1,u?h:!1):(typeof i.onMatch=="function"&&i.onMatch(h),u?h:!0)};return t&&(l.state=a),l};ke.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?X_.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=ke.matchBase(r,e,t,i):a=e.exec(c)),{isMatch:!!a,match:a,output:c}};ke.matchBase=(r,e,t,n=t&&t.windows)=>(e instanceof RegExp?e:ke.makeRe(e,t)).test(X_.basename(r,{windows:n}));ke.isMatch=(r,e,t)=>ke(e,t)(r);ke.parse=(r,e)=>Array.isArray(r)?r.map(t=>ke.parse(t,e)):Ku(r,{...e,fastpaths:!1});ke.scan=(r,e)=>oR(r,e);ke.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=ke.toRegex(a,e);return n===!0&&(c.state=r),c};ke.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=Ku.fastpaths(r,e)),i.output||(i=Ku(r,e)),ke.compileRe(i,e,t,n)};ke.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/$^/}};ke.constants=aR;Q_.exports=ke});var Wu=A((qL,rb)=>{"use strict";var eb=Z_(),lR=xs();function tb(r,e,t=!1){return e&&(e.windows===null||e.windows===void 0)&&(e={...e,windows:lR.isWindows()}),eb(r,e,t)}Object.assign(tb,eb);rb.exports=tb});var b,Ee=vp(()=>{b=class extends Error{constructor(t,n){super(n);I(this,"code");this.code=t}}});async function S0(r,e,t,n){if(r!=null&&r.batch){if(r.batch.plan.fingerprint!==e.fingerprint)throw new b("mirror_recovery_required","A different prepared sync batch must recover before this plan can apply.");return r}let i=r?structuredClone(r):HM(e.replica_id,e.scope_epoch,e.mode,e.selective_sync);return i.scope_epoch=e.scope_epoch,i.selective_sync=e.selective_sync,i.batch={phase:"prepared",plan:e,next_action:0,receipts:[],payloads:t,checkpoint_before:{generation:e.checkpoint_generation,cursor:e.base_cursor},checkpoint_after:{generation:e.checkpoint_generation+1,cursor:e.authority_cursor}},await n.write(i),i}async function E0(r,e){let t=nt(r);t.phase!=="effects_complete"&&(t.phase="applying",delete t.failure,await Tc(r,{type:"phase",plan_fingerprint:t.plan.fingerprint,phase:"applying"},e))}async function A0(r,e,t){let n=nt(r),i=n.plan.actions[n.next_action];if(!i||i.action_id!==e.action_id)throw new b("invalid_mirror_state","The durable sync receipt does not match the next prepared action.");let s={type:"receipt",plan_fingerprint:n.plan.fingerprint,receipt:structuredClone(e),delta:zM(r,i)};n.receipts.push(structuredClone(e)),n.next_action+=1,await Tc(r,s,t)}async function x0(r,e){let t=nt(r),n=t.plan.actions[t.next_action];if(!n||n.command!=="advance_checkpoint")throw new b("invalid_mirror_state","Sync effects cannot complete before the checkpoint action is next.");t.phase="effects_complete",await Tc(r,{type:"effects_complete",plan_fingerprint:t.plan.fingerprint},e)}async function Rc(r,e,t,n){let i=nt(r);i.phase=e,i.failure=t,await Tc(r,{type:"phase",plan_fingerprint:i.plan.fingerprint,phase:e,failure:t},n)}async function Tc(r,e,t){t.appendJournal?await t.appendJournal(e):await t.write(r)}function zM(r,e){var s,o,a,c;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]:io((s=r.planned_conflicts)==null?void 0:s[t])},local_bindings:{[t]:io((o=r.local_bindings)==null?void 0:o[t])}};return n==="record"?i.records={[t]:io(r.records[t])}:n==="resource"?i.resources={[t]:io((a=r.resources)==null?void 0:a[t])}:i.files={[t]:io((c=r.files)==null?void 0:c[t])},i}function io(r){return r===void 0?null:structuredClone(r)}function nt(r){if(!r.batch)throw new b("invalid_mirror_state","The mirror has no prepared sync batch.");return r.batch}async function k0(r,e){var n;let t=nt(r);if(t.phase!=="blocked"||((n=t.failure)==null?void 0:n.code)!=="sync_plan_stale")throw new b("mirror_recovery_required","Only a stale batch at a durable action boundary can be abandoned.");delete r.batch,await e.write(r)}function HM(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 Mc=vp(()=>{Ee()});var MC={};G0(MC,{default:()=>zc});module.exports=J0(MC);var L=require("obsidian");var N=class extends Error{constructor(t,n,i){super(n);I(this,"code");I(this,"details");this.code=t,this.details=i,this.name="InteropError"}toPortableError(t){return{code:this.code,message:this.message,...this.details===void 0?{}:{details:this.details},...t===void 0?{}:{retryable:t}}}},Ui=class extends Error{constructor(t,n){super(n.message);I(this,"status");I(this,"error");this.status=t,this.error=n,this.name="ActionHandlerError"}};var Ty=dn(Qd(),1),My=dn(cu(),1);var lu={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 fk=My.default;function Cy(){return Object.fromEntries(Object.entries(lu).map(([r,e])=>[r,structuredClone(e)]))}function du(){let r=new Ty.Ajv2020({allErrors:!0,strict:!1,validateFormats:!0});fk(r);let e=Cy();r.addSchema(e.profile);for(let[t,n]of Object.entries(e))t!=="profile"&&r.addSchema(n);return r}function br(r,e){let t=String(lu[e].$id),n=r.getSchema(t);if(!n)throw new Error(`Canonical interoperability schema is unavailable: ${e}`);return n}function Wr(r){return(r!=null?r:[]).map(e=>{var t;return`${e.instancePath||"/"} ${(t=e.message)!=null?t:e.keyword}`}).join("; ")}function ir(r,e){if(!("value"in r))throw new N("contract_digest_conflict",`${e} must be resolved to an inline JSON Schema before runtime registration.`);return structuredClone(r.value)}function Ny(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=ir(r.record_schema,"record_schema"),r.binding_schema&&(e.binding_schema=ir(r.binding_schema,"binding_schema"));break;case"event":e.data_schema=ir(r.data_schema,"data_schema"),r.source_schema&&(e.source_schema=ir(r.source_schema,"source_schema"));break;case"action":e.input_schema=ir(r.input_schema,"input_schema"),r.output_schema&&(e.output_schema=ir(r.output_schema,"output_schema")),r.error_schema&&(e.error_schema=ir(r.error_schema,"error_schema")),r.provider_schema&&(e.provider_schema=ir(r.provider_schema,"provider_schema")),r.behavior&&(e.behavior=structuredClone(r.behavior));break}return e}async function ea(r){return oi(Ny(r))}async function oi(r){return`sha256:${await pk(uu(r))}`}function Ly(r,e){return{data:si(r,e.data_schema,`${e.id} data_schema`),...e.source_schema?{source:si(r,e.source_schema,`${e.id} source_schema`)}:{}}}function jy(r,e){return{input:si(r,e.input_schema,`${e.id} input_schema`),...e.output_schema?{output:si(r,e.output_schema,`${e.id} output_schema`)}:{},...e.error_schema?{error:si(r,e.error_schema,`${e.id} error_schema`)}:{},...e.provider_schema?{provider:si(r,e.provider_schema,`${e.id} provider_schema`)}:{}}}function ta(r,e,t,n){if(!(!r||r(e)))throw new N(t,`${n} failed JSON Schema validation: ${Wr(r.errors)}`)}function si(r,e,t){try{return r.compile(ir(e,t))}catch(n){throw new N("contract_digest_conflict",`${t} could not be compiled: ${n instanceof Error?n.message:String(n)}`)}}function uu(r){return r===null||typeof r!="object"?JSON.stringify(r):Array.isArray(r)?`[${r.map(uu).join(",")}]`:`{${Object.entries(r).filter(([,t])=>t!==void 0).sort(([t],[n])=>tn?1:0).map(([t,n])=>`${JSON.stringify(t)}:${uu(n)}`).join(",")}}`}async function pk(r){let e=new TextEncoder().encode(r),t=await globalThis.crypto.subtle.digest("SHA-256",e);return[...new Uint8Array(t)].map(n=>n.toString(16).padStart(2,"0")).join("")}var vr=dn(P_(),1);var Tu={delivery:["ephemeral"],ordering:["none"],cancellation:!0,deadlines:!0,provider_discovery:!0,request_deduplication:!0,cross_process_identity:!1},vO=new Set(["specversion","id","source","type","time","subject","datacontenttype","dataschema","data","mdbaseprofile","mdbasecontractversion","mdbasecontractdigest","mdbaseapplication","mdbaseimplementation","mdbaseimplementationversion","mdbaseinstanceid","correlationid","causationid"]),Es=class{constructor(e={}){I(this,"options");I(this,"profileVersion","0.1");I(this,"transport");I(this,"ajv",du());I(this,"contractValidator",br(this.ajv,"contract"));I(this,"eventValidator",br(this.ajv,"event"));I(this,"actionRequestValidator",br(this.ajv,"actionRequest"));I(this,"actionInvocationValidator",br(this.ajv,"actionInvocation"));I(this,"actionOutcomeValidator",br(this.ajv,"actionOutcome"));I(this,"eventSourceDeclarationValidator",br(this.ajv,"eventSourceDeclaration"));I(this,"actionProviderDeclarationValidator",br(this.ajv,"actionProviderDeclaration"));I(this,"contracts",new Map);I(this,"clients",new Map);I(this,"eventSources",new Map);I(this,"actionProviders",new Map);I(this,"subscriptions",new Map);I(this,"activeActions",new Map);I(this,"completedActions",new Map);I(this,"admissionLocks",new Map);I(this,"recentEvents",new Map);I(this,"authorize");I(this,"now");I(this,"idFactory");I(this,"recentEventLimit");I(this,"completedRequestLimit");I(this,"nextSequence",0);I(this,"disposed",!1);var t,n,i,s,o,a,c,l,d,u;this.options=e,this.authorize=(t=e.authorize)!=null?t:(()=>!1),this.now=(n=e.now)!=null?n:(()=>new Date),this.idFactory=(i=e.idFactory)!=null?i:(f=>{var y;this.nextSequence+=1;let p=typeof((y=globalThis.crypto)==null?void 0:y.randomUUID)=="function"?globalThis.crypto.randomUUID():`${this.now().getTime().toString(36)}-${this.nextSequence.toString(36)}`;return`${f}_${p}`}),this.recentEventLimit=Math.max(1,(s=e.recentEventLimit)!=null?s:1e3),this.completedRequestLimit=Math.max(1,(o=e.completedRequestLimit)!=null?o:1e3),this.transport={...Tu,...structuredClone((a=e.transport)!=null?a:{}),delivery:[...(l=(c=e.transport)==null?void 0:c.delivery)!=null?l:Tu.delivery],ordering:[...(u=(d=e.transport)==null?void 0:d.ordering)!=null?u:Tu.ordering]}}connect(e){this.assertActive(),$O(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){var l;let n=this.requireClient(e);if(t.contracts.length===0)throw new N("request_rejected","An event-source declaration must include a contract.");let i=`${e}:${t.declaration_id}`;if(this.eventSources.has(i))throw new N("request_rejected",`Event-source declaration ${t.declaration_id} is already registered.`);let s=new Map;for(let d of t.contracts){let u=await this.prepareEventContract(d.contract),f=I_(d.requirement,u.reference);if(O_(f,u.reference),await this.assertAuthorized({operation:"register_event_source",principal:n.identity,contract:u.reference}),u.sourceValidator&&!u.sourceValidator((l=d.binding)!=null?l:{}))throw new N("request_rejected",`${u.reference.id} source binding is invalid: ${Wr(u.sourceValidator.errors)}`);let p=ha(u.reference);if(s.has(p))throw new N("contract_digest_conflict",`Event contract ${p} is repeated by one declaration.`);s.set(p,{contract:u,requirement:f,...d.binding===void 0?{}:{binding:structuredClone(d.binding)},...d.ordering===void 0?{}:{ordering:[...d.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:d,requirement:u,binding:f,ordering:p})=>({requirement:structuredClone(u),resolved:structuredClone(d.reference),...f===void 0?{}:{binding:f},...p===void 0?{}:{ordering:p}}))},a={...o,declaration_digest:await oi(o)};Jr(this.eventSourceDeclarationValidator,a,"request_rejected","Event-source declaration"),this.commitContracts([...s.values()].map(({contract:d})=>d)),this.eventSources.set(i,{id:i,clientId:e,declaration:structuredClone(a),contracts:new Map([...s.entries()].map(([d,u])=>[d,{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){var y,h,m,g;let n=this.requireClient(e),i=ha(t.contract),s=[...n.sources].map(_=>this.eventSources.get(_)).find(_=>_==null?void 0:_.contracts.has(i));if(!s)throw new N("unknown_contract",`This client has not registered event contract ${t.contract.id} ${t.contract.version}.`);let o=(y=s.contracts.get(i))==null?void 0:y.contract;if(!o)throw new N("unknown_contract",`Event contract ${i} is unavailable.`);if(t.contract.digest&&t.contract.digest!==o.reference.digest)throw new N("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}}),Mu(t.data,"invalid_event_data",`Event ${o.reference.id} data`),ta(o.dataValidator,t.data,"invalid_event_data",`Event ${o.reference.id} data`);let a=(h=t.extensions)!=null?h:{};for(let _ of Object.keys(a))if(vO.has(_))throw new N("request_rejected",`Event extension ${_} is reserved.`);let c={...structuredClone(a),specversion:"1.0",id:(m=t.id)!=null?m:this.idFactory("evt"),source:SO(n.identity),type:o.reference.id,time:(g=t.time)!=null?g:this.now().toISOString(),...t.subject===void 0?{}:{subject:t.subject},datacontenttype:"application/json",dataschema:M_(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}};Jr(this.eventValidator,c,"invalid_event_data","Event envelope"),Cu(this.transport,c),EO(c,o.reference);let l=`${c.source}\0${c.id}`,d=this.recentEvents.get(l);if(d){if(JSON.stringify(d)!==JSON.stringify(c))throw new N("contract_digest_conflict",`Event ${c.source} ${c.id} was reused with different content.`);return{event:structuredClone(d),deliveries:0,duplicate:!0}}this.recentEvents.set(l,structuredClone(c)),T_(this.recentEvents,this.recentEventLimit);let u=[...this.subscriptions.values()].filter(({subscription:_})=>ma(_.contract,o.reference)),f=await Promise.allSettled(u.map(async _=>await this.isAuthorized({operation:"subscribe_event",principal:_.principal,contract:o.reference,...c.subject===void 0?{}:{subject:c.subject}})?(await _.handler(structuredClone(c)),!0):!1)),p=0;for(let _ of f)_.status==="fulfilled"&&_.value?p+=1:_.status==="rejected"&&this.report({severity:"error",code:"event_consumer_failed",message:`An event consumer failed while handling ${c.type}.`,contract:o.reference,cause:_.reason});return{event:structuredClone(c),deliveries:p,duplicate:!1}}async subscribeEvents(e,t,n){let i=this.requireClient(e);Nu(t.contract),kO(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){var u,f,p,y,h,m,g;let n=this.requireClient(e);if(t.handlers.length===0)throw new N("request_rejected","An action-provider declaration must include a handler.");let i=`${e}:${t.declaration_id}`;if(this.actionProviders.has(i))throw new N("request_rejected",`Action-provider declaration ${t.declaration_id} is already registered.`);let s=[],o=new Set;for(let _ of t.handlers){if(o.has(_.handler_id))throw new N("request_rejected",`Handler ${_.handler_id} is repeated.`);o.add(_.handler_id);let w=await this.prepareActionContract(_.contract),k=I_(_.requirement,w.reference);if(O_(k,w.reference),await this.assertAuthorized({operation:"register_action_provider",principal:n.identity,contract:w.reference,provider:n.identity}),w.providerValidator&&!w.providerValidator((u=_.binding)!=null?u:{}))throw new N("request_rejected",`${w.reference.id} provider binding is invalid: ${Wr(w.providerValidator.errors)}`);let v=(p=(f=_.contract.behavior)==null?void 0:f.idempotency)!=null?p:"none";if(((y=_.idempotency)==null?void 0:y.mode)==="request"&&v==="none")throw new N("request_rejected",`${w.reference.id} does not permit request deduplication.`);if(v==="required"&&((h=_.idempotency)==null?void 0:h.mode)!=="request")throw new N("request_rejected",`${w.reference.id} requires a provider with request deduplication.`);let P=(g=(m=_.contract.behavior)==null?void 0:m.cancellation)!=null?g:"none";if(_.cancellation==="cooperative"&&P!=="cooperative")throw new N("request_rejected",`${w.reference.id} does not declare cooperative cancellation.`);s.push({contract:w,declaration:{handler_id:_.handler_id,requirement:k,resolved:structuredClone(w.reference),..._.binding===void 0?{}:{binding:structuredClone(_.binding)},..._.idempotency===void 0?{}:{idempotency:structuredClone(_.idempotency)},..._.cancellation===void 0?{}:{cancellation:_.cancellation},..._.max_concurrency===void 0?{}:{max_concurrency:_.max_concurrency}},handler:_.handler})}let a={kind:"mdbase.action-provider",profile_version:"0.1",declaration_id:t.declaration_id,provider:structuredClone(n.identity),handlers:s.map(({declaration:_})=>structuredClone(_))},c={...a,declaration_digest:await oi(a)};Jr(this.actionProviderDeclarationValidator,c,"request_rejected","Action-provider declaration"),this.commitContracts(s.map(({contract:_})=>_));let l=s.map(({contract:_,declaration:w,handler:k})=>({registrationId:i,clientId:e,declaration:structuredClone(c),handlerDeclaration:structuredClone(w),contract:_,handler:k,active:0}));this.actionProviders.set(i,{id:i,clientId:e,declaration:structuredClone(c),handlers:l}),n.providers.add(i);let d=!0;return{declaration:structuredClone(c),dispose:()=>{d&&(d=!1,this.removeActionProvider(i))}}}async invokeAction(e,t){var a,c,l,d,u,f,p,y,h,m,g,_;let n=this.requireClient(e);Nu(t.contract);let i=(a=t.request_id)!=null?a:this.idFactory("req");this.cleanCompletedActions(),Mu(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:(c=t.created_at)!=null?c:this.now().toISOString(),...t.correlation_id===void 0?{}:{correlation_id:t.correlation_id},...t.causation_id===void 0?{}:{causation_id:t.causation_id},...t.subject===void 0?{}:{subject:t.subject},...t.idempotency_key===void 0?{}:{idempotency_key:t.idempotency_key},...t.deadline===void 0?{}:{deadline:t.deadline},...t.requested_provider===void 0?{}:{requested_provider:structuredClone(t.requested_provider)},input:structuredClone(t.input)};Jr(this.actionRequestValidator,s,"request_rejected","Action request"),Cu(this.transport,s);let o=await this.acquireAdmission(i);try{let w=await oi(AO(s)),k=this.activeActions.get(i);if(k){if(R_(e,i,w,k),((l=k.handler.handlerDeclaration.idempotency)==null?void 0:l.mode)!=="request")throw new N("request_rejected",`Action request ${i} is already active without deduplication.`);return structuredClone(await k.promise)}let v=this.completedActions.get(i);if(v){if(R_(e,i,w,v),!v.reusable)throw new N("request_rejected",`Action request ${i} was already completed without deduplication.`);return structuredClone(v.outcome)}if(s.deadline&&new Date(s.deadline).getTime()<=this.now().getTime())throw new N("deadline_exceeded",`Action request ${i} passed its deadline before admission.`);if(s.deadline&&!this.transport.deadlines)throw new N("unsupported_transport_capability","The active transport cannot enforce action deadlines.");let P=this.resolveActionCandidates(s.contract,s.requested_provider);P.length===0&&this.throwResolutionFailure(s.contract,s.requested_provider);let O=[];for(let U of P)await this.isAuthorized({operation:"invoke_action",principal:n.identity,contract:U.contract.reference,provider:U.declaration.provider,...s.subject===void 0?{}:{subject:s.subject}})&&O.push(U);if(O.length===0)throw new N("unauthorized",`No authorized provider can execute ${s.contract.id}.`);if(O.length>1)throw new N("ambiguous_provider",`Action ${s.contract.id} has ${O.length} eligible providers; select one explicitly.`);let $=O[0];if($.handlerDeclaration.max_concurrency!==void 0&&$.active>=$.handlerDeclaration.max_concurrency)throw new N("request_rejected",`Provider ${$.declaration.provider.implementation} is at capacity.`);if(((u=(d=$.contract.artifact.behavior)==null?void 0:d.idempotency)!=null?u:"none")==="required"&&!s.idempotency_key)throw new N("request_rejected",`${$.contract.reference.id} requires an idempotency key.`);ta($.contract.inputValidator,s.input,"invalid_action_input",`Action ${$.contract.reference.id} input`);let S={operation:"invoke_action",principal:n.identity,contract:$.contract.reference,provider:$.declaration.provider,...s.subject===void 0?{}:{subject:s.subject}},V=await((p=(f=this.options).authorizationContext)==null?void 0:p.call(f,S)),B={kind:"mdbase.action.invocation",profile_version:"0.1",invocation_id:this.idFactory("inv"),attempt_id:this.idFactory("attempt"),request_id:i,contract:structuredClone($.contract.reference),caller:structuredClone(n.identity),provider:structuredClone($.declaration.provider),provider_declaration_digest:$.declaration.declaration_digest,handler_id:$.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},...V===void 0?{}:{authorization_context:V},input:structuredClone(s.input)};Jr(this.actionInvocationValidator,B,"request_rejected","Action invocation"),await((h=(y=this.options).onInvocation)==null?void 0:h.call(y,structuredClone(B)));let T=new AbortController,E;if(B.deadline){let U=Math.max(0,new Date(B.deadline).getTime()-this.now().getTime());E=setTimeout(()=>T.abort(new N("deadline_exceeded",`Action request ${i} exceeded its deadline.`)),U)}$.active+=1;let x=this.executeAction($,B,T).finally(()=>{E!==void 0&&clearTimeout(E),$.active=Math.max(0,$.active-1),this.activeActions.delete(i)});this.activeActions.set(i,{clientId:e,requestId:i,requestDigest:w,handler:$,invocation:B,controller:T,promise:x}),o();let de=await x,Z=(g=(m=$.handlerDeclaration.idempotency)==null?void 0:m.retention_seconds)!=null?g:300;return this.completedActions.set(i,{clientId:e,requestDigest:w,outcome:structuredClone(de),reusable:((_=$.handlerDeclaration.idempotency)==null?void 0:_.mode)==="request",expiresAt:this.now().getTime()+Z*1e3}),T_(this.completedActions,this.completedRequestLimit),structuredClone(de)}finally{o()}}async executeAction(e,t,n){var i;try{let s=await e.handler(structuredClone(t.input),{invocation:structuredClone(t),signal:n.signal});if(n.signal.aborted){let a=n.signal.reason;return a instanceof N&&a.code==="deadline_exceeded"?this.failureOutcome(t,"failed",a.toPortableError()):this.failureOutcome(t,"cancelled",{code:"cancelled",message:`Action request ${t.request_id} was cancelled.`})}Mu(s,"invalid_action_output",`Action ${e.contract.reference.id} output`),ta(e.contract.outputValidator,s,"invalid_action_output",`Action ${e.contract.reference.id} output`);let o={kind:"mdbase.action.outcome",profile_version:"0.1",outcome_id:this.idFactory("outcome"),request_id:t.request_id,invocation_id:t.invocation_id,attempt_id:t.attempt_id,contract:structuredClone(t.contract),provider:structuredClone(t.provider),provider_declaration_digest:t.provider_declaration_digest,status:"succeeded",completed_at:this.now().toISOString(),output:structuredClone(s)};return Jr(this.actionOutcomeValidator,o,"invalid_action_output","Action outcome"),Cu(this.transport,o),o}catch(s){if(s instanceof Ui)return e.contract.errorValidator&&!e.contract.errorValidator((i=s.error.details)!=null?i:{})?this.failureOutcome(t,"failed",{code:"handler_failure",message:`Provider returned invalid declared error details: ${Wr(e.contract.errorValidator.errors)}`}):this.failureOutcome(t,s.status,s.error);if(s instanceof N)return this.failureOutcome(t,s.code==="cancelled"?"cancelled":s.code==="outcome_indeterminate"?"outcome_indeterminate":"failed",s.toPortableError());if(n.signal.aborted||PO(s)){let o=n.signal.reason;return o instanceof N&&o.code==="deadline_exceeded"?this.failureOutcome(t,"failed",o.toPortableError()):this.failureOutcome(t,"cancelled",{code:"cancelled",message:`Action request ${t.request_id} was cancelled.`})}return this.report({severity:"error",code:"action_handler_failed",message:`Provider ${t.provider.implementation} failed ${t.contract.id}.`,principal:t.provider,contract:t.contract,cause:s}),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 Jr(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 N("unauthorized",`Action request ${t} belongs to another caller.`);return a?structuredClone(a.outcome):null}if(o.clientId!==e)throw new N("unauthorized",`Action request ${t} belongs to another caller.`);if(await this.assertAuthorized({operation:"cancel_action",principal:i.identity,contract:o.invocation.contract,provider:o.invocation.provider,...o.invocation.subject===void 0?{}:{subject:o.invocation.subject}}),!this.transport.cancellation)throw new N("unsupported_transport_capability","The active transport cannot deliver cancellation.");if(o.handler.handlerDeclaration.cancellation!=="cooperative")throw new N("cancellation_unsupported",`Provider ${o.invocation.provider.implementation} does not support cancellation.`);return o.controller.abort(new N("cancelled",(n==null?void 0:n.trim())||`Action request ${t} was cancelled.`)),structuredClone(await o.promise)}resolveActionCandidates(e,t){let n=[...this.actionProviders.values()].flatMap(({handlers:s})=>s).filter(({contract:s,declaration:o})=>ma(e,s.reference)&&xO(t,o.provider)),i=(0,vr.maxSatisfying)([...new Set(n.map(({contract:s})=>s.reference.version))],e.version,{includePrerelease:!0});return i?n.filter(({contract:s})=>s.reference.version===i).sort((s,o)=>{var a,c;return s.declaration.provider.application.localeCompare(o.declaration.provider.application)||s.declaration.provider.implementation.localeCompare(o.declaration.provider.implementation)||((a=s.declaration.provider.instance_id)!=null?a:"").localeCompare((c=o.declaration.provider.instance_id)!=null?c:"")||s.handlerDeclaration.handler_id.localeCompare(o.handlerDeclaration.handler_id)}):[]}throwResolutionFailure(e,t){let n=[...this.contracts.values()].filter(i=>i.artifact.contract_type==="action"&&i.reference.id===e.id);throw n.length===0?new N("unknown_contract",`Action contract ${e.id} is unknown.`):n.some(({reference:i})=>ma(e,i))?t?new N("requested_provider_unavailable",`The requested provider is unavailable for ${e.id}.`):new N("no_provider",`No provider is registered for ${e.id}.`):new N("unsupported_contract_version",`No ${e.id} artifact satisfies ${e.version}.`)}async prepareEventContract(e){if(this.assertContractArtifact(e),e.contract_type!=="event")throw new N("unknown_contract",`${e.id} is not an event contract.`);let t={id:e.id,version:e.version,digest:await ea(e)};this.assertNoContractConflict(t);let n=Ly(this.ajv,e);return{artifact:structuredClone(e),reference:t,dataValidator:n.data,...n.source===void 0?{}:{sourceValidator:n.source}}}async prepareActionContract(e){if(this.assertContractArtifact(e),e.contract_type!=="action")throw new N("unknown_contract",`${e.id} is not an action contract.`);let t={id:e.id,version:e.version,digest:await ea(e)};this.assertNoContractConflict(t);let n=jy(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(Jr(this.contractValidator,e,"contract_digest_conflict",`Contract ${e.id||""}`),!(0,vr.valid)(e.version))throw new N("unsupported_contract_version",`${e.id} version must be exact SemVer.`)}assertNoContractConflict(e){let t=this.contracts.get(ha(e));if(t&&t.reference.digest!==e.digest)throw new N("contract_digest_conflict",`Contract ${e.id} ${e.version} conflicts with the registered artifact.`)}commitContracts(e){var n;let t=new Map;for(let i of e){let s=ha(i.reference),o=(n=t.get(s))!=null?n:this.contracts.get(s);if(o&&o.reference.digest!==i.reference.digest)throw new N("contract_digest_conflict",`Contract ${i.reference.id} ${i.reference.version} conflicts within the registration.`);t.set(s,i)}for(let[i,s]of t)this.contracts.has(i)||this.contracts.set(i,s)}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 N("cancelled","The caller unloaded.")),i.handler.clientId===e&&i.handler.handlerDeclaration.cancellation==="cooperative"&&i.controller.abort(new N("cancelled","The provider unloaded."));this.clients.delete(e),t||this.assertActive()}}removeEventSource(e){var n;let t=this.eventSources.get(e);t&&(this.eventSources.delete(e),(n=this.clients.get(t.clientId))==null||n.sources.delete(e))}removeActionProvider(e){var n;let t=this.actionProviders.get(e);if(t){this.actionProviders.delete(e),(n=this.clients.get(t.clientId))==null||n.providers.delete(e);for(let i of this.activeActions.values())i.handler.registrationId===e&&i.handler.handlerDeclaration.cancellation==="cooperative"&&i.controller.abort(new N("cancelled","The provider unloaded."))}}removeSubscription(e){var n;let t=this.subscriptions.get(e);t&&(this.subscriptions.delete(e),(n=this.clients.get(t.clientId))==null||n.subscriptions.delete(e))}requireClient(e){this.assertActive();let t=this.clients.get(e);if(!t||t.disposed)throw new N("transport_unavailable","Interop client is disposed.");return t}assertActive(){if(this.disposed)throw new N("transport_unavailable","Interop bridge is disposed.")}async assertAuthorized(e){if(!await this.isAuthorized(e))throw new N("unauthorized",`${e.operation} is not authorized.`)}async isAuthorized(e){try{return await this.authorize(structuredClone(e))}catch(t){return this.report({severity:"error",code:"authorization_failed",message:`Authorization failed for ${e.operation}.`,principal:e.principal,cause:t}),!1}}cleanCompletedActions(){let e=this.now().getTime();for(let[t,n]of this.completedActions)n.expiresAt<=e&&this.completedActions.delete(t)}async acquireAdmission(e){var a;let t=(a=this.admissionLocks.get(e))!=null?a:Promise.resolve(),n,i=new Promise(c=>{n=c}),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){var t,n;(n=(t=this.options).onDiagnostic)==null||n.call(t,structuredClone(e))}};function Jr(r,e,t,n){if(!r(e))throw new N(t,`${n} is invalid: ${Wr(r.errors)}`)}function $O(r){for(let[e,t]of Object.entries(r))if(t!==void 0&&(typeof t!="string"||t.length===0||!/^[A-Za-z0-9][A-Za-z0-9._:@/-]*$/u.test(t)))throw new N("request_rejected",`Implementation identity ${e} is invalid.`);if(!(0,vr.valid)(r.version))throw new N("request_rejected","Implementation identity version must be exact SemVer.")}function Nu(r){if(!/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)+$/u.test(r.id))throw new N("unknown_contract",`Contract ID ${r.id} is invalid.`);if(!(0,vr.validRange)(r.version,{includePrerelease:!0}))throw new N("unsupported_contract_version",`Contract requirement ${r.version} is not a SemVer range.`);if(r.digest&&!/^sha256:[0-9a-f]{64}$/u.test(r.digest))throw new N("contract_digest_conflict","Contract digest is invalid.")}function I_(r,e){let t=r!=null?r:{id:e.id,version:e.version,digest:e.digest};return Nu(t),structuredClone(t)}function O_(r,e){if(!ma(r,e))throw new N("unsupported_contract_version",`${e.id} ${e.version} does not satisfy its implementation requirement.`)}function ma(r,e){return r.id===e.id&&(0,vr.satisfies)(e.version,r.version,{includePrerelease:!0})&&(!r.digest||r.digest===e.digest)}function ha(r){return`${r.id}@${r.version}`}function M_(r){return`urn:mdbase:contract:${r.id}:${r.version}:${r.digest}`}function SO(r){return`urn:mdbase:app:${[r.application,r.implementation,...r.instance_id?[r.instance_id]:[]].map(encodeURIComponent).join(":")}`}function EO(r,e){if(r.type!==e.id||r.mdbasecontractversion!==e.version||r.mdbasecontractdigest!==e.digest||r.dataschema!==M_(e))throw new N("contract_digest_conflict","Event contract evidence is inconsistent.")}function AO(r){let{created_at:e,...t}=r;return t}function R_(r,e,t,n){if(n.clientId!==r)throw new N("unauthorized",`Action request ${e} belongs to another caller.`);if(n.requestDigest!==t)throw new N("request_rejected",`Action request ${e} was reused with different content.`)}function Mu(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 N(e,`${t}${o} must be a finite JSON number.`)}if(typeof s!="object")throw new N(e,`${t}${o} is not a JSON value.`);if(n.has(s))throw new N(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 N(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 Cu(r,e){if(r.max_payload_bytes===void 0)return;let t=JSON.stringify(e),n=new TextEncoder().encode(t).byteLength;if(n>r.max_payload_bytes)throw new N("unsupported_transport_capability",`The portable envelope is ${n} bytes; the active transport allows ${r.max_payload_bytes}.`)}function xO(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 kO(r,e){var t,n;if(e){if((t=e.delivery)!=null&&t.some(i=>!r.delivery.includes(i)))throw new N("unsupported_transport_capability","The active transport lacks a required delivery capability.");if((n=e.ordering)!=null&&n.some(i=>!r.ordering.includes(i)))throw new N("unsupported_transport_capability","The active transport lacks a required ordering capability.");for(let i of["cancellation","deadlines","provider_discovery","request_deduplication","cross_process_identity"])if(e[i]===!0&&r[i]!==!0)throw new N("unsupported_transport_capability",`The active transport lacks ${i}.`);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 PO(r){return r instanceof Error&&r.name==="AbortError"}var ya=class{constructor(e,t){this.app=e;this.profileVersion="0.1";this.bridge=new Es({authorize:()=>t(),transport:{delivery:["ephemeral"],ordering:["none"],cancellation:!0,deadlines:!0,provider_discovery:!0,request_deduplication:!0,cross_process_identity:!1},onDiagnostic:n=>{var s;(n.severity==="error"?console.error:console.warn)(`[mdbase/interop] ${n.code}: ${n.message}`,(s=n.cause)!=null?s:"")}}),this.transport=this.bridge.describe().transport}connect(e){var s,o;let t=(s=e.manifest)==null?void 0:s.id,n=(o=e.manifest)==null?void 0:o.version;if(!t||!n)throw new Error("Only a loaded Obsidian plugin with manifest identity can connect to mdbase interop.");let 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()}};var me=require("obsidian"),ib=dn(Qd(),1),sb=dn(cu(),1),Xu=dn(Wu(),1),wa=class extends Error{constructor(t,n){super(n);this.code=t;this.name="MdbasePathError"}},jt={spec_version:"0.3.0",name:"My mdbase collection",description:"Typed markdown collection",settings:{types_folder:"_types",explicit_type_keys:["type","types"],default_strict:!1,include_subfolders:!0,exclude:["_types",".obsidian",".git","node_modules",".trash",".mdbase"]}},Is=null;function dR(){return Is||(Is=new ib.Ajv2020({allErrors:!0,strict:!1,allowUnionTypes:!0}),(0,sb.default)(Is),Is)}function re(r){return!!r&&typeof r=="object"&&!Array.isArray(r)}function Ze(r){return JSON.parse(JSON.stringify(r))}function uR(r){if(r===!0)return!0;if(r===!1)return!1;if(r==="warn")return"warn"}function Gu(r){return Array.isArray(r)?`[${r.map(e=>Gu(e)).join(",")}]`:re(r)?`{${Object.keys(r).sort().map(t=>`${JSON.stringify(t)}:${Gu(r[t])}`).join(",")}}`:JSON.stringify(r)}function fR(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 pR(r){let e=new Map,t=new Set,n=i=>{var l,d,u,f;let s=e.get(i);if(s)return s;let o=r.get(i);if(!o)return null;if(t.has(i)){let p={...o,fields:Ze(o.fields)};return e.set(i,p),p}t.add(i);let a=o.extends?n(o.extends):null;t.delete(i);let c={...o,fields:a?{...Ze(a.fields),...Ze(o.fields)}:Ze(o.fields),display_name_key:(l=o.display_name_key)!=null?l:a==null?void 0:a.display_name_key,path_pattern:(d=o.path_pattern)!=null?d:a==null?void 0:a.path_pattern,filename_pattern:(u=o.filename_pattern)!=null?u:a==null?void 0:a.filename_pattern,strict:o.strict!==void 0?o.strict:a==null?void 0:a.strict,match:(f=o.match)!=null?f:a==null?void 0:a.match};return e.set(i,c),c};for(let i of r.keys())n(i);return e}function ob(r){let e=(0,me.normalizePath)(r),t=e.lastIndexOf("/");return t>=0?e.slice(0,t):""}function ab(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 cb(r){return/^[a-z][a-z0-9+.-]*:\/\//i.test(r)}function lb(r,e,t){var c;let n=ab(t);if(!n||cb(n))return null;let i=new Set,s=(0,me.normalizePath)(n);i.add(s),s.endsWith(".md")||i.add(`${s}.md`);let o=ob(e);if(o){let l=(0,me.normalizePath)(`${o}/${n}`);i.add(l),l.endsWith(".md")||i.add(`${l}.md`)}for(let l of i){let d=r.getAbstractFileByPath(l);if(d instanceof me.TFile)return d}let a=n.replace(/\.md$/i,"");return(c=r.getMarkdownFiles().find(l=>l.basename===a))!=null?c:null}function hR(r,e,t){return cb(ab(t))||lb(r,e,t)!==null}function It(r){let e=r.match(/^---[ \t]*\r?\n([\s\S]*?)^---[ \t]*(?:\r?\n|$)/m);if(!e)return{hasFrontmatter:!1,frontmatter:{},body:r};try{let t=e[1],n=(0,me.parseYaml)(t);return n==null&&t.trim()!==""?{hasFrontmatter:!0,frontmatter:{},body:r.slice(e[0].length),error:"Frontmatter must be a YAML object"}:n!=null&&!re(n)?{hasFrontmatter:!0,frontmatter:{},body:r.slice(e[0].length),error:"Frontmatter must be a YAML object"}:{hasFrontmatter:!0,frontmatter:n!=null?n:{},body:r.slice(e[0].length)}}catch(t){return{hasFrontmatter:!0,frontmatter:{},body:r.slice(e[0].length),error:t instanceof Error?t.message:String(t)}}}function yt(r,e=""){if(Object.keys(r).length===0)return e;let t=(0,me.stringifyYaml)(r).trimEnd(),n=e.replace(/^\n+/,"");return`--- + deps: ${t}}`};var SA={keyword:"dependencies",type:"object",schemaType:"object",error:er.error,code(r){let[e,t]=EA(r);ym(r,e),gm(r,t)}};function EA({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 ym(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,ys.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,ys.checkReportMissingProp)(r,l)}):(t.if((0,pd._)`${c} && (${(0,ys.checkMissingProp)(r,a,s)})`),(0,ys.reportMissingProp)(r,s),t.else())}}er.validatePropertyDeps=ym;function gm(r,e=r.schema){let{gen:t,data:n,keyword:i,it:s}=r,o=t.name("valid");for(let a in e)(0,$A.alwaysValidSchema)(s,e[a])||(t.if((0,ys.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))}er.validateSchemaDeps=gm;er.default=SA});var bm=A(hd=>{"use strict";Object.defineProperty(hd,"__esModule",{value:!0});var _m=H(),AA=Q(),kA={message:"property name must be valid",params:({params:r})=>(0,_m._)`{propertyName: ${r.propertyName}}`},xA={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:kA,code(r){let{gen:e,schema:t,data:n,it:i}=r;if((0,AA.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,_m.not)(s),()=>{r.error(!0),i.allErrors||e.break()})}),r.ok(s)}};hd.default=xA});var yd=A(md=>{"use strict";Object.defineProperty(md,"__esModule",{value:!0});var Wo=$t(),Mt=H(),PA=vt(),Go=Q(),IA={message:"must NOT have additional properties",params:({params:r})=>(0,Mt._)`{additionalProperty: ${r.additionalProperty}}`},OA={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:IA,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,Go.alwaysValidSchema)(o,t))return;let l=(0,Wo.allSchemaProperties)(n.properties),d=(0,Wo.allSchemaProperties)(n.patternProperties);u(),r.ok((0,Mt._)`${s} === ${PA.default.errors}`);function u(){e.forIn("key",i,m=>{!l.length&&!d.length?y(m):e.if(f(m),()=>y(m))})}function f(m){let g;if(l.length>8){let _=(0,Go.schemaRefOrVal)(o,n.properties,"properties");g=(0,Wo.isOwnProperty)(e,_,m)}else l.length?g=(0,Mt.or)(...l.map(_=>(0,Mt._)`${m} === ${_}`)):g=Mt.nil;return d.length&&(g=(0,Mt.or)(g,...d.map(_=>(0,Mt._)`${(0,Wo.usePattern)(r,_)}.test(${m})`))),(0,Mt.not)(g)}function p(m){e.code((0,Mt._)`delete ${i}[${m}]`)}function y(m){if(c.removeAdditional==="all"||c.removeAdditional&&t===!1){p(m);return}if(t===!1){r.setParams({additionalProperty:m}),r.error(),a||e.break();return}if(typeof t=="object"&&!(0,Go.alwaysValidSchema)(o,t)){let g=e.name("valid");c.removeAdditional==="failing"?(h(m,g,!1),e.if((0,Mt.not)(g),()=>{r.reset(),p(m)})):(h(m,g),a||e.if((0,Mt.not)(g),()=>e.break()))}}function h(m,g,_){let w={keyword:"additionalProperties",dataProp:m,dataPropType:Go.Type.Str};_===!1&&Object.assign(w,{compositeRule:!0,createErrors:!1,allErrors:!1}),r.subschema(w,g)}}};md.default=OA});var $m=A(_d=>{"use strict";Object.defineProperty(_d,"__esModule",{value:!0});var RA=Wn(),wm=$t(),gd=Q(),vm=yd(),TA={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&&vm.default.code(new RA.KeywordCxt(s,vm.default,"additionalProperties"));let o=(0,wm.allSchemaProperties)(t);for(let u of o)s.definedProperties.add(u);s.opts.unevaluated&&o.length&&s.props!==!0&&(s.props=gd.mergeEvaluated.props(e,(0,gd.toHash)(o),s.props));let a=o.filter(u=>!(0,gd.alwaysValidSchema)(s,t[u]));if(a.length===0)return;let c=e.name("valid");for(let u of a)l(u)?d(u):(e.if((0,wm.propertyInData)(e,i,u,s.opts.ownProperties)),d(u),s.allErrors||e.else().var(c,!0),e.endIf()),r.it.definedProperties.add(u),r.ok(c);function l(u){return s.opts.useDefaults&&!s.compositeRule&&t[u].default!==void 0}function d(u){r.subschema({keyword:"properties",schemaProp:u,dataProp:u},c)}}};_d.default=TA});var km=A(bd=>{"use strict";Object.defineProperty(bd,"__esModule",{value:!0});var Sm=$t(),Jo=H(),Em=Q(),Am=Q(),CA={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,Sm.allSchemaProperties)(t),c=a.filter(h=>(0,Em.alwaysValidSchema)(s,t[h]));if(a.length===0||c.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let l=o.strictSchema&&!o.allowMatchingProperties&&i.properties,d=e.name("valid");s.props!==!0&&!(s.props instanceof Jo.Name)&&(s.props=(0,Am.evaluatedPropsToName)(e,s.props));let{props:u}=s;f();function f(){for(let h of a)l&&p(h),s.allErrors?y(h):(e.var(d,!0),y(h),e.if(d))}function p(h){for(let m in l)new RegExp(h).test(m)&&(0,Em.checkStrictMode)(s,`property ${m} matches pattern ${h} (use allowMatchingProperties)`)}function y(h){e.forIn("key",n,m=>{e.if((0,Jo._)`${(0,Sm.usePattern)(r,h)}.test(${m})`,()=>{let g=c.includes(h);g||r.subschema({keyword:"patternProperties",schemaProp:h,dataProp:m,dataPropType:Am.Type.Str},d),s.opts.unevaluated&&u!==!0?e.assign((0,Jo._)`${u}[${m}]`,!0):!g&&!s.allErrors&&e.if((0,Jo.not)(d),()=>e.break())})})}}};bd.default=CA});var xm=A(wd=>{"use strict";Object.defineProperty(wd,"__esModule",{value:!0});var MA=Q(),NA={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(r){let{gen:e,schema:t,it:n}=r;if((0,MA.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"}};wd.default=NA});var Pm=A(vd=>{"use strict";Object.defineProperty(vd,"__esModule",{value:!0});var LA=$t(),jA={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:LA.validateUnion,error:{message:"must match a schema in anyOf"}};vd.default=jA});var Im=A($d=>{"use strict";Object.defineProperty($d,"__esModule",{value:!0});var Yo=H(),DA=Q(),qA={message:"must match exactly one schema in oneOf",params:({params:r})=>(0,Yo._)`{passingSchemas: ${r.passing}}`},FA={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:qA,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((d,u)=>{let f;(0,DA.alwaysValidSchema)(i,d)?e.var(c,!0):f=r.subschema({keyword:"oneOf",schemaProp:u,compositeRule:!0},c),u>0&&e.if((0,Yo._)`${c} && ${o}`).assign(o,!1).assign(a,(0,Yo._)`[${a}, ${u}]`).else(),e.if(c,()=>{e.assign(o,!0),e.assign(a,u),f&&r.mergeEvaluated(f,Yo.Name)})})}}};$d.default=FA});var Om=A(Sd=>{"use strict";Object.defineProperty(Sd,"__esModule",{value:!0});var VA=Q(),UA={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,VA.alwaysValidSchema)(n,s))return;let a=r.subschema({keyword:"allOf",schemaProp:o},i);r.ok(i),r.mergeEvaluated(a)})}};Sd.default=UA});var Cm=A(Ed=>{"use strict";Object.defineProperty(Ed,"__esModule",{value:!0});var Xo=H(),Tm=Q(),BA={message:({params:r})=>(0,Xo.str)`must match "${r.ifClause}" schema`,params:({params:r})=>(0,Xo._)`{failingKeyword: ${r.ifClause}}`},zA={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:BA,code(r){let{gen:e,parentSchema:t,it:n}=r;t.then===void 0&&t.else===void 0&&(0,Tm.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let i=Rm(n,"then"),s=Rm(n,"else");if(!i&&!s)return;let o=e.let("valid",!0),a=e.name("_valid");if(c(),r.reset(),i&&s){let d=e.let("ifClause");r.setParams({ifClause:d}),e.if(a,l("then",d),l("else",d))}else i?e.if(a,l("then")):e.if((0,Xo.not)(a),l("else"));r.pass(o,()=>r.error(!0));function c(){let d=r.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);r.mergeEvaluated(d)}function l(d,u){return()=>{let f=r.subschema({keyword:d},a);e.assign(o,a),r.mergeValidEvaluated(f,o),u?e.assign(u,(0,Xo._)`${d}`):r.setParams({ifClause:d})}}}};function Rm(r,e){let t=r.schema[e];return t!==void 0&&!(0,Tm.alwaysValidSchema)(r,t)}Ed.default=zA});var Mm=A(Ad=>{"use strict";Object.defineProperty(Ad,"__esModule",{value:!0});var HA=Q(),KA={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:r,parentSchema:e,it:t}){e.if===void 0&&(0,HA.checkStrictMode)(t,`"${r}" without "if" is ignored`)}};Ad.default=KA});var xd=A(kd=>{"use strict";Object.defineProperty(kd,"__esModule",{value:!0});var WA=cd(),GA=fm(),JA=ld(),YA=hm(),XA=mm(),QA=Ko(),ZA=bm(),e1=yd(),t1=$m(),r1=km(),n1=xm(),i1=Pm(),s1=Im(),o1=Om(),a1=Cm(),c1=Mm();function l1(r=!1){let e=[n1.default,i1.default,s1.default,o1.default,a1.default,c1.default,ZA.default,e1.default,QA.default,t1.default,r1.default];return r?e.push(GA.default,YA.default):e.push(WA.default,JA.default),e.push(XA.default),e}kd.default=l1});var Id=A(gs=>{"use strict";Object.defineProperty(gs,"__esModule",{value:!0});gs.dynamicAnchor=void 0;var Pd=H(),d1=vt(),Nm=ns(),u1=Fo(),f1={keyword:"$dynamicAnchor",schemaType:"string",code:r=>Lm(r,r.schema)};function Lm(r,e){let{gen:t,it:n}=r;n.schemaEnv.root.dynamicAnchors[e]=!0;let i=(0,Pd._)`${d1.default.dynamicAnchors}${(0,Pd.getProperty)(e)}`,s=n.errSchemaPath==="#"?n.validateName:p1(r);t.if((0,Pd._)`!${i}`,()=>t.assign(i,s))}gs.dynamicAnchor=Lm;function p1(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 Nm.SchemaEnv({schema:t,schemaId:c,root:i,baseId:s,localRefs:o,meta:a});return Nm.compileSchema.call(n,l),(0,u1.getValidate)(r,l)}gs.default=f1});var Od=A(_s=>{"use strict";Object.defineProperty(_s,"__esModule",{value:!0});_s.dynamicRef=void 0;var jm=H(),h1=vt(),Dm=Fo(),m1={keyword:"$dynamicRef",schemaType:"string",code:r=>qm(r,r.schema)};function qm(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,jm._)`${h1.default.dynamicAnchors}${(0,jm.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,Dm.callRef)(r,c),t.let(l,!0)}):()=>(0,Dm.callRef)(r,c)}}_s.dynamicRef=qm;_s.default=m1});var Fm=A(Rd=>{"use strict";Object.defineProperty(Rd,"__esModule",{value:!0});var y1=Id(),g1=Q(),_1={keyword:"$recursiveAnchor",schemaType:"boolean",code(r){r.schema?(0,y1.dynamicAnchor)(r,""):(0,g1.checkStrictMode)(r.it,"$recursiveAnchor: false is ignored")}};Rd.default=_1});var Vm=A(Td=>{"use strict";Object.defineProperty(Td,"__esModule",{value:!0});var b1=Od(),w1={keyword:"$recursiveRef",schemaType:"string",code:r=>(0,b1.dynamicRef)(r,r.schema)};Td.default=w1});var Um=A(Cd=>{"use strict";Object.defineProperty(Cd,"__esModule",{value:!0});var v1=Id(),$1=Od(),S1=Fm(),E1=Vm(),A1=[v1.default,$1.default,S1.default,E1.default];Cd.default=A1});var zm=A(Md=>{"use strict";Object.defineProperty(Md,"__esModule",{value:!0});var Bm=Ko(),k1={keyword:"dependentRequired",type:"object",schemaType:"object",error:Bm.error,code:r=>(0,Bm.validatePropertyDeps)(r)};Md.default=k1});var Hm=A(Nd=>{"use strict";Object.defineProperty(Nd,"__esModule",{value:!0});var x1=Ko(),P1={keyword:"dependentSchemas",type:"object",schemaType:"object",code:r=>(0,x1.validateSchemaDeps)(r)};Nd.default=P1});var Km=A(Ld=>{"use strict";Object.defineProperty(Ld,"__esModule",{value:!0});var I1=Q(),O1={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword:r,parentSchema:e,it:t}){e.contains===void 0&&(0,I1.checkStrictMode)(t,`"${r}" without "contains" is ignored`)}};Ld.default=O1});var Wm=A(jd=>{"use strict";Object.defineProperty(jd,"__esModule",{value:!0});var R1=zm(),T1=Hm(),C1=Km(),M1=[R1.default,T1.default,C1.default];jd.default=M1});var Jm=A(Dd=>{"use strict";Object.defineProperty(Dd,"__esModule",{value:!0});var Wr=H(),Gm=Q(),N1=vt(),L1={message:"must NOT have unevaluated properties",params:({params:r})=>(0,Wr._)`{unevaluatedProperty: ${r.unevaluatedProperty}}`},j1={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 Wr.Name?e.if((0,Wr._)`${a} !== true`,()=>e.forIn("key",n,u=>e.if(l(a,u),()=>c(u)))):a!==!0&&e.forIn("key",n,u=>a===void 0?c(u):e.if(d(a,u),()=>c(u))),s.props=!0,r.ok((0,Wr._)`${i} === ${N1.default.errors}`);function c(u){if(t===!1){r.setParams({unevaluatedProperty:u}),r.error(),o||e.break();return}if(!(0,Gm.alwaysValidSchema)(s,t)){let f=e.name("valid");r.subschema({keyword:"unevaluatedProperties",dataProp:u,dataPropType:Gm.Type.Str},f),o||e.if((0,Wr.not)(f),()=>e.break())}}function l(u,f){return(0,Wr._)`!${u} || !${u}[${f}]`}function d(u,f){let p=[];for(let y in u)u[y]===!0&&p.push((0,Wr._)`${f} !== ${y}`);return(0,Wr.and)(...p)}}};Dd.default=j1});var Xm=A(qd=>{"use strict";Object.defineProperty(qd,"__esModule",{value:!0});var En=H(),Ym=Q(),D1={message:({params:{len:r}})=>(0,En.str)`must NOT have more than ${r} items`,params:({params:{len:r}})=>(0,En._)`{limit: ${r}}`},q1={keyword:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error:D1,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,En._)`${n}.length`);if(t===!1)r.setParams({len:s}),r.fail((0,En._)`${o} > ${s}`);else if(typeof t=="object"&&!(0,Ym.alwaysValidSchema)(i,t)){let c=e.var("valid",(0,En._)`${o} <= ${s}`);e.if((0,En.not)(c),()=>a(c,s)),r.ok(c)}i.items=!0;function a(c,l){e.forRange("i",l,o,d=>{r.subschema({keyword:"unevaluatedItems",dataProp:d,dataPropType:Ym.Type.Num},c),i.allErrors||e.if((0,En.not)(c),()=>e.break())})}}};qd.default=q1});var Qm=A(Fd=>{"use strict";Object.defineProperty(Fd,"__esModule",{value:!0});var F1=Jm(),V1=Xm(),U1=[F1.default,V1.default];Fd.default=U1});var Zm=A(Vd=>{"use strict";Object.defineProperty(Vd,"__esModule",{value:!0});var Ae=H(),B1={message:({schemaCode:r})=>(0,Ae.str)`must match format "${r}"`,params:({schemaCode:r})=>(0,Ae._)`{format: ${r}}`},z1={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:B1,code(r,e){let{gen:t,data:n,$data:i,schema:s,schemaCode:o,it:a}=r,{opts:c,errSchemaPath:l,schemaEnv:d,self:u}=a;if(!c.validateFormats)return;i?f():p();function f(){let y=t.scopeValue("formats",{ref:u.formats,code:c.code.formats}),h=t.const("fDef",(0,Ae._)`${y}[${o}]`),m=t.let("fType"),g=t.let("format");t.if((0,Ae._)`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>t.assign(m,(0,Ae._)`${h}.type || "string"`).assign(g,(0,Ae._)`${h}.validate`),()=>t.assign(m,(0,Ae._)`"string"`).assign(g,h)),r.fail$data((0,Ae.or)(_(),w()));function _(){return c.strictSchema===!1?Ae.nil:(0,Ae._)`${o} && !${g}`}function w(){let x=d.$async?(0,Ae._)`(${h}.async ? await ${g}(${n}) : ${g}(${n}))`:(0,Ae._)`${g}(${n})`,v=(0,Ae._)`(typeof ${g} == "function" ? ${x} : ${g}.test(${n}))`;return(0,Ae._)`${g} && ${g} !== true && ${m} === ${e} && !${v}`}}function p(){let y=u.formats[s];if(!y){_();return}if(y===!0)return;let[h,m,g]=w(y);h===e&&r.pass(x());function _(){if(c.strictSchema===!1){u.logger.warn(v());return}throw new Error(v());function v(){return`unknown format "${s}" ignored in schema at path "${l}"`}}function w(v){let P=v instanceof RegExp?(0,Ae.regexpCode)(v):c.code.formats?(0,Ae._)`${c.code.formats}${(0,Ae.getProperty)(s)}`:void 0,O=t.scopeValue("formats",{key:s,ref:v,code:P});return typeof v=="object"&&!(v instanceof RegExp)?[v.type||"string",v.validate,(0,Ae._)`${O}.validate`]:["string",v,O]}function x(){if(typeof y=="object"&&!(y instanceof RegExp)&&y.async){if(!d.$async)throw new Error("async format in sync schema");return(0,Ae._)`await ${g}(${n})`}return typeof m=="function"?(0,Ae._)`${g}(${n})`:(0,Ae._)`${g}.test(${n})`}}}};Vd.default=z1});var Bd=A(Ud=>{"use strict";Object.defineProperty(Ud,"__esModule",{value:!0});var H1=Zm(),K1=[H1.default];Ud.default=K1});var zd=A(Zn=>{"use strict";Object.defineProperty(Zn,"__esModule",{value:!0});Zn.contentVocabulary=Zn.metadataVocabulary=void 0;Zn.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Zn.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var ty=A(Hd=>{"use strict";Object.defineProperty(Hd,"__esModule",{value:!0});var W1=zl(),G1=od(),J1=xd(),Y1=Um(),X1=Wm(),Q1=Qm(),Z1=Bd(),ey=zd(),ek=[Y1.default,W1.default,G1.default,(0,J1.default)(!0),Z1.default,ey.metadataVocabulary,ey.contentVocabulary,X1.default,Q1.default];Hd.default=ek});var ny=A(Qo=>{"use strict";Object.defineProperty(Qo,"__esModule",{value:!0});Qo.DiscrError=void 0;var ry;(function(r){r.Tag="tag",r.Mapping="mapping"})(ry||(Qo.DiscrError=ry={}))});var Gd=A(Wd=>{"use strict";Object.defineProperty(Wd,"__esModule",{value:!0});var ei=H(),Kd=ny(),iy=ns(),tk=Gn(),rk=Q(),nk={message:({params:{discrError:r,tagName:e}})=>r===Kd.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:r,tag:e,tagName:t}})=>(0,ei._)`{error: ${r}, tag: ${t}, tagValue: ${e}}`},ik={keyword:"discriminator",type:"object",schemaType:"object",error:nk,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,ei._)`${t}${(0,ei.getProperty)(a)}`);e.if((0,ei._)`typeof ${l} == "string"`,()=>d(),()=>r.error(!1,{discrError:Kd.DiscrError.Tag,tag:l,tagName:a})),r.ok(c);function d(){let p=f();e.if(!1);for(let y in p)e.elseIf((0,ei._)`${l} === ${y}`),e.assign(c,u(p[y]));e.else(),r.error(!1,{discrError:Kd.DiscrError.Mapping,tag:l,tagName:a}),e.endIf()}function u(p){let y=e.name("valid"),h=r.subschema({keyword:"oneOf",schemaProp:p},y);return r.mergeEvaluated(h,ei.Name),y}function f(){var p;let y={},h=g(i),m=!0;for(let x=0;x{sk.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 oy=A((t2,ok)=>{ok.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 ay=A((r2,ak)=>{ak.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 cy=A((n2,ck)=>{ck.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 ly=A((i2,lk)=>{lk.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 dy=A((s2,dk)=>{dk.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 uy=A((o2,uk)=>{uk.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 fy=A((a2,fk)=>{fk.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 py=A(Jd=>{"use strict";Object.defineProperty(Jd,"__esModule",{value:!0});var pk=sy(),hk=oy(),mk=ay(),yk=cy(),gk=ly(),_k=dy(),bk=uy(),wk=fy(),vk=["/properties"];function $k(r){return[pk,hk,mk,yk,gk,e(this,_k),bk,e(this,wk)].forEach(t=>this.addMetaSchema(t,void 0,!1)),this;function e(t,n){return r?t.$dataMetaSchema(n,vk):n}}Jd.default=$k});var Qd=A((_e,Xd)=>{"use strict";Object.defineProperty(_e,"__esModule",{value:!0});_e.MissingRefError=_e.ValidationError=_e.CodeGen=_e.Name=_e.nil=_e.stringify=_e.str=_e._=_e.KeywordCxt=_e.Ajv2020=void 0;var Sk=Vl(),Ek=ty(),Ak=Gd(),kk=py(),Yd="https://json-schema.org/draft/2020-12/schema",ti=class extends Sk.default{constructor(e={}){super({...e,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){super._addVocabularies(),Ek.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(Ak.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data:e,meta:t}=this.opts;t&&(kk.default.call(this,e),this.refs["http://json-schema.org/schema"]=Yd)}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Yd)?Yd:void 0)}};_e.Ajv2020=ti;Xd.exports=_e=ti;Xd.exports.Ajv2020=ti;Object.defineProperty(_e,"__esModule",{value:!0});_e.default=ti;var xk=Wn();Object.defineProperty(_e,"KeywordCxt",{enumerable:!0,get:function(){return xk.KeywordCxt}});var ri=H();Object.defineProperty(_e,"_",{enumerable:!0,get:function(){return ri._}});Object.defineProperty(_e,"str",{enumerable:!0,get:function(){return ri.str}});Object.defineProperty(_e,"stringify",{enumerable:!0,get:function(){return ri.stringify}});Object.defineProperty(_e,"nil",{enumerable:!0,get:function(){return ri.nil}});Object.defineProperty(_e,"Name",{enumerable:!0,get:function(){return ri.Name}});Object.defineProperty(_e,"CodeGen",{enumerable:!0,get:function(){return ri.CodeGen}});var Pk=rs();Object.defineProperty(_e,"ValidationError",{enumerable:!0,get:function(){return Pk.default}});var Ik=Gn();Object.defineProperty(_e,"MissingRefError",{enumerable:!0,get:function(){return Ik.default}})});var vy=A(rr=>{"use strict";Object.defineProperty(rr,"__esModule",{value:!0});rr.formatNames=rr.fastFormats=rr.fullFormats=void 0;function tr(r,e){return{validate:r,compare:e}}rr.fullFormats={date:tr(gy,ru),time:tr(eu(!0),nu),"date-time":tr(hy(!0),by),"iso-time":tr(eu(),_y),"iso-date-time":tr(hy(),wy),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:Nk,"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:Uk,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:Lk,int32:{type:"number",validate:qk},int64:{type:"number",validate:Fk},float:{type:"number",validate:yy},double:{type:"number",validate:yy},password:!0,binary:!0};rr.fastFormats={...rr.fullFormats,date:tr(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,ru),time:tr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,nu),"date-time":tr(/^\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,by),"iso-time":tr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,_y),"iso-date-time":tr(/^\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,wy),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};rr.formatNames=Object.keys(rr.fullFormats);function Ok(r){return r%4===0&&(r%100!==0||r%400===0)}var Rk=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,Tk=[0,31,28,31,30,31,30,31,31,30,31,30,31];function gy(r){let e=Rk.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&&Ok(t)?29:Tk[n])}function ru(r,e){if(r&&e)return r>e?1:r23||d>59||r&&!a)return!1;if(i<=23&&s<=59&&o<60)return!0;let u=s-d*c,f=i-l*c-(u<0?1:0);return(f===23||f===-1)&&(u===59||u===-1)&&o<61}}function nu(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 _y(r,e){if(!(r&&e))return;let t=Zd.exec(r),n=Zd.exec(e);if(t&&n)return r=t[1]+t[2]+t[3],e=n[1]+n[2]+n[3],r>e?1:r=jk}function Fk(r){return Number.isInteger(r)}function yy(){return!0}var Vk=/[^\\]\\Z/;function Uk(r){if(Vk.test(r))return!1;try{return new RegExp(r),!0}catch(e){return!1}}});var Sy=A(iu=>{"use strict";Object.defineProperty(iu,"__esModule",{value:!0});var Bk=zl(),zk=od(),Hk=xd(),Kk=Bd(),$y=zd(),Wk=[Bk.default,zk.default,(0,Hk.default)(),Kk.default,$y.metadataVocabulary,$y.contentVocabulary];iu.default=Wk});var Ey=A((u2,Gk)=>{Gk.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 ky=A((be,su)=>{"use strict";Object.defineProperty(be,"__esModule",{value:!0});be.MissingRefError=be.ValidationError=be.CodeGen=be.Name=be.nil=be.stringify=be.str=be._=be.KeywordCxt=be.Ajv=void 0;var Jk=Vl(),Yk=Sy(),Xk=Gd(),Ay=Ey(),Qk=["/properties"],Zo="http://json-schema.org/draft-07/schema",ni=class extends Jk.default{_addVocabularies(){super._addVocabularies(),Yk.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(Xk.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(Ay,Qk):Ay;this.addMetaSchema(e,Zo,!1),this.refs["http://json-schema.org/schema"]=Zo}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Zo)?Zo:void 0)}};be.Ajv=ni;su.exports=be=ni;su.exports.Ajv=ni;Object.defineProperty(be,"__esModule",{value:!0});be.default=ni;var Zk=Wn();Object.defineProperty(be,"KeywordCxt",{enumerable:!0,get:function(){return Zk.KeywordCxt}});var ii=H();Object.defineProperty(be,"_",{enumerable:!0,get:function(){return ii._}});Object.defineProperty(be,"str",{enumerable:!0,get:function(){return ii.str}});Object.defineProperty(be,"stringify",{enumerable:!0,get:function(){return ii.stringify}});Object.defineProperty(be,"nil",{enumerable:!0,get:function(){return ii.nil}});Object.defineProperty(be,"Name",{enumerable:!0,get:function(){return ii.Name}});Object.defineProperty(be,"CodeGen",{enumerable:!0,get:function(){return ii.CodeGen}});var ex=rs();Object.defineProperty(be,"ValidationError",{enumerable:!0,get:function(){return ex.default}});var tx=Gn();Object.defineProperty(be,"MissingRefError",{enumerable:!0,get:function(){return tx.default}})});var xy=A(si=>{"use strict";Object.defineProperty(si,"__esModule",{value:!0});si.formatLimitDefinition=void 0;var rx=ky(),Nt=H(),Gr=Nt.operators,ea={formatMaximum:{okStr:"<=",ok:Gr.LTE,fail:Gr.GT},formatMinimum:{okStr:">=",ok:Gr.GTE,fail:Gr.LT},formatExclusiveMaximum:{okStr:"<",ok:Gr.LT,fail:Gr.GTE},formatExclusiveMinimum:{okStr:">",ok:Gr.GT,fail:Gr.LTE}},nx={message:({keyword:r,schemaCode:e})=>(0,Nt.str)`should be ${ea[r].okStr} ${e}`,params:({keyword:r,schemaCode:e})=>(0,Nt._)`{comparison: ${ea[r].okStr}, limit: ${e}}`};si.formatLimitDefinition={keyword:Object.keys(ea),type:"string",schemaType:"string",$data:!0,error:nx,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 rx.KeywordCxt(s,a.RULES.all.format.definition,"format");c.$data?l():d();function l(){let f=e.scopeValue("formats",{ref:a.formats,code:o.code.formats}),p=e.const("fmt",(0,Nt._)`${f}[${c.schemaCode}]`);r.fail$data((0,Nt.or)((0,Nt._)`typeof ${p} != "object"`,(0,Nt._)`${p} instanceof RegExp`,(0,Nt._)`typeof ${p}.compare != "function"`,u(p)))}function d(){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 y=e.scopeValue("formats",{key:f,ref:p,code:o.code.formats?(0,Nt._)`${o.code.formats}${(0,Nt.getProperty)(f)}`:void 0});r.fail$data(u(y))}function u(f){return(0,Nt._)`${f}.compare(${t}, ${n}) ${ea[i].fail} 0`}},dependencies:["format"]};var ix=r=>(r.addKeyword(si.formatLimitDefinition),r);si.default=ix});var cu=A((bs,Oy)=>{"use strict";Object.defineProperty(bs,"__esModule",{value:!0});var oi=vy(),sx=xy(),ou=H(),Py=new ou.Name("fullFormats"),ox=new ou.Name("fastFormats"),au=(r,e={keywords:!0})=>{if(Array.isArray(e))return Iy(r,e,oi.fullFormats,Py),r;let[t,n]=e.mode==="fast"?[oi.fastFormats,ox]:[oi.fullFormats,Py],i=e.formats||oi.formatNames;return Iy(r,i,t,n),e.keywords&&(0,sx.default)(r),r};au.get=(r,e="full")=>{let n=(e==="fast"?oi.fastFormats:oi.fullFormats)[r];if(!n)throw new Error(`Unknown format "${r}"`);return n};function Iy(r,e,t,n){var i,s;(i=(s=r.opts.code).formats)!==null&&i!==void 0||(s.formats=(0,ou._)`require("ajv-formats/dist/formats").${n}`);for(let o of e)r.addFormat(o,t[o])}Oy.exports=bs=au;Object.defineProperty(bs,"__esModule",{value:!0});bs.default=au});var li=A((b2,jy)=>{"use strict";var lx="2.0.0",dx=Number.MAX_SAFE_INTEGER||9007199254740991,ux=16,fx=250,px=["major","premajor","minor","preminor","patch","prepatch","prerelease"];jy.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:ux,MAX_SAFE_BUILD_LENGTH:fx,MAX_SAFE_INTEGER:dx,RELEASE_TYPES:px,SEMVER_SPEC_VERSION:lx,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var ws=A((w2,Dy)=>{"use strict";var hx=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...r)=>console.error("SEMVER",...r):()=>{};Dy.exports=hx});var di=A((ir,qy)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:fu,MAX_SAFE_BUILD_LENGTH:mx,MAX_LENGTH:yx}=li(),gx=ws();ir=qy.exports={};var _x=ir.re=[],bx=ir.safeRe=[],j=ir.src=[],wx=ir.safeSrc=[],D=ir.t={},vx=0,pu="[a-zA-Z0-9-]",$x=[["\\s",1],["\\d",yx],[pu,mx]],Sx=r=>{for(let[e,t]of $x)r=r.split(`${e}*`).join(`${e}{0,${t}}`).split(`${e}+`).join(`${e}{1,${t}}`);return r},K=(r,e,t)=>{let n=Sx(e),i=vx++;gx(r,i,e),D[r]=i,j[i]=e,wx[i]=n,_x[i]=new RegExp(e,t?"g":void 0),bx[i]=new RegExp(n,t?"g":void 0)};K("NUMERICIDENTIFIER","0|[1-9]\\d*");K("NUMERICIDENTIFIERLOOSE","\\d+");K("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${pu}*`);K("MAINVERSION",`(${j[D.NUMERICIDENTIFIER]})\\.(${j[D.NUMERICIDENTIFIER]})\\.(${j[D.NUMERICIDENTIFIER]})`);K("MAINVERSIONLOOSE",`(${j[D.NUMERICIDENTIFIERLOOSE]})\\.(${j[D.NUMERICIDENTIFIERLOOSE]})\\.(${j[D.NUMERICIDENTIFIERLOOSE]})`);K("PRERELEASEIDENTIFIER",`(?:${j[D.NONNUMERICIDENTIFIER]}|${j[D.NUMERICIDENTIFIER]})`);K("PRERELEASEIDENTIFIERLOOSE",`(?:${j[D.NONNUMERICIDENTIFIER]}|${j[D.NUMERICIDENTIFIERLOOSE]})`);K("PRERELEASE",`(?:-(${j[D.PRERELEASEIDENTIFIER]}(?:\\.${j[D.PRERELEASEIDENTIFIER]})*))`);K("PRERELEASELOOSE",`(?:-?(${j[D.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${j[D.PRERELEASEIDENTIFIERLOOSE]})*))`);K("BUILDIDENTIFIER",`${pu}+`);K("BUILD",`(?:\\+(${j[D.BUILDIDENTIFIER]}(?:\\.${j[D.BUILDIDENTIFIER]})*))`);K("FULLPLAIN",`v?${j[D.MAINVERSION]}${j[D.PRERELEASE]}?${j[D.BUILD]}?`);K("FULL",`^${j[D.FULLPLAIN]}$`);K("LOOSEPLAIN",`[v=\\s]*${j[D.MAINVERSIONLOOSE]}${j[D.PRERELEASELOOSE]}?${j[D.BUILD]}?`);K("LOOSE",`^${j[D.LOOSEPLAIN]}$`);K("GTLT","((?:<|>)?=?)");K("XRANGEIDENTIFIERLOOSE",`${j[D.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);K("XRANGEIDENTIFIER",`${j[D.NUMERICIDENTIFIER]}|x|X|\\*`);K("XRANGEPLAIN",`[v=\\s]*(${j[D.XRANGEIDENTIFIER]})(?:\\.(${j[D.XRANGEIDENTIFIER]})(?:\\.(${j[D.XRANGEIDENTIFIER]})(?:${j[D.PRERELEASE]})?${j[D.BUILD]}?)?)?`);K("XRANGEPLAINLOOSE",`[v=\\s]*(${j[D.XRANGEIDENTIFIERLOOSE]})(?:\\.(${j[D.XRANGEIDENTIFIERLOOSE]})(?:\\.(${j[D.XRANGEIDENTIFIERLOOSE]})(?:${j[D.PRERELEASELOOSE]})?${j[D.BUILD]}?)?)?`);K("XRANGE",`^${j[D.GTLT]}\\s*${j[D.XRANGEPLAIN]}$`);K("XRANGELOOSE",`^${j[D.GTLT]}\\s*${j[D.XRANGEPLAINLOOSE]}$`);K("COERCEPLAIN",`(^|[^\\d])(\\d{1,${fu}})(?:\\.(\\d{1,${fu}}))?(?:\\.(\\d{1,${fu}}))?`);K("COERCE",`${j[D.COERCEPLAIN]}(?:$|[^\\d])`);K("COERCEFULL",j[D.COERCEPLAIN]+`(?:${j[D.PRERELEASE]})?(?:${j[D.BUILD]})?(?:$|[^\\d])`);K("COERCERTL",j[D.COERCE],!0);K("COERCERTLFULL",j[D.COERCEFULL],!0);K("LONETILDE","(?:~>?)");K("TILDETRIM",`(\\s*)${j[D.LONETILDE]}\\s+`,!0);ir.tildeTrimReplace="$1~";K("TILDE",`^${j[D.LONETILDE]}${j[D.XRANGEPLAIN]}$`);K("TILDELOOSE",`^${j[D.LONETILDE]}${j[D.XRANGEPLAINLOOSE]}$`);K("LONECARET","(?:\\^)");K("CARETTRIM",`(\\s*)${j[D.LONECARET]}\\s+`,!0);ir.caretTrimReplace="$1^";K("CARET",`^${j[D.LONECARET]}${j[D.XRANGEPLAIN]}$`);K("CARETLOOSE",`^${j[D.LONECARET]}${j[D.XRANGEPLAINLOOSE]}$`);K("COMPARATORLOOSE",`^${j[D.GTLT]}\\s*(${j[D.LOOSEPLAIN]})$|^$`);K("COMPARATOR",`^${j[D.GTLT]}\\s*(${j[D.FULLPLAIN]})$|^$`);K("COMPARATORTRIM",`(\\s*)${j[D.GTLT]}\\s*(${j[D.LOOSEPLAIN]}|${j[D.XRANGEPLAIN]})`,!0);ir.comparatorTrimReplace="$1$2$3";K("HYPHENRANGE",`^\\s*(${j[D.XRANGEPLAIN]})\\s+-\\s+(${j[D.XRANGEPLAIN]})\\s*$`);K("HYPHENRANGELOOSE",`^\\s*(${j[D.XRANGEPLAINLOOSE]})\\s+-\\s+(${j[D.XRANGEPLAINLOOSE]})\\s*$`);K("STAR","(<|>)?=?\\s*\\*");K("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");K("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")});var na=A((v2,Fy)=>{"use strict";var Ex=Object.freeze({loose:!0}),Ax=Object.freeze({}),kx=r=>r?typeof r!="object"?Ex:r:Ax;Fy.exports=kx});var hu=A(($2,By)=>{"use strict";var Vy=/^[0-9]+$/,Uy=(r,e)=>{if(typeof r=="number"&&typeof e=="number")return r===e?0:rUy(e,r);By.exports={compareIdentifiers:Uy,rcompareIdentifiers:xx}});var De=A((S2,Hy)=>{"use strict";var ia=ws(),{MAX_LENGTH:zy,MAX_SAFE_INTEGER:sa}=li(),{safeRe:oa,t:aa}=di(),Px=na(),{compareIdentifiers:mu}=hu(),Ix=(r,e)=>{let t=e.split(".");if(t.length>r.length)return!1;for(let n=0;nzy)throw new TypeError(`version is longer than ${zy} characters`);ia("SemVer",e,t),this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease;let n=e.trim().match(t.loose?oa[aa.LOOSE]:oa[aa.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>sa||this.major<0)throw new TypeError("Invalid major version");if(this.minor>sa||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>sa||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(ia("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 mu(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(ia("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 mu(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?oa[aa.PRERELEASELOOSE]:oa[aa.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]),Ix(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}};Hy.exports=yu});var Yr=A((E2,Wy)=>{"use strict";var Ky=De(),Ox=(r,e,t=!1)=>{if(r instanceof Ky)return r;try{return new Ky(r,e)}catch(n){if(!t)return null;throw n}};Wy.exports=Ox});var Jy=A((A2,Gy)=>{"use strict";var Rx=Yr(),Tx=(r,e)=>{let t=Rx(r,e);return t?t.version:null};Gy.exports=Tx});var Xy=A((k2,Yy)=>{"use strict";var Cx=Yr(),Mx=(r,e)=>{let t=Cx(r.trim().replace(/^[=v]+/,""),e);return t?t.version:null};Yy.exports=Mx});var eg=A((x2,Zy)=>{"use strict";var Qy=De(),Nx=(r,e,t,n,i)=>{typeof t=="string"&&(i=n,n=t,t=void 0);try{return new Qy(r instanceof Qy?r.version:r,t).inc(e,n,i).version}catch(s){return null}};Zy.exports=Nx});var ng=A((P2,rg)=>{"use strict";var tg=Yr(),Lx=(r,e)=>{let t=tg(r,null,!0),n=tg(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 d=c?"pre":"";return t.major!==n.major?d+"major":t.minor!==n.minor?d+"minor":t.patch!==n.patch?d+"patch":"prerelease"};rg.exports=Lx});var sg=A((I2,ig)=>{"use strict";var jx=De(),Dx=(r,e)=>new jx(r,e).major;ig.exports=Dx});var ag=A((O2,og)=>{"use strict";var qx=De(),Fx=(r,e)=>new qx(r,e).minor;og.exports=Fx});var lg=A((R2,cg)=>{"use strict";var Vx=De(),Ux=(r,e)=>new Vx(r,e).patch;cg.exports=Ux});var ug=A((T2,dg)=>{"use strict";var Bx=Yr(),zx=(r,e)=>{let t=Bx(r,e);return t&&t.prerelease.length?t.prerelease:null};dg.exports=zx});var At=A((C2,pg)=>{"use strict";var fg=De(),Hx=(r,e,t)=>new fg(r,t).compare(new fg(e,t));pg.exports=Hx});var mg=A((M2,hg)=>{"use strict";var Kx=At(),Wx=(r,e,t)=>Kx(e,r,t);hg.exports=Wx});var gg=A((N2,yg)=>{"use strict";var Gx=At(),Jx=(r,e)=>Gx(r,e,!0);yg.exports=Jx});var ca=A((L2,bg)=>{"use strict";var _g=De(),Yx=(r,e,t)=>{let n=new _g(r,t),i=new _g(e,t);return n.compare(i)||n.compareBuild(i)};bg.exports=Yx});var vg=A((j2,wg)=>{"use strict";var Xx=ca(),Qx=(r,e)=>r.sort((t,n)=>Xx(t,n,e));wg.exports=Qx});var Sg=A((D2,$g)=>{"use strict";var Zx=ca(),eP=(r,e)=>r.sort((t,n)=>Zx(n,t,e));$g.exports=eP});var vs=A((q2,Eg)=>{"use strict";var tP=At(),rP=(r,e,t)=>tP(r,e,t)>0;Eg.exports=rP});var la=A((F2,Ag)=>{"use strict";var nP=At(),iP=(r,e,t)=>nP(r,e,t)<0;Ag.exports=iP});var gu=A((V2,kg)=>{"use strict";var sP=At(),oP=(r,e,t)=>sP(r,e,t)===0;kg.exports=oP});var _u=A((U2,xg)=>{"use strict";var aP=At(),cP=(r,e,t)=>aP(r,e,t)!==0;xg.exports=cP});var da=A((B2,Pg)=>{"use strict";var lP=At(),dP=(r,e,t)=>lP(r,e,t)>=0;Pg.exports=dP});var ua=A((z2,Ig)=>{"use strict";var uP=At(),fP=(r,e,t)=>uP(r,e,t)<=0;Ig.exports=fP});var bu=A((H2,Og)=>{"use strict";var pP=gu(),hP=_u(),mP=vs(),yP=da(),gP=la(),_P=ua(),bP=(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 pP(r,t,n);case"!=":return hP(r,t,n);case">":return mP(r,t,n);case">=":return yP(r,t,n);case"<":return gP(r,t,n);case"<=":return _P(r,t,n);default:throw new TypeError(`Invalid operator: ${e}`)}};Og.exports=bP});var Tg=A((K2,Rg)=>{"use strict";var wP=De(),vP=Yr(),{safeRe:fa,t:pa}=di(),$P=(r,e)=>{if(r instanceof wP)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?fa[pa.COERCEFULL]:fa[pa.COERCE]);else{let c=e.includePrerelease?fa[pa.COERCERTLFULL]:fa[pa.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 vP(`${n}.${i}.${s}${o}${a}`,e)};Rg.exports=$P});var Mg=A((W2,Cg)=>{"use strict";var SP=Yr(),EP=li(),AP=De(),kP=(r,e,t)=>{if(!EP.RELEASE_TYPES.includes(e))return null;let n=xP(r,t);return n&&PP(n,e)},xP=(r,e)=>{let t=r instanceof AP?r.version:r;return SP(t,e)},PP=(r,e)=>{if(IP(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()},IP=r=>r.startsWith("pre");Cg.exports=kP});var Lg=A((G2,Ng)=>{"use strict";var wu=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}};Ng.exports=wu});var kt=A((J2,Fg)=>{"use strict";var OP=/\s+/g,vu=class r{constructor(e,t){if(t=TP(t),e instanceof r)return e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease?e:new r(e.raw,t);if(e instanceof $u)return this.raw=e.value,this.set=[[e]],this.formatted=void 0,this;if(this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease,this.raw=e.trim().replace(OP," "),this.set=this.raw.split("||").map(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=>!Dg(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&&VP(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(FP,"");let n=((this.options.includePrerelease&&DP)|(this.options.loose&&qP))+":"+e,i=jg.get(n);if(i)return i;let s=this.options.loose,o=s?Xe[qe.HYPHENRANGELOOSE]:Xe[qe.HYPHENRANGE];e=e.replace(o,QP(this.options.includePrerelease)),we("hyphen replace",e),e=e.replace(Xe[qe.COMPARATORTRIM],NP),we("comparator trim",e),e=e.replace(Xe[qe.TILDETRIM],LP),we("tilde trim",e),e=e.replace(Xe[qe.CARETTRIM],jP),we("caret trim",e);let a=e.split(" ").map(u=>UP(u,this.options)).join(" ").split(/\s+/).map(u=>XP(u,this.options));s&&(a=a.filter(u=>(we("loose invalid filter",u,this.options),!!u.match(Xe[qe.COMPARATORLOOSE])))),we("range list",a);let c=new Map,l=a.map(u=>new $u(u,this.options));for(let u of l){if(Dg(u))return[u];c.set(u.value,u)}c.size>1&&c.has("")&&c.delete("");let d=[...c.values()];return jg.set(n,d),d}intersects(e,t){if(!(e instanceof r))throw new TypeError("a Range is required");return this.set.some(n=>qg(n,t)&&e.set.some(i=>qg(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 CP(e,this.options)}catch(t){return!1}for(let t=0;tr.value==="<0.0.0-0",VP=r=>r.value==="",qg=(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},UP=(r,e)=>(r=r.replace(Xe[qe.BUILD],""),we("comp",r,e),r=KP(r,e),we("caret",r),r=zP(r,e),we("tildes",r),r=GP(r,e),we("xrange",r),r=YP(r,e),we("stars",r),r),Oe=r=>!r||r.toLowerCase()==="x"||r==="*",BP=(r,e,t)=>Oe(r)&&!Oe(e)||Oe(e)&&t&&!Oe(t),zP=(r,e)=>r.trim().split(/\s+/).map(t=>HP(t,e)).join(" "),HP=(r,e)=>{let t=e.loose?Xe[qe.TILDELOOSE]:Xe[qe.TILDE],n=e.includePrerelease?"-0":"";return r.replace(t,(i,s,o,a,c)=>{we("tilde",r,i,s,o,a,c);let l;return Oe(s)?l="":Oe(o)?l=`>=${s}.0.0${n} <${+s+1}.0.0-0`:Oe(a)?l=`>=${s}.${o}.0${n} <${s}.${+o+1}.0-0`:c?(we("replaceTilde pr",c),l=`>=${s}.${o}.${a}-${c} <${s}.${+o+1}.0-0`):l=`>=${s}.${o}.${a} <${s}.${+o+1}.0-0`,we("tilde return",l),l})},KP=(r,e)=>r.trim().split(/\s+/).map(t=>WP(t,e)).join(" "),WP=(r,e)=>{we("caret",r,e);let t=e.loose?Xe[qe.CARETLOOSE]:Xe[qe.CARET],n=e.includePrerelease?"-0":"";return r.replace(t,(i,s,o,a,c)=>{we("caret",r,i,s,o,a,c);let l;return Oe(s)?l="":Oe(o)?l=`>=${s}.0.0${n} <${+s+1}.0.0-0`:Oe(a)?s==="0"?l=`>=${s}.${o}.0${n} <${s}.${+o+1}.0-0`:l=`>=${s}.${o}.0${n} <${+s+1}.0.0-0`:c?(we("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`):(we("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`),we("caret return",l),l})},GP=(r,e)=>(we("replaceXRanges",r,e),r.split(/\s+/).map(t=>JP(t,e)).join(" ")),JP=(r,e)=>{r=r.trim();let t=e.loose?Xe[qe.XRANGELOOSE]:Xe[qe.XRANGE];return r.replace(t,(n,i,s,o,a,c)=>{if(we("xRange",r,n,i,s,o,a,c),BP(s,o,a))return r;let l=Oe(s),d=l||Oe(o),u=d||Oe(a),f=u;return i==="="&&f&&(i=""),c=e.includePrerelease?"-0":"",l?i===">"||i==="<"?n="<0.0.0-0":n="*":i&&f?(d&&(o=0),a=0,i===">"?(i=">=",d?(s=+s+1,o=0,a=0):(o=+o+1,a=0)):i==="<="&&(i="<",d?s=+s+1:o=+o+1),i==="<"&&(c="-0"),n=`${i+s}.${o}.${a}${c}`):d?n=`>=${s}.0.0${c} <${+s+1}.0.0-0`:u&&(n=`>=${s}.${o}.0${c} <${s}.${+o+1}.0-0`),we("xRange return",n),n})},YP=(r,e)=>(we("replaceStars",r,e),r.trim().replace(Xe[qe.STAR],"")),XP=(r,e)=>(we("replaceGTE0",r,e),r.trim().replace(Xe[e.includePrerelease?qe.GTE0PRE:qe.GTE0],"")),QP=r=>(e,t,n,i,s,o,a,c,l,d,u,f)=>(Oe(n)?t="":Oe(i)?t=`>=${n}.0.0${r?"-0":""}`:Oe(s)?t=`>=${n}.${i}.0${r?"-0":""}`:o?t=`>=${t}`:t=`>=${t}${r?"-0":""}`,Oe(l)?c="":Oe(d)?c=`<${+l+1}.0.0-0`:Oe(u)?c=`<${l}.${+d+1}.0-0`:f?c=`<=${l}.${d}.${u}-${f}`:r?c=`<${l}.${d}.${+u+1}-0`:c=`<=${c}`,`${t} ${c}`.trim()),ZP=(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 $s=A((Y2,Kg)=>{"use strict";var Ss=Symbol("SemVer ANY"),Au=class r{static get ANY(){return Ss}constructor(e,t){if(t=Vg(t),e instanceof r){if(e.loose===!!t.loose)return e;e=e.value}e=e.trim().split(/\s+/).join(" "),Eu("comparator",e,t),this.options=t,this.loose=!!t.loose,this.parse(e),this.semver===Ss?this.value="":this.value=this.operator+this.semver.version,Eu("comp",this)}parse(e){let t=this.options.loose?Ug[Bg.COMPARATORLOOSE]:Ug[Bg.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 zg(n[2],this.options.loose):this.semver=Ss}toString(){return this.value}test(e){if(Eu("Comparator.test",e,this.options.loose),this.semver===Ss||e===Ss)return!0;if(typeof e=="string")try{e=new zg(e,this.options)}catch(t){return!1}return Su(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 Hg(e.value,t).test(this.value):e.operator===""?e.value===""?!0:new Hg(this.value,t).test(e.semver):(t=Vg(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("=")||Su(this.semver,"<",e.semver,t)&&this.operator.startsWith(">")&&e.operator.startsWith("<")||Su(this.semver,">",e.semver,t)&&this.operator.startsWith("<")&&e.operator.startsWith(">")))}};Kg.exports=Au;var Vg=na(),{safeRe:Ug,t:Bg}=di(),Su=bu(),Eu=ws(),zg=De(),Hg=kt()});var Es=A((X2,Wg)=>{"use strict";var eI=kt(),tI=(r,e,t)=>{try{e=new eI(e,t)}catch(n){return!1}return e.test(r)};Wg.exports=tI});var Jg=A((Q2,Gg)=>{"use strict";var rI=kt(),nI=(r,e)=>new rI(r,e).set.map(t=>t.map(n=>n.value).join(" ").trim().split(" "));Gg.exports=nI});var Xg=A((Z2,Yg)=>{"use strict";var iI=De(),sI=kt(),oI=(r,e,t)=>{let n=null,i=null,s=null;try{s=new sI(e,t)}catch(o){return null}return r.forEach(o=>{s.test(o)&&(!n||i.compare(o)===-1)&&(n=o,i=new iI(n,t))}),n};Yg.exports=oI});var Zg=A((eL,Qg)=>{"use strict";var aI=De(),cI=kt(),lI=(r,e,t)=>{let n=null,i=null,s=null;try{s=new cI(e,t)}catch(o){return null}return r.forEach(o=>{s.test(o)&&(!n||i.compare(o)===1)&&(n=o,i=new aI(n,t))}),n};Qg.exports=lI});var r_=A((tL,t_)=>{"use strict";var ku=De(),dI=kt(),e_=vs(),uI=(r,e)=>{r=new dI(r,e);let t=new ku("0.0.0");if(r.test(t)||(t=new ku("0.0.0-0"),r.test(t)))return t;t=null;for(let n=0;n{let a=new ku(o.semver.version);switch(o.operator){case">":a.prerelease.length===0?a.patch++:a.prerelease.push(0),a.raw=a.format();case"":case">=":(!s||e_(a,s))&&(s=a);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${o.operator}`)}}),s&&(!t||e_(t,s))&&(t=s)}return t&&r.test(t)?t:null};t_.exports=uI});var i_=A((rL,n_)=>{"use strict";var fI=kt(),pI=(r,e)=>{try{return new fI(r,e).range||"*"}catch(t){return null}};n_.exports=pI});var ha=A((nL,c_)=>{"use strict";var hI=De(),a_=$s(),{ANY:mI}=a_,yI=kt(),gI=Es(),s_=vs(),o_=la(),_I=ua(),bI=da(),wI=(r,e,t,n)=>{r=new hI(r,n),e=new yI(e,n);let i,s,o,a,c;switch(t){case">":i=s_,s=_I,o=o_,a=">",c=">=";break;case"<":i=o_,s=bI,o=s_,a="<",c="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(gI(r,e,n))return!1;for(let l=0;l{p.semver===mI&&(p=new a_(">=0.0.0")),u=u||p,f=f||p,i(p.semver,u.semver,n)?u=p:o(p.semver,f.semver,n)&&(f=p)}),u.operator===a||u.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};c_.exports=wI});var d_=A((iL,l_)=>{"use strict";var vI=ha(),$I=(r,e,t)=>vI(r,e,">",t);l_.exports=$I});var f_=A((sL,u_)=>{"use strict";var SI=ha(),EI=(r,e,t)=>SI(r,e,"<",t);u_.exports=EI});var m_=A((oL,h_)=>{"use strict";var p_=kt(),AI=(r,e,t)=>(r=new p_(r,t),e=new p_(e,t),r.intersects(e,t));h_.exports=AI});var g_=A((aL,y_)=>{"use strict";var kI=Es(),xI=At();y_.exports=(r,e,t)=>{let n=[],i=null,s=null,o=r.sort((d,u)=>xI(d,u,t));for(let d of o)kI(d,e,t)?(s=d,i||(i=d)):(s&&n.push([i,s]),s=null,i=null);i&&n.push([i,null]);let a=[];for(let[d,u]of n)d===u?a.push(d):!u&&d===o[0]?a.push("*"):u?d===o[0]?a.push(`<=${u}`):a.push(`${d} - ${u}`):a.push(`>=${d}`);let c=a.join(" || "),l=typeof e.raw=="string"?e.raw:String(e);return c.length{"use strict";var __=kt(),Iu=$s(),{ANY:xu}=Iu,Pu=Es(),Ou=At(),PI=(r,e,t={})=>{if(r===e)return!0;r=new __(r,t),e=new __(e,t);let n=!1;e:for(let i of r.set){for(let s of e.set){let o=OI(i,s,t);if(n=n||o!==null,o)continue e}if(n)return!1}return!0},II=[new Iu(">=0.0.0-0")],b_=[new Iu(">=0.0.0")],OI=(r,e,t)=>{if(r===e)return!0;if(r.length===1&&r[0].semver===xu){if(e.length===1&&e[0].semver===xu)return!0;t.includePrerelease?r=II:r=b_}if(e.length===1&&e[0].semver===xu){if(t.includePrerelease)return!0;e=b_}let n=new Set,i,s;for(let p of r)p.operator===">"||p.operator===">="?i=w_(i,p,t):p.operator==="<"||p.operator==="<="?s=v_(s,p,t):n.add(p.semver);if(n.size>1)return null;let o;if(i&&s){if(o=Ou(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&&!Pu(p,String(i),t)||s&&!Pu(p,String(s),t))return null;for(let y of e)if(!Pu(p,String(y),t))return!1;return!0}let a,c,l,d,u=s&&!t.includePrerelease&&s.semver.prerelease.length?s.semver:!1,f=i&&!t.includePrerelease&&i.semver.prerelease.length?i.semver:!1;u&&u.prerelease.length===1&&s.operator==="<"&&u.prerelease[0]===0&&(u=!1);for(let p of e){if(d=d||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=w_(i,p,t),a===p&&a!==i)return!1}else if(i.operator===">="&&!p.test(i.semver))return!1}if(s){if(u&&p.semver.prerelease&&p.semver.prerelease.length&&p.semver.major===u.major&&p.semver.minor===u.minor&&p.semver.patch===u.patch&&(u=!1),p.operator==="<"||p.operator==="<="){if(c=v_(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&&d&&!i&&o!==0||f||u)},w_=(r,e,t)=>{if(!r)return e;let n=Ou(r.semver,e.semver,t);return n>0?r:n<0||e.operator===">"&&r.operator===">="?e:r},v_=(r,e,t)=>{if(!r)return e;let n=Ou(r.semver,e.semver,t);return n<0?r:n>0||e.operator==="<"&&r.operator==="<="?e:r};$_.exports=PI});var x_=A((lL,k_)=>{"use strict";var Ru=di(),E_=li(),RI=De(),A_=hu(),TI=Yr(),CI=Jy(),MI=Xy(),NI=eg(),LI=ng(),jI=sg(),DI=ag(),qI=lg(),FI=ug(),VI=At(),UI=mg(),BI=gg(),zI=ca(),HI=vg(),KI=Sg(),WI=vs(),GI=la(),JI=gu(),YI=_u(),XI=da(),QI=ua(),ZI=bu(),eO=Tg(),tO=Mg(),rO=$s(),nO=kt(),iO=Es(),sO=Jg(),oO=Xg(),aO=Zg(),cO=r_(),lO=i_(),dO=ha(),uO=d_(),fO=f_(),pO=m_(),hO=g_(),mO=S_();k_.exports={parse:TI,valid:CI,clean:MI,inc:NI,diff:LI,major:jI,minor:DI,patch:qI,prerelease:FI,compare:VI,rcompare:UI,compareLoose:BI,compareBuild:zI,sort:HI,rsort:KI,gt:WI,lt:GI,eq:JI,neq:YI,gte:XI,lte:QI,cmp:ZI,coerce:eO,truncate:tO,Comparator:rO,Range:nO,satisfies:iO,toComparators:sO,maxSatisfying:oO,minSatisfying:aO,minVersion:cO,validRange:lO,outside:dO,gtr:uO,ltr:fO,intersects:pO,simplifyRange:hO,subset:mO,SemVer:RI,re:Ru.re,src:Ru.src,tokens:Ru.t,SEMVER_SPEC_VERSION:E_.SEMVER_SPEC_VERSION,RELEASE_TYPES:E_.RELEASE_TYPES,compareIdentifiers:A_.compareIdentifiers,rcompareIdentifiers:A_.rcompareIdentifiers}});var ks=A((xL,j_)=>{"use strict";var C_="[^\\\\/]",EO="(?=.)",M_="[^/]",Lu="(?:\\/|$)",N_="(?:^|\\/)",ju=`\\.{1,2}${Lu}`,AO="(?!\\.)",kO=`(?!${N_}${ju})`,xO=`(?!\\.{0,1}${Lu})`,PO=`(?!${ju})`,IO="[^.\\/]",OO=`${M_}*?`,RO="/",L_={DOT_LITERAL:"\\.",PLUS_LITERAL:"\\+",QMARK_LITERAL:"\\?",SLASH_LITERAL:"\\/",ONE_CHAR:EO,QMARK:M_,END_ANCHOR:Lu,DOTS_SLASH:ju,NO_DOT:AO,NO_DOTS:kO,NO_DOT_SLASH:xO,NO_DOTS_SLASH:PO,QMARK_NO_DOT:IO,STAR:OO,START_ANCHOR:N_,SEP:RO},TO={...L_,SLASH_LITERAL:"[\\\\/]",QMARK:C_,STAR:`${C_}*?`,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:"\\"},CO={__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"};j_.exports={DEFAULT_MAX_EXTGLOB_RECURSION:0,MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:CO,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?TO:L_}}});var xs=A(ct=>{"use strict";var{REGEX_BACKSLASH:MO,REGEX_REMOVE_BACKSLASH:NO,REGEX_SPECIAL_CHARS:LO,REGEX_SPECIAL_CHARS_GLOBAL:jO}=ks();ct.isObject=r=>r!==null&&typeof r=="object"&&!Array.isArray(r);ct.hasRegexChars=r=>LO.test(r);ct.isRegexChar=r=>r.length===1&&ct.hasRegexChars(r);ct.escapeRegex=r=>r.replace(jO,"\\$1");ct.toPosixSlashes=r=>r.replace(MO,"/");ct.isWindows=()=>{if(typeof navigator!="undefined"&&navigator.platform){let r=navigator.platform.toLowerCase();return r==="win32"||r==="windows"}return typeof process!="undefined"&&process.platform?process.platform==="win32":!1};ct.removeBackslashes=r=>r.replace(NO,e=>e==="\\"?"":e);ct.escapeLast=(r,e,t)=>{let n=r.lastIndexOf(e,t);return n===-1?r:r[n-1]==="\\"?ct.escapeLast(r,e,n-1):`${r.slice(0,n)}\\${r.slice(n)}`};ct.removePrefix=(r,e={})=>{let t=r;return t.startsWith("./")&&(t=t.slice(2),e.prefix="./"),t};ct.wrapOutput=(r,e={},t={})=>{let n=t.contains?"":"^",i=t.contains?"":"$",s=`${n}(?:${r})${i}`;return e.negated===!0&&(s=`(?:^(?!${s}).*$)`),s};ct.basename=(r,{windows:e}={})=>{let t=r.split(e?/[\\/]/:"/"),n=t[t.length-1];return n===""?t[t.length-2]:n}});var H_=A((IL,z_)=>{"use strict";var D_=xs(),{CHAR_ASTERISK:Du,CHAR_AT:DO,CHAR_BACKWARD_SLASH:Ps,CHAR_COMMA:qO,CHAR_DOT:qu,CHAR_EXCLAMATION_MARK:Fu,CHAR_FORWARD_SLASH:B_,CHAR_LEFT_CURLY_BRACE:Vu,CHAR_LEFT_PARENTHESES:Uu,CHAR_LEFT_SQUARE_BRACKET:FO,CHAR_PLUS:VO,CHAR_QUESTION_MARK:q_,CHAR_RIGHT_CURLY_BRACE:UO,CHAR_RIGHT_PARENTHESES:F_,CHAR_RIGHT_SQUARE_BRACKET:BO}=ks(),V_=r=>r===B_||r===Ps,U_=r=>{r.isPrefix!==!0&&(r.depth=r.isGlobstar?1/0:1)},zO=(r,e)=>{let t=e||{},n=r.length-1,i=t.parts===!0||t.scanToEnd===!0,s=[],o=[],a=[],c=r,l=-1,d=0,u=0,f=!1,p=!1,y=!1,h=!1,m=!1,g=!1,_=!1,w=!1,x=!1,v=!1,P=0,O,$,R={value:"",depth:0,isGlob:!1},S=()=>l>=n,U=()=>c.charCodeAt(l+1),B=()=>(O=$,c.charCodeAt(++l));for(;l0&&(E=c.slice(0,d),c=c.slice(d),u-=d),T&&y===!0&&u>0?(T=c.slice(0,u),k=c.slice(u)):y===!0?(T="",k=c):T=c,T&&T!==""&&T!=="/"&&T!==c&&V_(T.charCodeAt(T.length-1))&&(T=T.slice(0,-1)),t.unescape===!0&&(k&&(k=D_.removeBackslashes(k)),T&&_===!0&&(T=D_.removeBackslashes(T)));let de={prefix:E,input:r,start:d,base:T,glob:k,isBrace:f,isBracket:p,isGlob:y,isExtglob:h,isGlobstar:m,negated:w,negatedExtglob:x};if(t.tokens===!0&&(de.maxDepth=0,V_($)||o.push(R),de.tokens=o),t.parts===!0||t.tokens===!0){let Z;for(let V=0;V{"use strict";var Is=ks(),ht=xs(),{MAX_LENGTH:_a,POSIX_REGEX_SOURCE:HO,REGEX_NON_SPECIAL_CHARS:KO,REGEX_SPECIAL_CHARS_BACKREF:WO,REPLACEMENTS:K_}=Is,GO=(r,e)=>{if(typeof e.expandRange=="function")return e.expandRange(...r,e);r.sort();let t=`[${r.join("-")}]`;try{new RegExp(t)}catch(n){return r.map(i=>ht.escapeRegex(i)).join("..")}return t},ui=(r,e)=>`Missing ${r}: "${e}" - use "\\\\${e}" to match literal characters`,W_=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},JO=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},zu=r=>{let e=r.trim(),t=!0;for(;t===!0;)t=!1,/^@\([^\\()[\]{}|]+\)$/.test(e)&&(e=e.slice(2,-1),t=!0);if(JO(e))return e.replace(/\\(.)/g,"$1")},YO=r=>{let e=r.map(zu).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}}}}},XO=r=>`${r.length===1?ht.escapeRegex(r[0]):`[${r.map(t=>ht.escapeRegex(t)).join("")}]`}*`,QO=r=>{let e=0,t=[];for(;eo.trim());if(i.length!==1)return;let s=zu(i[0]);if(!s||s.length!==1)return;t.push(s),e+=n.end+1}if(!(t.length<1))return t},ZO=r=>{let e=0,t=r.trim(),n=Bu(t);for(;n;)e++,t=n.body.trim(),n=Bu(t);return e},eR=(r,e)=>{if(e.maxExtglobRecursion===!1)return{risky:!1};let t=typeof e.maxExtglobRecursion=="number"?e.maxExtglobRecursion:Is.DEFAULT_MAX_EXTGLOB_RECURSION,n=W_(r).map(a=>a.trim());if(n.length>1&&(n.some(a=>a==="")||n.some(a=>/^[*?]+$/.test(a))||YO(n)))return{risky:!0};let i=[],s=!1,o=!0;for(let a of n){let c=QO(a);if(c){s=!0,i.push(...c);continue}let l=zu(a);if(l&&l.length===1){i.push(l);continue}if(o=!1,ZO(a)>t)return{risky:!0}}return s?o?{risky:!0,safeOutput:XO([...new Set(i)])}:{risky:!0}:{risky:!1}},Hu=(r,e)=>{if(typeof r!="string")throw new TypeError("Expected a string");r=K_[r]||r;let t={...e},n=typeof t.maxLength=="number"?Math.min(_a,t.maxLength):_a,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=Is.globChars(t.windows),l=Is.extglobChars(c),{DOT_LITERAL:d,PLUS_LITERAL:u,SLASH_LITERAL:f,ONE_CHAR:p,DOTS_SLASH:y,NO_DOT:h,NO_DOT_SLASH:m,NO_DOTS_SLASH:g,QMARK:_,QMARK_NO_DOT:w,STAR:x,START_ANCHOR:v}=c,P=M=>`(${a}(?:(?!${v}${M.dot?y:d}).)*?)`,O=t.dot?"":h,$=t.dot?_:w,R=t.bash===!0?P(t):x;t.capture&&(R=`(${R})`),typeof t.noext=="boolean"&&(t.noextglob=t.noext);let S={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=ht.removePrefix(r,S),i=r.length;let U=[],B=[],T=[],E=s,k,de=()=>S.index===i-1,Z=S.peek=(M=1)=>r[S.index+M],V=S.advance=()=>r[++S.index]||"",fe=()=>r.slice(S.index+1),Ve=(M="",$e=0)=>{S.consumed+=M,S.index+=$e},Jt=M=>{S.output+=M.output!=null?M.output:M.value,Ve(M.value)},Dr=()=>{let M=1;for(;Z()==="!"&&(Z(2)!=="("||Z(3)==="?");)V(),S.start++,M++;return M%2===0?!1:(S.negated=!0,S.start++,!0)},un=M=>{S[M]++,T.push(M)},qr=M=>{S[M]--,T.pop()},ee=M=>{if(E.type==="globstar"){let $e=S.braces>0&&(M.type==="comma"||M.type==="brace"),C=M.extglob===!0||U.length&&(M.type==="pipe"||M.type==="paren");M.type!=="slash"&&M.type!=="paren"&&!$e&&!C&&(S.output=S.output.slice(0,-E.output.length),E.type="star",E.value="*",E.output=R,S.output+=E.output)}if(U.length&&M.type!=="paren"&&(U[U.length-1].inner+=M.value),(M.value||M.output)&&Jt(M),E&&E.type==="text"&&M.type==="text"){E.output=(E.output||E.value)+M.value,E.value+=M.value;return}M.prev=E,o.push(M),E=M},_o=(M,$e)=>{let C={...l[$e],conditions:1,inner:""};C.prev=E,C.parens=S.parens,C.output=S.output,C.startIndex=S.index,C.tokensIndex=o.length;let te=(t.capture?"(":"")+C.open;un("parens"),ee({type:M,value:$e,output:S.output?"":p}),ee({type:"paren",extglob:!0,value:V(),output:te}),U.push(C)},L0=M=>{let $e=r.slice(M.startIndex,S.index+1),C=r.slice(M.startIndex+2,S.index),te=eR(C,t);if((M.type==="plus"||M.type==="star")&&te.risky){let he=te.safeOutput?(M.output?"":p)+(t.capture?`(${te.safeOutput})`:te.safeOutput):void 0,Yt=o[M.tokensIndex];Yt.type="text",Yt.value=$e,Yt.output=he||ht.escapeRegex($e);for(let Xt=M.tokensIndex+1;Xt1&&M.inner.includes("/")&&(he=P(t)),(he!==R||de()||/^\)+$/.test(fe()))&&(ye=M.close=`)$))${he}`),M.inner.includes("*")&&(Ie=fe())&&/^\.[^\\/.]+$/.test(Ie)){let Yt=Hu(Ie,{...e,fastpaths:!1}).output;ye=M.close=`)${Yt})${he})`}M.prev.type==="bos"&&(S.negatedExtglob=!0)}ee({type:"paren",extglob:!0,value:k,output:ye}),qr("parens")};if(t.fastpaths!==!1&&!/(^[*!]|[/()[\]{}"])/.test(r)){let M=!1,$e=r.replace(WO,(C,te,ye,Ie,he,Yt)=>Ie==="\\"?(M=!0,C):Ie==="?"?te?te+Ie+(he?_.repeat(he.length):""):Yt===0?$+(he?_.repeat(he.length):""):_.repeat(ye.length):Ie==="."?d.repeat(ye.length):Ie==="*"?te?te+Ie+(he?R:""):R:te?C:`\\${C}`);return M===!0&&(t.unescape===!0?$e=$e.replace(/\\/g,""):$e=$e.replace(/\\+/g,C=>C.length%2===0?"\\\\":C?"\\":"")),$e===r&&t.contains===!0?(S.output=r,S):(S.output=ht.wrapOutput($e,S,e),S)}for(;!de();){if(k=V(),k==="\0")continue;if(k==="\\"){let C=Z();if(C==="/"&&t.bash!==!0||C==="."||C===";")continue;if(!C){k+="\\",ee({type:"text",value:k});continue}let te=/^\\+/.exec(fe()),ye=0;if(te&&te[0].length>2&&(ye=te[0].length,S.index+=ye,ye%2!==0&&(k+="\\")),t.unescape===!0?k=V():k+=V(),S.brackets===0){ee({type:"text",value:k});continue}}if(S.brackets>0&&(k!=="]"||E.value==="["||E.value==="[^")){if(t.posix!==!1&&k===":"){let C=E.value.slice(1);if(C.includes("[")&&(E.posix=!0,C.includes(":"))){let te=E.value.lastIndexOf("["),ye=E.value.slice(0,te),Ie=E.value.slice(te+2),he=HO[Ie];if(he){E.value=ye+he,S.backtrack=!0,V(),!s.output&&o.indexOf(E)===1&&(s.output=p);continue}}}(k==="["&&Z()!==":"||k==="-"&&Z()==="]")&&(k=`\\${k}`),k==="]"&&(E.value==="["||E.value==="[^")&&(k=`\\${k}`),t.posix===!0&&k==="!"&&E.value==="["&&(k="^"),E.value+=k,Jt({value:k});continue}if(S.quotes===1&&k!=='"'){k=ht.escapeRegex(k),E.value+=k,Jt({value:k});continue}if(k==='"'){S.quotes=S.quotes===1?0:1,t.keepQuotes===!0&&ee({type:"text",value:k});continue}if(k==="("){un("parens"),ee({type:"paren",value:k});continue}if(k===")"){if(S.parens===0&&t.strictBrackets===!0)throw new SyntaxError(ui("opening","("));let C=U[U.length-1];if(C&&S.parens===C.parens+1){L0(U.pop());continue}ee({type:"paren",value:k,output:S.parens?")":"\\)"}),qr("parens");continue}if(k==="["){if(t.nobracket===!0||!fe().includes("]")){if(t.nobracket!==!0&&t.strictBrackets===!0)throw new SyntaxError(ui("closing","]"));k=`\\${k}`}else un("brackets");ee({type:"bracket",value:k});continue}if(k==="]"){if(t.nobracket===!0||E&&E.type==="bracket"&&E.value.length===1){ee({type:"text",value:k,output:`\\${k}`});continue}if(S.brackets===0){if(t.strictBrackets===!0)throw new SyntaxError(ui("opening","["));ee({type:"text",value:k,output:`\\${k}`});continue}qr("brackets");let C=E.value.slice(1);if(E.posix!==!0&&C[0]==="^"&&!C.includes("/")&&(k=`/${k}`),E.value+=k,Jt({value:k}),t.literalBrackets===!1||ht.hasRegexChars(C))continue;let te=ht.escapeRegex(E.value);if(S.output=S.output.slice(0,-E.value.length),t.literalBrackets===!0){S.output+=te,E.value=te;continue}E.value=`(${a}${te}|${E.value})`,S.output+=E.value;continue}if(k==="{"&&t.nobrace!==!0){un("braces");let C={type:"brace",value:k,output:"(",outputIndex:S.output.length,tokensIndex:S.tokens.length};B.push(C),ee(C);continue}if(k==="}"){let C=B[B.length-1];if(t.nobrace===!0||!C){ee({type:"text",value:k,output:k});continue}let te=")";if(C.dots===!0){let ye=o.slice(),Ie=[];for(let he=ye.length-1;he>=0&&(o.pop(),ye[he].type!=="brace");he--)ye[he].type!=="dots"&&Ie.unshift(ye[he].value);te=GO(Ie,t),S.backtrack=!0}if(C.comma!==!0&&C.dots!==!0){let ye=S.output.slice(0,C.outputIndex),Ie=S.tokens.slice(C.tokensIndex);C.value=C.output="\\{",k=te="\\}",S.output=ye;for(let he of Ie)S.output+=he.output||he.value}ee({type:"brace",value:k,output:te}),qr("braces"),B.pop();continue}if(k==="|"){U.length>0&&U[U.length-1].conditions++,ee({type:"text",value:k});continue}if(k===","){let C=k,te=B[B.length-1];te&&T[T.length-1]==="braces"&&(te.comma=!0,C="|"),ee({type:"comma",value:k,output:C});continue}if(k==="/"){if(E.type==="dot"&&S.index===S.start+1){S.start=S.index+1,S.consumed="",S.output="",o.pop(),E=s;continue}ee({type:"slash",value:k,output:f});continue}if(k==="."){if(S.braces>0&&E.type==="dot"){E.value==="."&&(E.output=d);let C=B[B.length-1];E.type="dots",E.output+=k,E.value+=k,C.dots=!0;continue}if(S.braces+S.parens===0&&E.type!=="bos"&&E.type!=="slash"){ee({type:"text",value:k,output:d});continue}ee({type:"dot",value:k,output:d});continue}if(k==="?"){if(!(E&&E.value==="(")&&t.noextglob!==!0&&Z()==="("&&Z(2)!=="?"){_o("qmark",k);continue}if(E&&E.type==="paren"){let te=Z(),ye=k;(E.value==="("&&!/[!=<:]/.test(te)||te==="<"&&!/<([!=]|\w+>)/.test(fe()))&&(ye=`\\${k}`),ee({type:"text",value:k,output:ye});continue}if(t.dot!==!0&&(E.type==="slash"||E.type==="bos")){ee({type:"qmark",value:k,output:w});continue}ee({type:"qmark",value:k,output:_});continue}if(k==="!"){if(t.noextglob!==!0&&Z()==="("&&(Z(2)!=="?"||!/[!=<:]/.test(Z(3)))){_o("negate",k);continue}if(t.nonegate!==!0&&S.index===0){Dr();continue}}if(k==="+"){if(t.noextglob!==!0&&Z()==="("&&Z(2)!=="?"){_o("plus",k);continue}if(E&&E.value==="("||t.regex===!1){ee({type:"plus",value:k,output:u});continue}if(E&&(E.type==="bracket"||E.type==="paren"||E.type==="brace")||S.parens>0){ee({type:"plus",value:k});continue}ee({type:"plus",value:u});continue}if(k==="@"){if(t.noextglob!==!0&&Z()==="("&&Z(2)!=="?"){ee({type:"at",extglob:!0,value:k,output:""});continue}ee({type:"text",value:k});continue}if(k!=="*"){(k==="$"||k==="^")&&(k=`\\${k}`);let C=KO.exec(fe());C&&(k+=C[0],S.index+=C[0].length),ee({type:"text",value:k});continue}if(E&&(E.type==="globstar"||E.star===!0)){E.type="star",E.star=!0,E.value+=k,E.output=R,S.backtrack=!0,S.globstar=!0,Ve(k);continue}let M=fe();if(t.noextglob!==!0&&/^\([^?]/.test(M)){_o("star",k);continue}if(E.type==="star"){if(t.noglobstar===!0){Ve(k);continue}let C=E.prev,te=C.prev,ye=C.type==="slash"||C.type==="bos",Ie=te&&(te.type==="star"||te.type==="globstar");if(t.bash===!0&&(!ye||M[0]&&M[0]!=="/")){ee({type:"star",value:k,output:""});continue}let he=S.braces>0&&(C.type==="comma"||C.type==="brace"),Yt=U.length&&(C.type==="pipe"||C.type==="paren");if(!ye&&C.type!=="paren"&&!he&&!Yt){ee({type:"star",value:k,output:""});continue}for(;M.slice(0,3)==="/**";){let Xt=r[S.index+4];if(Xt&&Xt!=="/")break;M=M.slice(3),Ve("/**",3)}if(C.type==="bos"&&de()){E.type="globstar",E.value+=k,E.output=P(t),S.output=E.output,S.globstar=!0,Ve(k);continue}if(C.type==="slash"&&C.prev.type!=="bos"&&!Ie&&de()){S.output=S.output.slice(0,-(C.output+E.output).length),C.output=`(?:${C.output}`,E.type="globstar",E.output=P(t)+(t.strictSlashes?")":"|$)"),E.value+=k,S.globstar=!0,S.output+=C.output+E.output,Ve(k);continue}if(C.type==="slash"&&C.prev.type!=="bos"&&M[0]==="/"){let Xt=M[1]!==void 0?"|$":"";S.output=S.output.slice(0,-(C.output+E.output).length),C.output=`(?:${C.output}`,E.type="globstar",E.output=`${P(t)}${f}|${f}${Xt})`,E.value+=k,S.output+=C.output+E.output,S.globstar=!0,Ve(k+V()),ee({type:"slash",value:"/",output:""});continue}if(C.type==="bos"&&M[0]==="/"){E.type="globstar",E.value+=k,E.output=`(?:^|${f}|${P(t)}${f})`,S.output=E.output,S.globstar=!0,Ve(k+V()),ee({type:"slash",value:"/",output:""});continue}S.output=S.output.slice(0,-E.output.length),E.type="globstar",E.output=P(t),E.value+=k,S.output+=E.output,S.globstar=!0,Ve(k);continue}let $e={type:"star",value:k,output:R};if(t.bash===!0){$e.output=".*?",(E.type==="bos"||E.type==="slash")&&($e.output=O+$e.output),ee($e);continue}if(E&&(E.type==="bracket"||E.type==="paren")&&t.regex===!0){$e.output=k,ee($e);continue}(S.index===S.start||E.type==="slash"||E.type==="dot")&&(E.type==="dot"?(S.output+=m,E.output+=m):t.dot===!0?(S.output+=g,E.output+=g):(S.output+=O,E.output+=O),Z()!=="*"&&(S.output+=p,E.output+=p)),ee($e)}for(;S.brackets>0;){if(t.strictBrackets===!0)throw new SyntaxError(ui("closing","]"));S.output=ht.escapeLast(S.output,"["),qr("brackets")}for(;S.parens>0;){if(t.strictBrackets===!0)throw new SyntaxError(ui("closing",")"));S.output=ht.escapeLast(S.output,"("),qr("parens")}for(;S.braces>0;){if(t.strictBrackets===!0)throw new SyntaxError(ui("closing","}"));S.output=ht.escapeLast(S.output,"{"),qr("braces")}if(t.strictSlashes!==!0&&(E.type==="star"||E.type==="bracket")&&ee({type:"maybe_slash",value:"",output:`${f}?`}),S.backtrack===!0){S.output="";for(let M of S.tokens)S.output+=M.output!=null?M.output:M.value,M.suffix&&(S.output+=M.suffix)}return S};Hu.fastpaths=(r,e)=>{let t={...e},n=typeof t.maxLength=="number"?Math.min(_a,t.maxLength):_a,i=r.length;if(i>n)throw new SyntaxError(`Input length: ${i}, exceeds maximum allowed length: ${n}`);r=K_[r]||r;let{DOT_LITERAL:s,SLASH_LITERAL:o,ONE_CHAR:a,DOTS_SLASH:c,NO_DOT:l,NO_DOTS:d,NO_DOTS_SLASH:u,STAR:f,START_ANCHOR:p}=Is.globChars(t.windows),y=t.dot?d:l,h=t.dot?u:l,m=t.capture?"":"?:",g={negated:!1,prefix:""},_=t.bash===!0?".*?":f;t.capture&&(_=`(${_})`);let w=O=>O.noglobstar===!0?_:`(${m}(?:(?!${p}${O.dot?c:s}).)*?)`,x=O=>{switch(O){case"*":return`${y}${a}${_}`;case".*":return`${s}${a}${_}`;case"*.*":return`${y}${_}${s}${a}${_}`;case"*/*":return`${y}${_}${o}${a}${h}${_}`;case"**":return y+w(t);case"**/*":return`(?:${y}${w(t)}${o})?${h}${a}${_}`;case"**/*.*":return`(?:${y}${w(t)}${o})?${h}${_}${s}${a}${_}`;case"**/.*":return`(?:${y}${w(t)}${o})?${s}${a}${_}`;default:{let $=/^(.*?)\.(\w+)$/.exec(O);if(!$)return;let R=x($[1]);return R?R+s+$[2]:void 0}}},v=ht.removePrefix(r,g),P=x(v);return P&&t.strictSlashes!==!0&&(P+=`${o}?`),P};G_.exports=Hu});var Q_=A((RL,X_)=>{"use strict";var tR=H_(),Ku=J_(),Y_=xs(),rR=ks(),nR=r=>r&&typeof r=="object"&&!Array.isArray(r),ke=(r,e,t=!1)=>{if(Array.isArray(r)){let d=r.map(f=>ke(f,e,t));return f=>{for(let p of d){let y=p(f);if(y)return y}return!1}}let n=nR(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?ke.compileRe(r,e):ke.makeRe(r,e,!1,!0),a=o.state;delete o.state;let c=()=>!1;if(i.ignore){let d={...e,ignore:null,onMatch:null,onResult:null};c=ke(i.ignore,d,t)}let l=(d,u=!1)=>{let{isMatch:f,match:p,output:y}=ke.test(d,o,e,{glob:r,posix:s}),h={glob:r,state:a,regex:o,posix:s,input:d,output:y,match:p,isMatch:f};return typeof i.onResult=="function"&&i.onResult(h),f===!1?(h.isMatch=!1,u?h:!1):c(d)?(typeof i.onIgnore=="function"&&i.onIgnore(h),h.isMatch=!1,u?h:!1):(typeof i.onMatch=="function"&&i.onMatch(h),u?h:!0)};return t&&(l.state=a),l};ke.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?Y_.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=ke.matchBase(r,e,t,i):a=e.exec(c)),{isMatch:!!a,match:a,output:c}};ke.matchBase=(r,e,t,n=t&&t.windows)=>(e instanceof RegExp?e:ke.makeRe(e,t)).test(Y_.basename(r,{windows:n}));ke.isMatch=(r,e,t)=>ke(e,t)(r);ke.parse=(r,e)=>Array.isArray(r)?r.map(t=>ke.parse(t,e)):Ku(r,{...e,fastpaths:!1});ke.scan=(r,e)=>tR(r,e);ke.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=ke.toRegex(a,e);return n===!0&&(c.state=r),c};ke.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=Ku.fastpaths(r,e)),i.output||(i=Ku(r,e)),ke.compileRe(i,e,t,n)};ke.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/$^/}};ke.constants=rR;X_.exports=ke});var Wu=A((TL,tb)=>{"use strict";var Z_=Q_(),iR=xs();function eb(r,e,t=!1){return e&&(e.windows===null||e.windows===void 0)&&(e={...e,windows:iR.isWindows()}),Z_(r,e,t)}Object.assign(eb,Z_);tb.exports=eb});var kM={};B0(kM,{default:()=>zc});module.exports=z0(kM);var L=require("obsidian");var N=class extends Error{constructor(t,n,i){super(n);I(this,"code");I(this,"details");this.code=t,this.details=i,this.name="InteropError"}toPortableError(t){return{code:this.code,message:this.message,...this.details===void 0?{}:{details:this.details},...t===void 0?{}:{retryable:t}}}},Ui=class extends Error{constructor(t,n){super(n.message);I(this,"status");I(this,"error");this.status=t,this.error=n,this.name="ActionHandlerError"}};var Ry=fn(Qd(),1),Ty=fn(cu(),1);var lu={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 ax=Ty.default;function Cy(){return Object.fromEntries(Object.entries(lu).map(([r,e])=>[r,structuredClone(e)]))}function du(){let r=new Ry.Ajv2020({allErrors:!0,strict:!1,validateFormats:!0});ax(r);let e=Cy();r.addSchema(e.profile);for(let[t,n]of Object.entries(e))t!=="profile"&&r.addSchema(n);return r}function br(r,e){let t=String(lu[e].$id),n=r.getSchema(t);if(!n)throw new Error(`Canonical interoperability schema is unavailable: ${e}`);return n}function Jr(r){return(r!=null?r:[]).map(e=>{var t;return`${e.instancePath||"/"} ${(t=e.message)!=null?t:e.keyword}`}).join("; ")}function nr(r,e){if(!("value"in r))throw new N("contract_digest_conflict",`${e} must be resolved to an inline JSON Schema before runtime registration.`);return structuredClone(r.value)}function My(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=nr(r.record_schema,"record_schema"),r.binding_schema&&(e.binding_schema=nr(r.binding_schema,"binding_schema"));break;case"event":e.data_schema=nr(r.data_schema,"data_schema"),r.source_schema&&(e.source_schema=nr(r.source_schema,"source_schema"));break;case"action":e.input_schema=nr(r.input_schema,"input_schema"),r.output_schema&&(e.output_schema=nr(r.output_schema,"output_schema")),r.error_schema&&(e.error_schema=nr(r.error_schema,"error_schema")),r.provider_schema&&(e.provider_schema=nr(r.provider_schema,"provider_schema")),r.behavior&&(e.behavior=structuredClone(r.behavior));break}return e}async function ta(r){return ci(My(r))}async function ci(r){return`sha256:${await cx(uu(r))}`}function Ny(r,e){return{data:ai(r,e.data_schema,`${e.id} data_schema`),...e.source_schema?{source:ai(r,e.source_schema,`${e.id} source_schema`)}:{}}}function Ly(r,e){return{input:ai(r,e.input_schema,`${e.id} input_schema`),...e.output_schema?{output:ai(r,e.output_schema,`${e.id} output_schema`)}:{},...e.error_schema?{error:ai(r,e.error_schema,`${e.id} error_schema`)}:{},...e.provider_schema?{provider:ai(r,e.provider_schema,`${e.id} provider_schema`)}:{}}}function ra(r,e,t,n){if(!(!r||r(e)))throw new N(t,`${n} failed JSON Schema validation: ${Jr(r.errors)}`)}function ai(r,e,t){try{return r.compile(nr(e,t))}catch(n){throw new N("contract_digest_conflict",`${t} could not be compiled: ${n instanceof Error?n.message:String(n)}`)}}function uu(r){return r===null||typeof r!="object"?JSON.stringify(r):Array.isArray(r)?`[${r.map(uu).join(",")}]`:`{${Object.entries(r).filter(([,t])=>t!==void 0).sort(([t],[n])=>tn?1:0).map(([t,n])=>`${JSON.stringify(t)}:${uu(n)}`).join(",")}}`}async function cx(r){let e=new TextEncoder().encode(r),t=await globalThis.crypto.subtle.digest("SHA-256",e);return[...new Uint8Array(t)].map(n=>n.toString(16).padStart(2,"0")).join("")}var vr=fn(x_(),1);var Tu={delivery:["ephemeral"],ordering:["none"],cancellation:!0,deadlines:!0,provider_discovery:!0,request_deduplication:!0,cross_process_identity:!1},yO=new Set(["specversion","id","source","type","time","subject","datacontenttype","dataschema","data","mdbaseprofile","mdbasecontractversion","mdbasecontractdigest","mdbaseapplication","mdbaseimplementation","mdbaseimplementationversion","mdbaseinstanceid","correlationid","causationid"]),As=class{constructor(e={}){I(this,"options");I(this,"profileVersion","0.1");I(this,"transport");I(this,"ajv",du());I(this,"contractValidator",br(this.ajv,"contract"));I(this,"eventValidator",br(this.ajv,"event"));I(this,"actionRequestValidator",br(this.ajv,"actionRequest"));I(this,"actionInvocationValidator",br(this.ajv,"actionInvocation"));I(this,"actionOutcomeValidator",br(this.ajv,"actionOutcome"));I(this,"eventSourceDeclarationValidator",br(this.ajv,"eventSourceDeclaration"));I(this,"actionProviderDeclarationValidator",br(this.ajv,"actionProviderDeclaration"));I(this,"contracts",new Map);I(this,"clients",new Map);I(this,"eventSources",new Map);I(this,"actionProviders",new Map);I(this,"subscriptions",new Map);I(this,"activeActions",new Map);I(this,"completedActions",new Map);I(this,"admissionLocks",new Map);I(this,"recentEvents",new Map);I(this,"authorize");I(this,"now");I(this,"idFactory");I(this,"recentEventLimit");I(this,"completedRequestLimit");I(this,"nextSequence",0);I(this,"disposed",!1);var t,n,i,s,o,a,c,l,d,u;this.options=e,this.authorize=(t=e.authorize)!=null?t:(()=>!1),this.now=(n=e.now)!=null?n:(()=>new Date),this.idFactory=(i=e.idFactory)!=null?i:(f=>{var y;this.nextSequence+=1;let p=typeof((y=globalThis.crypto)==null?void 0:y.randomUUID)=="function"?globalThis.crypto.randomUUID():`${this.now().getTime().toString(36)}-${this.nextSequence.toString(36)}`;return`${f}_${p}`}),this.recentEventLimit=Math.max(1,(s=e.recentEventLimit)!=null?s:1e3),this.completedRequestLimit=Math.max(1,(o=e.completedRequestLimit)!=null?o:1e3),this.transport={...Tu,...structuredClone((a=e.transport)!=null?a:{}),delivery:[...(l=(c=e.transport)==null?void 0:c.delivery)!=null?l:Tu.delivery],ordering:[...(u=(d=e.transport)==null?void 0:d.ordering)!=null?u:Tu.ordering]}}connect(e){this.assertActive(),gO(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){var l;let n=this.requireClient(e);if(t.contracts.length===0)throw new N("request_rejected","An event-source declaration must include a contract.");let i=`${e}:${t.declaration_id}`;if(this.eventSources.has(i))throw new N("request_rejected",`Event-source declaration ${t.declaration_id} is already registered.`);let s=new Map;for(let d of t.contracts){let u=await this.prepareEventContract(d.contract),f=P_(d.requirement,u.reference);if(I_(f,u.reference),await this.assertAuthorized({operation:"register_event_source",principal:n.identity,contract:u.reference}),u.sourceValidator&&!u.sourceValidator((l=d.binding)!=null?l:{}))throw new N("request_rejected",`${u.reference.id} source binding is invalid: ${Jr(u.sourceValidator.errors)}`);let p=ma(u.reference);if(s.has(p))throw new N("contract_digest_conflict",`Event contract ${p} is repeated by one declaration.`);s.set(p,{contract:u,requirement:f,...d.binding===void 0?{}:{binding:structuredClone(d.binding)},...d.ordering===void 0?{}:{ordering:[...d.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:d,requirement:u,binding:f,ordering:p})=>({requirement:structuredClone(u),resolved:structuredClone(d.reference),...f===void 0?{}:{binding:f},...p===void 0?{}:{ordering:p}}))},a={...o,declaration_digest:await ci(o)};Xr(this.eventSourceDeclarationValidator,a,"request_rejected","Event-source declaration"),this.commitContracts([...s.values()].map(({contract:d})=>d)),this.eventSources.set(i,{id:i,clientId:e,declaration:structuredClone(a),contracts:new Map([...s.entries()].map(([d,u])=>[d,{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){var y,h,m,g;let n=this.requireClient(e),i=ma(t.contract),s=[...n.sources].map(_=>this.eventSources.get(_)).find(_=>_==null?void 0:_.contracts.has(i));if(!s)throw new N("unknown_contract",`This client has not registered event contract ${t.contract.id} ${t.contract.version}.`);let o=(y=s.contracts.get(i))==null?void 0:y.contract;if(!o)throw new N("unknown_contract",`Event contract ${i} is unavailable.`);if(t.contract.digest&&t.contract.digest!==o.reference.digest)throw new N("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}}),Cu(t.data,"invalid_event_data",`Event ${o.reference.id} data`),ra(o.dataValidator,t.data,"invalid_event_data",`Event ${o.reference.id} data`);let a=(h=t.extensions)!=null?h:{};for(let _ of Object.keys(a))if(yO.has(_))throw new N("request_rejected",`Event extension ${_} is reserved.`);let c={...structuredClone(a),specversion:"1.0",id:(m=t.id)!=null?m:this.idFactory("evt"),source:_O(n.identity),type:o.reference.id,time:(g=t.time)!=null?g:this.now().toISOString(),...t.subject===void 0?{}:{subject:t.subject},datacontenttype:"application/json",dataschema:T_(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}};Xr(this.eventValidator,c,"invalid_event_data","Event envelope"),Mu(this.transport,c),bO(c,o.reference);let l=`${c.source}\0${c.id}`,d=this.recentEvents.get(l);if(d){if(JSON.stringify(d)!==JSON.stringify(c))throw new N("contract_digest_conflict",`Event ${c.source} ${c.id} was reused with different content.`);return{event:structuredClone(d),deliveries:0,duplicate:!0}}this.recentEvents.set(l,structuredClone(c)),R_(this.recentEvents,this.recentEventLimit);let u=[...this.subscriptions.values()].filter(({subscription:_})=>ya(_.contract,o.reference)),f=await Promise.allSettled(u.map(async _=>await this.isAuthorized({operation:"subscribe_event",principal:_.principal,contract:o.reference,...c.subject===void 0?{}:{subject:c.subject}})?(await _.handler(structuredClone(c)),!0):!1)),p=0;for(let _ of f)_.status==="fulfilled"&&_.value?p+=1:_.status==="rejected"&&this.report({severity:"error",code:"event_consumer_failed",message:`An event consumer failed while handling ${c.type}.`,contract:o.reference,cause:_.reason});return{event:structuredClone(c),deliveries:p,duplicate:!1}}async subscribeEvents(e,t,n){let i=this.requireClient(e);Nu(t.contract),$O(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){var u,f,p,y,h,m,g;let n=this.requireClient(e);if(t.handlers.length===0)throw new N("request_rejected","An action-provider declaration must include a handler.");let i=`${e}:${t.declaration_id}`;if(this.actionProviders.has(i))throw new N("request_rejected",`Action-provider declaration ${t.declaration_id} is already registered.`);let s=[],o=new Set;for(let _ of t.handlers){if(o.has(_.handler_id))throw new N("request_rejected",`Handler ${_.handler_id} is repeated.`);o.add(_.handler_id);let w=await this.prepareActionContract(_.contract),x=P_(_.requirement,w.reference);if(I_(x,w.reference),await this.assertAuthorized({operation:"register_action_provider",principal:n.identity,contract:w.reference,provider:n.identity}),w.providerValidator&&!w.providerValidator((u=_.binding)!=null?u:{}))throw new N("request_rejected",`${w.reference.id} provider binding is invalid: ${Jr(w.providerValidator.errors)}`);let v=(p=(f=_.contract.behavior)==null?void 0:f.idempotency)!=null?p:"none";if(((y=_.idempotency)==null?void 0:y.mode)==="request"&&v==="none")throw new N("request_rejected",`${w.reference.id} does not permit request deduplication.`);if(v==="required"&&((h=_.idempotency)==null?void 0:h.mode)!=="request")throw new N("request_rejected",`${w.reference.id} requires a provider with request deduplication.`);let P=(g=(m=_.contract.behavior)==null?void 0:m.cancellation)!=null?g:"none";if(_.cancellation==="cooperative"&&P!=="cooperative")throw new N("request_rejected",`${w.reference.id} does not declare cooperative cancellation.`);s.push({contract:w,declaration:{handler_id:_.handler_id,requirement:x,resolved:structuredClone(w.reference),..._.binding===void 0?{}:{binding:structuredClone(_.binding)},..._.idempotency===void 0?{}:{idempotency:structuredClone(_.idempotency)},..._.cancellation===void 0?{}:{cancellation:_.cancellation},..._.max_concurrency===void 0?{}:{max_concurrency:_.max_concurrency}},handler:_.handler})}let a={kind:"mdbase.action-provider",profile_version:"0.1",declaration_id:t.declaration_id,provider:structuredClone(n.identity),handlers:s.map(({declaration:_})=>structuredClone(_))},c={...a,declaration_digest:await ci(a)};Xr(this.actionProviderDeclarationValidator,c,"request_rejected","Action-provider declaration"),this.commitContracts(s.map(({contract:_})=>_));let l=s.map(({contract:_,declaration:w,handler:x})=>({registrationId:i,clientId:e,declaration:structuredClone(c),handlerDeclaration:structuredClone(w),contract:_,handler:x,active:0}));this.actionProviders.set(i,{id:i,clientId:e,declaration:structuredClone(c),handlers:l}),n.providers.add(i);let d=!0;return{declaration:structuredClone(c),dispose:()=>{d&&(d=!1,this.removeActionProvider(i))}}}async invokeAction(e,t){var a,c,l,d,u,f,p,y,h,m,g,_;let n=this.requireClient(e);Nu(t.contract);let i=(a=t.request_id)!=null?a:this.idFactory("req");this.cleanCompletedActions(),Cu(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:(c=t.created_at)!=null?c:this.now().toISOString(),...t.correlation_id===void 0?{}:{correlation_id:t.correlation_id},...t.causation_id===void 0?{}:{causation_id:t.causation_id},...t.subject===void 0?{}:{subject:t.subject},...t.idempotency_key===void 0?{}:{idempotency_key:t.idempotency_key},...t.deadline===void 0?{}:{deadline:t.deadline},...t.requested_provider===void 0?{}:{requested_provider:structuredClone(t.requested_provider)},input:structuredClone(t.input)};Xr(this.actionRequestValidator,s,"request_rejected","Action request"),Mu(this.transport,s);let o=await this.acquireAdmission(i);try{let w=await ci(wO(s)),x=this.activeActions.get(i);if(x){if(O_(e,i,w,x),((l=x.handler.handlerDeclaration.idempotency)==null?void 0:l.mode)!=="request")throw new N("request_rejected",`Action request ${i} is already active without deduplication.`);return structuredClone(await x.promise)}let v=this.completedActions.get(i);if(v){if(O_(e,i,w,v),!v.reusable)throw new N("request_rejected",`Action request ${i} was already completed without deduplication.`);return structuredClone(v.outcome)}if(s.deadline&&new Date(s.deadline).getTime()<=this.now().getTime())throw new N("deadline_exceeded",`Action request ${i} passed its deadline before admission.`);if(s.deadline&&!this.transport.deadlines)throw new N("unsupported_transport_capability","The active transport cannot enforce action deadlines.");let P=this.resolveActionCandidates(s.contract,s.requested_provider);P.length===0&&this.throwResolutionFailure(s.contract,s.requested_provider);let O=[];for(let V of P)await this.isAuthorized({operation:"invoke_action",principal:n.identity,contract:V.contract.reference,provider:V.declaration.provider,...s.subject===void 0?{}:{subject:s.subject}})&&O.push(V);if(O.length===0)throw new N("unauthorized",`No authorized provider can execute ${s.contract.id}.`);if(O.length>1)throw new N("ambiguous_provider",`Action ${s.contract.id} has ${O.length} eligible providers; select one explicitly.`);let $=O[0];if($.handlerDeclaration.max_concurrency!==void 0&&$.active>=$.handlerDeclaration.max_concurrency)throw new N("request_rejected",`Provider ${$.declaration.provider.implementation} is at capacity.`);if(((u=(d=$.contract.artifact.behavior)==null?void 0:d.idempotency)!=null?u:"none")==="required"&&!s.idempotency_key)throw new N("request_rejected",`${$.contract.reference.id} requires an idempotency key.`);ra($.contract.inputValidator,s.input,"invalid_action_input",`Action ${$.contract.reference.id} input`);let S={operation:"invoke_action",principal:n.identity,contract:$.contract.reference,provider:$.declaration.provider,...s.subject===void 0?{}:{subject:s.subject}},U=await((p=(f=this.options).authorizationContext)==null?void 0:p.call(f,S)),B={kind:"mdbase.action.invocation",profile_version:"0.1",invocation_id:this.idFactory("inv"),attempt_id:this.idFactory("attempt"),request_id:i,contract:structuredClone($.contract.reference),caller:structuredClone(n.identity),provider:structuredClone($.declaration.provider),provider_declaration_digest:$.declaration.declaration_digest,handler_id:$.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},...U===void 0?{}:{authorization_context:U},input:structuredClone(s.input)};Xr(this.actionInvocationValidator,B,"request_rejected","Action invocation"),await((h=(y=this.options).onInvocation)==null?void 0:h.call(y,structuredClone(B)));let T=new AbortController,E;if(B.deadline){let V=Math.max(0,new Date(B.deadline).getTime()-this.now().getTime());E=setTimeout(()=>T.abort(new N("deadline_exceeded",`Action request ${i} exceeded its deadline.`)),V)}$.active+=1;let k=this.executeAction($,B,T).finally(()=>{E!==void 0&&clearTimeout(E),$.active=Math.max(0,$.active-1),this.activeActions.delete(i)});this.activeActions.set(i,{clientId:e,requestId:i,requestDigest:w,handler:$,invocation:B,controller:T,promise:k}),o();let de=await k,Z=(g=(m=$.handlerDeclaration.idempotency)==null?void 0:m.retention_seconds)!=null?g:300;return this.completedActions.set(i,{clientId:e,requestDigest:w,outcome:structuredClone(de),reusable:((_=$.handlerDeclaration.idempotency)==null?void 0:_.mode)==="request",expiresAt:this.now().getTime()+Z*1e3}),R_(this.completedActions,this.completedRequestLimit),structuredClone(de)}finally{o()}}async executeAction(e,t,n){var i;try{let s=await e.handler(structuredClone(t.input),{invocation:structuredClone(t),signal:n.signal});if(n.signal.aborted){let a=n.signal.reason;return a instanceof N&&a.code==="deadline_exceeded"?this.failureOutcome(t,"failed",a.toPortableError()):this.failureOutcome(t,"cancelled",{code:"cancelled",message:`Action request ${t.request_id} was cancelled.`})}Cu(s,"invalid_action_output",`Action ${e.contract.reference.id} output`),ra(e.contract.outputValidator,s,"invalid_action_output",`Action ${e.contract.reference.id} output`);let o={kind:"mdbase.action.outcome",profile_version:"0.1",outcome_id:this.idFactory("outcome"),request_id:t.request_id,invocation_id:t.invocation_id,attempt_id:t.attempt_id,contract:structuredClone(t.contract),provider:structuredClone(t.provider),provider_declaration_digest:t.provider_declaration_digest,status:"succeeded",completed_at:this.now().toISOString(),output:structuredClone(s)};return Xr(this.actionOutcomeValidator,o,"invalid_action_output","Action outcome"),Mu(this.transport,o),o}catch(s){if(s instanceof Ui)return e.contract.errorValidator&&!e.contract.errorValidator((i=s.error.details)!=null?i:{})?this.failureOutcome(t,"failed",{code:"handler_failure",message:`Provider returned invalid declared error details: ${Jr(e.contract.errorValidator.errors)}`}):this.failureOutcome(t,s.status,s.error);if(s instanceof N)return this.failureOutcome(t,s.code==="cancelled"?"cancelled":s.code==="outcome_indeterminate"?"outcome_indeterminate":"failed",s.toPortableError());if(n.signal.aborted||SO(s)){let o=n.signal.reason;return o instanceof N&&o.code==="deadline_exceeded"?this.failureOutcome(t,"failed",o.toPortableError()):this.failureOutcome(t,"cancelled",{code:"cancelled",message:`Action request ${t.request_id} was cancelled.`})}return this.report({severity:"error",code:"action_handler_failed",message:`Provider ${t.provider.implementation} failed ${t.contract.id}.`,principal:t.provider,contract:t.contract,cause:s}),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 Xr(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 N("unauthorized",`Action request ${t} belongs to another caller.`);return a?structuredClone(a.outcome):null}if(o.clientId!==e)throw new N("unauthorized",`Action request ${t} belongs to another caller.`);if(await this.assertAuthorized({operation:"cancel_action",principal:i.identity,contract:o.invocation.contract,provider:o.invocation.provider,...o.invocation.subject===void 0?{}:{subject:o.invocation.subject}}),!this.transport.cancellation)throw new N("unsupported_transport_capability","The active transport cannot deliver cancellation.");if(o.handler.handlerDeclaration.cancellation!=="cooperative")throw new N("cancellation_unsupported",`Provider ${o.invocation.provider.implementation} does not support cancellation.`);return o.controller.abort(new N("cancelled",(n==null?void 0:n.trim())||`Action request ${t} was cancelled.`)),structuredClone(await o.promise)}resolveActionCandidates(e,t){let n=[...this.actionProviders.values()].flatMap(({handlers:s})=>s).filter(({contract:s,declaration:o})=>ya(e,s.reference)&&vO(t,o.provider)),i=(0,vr.maxSatisfying)([...new Set(n.map(({contract:s})=>s.reference.version))],e.version,{includePrerelease:!0});return i?n.filter(({contract:s})=>s.reference.version===i).sort((s,o)=>{var a,c;return s.declaration.provider.application.localeCompare(o.declaration.provider.application)||s.declaration.provider.implementation.localeCompare(o.declaration.provider.implementation)||((a=s.declaration.provider.instance_id)!=null?a:"").localeCompare((c=o.declaration.provider.instance_id)!=null?c:"")||s.handlerDeclaration.handler_id.localeCompare(o.handlerDeclaration.handler_id)}):[]}throwResolutionFailure(e,t){let n=[...this.contracts.values()].filter(i=>i.artifact.contract_type==="action"&&i.reference.id===e.id);throw n.length===0?new N("unknown_contract",`Action contract ${e.id} is unknown.`):n.some(({reference:i})=>ya(e,i))?t?new N("requested_provider_unavailable",`The requested provider is unavailable for ${e.id}.`):new N("no_provider",`No provider is registered for ${e.id}.`):new N("unsupported_contract_version",`No ${e.id} artifact satisfies ${e.version}.`)}async prepareEventContract(e){if(this.assertContractArtifact(e),e.contract_type!=="event")throw new N("unknown_contract",`${e.id} is not an event contract.`);let t={id:e.id,version:e.version,digest:await ta(e)};this.assertNoContractConflict(t);let n=Ny(this.ajv,e);return{artifact:structuredClone(e),reference:t,dataValidator:n.data,...n.source===void 0?{}:{sourceValidator:n.source}}}async prepareActionContract(e){if(this.assertContractArtifact(e),e.contract_type!=="action")throw new N("unknown_contract",`${e.id} is not an action contract.`);let t={id:e.id,version:e.version,digest:await ta(e)};this.assertNoContractConflict(t);let n=Ly(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(Xr(this.contractValidator,e,"contract_digest_conflict",`Contract ${e.id||""}`),!(0,vr.valid)(e.version))throw new N("unsupported_contract_version",`${e.id} version must be exact SemVer.`)}assertNoContractConflict(e){let t=this.contracts.get(ma(e));if(t&&t.reference.digest!==e.digest)throw new N("contract_digest_conflict",`Contract ${e.id} ${e.version} conflicts with the registered artifact.`)}commitContracts(e){var n;let t=new Map;for(let i of e){let s=ma(i.reference),o=(n=t.get(s))!=null?n:this.contracts.get(s);if(o&&o.reference.digest!==i.reference.digest)throw new N("contract_digest_conflict",`Contract ${i.reference.id} ${i.reference.version} conflicts within the registration.`);t.set(s,i)}for(let[i,s]of t)this.contracts.has(i)||this.contracts.set(i,s)}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 N("cancelled","The caller unloaded.")),i.handler.clientId===e&&i.handler.handlerDeclaration.cancellation==="cooperative"&&i.controller.abort(new N("cancelled","The provider unloaded."));this.clients.delete(e),t||this.assertActive()}}removeEventSource(e){var n;let t=this.eventSources.get(e);t&&(this.eventSources.delete(e),(n=this.clients.get(t.clientId))==null||n.sources.delete(e))}removeActionProvider(e){var n;let t=this.actionProviders.get(e);if(t){this.actionProviders.delete(e),(n=this.clients.get(t.clientId))==null||n.providers.delete(e);for(let i of this.activeActions.values())i.handler.registrationId===e&&i.handler.handlerDeclaration.cancellation==="cooperative"&&i.controller.abort(new N("cancelled","The provider unloaded."))}}removeSubscription(e){var n;let t=this.subscriptions.get(e);t&&(this.subscriptions.delete(e),(n=this.clients.get(t.clientId))==null||n.subscriptions.delete(e))}requireClient(e){this.assertActive();let t=this.clients.get(e);if(!t||t.disposed)throw new N("transport_unavailable","Interop client is disposed.");return t}assertActive(){if(this.disposed)throw new N("transport_unavailable","Interop bridge is disposed.")}async assertAuthorized(e){if(!await this.isAuthorized(e))throw new N("unauthorized",`${e.operation} is not authorized.`)}async isAuthorized(e){try{return await this.authorize(structuredClone(e))}catch(t){return this.report({severity:"error",code:"authorization_failed",message:`Authorization failed for ${e.operation}.`,principal:e.principal,cause:t}),!1}}cleanCompletedActions(){let e=this.now().getTime();for(let[t,n]of this.completedActions)n.expiresAt<=e&&this.completedActions.delete(t)}async acquireAdmission(e){var a;let t=(a=this.admissionLocks.get(e))!=null?a:Promise.resolve(),n,i=new Promise(c=>{n=c}),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){var t,n;(n=(t=this.options).onDiagnostic)==null||n.call(t,structuredClone(e))}};function Xr(r,e,t,n){if(!r(e))throw new N(t,`${n} is invalid: ${Jr(r.errors)}`)}function gO(r){for(let[e,t]of Object.entries(r))if(t!==void 0&&(typeof t!="string"||t.length===0||!/^[A-Za-z0-9][A-Za-z0-9._:@/-]*$/u.test(t)))throw new N("request_rejected",`Implementation identity ${e} is invalid.`);if(!(0,vr.valid)(r.version))throw new N("request_rejected","Implementation identity version must be exact SemVer.")}function Nu(r){if(!/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)+$/u.test(r.id))throw new N("unknown_contract",`Contract ID ${r.id} is invalid.`);if(!(0,vr.validRange)(r.version,{includePrerelease:!0}))throw new N("unsupported_contract_version",`Contract requirement ${r.version} is not a SemVer range.`);if(r.digest&&!/^sha256:[0-9a-f]{64}$/u.test(r.digest))throw new N("contract_digest_conflict","Contract digest is invalid.")}function P_(r,e){let t=r!=null?r:{id:e.id,version:e.version,digest:e.digest};return Nu(t),structuredClone(t)}function I_(r,e){if(!ya(r,e))throw new N("unsupported_contract_version",`${e.id} ${e.version} does not satisfy its implementation requirement.`)}function ya(r,e){return r.id===e.id&&(0,vr.satisfies)(e.version,r.version,{includePrerelease:!0})&&(!r.digest||r.digest===e.digest)}function ma(r){return`${r.id}@${r.version}`}function T_(r){return`urn:mdbase:contract:${r.id}:${r.version}:${r.digest}`}function _O(r){return`urn:mdbase:app:${[r.application,r.implementation,...r.instance_id?[r.instance_id]:[]].map(encodeURIComponent).join(":")}`}function bO(r,e){if(r.type!==e.id||r.mdbasecontractversion!==e.version||r.mdbasecontractdigest!==e.digest||r.dataschema!==T_(e))throw new N("contract_digest_conflict","Event contract evidence is inconsistent.")}function wO(r){let{created_at:e,...t}=r;return t}function O_(r,e,t,n){if(n.clientId!==r)throw new N("unauthorized",`Action request ${e} belongs to another caller.`);if(n.requestDigest!==t)throw new N("request_rejected",`Action request ${e} was reused with different content.`)}function Cu(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 N(e,`${t}${o} must be a finite JSON number.`)}if(typeof s!="object")throw new N(e,`${t}${o} is not a JSON value.`);if(n.has(s))throw new N(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 N(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 Mu(r,e){if(r.max_payload_bytes===void 0)return;let t=JSON.stringify(e),n=new TextEncoder().encode(t).byteLength;if(n>r.max_payload_bytes)throw new N("unsupported_transport_capability",`The portable envelope is ${n} bytes; the active transport allows ${r.max_payload_bytes}.`)}function vO(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 $O(r,e){var t,n;if(e){if((t=e.delivery)!=null&&t.some(i=>!r.delivery.includes(i)))throw new N("unsupported_transport_capability","The active transport lacks a required delivery capability.");if((n=e.ordering)!=null&&n.some(i=>!r.ordering.includes(i)))throw new N("unsupported_transport_capability","The active transport lacks a required ordering capability.");for(let i of["cancellation","deadlines","provider_discovery","request_deduplication","cross_process_identity"])if(e[i]===!0&&r[i]!==!0)throw new N("unsupported_transport_capability",`The active transport lacks ${i}.`);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 SO(r){return r instanceof Error&&r.name==="AbortError"}var ga=class{constructor(e,t){this.app=e;this.profileVersion="0.1";this.bridge=new As({authorize:()=>t(),transport:{delivery:["ephemeral"],ordering:["none"],cancellation:!0,deadlines:!0,provider_discovery:!0,request_deduplication:!0,cross_process_identity:!1},onDiagnostic:n=>{var s;(n.severity==="error"?console.error:console.warn)(`[mdbase/interop] ${n.code}: ${n.message}`,(s=n.cause)!=null?s:"")}}),this.transport=this.bridge.describe().transport}connect(e){var s,o;let t=(s=e.manifest)==null?void 0:s.id,n=(o=e.manifest)==null?void 0:o.version;if(!t||!n)throw new Error("Only a loaded Obsidian plugin with manifest identity can connect to mdbase interop.");let 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()}};var me=require("obsidian"),nb=fn(Qd(),1),ib=fn(cu(),1),Xu=fn(Wu(),1),va=class extends Error{constructor(t,n){super(n);this.code=t;this.name="MdbasePathError"}},Lt={spec_version:"0.3.0",name:"My mdbase collection",description:"Typed markdown collection",settings:{types_folder:"_types",explicit_type_keys:["type","types"],default_strict:!1,include_subfolders:!0,exclude:["_types",".obsidian",".git","node_modules",".trash",".mdbase"]}},Os=null;function sR(){return Os||(Os=new nb.Ajv2020({allErrors:!0,strict:!1,allowUnionTypes:!0}),(0,ib.default)(Os),Os)}function re(r){return!!r&&typeof r=="object"&&!Array.isArray(r)}function Qe(r){return JSON.parse(JSON.stringify(r))}function oR(r){if(r===!0)return!0;if(r===!1)return!1;if(r==="warn")return"warn"}function Gu(r){return Array.isArray(r)?`[${r.map(e=>Gu(e)).join(",")}]`:re(r)?`{${Object.keys(r).sort().map(t=>`${JSON.stringify(t)}:${Gu(r[t])}`).join(",")}}`:JSON.stringify(r)}function aR(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 cR(r){let e=new Map,t=new Set,n=i=>{var l,d,u,f;let s=e.get(i);if(s)return s;let o=r.get(i);if(!o)return null;if(t.has(i)){let p={...o,fields:Qe(o.fields)};return e.set(i,p),p}t.add(i);let a=o.extends?n(o.extends):null;t.delete(i);let c={...o,fields:a?{...Qe(a.fields),...Qe(o.fields)}:Qe(o.fields),display_name_key:(l=o.display_name_key)!=null?l:a==null?void 0:a.display_name_key,path_pattern:(d=o.path_pattern)!=null?d:a==null?void 0:a.path_pattern,filename_pattern:(u=o.filename_pattern)!=null?u:a==null?void 0:a.filename_pattern,strict:o.strict!==void 0?o.strict:a==null?void 0:a.strict,match:(f=o.match)!=null?f:a==null?void 0:a.match};return e.set(i,c),c};for(let i of r.keys())n(i);return e}function sb(r){let e=(0,me.normalizePath)(r),t=e.lastIndexOf("/");return t>=0?e.slice(0,t):""}function ob(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 ab(r){return/^[a-z][a-z0-9+.-]*:\/\//i.test(r)}function cb(r,e,t){var c;let n=ob(t);if(!n||ab(n))return null;let i=new Set,s=(0,me.normalizePath)(n);i.add(s),s.endsWith(".md")||i.add(`${s}.md`);let o=sb(e);if(o){let l=(0,me.normalizePath)(`${o}/${n}`);i.add(l),l.endsWith(".md")||i.add(`${l}.md`)}for(let l of i){let d=r.getAbstractFileByPath(l);if(d instanceof me.TFile)return d}let a=n.replace(/\.md$/i,"");return(c=r.getMarkdownFiles().find(l=>l.basename===a))!=null?c:null}function lR(r,e,t){return ab(ob(t))||cb(r,e,t)!==null}function Pt(r){let e=r.match(/^---[ \t]*\r?\n([\s\S]*?)^---[ \t]*(?:\r?\n|$)/m);if(!e)return{hasFrontmatter:!1,frontmatter:{},body:r};try{let t=e[1],n=(0,me.parseYaml)(t);return n==null&&t.trim()!==""?{hasFrontmatter:!0,frontmatter:{},body:r.slice(e[0].length),error:"Frontmatter must be a YAML object"}:n!=null&&!re(n)?{hasFrontmatter:!0,frontmatter:{},body:r.slice(e[0].length),error:"Frontmatter must be a YAML object"}:{hasFrontmatter:!0,frontmatter:n!=null?n:{},body:r.slice(e[0].length)}}catch(t){return{hasFrontmatter:!0,frontmatter:{},body:r.slice(e[0].length),error:t instanceof Error?t.message:String(t)}}}function mt(r,e=""){if(Object.keys(r).length===0)return e;let t=(0,me.stringifyYaml)(r).trimEnd(),n=e.replace(/^\n+/,"");return`--- ${t} --- -${n}`}async function ui(r){let e=r.getAbstractFileByPath("mdbase.yaml");if(!(e instanceof me.TFile))return null;try{let t=await r.cachedRead(e),n=(0,me.parseYaml)(t);if(!re(n))return null;let i=re(n.settings)?n.settings:{},s=re(n.runtime)?n.runtime:void 0;return{spec_version:typeof n.spec_version=="string"?n.spec_version:jt.spec_version,name:typeof n.name=="string"?n.name:jt.name,description:typeof n.description=="string"?n.description:jt.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:jt.settings.types_folder,explicit_type_keys:Array.isArray(i.explicit_type_keys)?i.explicit_type_keys.filter(o=>typeof o=="string"):[...jt.settings.explicit_type_keys],default_strict:typeof i.default_strict=="boolean"?i.default_strict:jt.settings.default_strict,include_subfolders:typeof i.include_subfolders=="boolean"?i.include_subfolders:jt.settings.include_subfolders,exclude:Array.isArray(i.exclude)?i.exclude.filter(o=>typeof o=="string"):[...jt.settings.exclude]}}}catch(t){return null}}async function db(r){var c;let e=[];if(!(r.getAbstractFileByPath("mdbase.yaml")instanceof me.TFile)){let l=(0,me.stringifyYaml)(jt).trimEnd()+` -`;await r.create("mdbase.yaml",l),e.push("mdbase.yaml")}let n=(c=await ui(r))!=null?c:jt,i=n.settings.types_folder;await r.adapter.exists(i)||(await r.createFolder(i),e.push(i));let o=(0,me.normalizePath)(`${i}/note.md`);if(!await r.adapter.exists(o)){let l=NR("note",void 0,n.spec_version);await r.create(o,l),e.push(o)}return{created:e}}function ub(r,e){let t=re(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=Ze(t.enum)):n==="array"?(i.type="list",i.items=ub(t.items,!1)):n==="object"?(i.type="object",i.fields=Sn(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=Ze(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 Sn(r){let e=re(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,ub(i,t.has(n))]))}function fb(r,e){var c,l,d,u;let t={...Ze(e)},n=(c=r.type)!=null?c:"string",i=()=>{delete t.properties,delete t.required,delete t.additionalProperties},s=()=>{delete t.items};if(n==="enum")delete t.type,t.enum=Ze((l=r.values)!=null?l:[]),delete t.format,i(),s();else if(n==="list")t.type="array",delete t.enum,delete t.format,i(),t.items=fb((d=r.items)!=null?d:{type:"any"},re(t.items)?t.items:{});else if(n==="object"){t.type="object",delete t.enum,delete t.format,s();let f=Qu((u=r.fields)!=null?u:{},re(t)?t:{},!1);t.properties=f.properties,f.required?t.required=f.required:delete t.required}else n==="link"?(t.type="string",delete t.enum,delete t.format,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=Ze(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 Qu(r,e={},t=!1){let n=re(e.properties)?e.properties:{},i=Object.create(null),s=[];for(let[a,c]of Object.entries(r))i[a]=fb(c,re(n[a])?n[a]:{}),c.required===!0&&s.push(a);let o={...Ze(e),type:"object",properties:i,additionalProperties:!t};return s.length>0?o.required=s:delete o.required,o}function mR(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(re(t)&&i in t)t=t[i];else return}return t}async function yR(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=ob(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,me.normalizePath)(o.join("/")),c=r.getAbstractFileByPath(a);if(!(c instanceof me.TFile))return null;try{let l=JSON.parse(await r.cachedRead(c)),d=mR(l,i);return re(d)?d:null}catch(l){return null}}async function pb(r,e){var i,s,o,a;let t=new Map,n=`${(0,me.normalizePath)(e.settings.types_folder)}/`;for(let c of r.getMarkdownFiles()){if(!c.path.startsWith(n))continue;let l=await r.cachedRead(c),d=It(l);if(!d.hasFrontmatter||d.error)continue;let u=d.frontmatter;if(e.spec_version.startsWith("0.3.")){if(u.kind!=="mdbase.type"||typeof u.name!="string"||!re(u.schema))continue;let y=u.schema,h=re(y.value)?y.value:null;if(!h&&typeof y.ref=="string"&&(h=await yR(r,c.path,y.ref)),!h)continue;let m=re(u.collection)?Ze(u.collection):void 0,g=Sn(h);for(let _ of(i=m==null?void 0:m.unique)!=null?i:[])typeof _.field=="string"&&g[_.field]&&(g[_.field].unique=!0);for(let[_,w]of Object.entries((s=m==null?void 0:m.links)!=null?s:{}))g[_]&&(g[_].target=w.target_type,g[_].validate_exists=w.validate_exists);t.set(u.name,{name:u.name,version:typeof u.version=="number"?u.version:void 0,description:typeof u.description=="string"?u.description:void 0,display_name_key:(o=m==null?void 0:m.display)==null?void 0:o.name_field,path_pattern:(a=m==null?void 0:m.path)==null?void 0:a.pattern,strict:h.additionalProperties===!1,match:re(u.match)?u.match:void 0,fields:g,filePath:c.path,specProfile:"v0.3",schema:Ze(h),collection:m,originalFrontmatter:Ze(u)});continue}if(!re(u.fields))continue;let f=typeof u.name=="string"&&u.name.trim().length>0?u.name.trim():c.basename,p={};for(let[y,h]of Object.entries(u.fields))re(h)&&(p[y]=h);t.set(f,{name:f,extends:typeof u.extends=="string"?u.extends:void 0,display_name_key:typeof u.display_name_key=="string"?u.display_name_key:void 0,path_pattern:typeof u.path_pattern=="string"?u.path_pattern:void 0,filename_pattern:typeof u.filename_pattern=="string"?u.filename_pattern:void 0,strict:uR(u.strict),match:re(u.match)?u.match:void 0,fields:p,filePath:c.path,specProfile:"v0.2",originalFrontmatter:Ze(u)})}return pR(t)}function gR(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 Zu(r,e){return r.replace(/\{([^}]+)\}/g,(t,n)=>{let i=e[n];return i==null?"":Array.isArray(i)?i.join("-"):String(i)})}function Os(r){let e=r.replace(/\\/g,"/");if(!e||e.startsWith("/")||/^[A-Za-z]:\//.test(e)||e.includes("\0"))throw new wa("invalid_path",`Invalid collection-relative path: ${r}`);let t=e.split("/");if(t.includes(".."))throw new wa("path_traversal",`Path escapes the collection root: ${r}`);return(0,me.normalizePath)(t.filter(n=>n&&n!==".").join("/"))}function _R(r){let e=r.search(/[\*\?\[]/),n=(e===-1?r:r.slice(0,e)).replace(/\/+$/,"");if(n.endsWith(".md")){let i=n.lastIndexOf("/");return i>=0?n.slice(0,i):""}return n}function bR(r,e){var t;if(r.path_pattern){let n=(0,me.normalizePath)(Zu(r.path_pattern,e));if(n.endsWith(".md")){let i=n.lastIndexOf("/");return i>=0?n.slice(0,i):""}return n.replace(/\/+$/,"")}return(t=r.match)!=null&&t.path_glob?_R(r.match.path_glob):""}function wR(r,e){var o,a;let t=(o=r.display_name_key)!=null?o:"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 c=(0,me.normalizePath)(Zu(r.filename_pattern,e)),d=((a=c.split("/").pop())!=null?a:c).replace(/\.md$/i,"").trim();if(d.length>0)return`${nb(d)}.md`}return`${nb(s)}.md`}function di(r){return Array.isArray(r)?`[${r.map(di).join(",")}]`:re(r)?`{${Object.keys(r).sort().map(e=>`${JSON.stringify(e)}:${di(r[e])}`).join(",")}}`:JSON.stringify(r)}function vR(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(!re(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 _a(r,e,t){return(typeof r=="number"&&typeof e=="number"&&Number.isFinite(r)&&Number.isFinite(e)||typeof r=="string"&&typeof e=="string")&&t(r,e)}function $R(r,e,t,n){let i=(s,o)=>di(s)===di(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 _a(r.value,t,(s,o)=>s>o);case"gte":return _a(r.value,t,(s,o)=>s>=o);case"lt":return _a(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"&&r.value.startsWith(String(t));case"endsWith":case"ends_with":return typeof r.value=="string"&&r.value.endsWith(String(t));case"matches":try{return r.value!=null&&new RegExp(String(t).replace(/\\\\/g,"\\")).test(String(r.value))}catch(s){return!1}default:return!1}}function ba(r,e,t){if("and"in r)return Array.isArray(r.and)&&r.and.every(n=>re(n)&&ba(n,e,t));if("or"in r)return Array.isArray(r.or)&&r.or.some(n=>re(n)&&ba(n,e,t));if("not"in r)return re(r.not)&&!ba(r.not,e,t);for(let[n,i]of Object.entries(r)){let s=vR(e,n);if(!re(i)){if(!s.present||di(s.value)!==di(i))return!1;continue}for(let[o,a]of Object.entries(i))if(!$R(s,o,a,t))return!1}return!0}function fi(r,e,t,n){let i=gR(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"&&((0,Xu.default)(c.path_glob,{dot:!0})(r)||(l=!1)),l&&Array.isArray(c.fields_present)){for(let d of c.fields_present)if(!(d in e)){l=!1;break}}l&&re(c.where)&&(l=ba(c.where,e,t.spec_version)),l&&typeof c.where=="string"&&(l=!1),l&&s.push(o)}return s}function hb(r){return r==null||typeof r=="string"&&r.trim().length===0}function SR(r){return/^\d{4}-\d{2}-\d{2}$/.test(r)}function ER(r){return/^\d{2}:\d{2}(:\d{2})?$/.test(r)}function AR(r){return typeof r=="string"||Array.isArray(r)?r.length:null}function Te(r,e,t,n,i,s){r.push({path:e,code:n,message:i,severity:t,field:s})}function Pt(r,e,t,n,i){typeof r=="number"&&(typeof e.min=="number"&&r= ${e.min}`,t),typeof e.max=="number"&&r>e.max&&Te(i,n,"error","above_max",`Field '${t}' must be <= ${e.max}`,t));let s=AR(r);if(s!=null&&(typeof e.min_length=="number"&&s= ${e.min_length}`,t),typeof e.max_length=="number"&&s>e.max_length&&Te(i,n,"error","above_max_length",`Field '${t}' length must be <= ${e.max_length}`,t)),typeof e.pattern=="string"&&typeof r=="string")try{new RegExp(e.pattern).test(r)||Te(i,n,"error","pattern_mismatch",`Field '${t}' must match pattern /${e.pattern}/`,t)}catch(o){Te(i,n,"warn","invalid_pattern",`Field '${t}' has invalid regex pattern: ${o instanceof Error?o.message:String(o)}`,t)}}function Ju(r,e,t,n,i,s){var c;let o=(c=e.type)!=null?c:"any";if(r==null)return;e.deprecated===!0&&Te(i,n,"warn","deprecated_field",`Field '${t}' is marked deprecated`,t);let a=l=>{Te(i,n,"error","invalid_type",`Field '${t}' expected ${l}`,t)};switch(o){case"any":Pt(r,e,t,n,i);return;case"string":if(typeof r!="string"){a("a string");return}Pt(r,e,t,n,i);return;case"integer":if(typeof r!="number"||!Number.isInteger(r)){a("an integer");return}Pt(r,e,t,n,i);return;case"number":if(typeof r!="number"||Number.isNaN(r)){a("a number");return}Pt(r,e,t,n,i);return;case"boolean":typeof r!="boolean"&&a("a boolean");return;case"date":if(typeof r!="string"||!SR(r)){a("a date (YYYY-MM-DD)");return}Pt(r,e,t,n,i);return;case"datetime":if(typeof r!="string"||Number.isNaN(Date.parse(r))){a("a datetime string");return}Pt(r,e,t,n,i);return;case"time":if(typeof r!="string"||!ER(r)){a("a time string (HH:MM)");return}Pt(r,e,t,n,i);return;case"enum":{let l=Array.isArray(e.values)?e.values:[];if(!l.includes(r)){Te(i,n,"error","invalid_enum",`Field '${t}' must be one of: ${l.map(d=>String(d)).join(", ")}`,t);return}Pt(r,e,t,n,i);return}case"list":{if(!Array.isArray(r)){a("a list");return}Pt(r,e,t,n,i),e.items&&r.forEach((l,d)=>{Ju(l,e.items,`${t}[${d}]`,n,i,s)});return}case"object":{if(!re(r)){a("an object");return}if(e.fields&&re(e.fields))for(let[l,d]of Object.entries(e.fields)){if(!re(d))continue;let u=d,f=`${t}.${l}`,p=r[l];if(u.required&&hb(p)){Te(i,n,"error","missing_required",`Missing required field '${f}'`,f);continue}Ju(p,u,f,n,i,s)}return}case"link":{if(typeof r!="string"&&!re(r)){a("a link string");return}if(e.validate_exists===!0&&s){let l=typeof r=="string"?r:typeof r.path=="string"?r.path:typeof r.file=="string"?r.file:"";(!l||!hR(s,n,l))&&Te(i,n,"error","missing_link_target",`Field '${t}' references a missing note`,t)}return}case"tags":if(typeof r=="string"){Pt(r,e,t,n,i);return}if(Array.isArray(r)&&r.every(l=>typeof l=="string")){Pt(r,e,t,n,i);return}a("a tag string or list of strings");return;default:Pt(r,e,t,n,i);return}}function xR(r){return r.replace(/^\//,"").split("/").filter(Boolean).map(t=>t.replace(/~1/g,"/").replace(/~0/g,"~")).join(".")||void 0}function kR(r){return r.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase()}function PR(r,e,t){var c;let n=r.params,i=xR(r.instancePath),s=typeof n.missingProperty=="string"?n.missingProperty:typeof n.additionalProperty=="string"?n.additionalProperty:void 0,o=i&&s?`${i}.${s}`:s!=null?s:i,a=r.keyword==="format"?"format_invalid":`schema_${kR(r.keyword)}`;return{path:e,code:a,message:`JSON Schema ${r.keyword} failed for type '${t}': ${(c=r.message)!=null?c:"invalid value"}`,severity:"error",field:o,type:t,schema_location:`embedded://type/schema#${r.schemaPath}`,details:{instance_path:r.instancePath,schema_path:r.schemaPath}}}function Yu(r){if(Array.isArray(r)){for(let e of r){let t=Yu(e);if(t)return t}return null}if(!re(r))return null;if(typeof r.$ref=="string"&&!r.$ref.startsWith("#"))return r.$ref;for(let e of Object.values(r)){let t=Yu(e);if(t)return t}return null}function IR(r,e,t,n){var s;if(!t.schema)return;let i=Yu(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 o=dR().compile(t.schema);if(o(e))return;for(let a of(s=o.errors)!=null?s:[])n.push(PR(a,r,t.name))}catch(o){n.push({path:r,code:"invalid_embedded_schema",message:o instanceof Error?o.message:String(o),severity:"error",type:t.name})}}async function OR(r,e,t,n,i,s,o){var a,c;for(let[l,d]of Object.entries((c=(a=n.collection)==null?void 0:a.links)!=null?c:{})){let u=t[l],f=Array.isArray(u)?u:[u];for(let p of f){if(p==null||typeof p!="string")continue;let y=lb(r,e,p);if(!y&&d.validate_exists===!0){Te(o,e,"error","link_not_found",`Field '${l}' references a missing note`,l);continue}if(y&&d.target_type&&d.target_type!=="any"){let h=It(await r.cachedRead(y));fi(y.path,h.frontmatter,i,s).includes(d.target_type)||Te(o,e,"error","link_wrong_type",`Field '${l}' must reference type '${d.target_type}'`,l)}}}}function RR(r,e,t,n,i){if(t.specProfile==="v0.3"){IR(r,e,t,n);return}for(let[s,o]of Object.entries(t.fields)){if(!re(o))continue;let a=o,c=e[s];if(a.required&&hb(c)){Te(n,r,"error","missing_required",`Missing required field '${s}' for type '${t.name}'`,s);continue}Ju(c,a,s,r,n,i)}}function TR(r){let e=new Set;for(let t of r)for(let n of Object.keys(t.fields))e.add(n);return e}function MR(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 Rs(r,e){let t=(0,me.normalizePath)(r),n=(0,me.normalizePath)(e.settings.types_folder);if(t.startsWith(`${n}/`)||t===n||!e.settings.include_subfolders&&t.includes("/"))return!0;for(let i of e.settings.exclude)if((0,Xu.default)(i,{dot:!0,matchBase:!i.includes("/")})(t)||!i.includes("*")&&!i.includes("?")&&!i.includes("/")&&t.startsWith(`${i}/`))return!0;return!1}async function ef(r,e,t,n){if(Rs(e.path,t))return[];let i=[],s=await r.cachedRead(e),o=It(s);if(o.error)return Te(i,e.path,"error","invalid_frontmatter",o.error),i;let a=o.frontmatter,c=fi(e.path,a,t,n);if(c.length===0)return Te(i,e.path,"warn","no_matching_type","No type could be resolved for this file"),i;let l=c.map(u=>n.get(u)).filter(u=>!!u);if(l.length===0)return Te(i,e.path,"error","unknown_type",`Resolved types are not defined: ${c.join(", ")}`),i;for(let u of l)RR(e.path,a,u,i,r),u.specProfile==="v0.3"&&await OR(r,e.path,a,u,t,n,i);let d=t.spec_version.startsWith("0.3.")?!1:MR(l,t);if(d!==!1){let u=TR(l),f=new Set(t.settings.explicit_type_keys),p=d===!0?"error":"warn";for(let y of Object.keys(a))u.has(y)||f.has(y)||Te(i,e.path,p,"unknown_field",`Unknown field '${y}' in strict mode`,y)}return i}async function CR(r,e,t){var s,o;let n=new Map;for(let a of r.getMarkdownFiles()){if(Rs(a.path,e))continue;let c=await r.cachedRead(a),l=It(c);if(l.error)continue;let u=fi(a.path,l.frontmatter,e,t).map(f=>t.get(f)).filter(f=>!!f);for(let f of u)for(let[p,y]of Object.entries(f.fields)){if(!re(y)||y.unique!==!0)continue;let m=l.frontmatter[p];if(m==null)continue;let g=Gu(m),_=`${f.name}::${p}::${g}`,w=(s=n.get(_))!=null?s:[];w.push({path:a.path,typeName:f.name,fieldName:p,value:m,fingerprint:g}),n.set(_,w)}}let i=[];for(let a of n.values())if(!(a.length<=1))for(let c of a){let l=a.filter(d=>d.path!==c.path).map(d=>d.path).join(", ");Te(i,c.path,"error",((o=t.get(c.typeName))==null?void 0:o.specProfile)==="v0.3"?"duplicate_value":"duplicate_unique",`Field '${c.fieldName}' must be unique for type '${c.typeName}'. Duplicate found in: ${l}`,c.fieldName)}return i}async function mb(r,e,t){let n=[];for(let s of r.getMarkdownFiles()){if(Rs(s.path,e))continue;let o=await ef(r,s,e,t);n.push(...o)}let i=await CR(r,e,t);return n.push(...i),n}function NR(r,e,t=jt.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()}),`${yt(i,`# ${r} +${n}`}async function pi(r){let e=r.getAbstractFileByPath("mdbase.yaml");if(!(e instanceof me.TFile))return null;try{let t=await r.cachedRead(e),n=(0,me.parseYaml)(t);if(!re(n))return null;let i=re(n.settings)?n.settings:{},s=re(n.runtime)?n.runtime:void 0;return{spec_version:typeof n.spec_version=="string"?n.spec_version:Lt.spec_version,name:typeof n.name=="string"?n.name:Lt.name,description:typeof n.description=="string"?n.description:Lt.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:Lt.settings.types_folder,explicit_type_keys:Array.isArray(i.explicit_type_keys)?i.explicit_type_keys.filter(o=>typeof o=="string"):[...Lt.settings.explicit_type_keys],default_strict:typeof i.default_strict=="boolean"?i.default_strict:Lt.settings.default_strict,include_subfolders:typeof i.include_subfolders=="boolean"?i.include_subfolders:Lt.settings.include_subfolders,exclude:Array.isArray(i.exclude)?i.exclude.filter(o=>typeof o=="string"):[...Lt.settings.exclude]}}}catch(t){return null}}async function lb(r){var c;let e=[];if(!(r.getAbstractFileByPath("mdbase.yaml")instanceof me.TFile)){let l=(0,me.stringifyYaml)(Lt).trimEnd()+` +`;await r.create("mdbase.yaml",l),e.push("mdbase.yaml")}let n=(c=await pi(r))!=null?c:Lt,i=n.settings.types_folder;await r.adapter.exists(i)||(await r.createFolder(i),e.push(i));let o=(0,me.normalizePath)(`${i}/note.md`);if(!await r.adapter.exists(o)){let l=OR("note",void 0,n.spec_version);await r.create(o,l),e.push(o)}return{created:e}}function db(r,e){let t=re(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=Qe(t.enum)):n==="array"?(i.type="list",i.items=db(t.items,!1)):n==="object"?(i.type="object",i.fields=An(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=Qe(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 An(r){let e=re(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,db(i,t.has(n))]))}function ub(r,e){var c,l,d,u;let t={...Qe(e)},n=(c=r.type)!=null?c:"string",i=()=>{delete t.properties,delete t.required,delete t.additionalProperties},s=()=>{delete t.items};if(n==="enum")delete t.type,t.enum=Qe((l=r.values)!=null?l:[]),delete t.format,i(),s();else if(n==="list")t.type="array",delete t.enum,delete t.format,i(),t.items=ub((d=r.items)!=null?d:{type:"any"},re(t.items)?t.items:{});else if(n==="object"){t.type="object",delete t.enum,delete t.format,s();let f=Qu((u=r.fields)!=null?u:{},re(t)?t:{},!1);t.properties=f.properties,f.required?t.required=f.required:delete t.required}else n==="link"?(t.type="string",delete t.enum,delete t.format,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=Qe(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 Qu(r,e={},t=!1){let n=re(e.properties)?e.properties:{},i=Object.create(null),s=[];for(let[a,c]of Object.entries(r))i[a]=ub(c,re(n[a])?n[a]:{}),c.required===!0&&s.push(a);let o={...Qe(e),type:"object",properties:i,additionalProperties:!t};return s.length>0?o.required=s:delete o.required,o}function dR(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(re(t)&&i in t)t=t[i];else return}return t}async function uR(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=sb(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,me.normalizePath)(o.join("/")),c=r.getAbstractFileByPath(a);if(!(c instanceof me.TFile))return null;try{let l=JSON.parse(await r.cachedRead(c)),d=dR(l,i);return re(d)?d:null}catch(l){return null}}async function fb(r,e){var i,s,o,a;let t=new Map,n=`${(0,me.normalizePath)(e.settings.types_folder)}/`;for(let c of r.getMarkdownFiles()){if(!c.path.startsWith(n))continue;let l=await r.cachedRead(c),d=Pt(l);if(!d.hasFrontmatter||d.error)continue;let u=d.frontmatter;if(e.spec_version.startsWith("0.3.")){if(u.kind!=="mdbase.type"||typeof u.name!="string"||!re(u.schema))continue;let y=u.schema,h=re(y.value)?y.value:null;if(!h&&typeof y.ref=="string"&&(h=await uR(r,c.path,y.ref)),!h)continue;let m=re(u.collection)?Qe(u.collection):void 0,g=An(h);for(let _ of(i=m==null?void 0:m.unique)!=null?i:[])typeof _.field=="string"&&g[_.field]&&(g[_.field].unique=!0);for(let[_,w]of Object.entries((s=m==null?void 0:m.links)!=null?s:{}))g[_]&&(g[_].target=w.target_type,g[_].validate_exists=w.validate_exists);t.set(u.name,{name:u.name,version:typeof u.version=="number"?u.version:void 0,description:typeof u.description=="string"?u.description:void 0,display_name_key:(o=m==null?void 0:m.display)==null?void 0:o.name_field,path_pattern:(a=m==null?void 0:m.path)==null?void 0:a.pattern,strict:h.additionalProperties===!1,match:re(u.match)?u.match:void 0,fields:g,filePath:c.path,specProfile:"v0.3",schema:Qe(h),collection:m,originalFrontmatter:Qe(u)});continue}if(!re(u.fields))continue;let f=typeof u.name=="string"&&u.name.trim().length>0?u.name.trim():c.basename,p={};for(let[y,h]of Object.entries(u.fields))re(h)&&(p[y]=h);t.set(f,{name:f,extends:typeof u.extends=="string"?u.extends:void 0,display_name_key:typeof u.display_name_key=="string"?u.display_name_key:void 0,path_pattern:typeof u.path_pattern=="string"?u.path_pattern:void 0,filename_pattern:typeof u.filename_pattern=="string"?u.filename_pattern:void 0,strict:oR(u.strict),match:re(u.match)?u.match:void 0,fields:p,filePath:c.path,specProfile:"v0.2",originalFrontmatter:Qe(u)})}return cR(t)}function fR(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 Zu(r,e){return r.replace(/\{([^}]+)\}/g,(t,n)=>{let i=e[n];return i==null?"":Array.isArray(i)?i.join("-"):String(i)})}function Rs(r){let e=r.replace(/\\/g,"/");if(!e||e.startsWith("/")||/^[A-Za-z]:\//.test(e)||e.includes("\0"))throw new va("invalid_path",`Invalid collection-relative path: ${r}`);let t=e.split("/");if(t.includes(".."))throw new va("path_traversal",`Path escapes the collection root: ${r}`);return(0,me.normalizePath)(t.filter(n=>n&&n!==".").join("/"))}function pR(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 hR(r,e){var t;if(r.path_pattern){let n=(0,me.normalizePath)(Zu(r.path_pattern,e));if(n.endsWith(".md")){let i=n.lastIndexOf("/");return i>=0?n.slice(0,i):""}return n.replace(/\/+$/,"")}return(t=r.match)!=null&&t.path_glob?pR(r.match.path_glob):""}function mR(r,e){var o,a;let t=(o=r.display_name_key)!=null?o:"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 c=(0,me.normalizePath)(Zu(r.filename_pattern,e)),d=((a=c.split("/").pop())!=null?a:c).replace(/\.md$/i,"").trim();if(d.length>0)return`${rb(d)}.md`}return`${rb(s)}.md`}function fi(r){return Array.isArray(r)?`[${r.map(fi).join(",")}]`:re(r)?`{${Object.keys(r).sort().map(e=>`${JSON.stringify(e)}:${fi(r[e])}`).join(",")}}`:JSON.stringify(r)}function yR(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(!re(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 ba(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 gR(r,e,t,n){let i=(s,o)=>fi(s)===fi(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 ba(r.value,t,(s,o)=>s>o);case"gte":return ba(r.value,t,(s,o)=>s>=o);case"lt":return ba(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"&&r.value.startsWith(String(t));case"endsWith":case"ends_with":return typeof r.value=="string"&&r.value.endsWith(String(t));case"matches":try{return r.value!=null&&new RegExp(String(t).replace(/\\\\/g,"\\")).test(String(r.value))}catch(s){return!1}default:return!1}}function wa(r,e,t){if("and"in r)return Array.isArray(r.and)&&r.and.every(n=>re(n)&&wa(n,e,t));if("or"in r)return Array.isArray(r.or)&&r.or.some(n=>re(n)&&wa(n,e,t));if("not"in r)return re(r.not)&&!wa(r.not,e,t);for(let[n,i]of Object.entries(r)){let s=yR(e,n);if(!re(i)){if(!s.present||fi(s.value)!==fi(i))return!1;continue}for(let[o,a]of Object.entries(i))if(!gR(s,o,a,t))return!1}return!0}function hi(r,e,t,n){let i=fR(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"&&((0,Xu.default)(c.path_glob,{dot:!0})(r)||(l=!1)),l&&Array.isArray(c.fields_present)){for(let d of c.fields_present)if(!(d in e)){l=!1;break}}l&&re(c.where)&&(l=wa(c.where,e,t.spec_version)),l&&typeof c.where=="string"&&(l=!1),l&&s.push(o)}return s}function pb(r){return r==null||typeof r=="string"&&r.trim().length===0}function _R(r){return/^\d{4}-\d{2}-\d{2}$/.test(r)}function bR(r){return/^\d{2}:\d{2}(:\d{2})?$/.test(r)}function wR(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 xt(r,e,t,n,i){typeof r=="number"&&(typeof e.min=="number"&&r= ${e.min}`,t),typeof e.max=="number"&&r>e.max&&Re(i,n,"error","above_max",`Field '${t}' must be <= ${e.max}`,t));let s=wR(r);if(s!=null&&(typeof e.min_length=="number"&&s= ${e.min_length}`,t),typeof e.max_length=="number"&&s>e.max_length&&Re(i,n,"error","above_max_length",`Field '${t}' length must be <= ${e.max_length}`,t)),typeof e.pattern=="string"&&typeof r=="string")try{new RegExp(e.pattern).test(r)||Re(i,n,"error","pattern_mismatch",`Field '${t}' must match pattern /${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 Ju(r,e,t,n,i,s){var c;let o=(c=e.type)!=null?c:"any";if(r==null)return;e.deprecated===!0&&Re(i,n,"warn","deprecated_field",`Field '${t}' is marked deprecated`,t);let a=l=>{Re(i,n,"error","invalid_type",`Field '${t}' expected ${l}`,t)};switch(o){case"any":xt(r,e,t,n,i);return;case"string":if(typeof r!="string"){a("a string");return}xt(r,e,t,n,i);return;case"integer":if(typeof r!="number"||!Number.isInteger(r)){a("an integer");return}xt(r,e,t,n,i);return;case"number":if(typeof r!="number"||Number.isNaN(r)){a("a number");return}xt(r,e,t,n,i);return;case"boolean":typeof r!="boolean"&&a("a boolean");return;case"date":if(typeof r!="string"||!_R(r)){a("a date (YYYY-MM-DD)");return}xt(r,e,t,n,i);return;case"datetime":if(typeof r!="string"||Number.isNaN(Date.parse(r))){a("a datetime string");return}xt(r,e,t,n,i);return;case"time":if(typeof r!="string"||!bR(r)){a("a time string (HH:MM)");return}xt(r,e,t,n,i);return;case"enum":{let l=Array.isArray(e.values)?e.values:[];if(!l.includes(r)){Re(i,n,"error","invalid_enum",`Field '${t}' must be one of: ${l.map(d=>String(d)).join(", ")}`,t);return}xt(r,e,t,n,i);return}case"list":{if(!Array.isArray(r)){a("a list");return}xt(r,e,t,n,i),e.items&&r.forEach((l,d)=>{Ju(l,e.items,`${t}[${d}]`,n,i,s)});return}case"object":{if(!re(r)){a("an object");return}if(e.fields&&re(e.fields))for(let[l,d]of Object.entries(e.fields)){if(!re(d))continue;let u=d,f=`${t}.${l}`,p=r[l];if(u.required&&pb(p)){Re(i,n,"error","missing_required",`Missing required field '${f}'`,f);continue}Ju(p,u,f,n,i,s)}return}case"link":{if(typeof r!="string"&&!re(r)){a("a link string");return}if(e.validate_exists===!0&&s){let l=typeof r=="string"?r:typeof r.path=="string"?r.path:typeof r.file=="string"?r.file:"";(!l||!lR(s,n,l))&&Re(i,n,"error","missing_link_target",`Field '${t}' references a missing note`,t)}return}case"tags":if(typeof r=="string"){xt(r,e,t,n,i);return}if(Array.isArray(r)&&r.every(l=>typeof l=="string")){xt(r,e,t,n,i);return}a("a tag string or list of strings");return;default:xt(r,e,t,n,i);return}}function vR(r){return r.replace(/^\//,"").split("/").filter(Boolean).map(t=>t.replace(/~1/g,"/").replace(/~0/g,"~")).join(".")||void 0}function $R(r){return r.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase()}function SR(r,e,t){var c;let n=r.params,i=vR(r.instancePath),s=typeof n.missingProperty=="string"?n.missingProperty:typeof n.additionalProperty=="string"?n.additionalProperty:void 0,o=i&&s?`${i}.${s}`:s!=null?s:i,a=r.keyword==="format"?"format_invalid":`schema_${$R(r.keyword)}`;return{path:e,code:a,message:`JSON Schema ${r.keyword} failed for type '${t}': ${(c=r.message)!=null?c:"invalid value"}`,severity:"error",field:o,type:t,schema_location:`embedded://type/schema#${r.schemaPath}`,details:{instance_path:r.instancePath,schema_path:r.schemaPath}}}function Yu(r){if(Array.isArray(r)){for(let e of r){let t=Yu(e);if(t)return t}return null}if(!re(r))return null;if(typeof r.$ref=="string"&&!r.$ref.startsWith("#"))return r.$ref;for(let e of Object.values(r)){let t=Yu(e);if(t)return t}return null}function ER(r,e,t,n){var s;if(!t.schema)return;let i=Yu(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 o=sR().compile(t.schema);if(o(e))return;for(let a of(s=o.errors)!=null?s:[])n.push(SR(a,r,t.name))}catch(o){n.push({path:r,code:"invalid_embedded_schema",message:o instanceof Error?o.message:String(o),severity:"error",type:t.name})}}async function AR(r,e,t,n,i,s,o){var a,c;for(let[l,d]of Object.entries((c=(a=n.collection)==null?void 0:a.links)!=null?c:{})){let u=t[l],f=Array.isArray(u)?u:[u];for(let p of f){if(p==null||typeof p!="string")continue;let y=cb(r,e,p);if(!y&&d.validate_exists===!0){Re(o,e,"error","link_not_found",`Field '${l}' references a missing note`,l);continue}if(y&&d.target_type&&d.target_type!=="any"){let h=Pt(await r.cachedRead(y));hi(y.path,h.frontmatter,i,s).includes(d.target_type)||Re(o,e,"error","link_wrong_type",`Field '${l}' must reference type '${d.target_type}'`,l)}}}}function kR(r,e,t,n,i){if(t.specProfile==="v0.3"){ER(r,e,t,n);return}for(let[s,o]of Object.entries(t.fields)){if(!re(o))continue;let a=o,c=e[s];if(a.required&&pb(c)){Re(n,r,"error","missing_required",`Missing required field '${s}' for type '${t.name}'`,s);continue}Ju(c,a,s,r,n,i)}}function xR(r){let e=new Set;for(let t of r)for(let n of Object.keys(t.fields))e.add(n);return e}function PR(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 Ts(r,e){let t=(0,me.normalizePath)(r),n=(0,me.normalizePath)(e.settings.types_folder);if(t.startsWith(`${n}/`)||t===n||!e.settings.include_subfolders&&t.includes("/"))return!0;for(let i of e.settings.exclude)if((0,Xu.default)(i,{dot:!0,matchBase:!i.includes("/")})(t)||!i.includes("*")&&!i.includes("?")&&!i.includes("/")&&t.startsWith(`${i}/`))return!0;return!1}async function ef(r,e,t,n){if(Ts(e.path,t))return[];let i=[],s=await r.cachedRead(e),o=Pt(s);if(o.error)return Re(i,e.path,"error","invalid_frontmatter",o.error),i;let a=o.frontmatter,c=hi(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(u=>n.get(u)).filter(u=>!!u);if(l.length===0)return Re(i,e.path,"error","unknown_type",`Resolved types are not defined: ${c.join(", ")}`),i;for(let u of l)kR(e.path,a,u,i,r),u.specProfile==="v0.3"&&await AR(r,e.path,a,u,t,n,i);let d=t.spec_version.startsWith("0.3.")?!1:PR(l,t);if(d!==!1){let u=xR(l),f=new Set(t.settings.explicit_type_keys),p=d===!0?"error":"warn";for(let y of Object.keys(a))u.has(y)||f.has(y)||Re(i,e.path,p,"unknown_field",`Unknown field '${y}' in strict mode`,y)}return i}async function IR(r,e,t){var s,o;let n=new Map;for(let a of r.getMarkdownFiles()){if(Ts(a.path,e))continue;let c=await r.cachedRead(a),l=Pt(c);if(l.error)continue;let u=hi(a.path,l.frontmatter,e,t).map(f=>t.get(f)).filter(f=>!!f);for(let f of u)for(let[p,y]of Object.entries(f.fields)){if(!re(y)||y.unique!==!0)continue;let m=l.frontmatter[p];if(m==null)continue;let g=Gu(m),_=`${f.name}::${p}::${g}`,w=(s=n.get(_))!=null?s:[];w.push({path:a.path,typeName:f.name,fieldName:p,value:m,fingerprint:g}),n.set(_,w)}}let i=[];for(let a of n.values())if(!(a.length<=1))for(let c of a){let l=a.filter(d=>d.path!==c.path).map(d=>d.path).join(", ");Re(i,c.path,"error",((o=t.get(c.typeName))==null?void 0:o.specProfile)==="v0.3"?"duplicate_value":"duplicate_unique",`Field '${c.fieldName}' must be unique for type '${c.typeName}'. Duplicate found in: ${l}`,c.fieldName)}return i}async function hb(r,e,t){let n=[];for(let s of r.getMarkdownFiles()){if(Ts(s.path,e))continue;let o=await ef(r,s,e,t);n.push(...o)}let i=await IR(r,e,t);return n.push(...i),n}function OR(r,e,t=Lt.spec_version){if(t.startsWith("0.3.")){let i={kind:"mdbase.type",name:r,version:1,description:`${r} type`,schema:{dialect:"json-schema-2020-12",value:{$schema:"https://json-schema.org/draft/2020-12/schema",type:"object",required:["title"],additionalProperties:!0,properties:{title:{type:"string",minLength:1},tags:{type:"array",items:{type:"string"}}}}}};return e&&e.trim()&&(i.match={path_glob:e.trim()}),`${mt(i,`# ${r} Type definition for ${r}.`)} -`}let n={name:r,description:`${r} type`,strict:!1,fields:{title:{type:"string",required:!0}}};return e&&e.trim().length>0&&(n.match={path_glob:e.trim()}),`${yt(n,`# ${r} +`}let n={name:r,description:`${r} type`,strict:!1,fields:{title:{type:"string",required:!0}}};return e&&e.trim().length>0&&(n.match={path_glob:e.trim()}),`${mt(n,`# ${r} Type definition for ${r}.`)} -`}function yb(r,e){var i;let t={},n=(i=e.settings.explicit_type_keys[0])!=null?i:"type";t[n]=n==="types"?[r.name]:r.name;for(let[s,o]of Object.entries(r.fields)){if(!re(o))continue;let a=o;a.default!==void 0&&(t[s]=Ze(a.default))}return t}function gb(r,e){let t=[];for(let[n,i]of Object.entries(r.fields)){if(!re(i))continue;let s=i;s.computed||s.required&&e[n]===void 0&&t.push([n,s])}return t}function tf(r,e){var i;let t=r.trim();switch((i=e.type)!=null?i:"string"){case"string":case"date":case"datetime":case"time":case"link":case"enum":case"any":return t;case"integer":{let s=Number.parseInt(t,10);if(!Number.isInteger(s))throw new Error("Expected integer input");return s}case"number":{let s=Number.parseFloat(t);if(Number.isNaN(s))throw new Error("Expected numeric input");return s}case"boolean":{let s=t.toLowerCase();if(["true","1","yes","y"].includes(s))return!0;if(["false","0","no","n"].includes(s))return!1;throw new Error("Expected boolean input: true/false")}case"list":{let s=t.split(",").map(o=>o.trim()).filter(o=>o.length>0);return e.items?s.map(o=>tf(o,e.items)):s}case"object":{let s=(0,me.parseYaml)(t);if(!re(s))throw new Error("Expected YAML object value");return s}case"tags":return t.split(",").map(s=>s.trim()).filter(s=>s.length>0);default:return t}}function nb(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 _b(r,e){let t=(0,me.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 LR(r,e){if(!r.path_pattern||r.path_pattern.trim().length===0)return null;let t=(0,me.normalizePath)(Zu(r.path_pattern,e));return t.endsWith(".md")?t:null}async function bb(r,e,t){var d;let n=LR(e,t),i=bR(e,t),s=n?(d=n.split("/").pop())!=null?d:n:wR(e,t),o=Os(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;let l=a.lastIndexOf("/");return l>0&&await _b(r,a.slice(0,l)),a}async function wb(r,e,t,n=""){let i=Os(e),s=i.lastIndexOf("/");if(s>0&&await _b(r,i.slice(0,s)),await r.adapter.exists(i))throw new Error(`File already exists: ${i}`);let o=`${yt(t,n)} -`;return r.create(i,o)}function va(r){return fR(r)}var oe=require("obsidian"),R0=dn(Wu(),1);var $a=Symbol.for("yaml.alias"),Sa=Symbol.for("yaml.document"),Dt=Symbol.for("yaml.map"),rf=Symbol.for("yaml.pair"),gt=Symbol.for("yaml.scalar"),$r=Symbol.for("yaml.seq"),et=Symbol.for("yaml.node.type"),qt=r=>!!r&&typeof r=="object"&&r[et]===$a,or=r=>!!r&&typeof r=="object"&&r[et]===Sa,Ft=r=>!!r&&typeof r=="object"&&r[et]===Dt,ne=r=>!!r&&typeof r=="object"&&r[et]===rf,G=r=>!!r&&typeof r=="object"&&r[et]===gt,Ut=r=>!!r&&typeof r=="object"&&r[et]===$r;function le(r){if(r&&typeof r=="object")switch(r[et]){case Dt:case $r:return!0}return!1}function se(r){if(r&&typeof r=="object")switch(r[et]){case $a:case Dt:case gt:case $r:return!0}return!1}var Ea=r=>(G(r)||le(r))&&!!r.anchor;var dt=Symbol("break visit"),vb=Symbol("skip children"),ar=Symbol("remove node");function cr(r,e){let t=$b(e);or(r)?pi(null,r.contents,t,Object.freeze([r]))===ar&&(r.contents=null):pi(null,r,t,Object.freeze([]))}cr.BREAK=dt;cr.SKIP=vb;cr.REMOVE=ar;function pi(r,e,t,n){let i=Sb(r,e,t,n);if(se(i)||ne(i))return Eb(r,n,i),pi(r,i,t,n);if(typeof i!="symbol"){if(le(e)){n=Object.freeze(n.concat(e));for(let s=0;sr.replace(/[!,[\]{}]/g,e=>jR[e]),lr=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+DR(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&&se(e.contents)){let s={};cr(e.contents,(o,a)=>{se(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(` -`)}};lr.defaultYaml={explicit:!1,version:"1.2"};lr.defaultTags={"!!":"tag:yaml.org,2002:"};function xa(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 nf(r){let e=new Set;return cr(r,{Value(t,n){n.anchor&&e.add(n.anchor)}}),e}function sf(r,e){for(let t=1;;++t){let n=`${r}${t}`;if(!e.has(n))return n}}function Ab(r,e){let t=[],n=new Map,i=null;return{onAnchor:s=>{t.push(s),i!=null||(i=nf(r));let o=sf(e,i);return i.add(o),o},setAnchors:()=>{for(let s of t){let o=n.get(s);if(typeof o=="object"&&o.anchor&&(G(o.node)||le(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 Yr(r,e,t,n){if(n&&typeof n=="object")if(Array.isArray(n))for(let i=0,s=n.length;iMe(n,String(i),t));if(r&&typeof r.toJSON=="function"){if(!t||!Ea(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!=null&&t.keep)?Number(r):r}var Xr=class{constructor(e){Object.defineProperty(this,et,{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(!or(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=Me(this,"",o);if(typeof i=="function")for(let{count:c,res:l}of o.anchors.values())i(l,c);return typeof s=="function"?Yr(s,{"":a},"",a):a}};var Sr=class extends Xr{constructor(e){super($a),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,t){if((t==null?void 0:t.maxAliasCount)===0)throw new ReferenceError("Alias resolution is disabled");let n;t!=null&&t.aliasResolveCache?n=t.aliasResolveCache:(n=[],cr(e,{Node:(s,o)=>{(qt(o)||Ea(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)}return i}toJSON(e,t){if(!t)return{source:this.source};let{anchors:n,doc:i,maxAliasCount:s}=t,o=this.resolve(i,t);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let a=n.get(o);if(a||(Me(o,null,t),a=n.get(o)),(a==null?void 0:a.res)===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(s>=0&&(a.count+=1,a.aliasCount===0&&(a.aliasCount=ka(i,o,n)),a.count*a.aliasCount>s)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return a.res}toString(e,t,n){let i=`*${this.source}`;if(e){if(xa(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 ka(r,e,t){if(qt(e)){let n=e.resolve(r),i=t&&n&&t.get(n);return i?i.count*i.aliasCount:0}else if(le(e)){let n=0;for(let i of e.items){let s=ka(r,i,t);s>n&&(n=s)}return n}else if(ne(e)){let n=ka(r,e.key,t),i=ka(r,e.value,t);return Math.max(n,i)}return 1}var Pa=r=>!r||typeof r!="function"&&typeof r!="object",q=class extends Xr{constructor(e){super(gt),this.value=e}toJSON(e,t){return t!=null&&t.keep?this.value:Me(this.value,e,t)}toString(){return String(this.value)}};q.BLOCK_FOLDED="BLOCK_FOLDED";q.BLOCK_LITERAL="BLOCK_LITERAL";q.PLAIN="PLAIN";q.QUOTE_DOUBLE="QUOTE_DOUBLE";q.QUOTE_SINGLE="QUOTE_SINGLE";var qR="tag:yaml.org,2002:";function FR(r,e,t){var n;if(e){let i=t.filter(o=>o.tag===e),s=(n=i.find(o=>!o.format))!=null?n:i[0];if(!s)throw new Error(`Tag ${e} not found`);return s}return t.find(i=>{var s;return((s=i.identify)==null?void 0:s.call(i,r))&&!i.format})}function Er(r,e,t){var u,f,p,y;if(or(r)&&(r=r.contents),se(r))return r;if(ne(r)){let h=(f=(u=t.schema[Dt]).createNode)==null?void 0:f.call(u,t.schema,null,t);return h.items.push(r),h}(r instanceof String||r instanceof Number||r instanceof Boolean||typeof BigInt!="undefined"&&r instanceof BigInt)&&(r=r.valueOf());let{aliasDuplicateObjects:n,onAnchor:i,onTagObj:s,schema:o,sourceObjects:a}=t,c;if(n&&r&&typeof r=="object"){if(c=a.get(r),c)return(p=c.anchor)!=null||(c.anchor=i(r)),new Sr(c.anchor);c={anchor:null,node:null},a.set(r,c)}e!=null&&e.startsWith("!!")&&(e=qR+e.slice(2));let l=FR(r,e,o.tags);if(!l){if(r&&typeof r.toJSON=="function"&&(r=r.toJSON()),!r||typeof r!="object"){let h=new q(r);return c&&(c.node=h),h}l=r instanceof Map?o[Dt]:Symbol.iterator in Object(r)?o[$r]:o[Dt]}s&&(s(l),delete t.onTagObj);let d=l!=null&&l.createNode?l.createNode(t.schema,r,t):typeof((y=l==null?void 0:l.nodeClass)==null?void 0:y.from)=="function"?l.nodeClass.from(t.schema,r,t):new q(r);return e?d.tag=e:l.default||(d.tag=l.tag),c&&(c.node=d),d}function Ts(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 Er(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 yi=r=>r==null||typeof r=="object"&&!!r[Symbol.iterator]().next().done,mi=class extends Xr{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=>se(n)||ne(n)?n.clone(e):n),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(yi(e))this.add(t);else{let[n,...i]=e,s=this.get(n,!0);if(le(s))s.addIn(i,t);else if(s===void 0&&this.schema)this.set(n,Ts(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(le(i))return i.deleteIn(n);throw new Error(`Expected YAML collection at ${t}. Remaining path: ${n}`)}getIn(e,t){let[n,...i]=e,s=this.get(n,!0);return i.length===0?!t&&G(s)?s.value:s:le(s)?s.getIn(i,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!ne(t))return!1;let n=t.value;return n==null||e&&G(n)&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn(e){let[t,...n]=e;if(n.length===0)return this.has(t);let i=this.get(t,!0);return le(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(le(s))s.setIn(i,t);else if(s===void 0&&this.schema)this.set(n,Ts(this.schema,i,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${i}`)}}};var xb=r=>r.replace(/^(?!$)(?: $)?/gm,"#");function Ot(r,e){return/^\n+$/.test(r)?r.substring(1):e?r.replace(/^(?! *$)/gm,e):r}var dr=(r,e,t)=>r.endsWith(` -`)?Ot(t,e):t.includes(` +`}function mb(r,e){var i;let t={},n=(i=e.settings.explicit_type_keys[0])!=null?i:"type";t[n]=n==="types"?[r.name]:r.name;for(let[s,o]of Object.entries(r.fields)){if(!re(o))continue;let a=o;a.default!==void 0&&(t[s]=Qe(a.default))}return t}function yb(r,e){let t=[];for(let[n,i]of Object.entries(r.fields)){if(!re(i))continue;let s=i;s.computed||s.required&&e[n]===void 0&&t.push([n,s])}return t}function tf(r,e){var i;let t=r.trim();switch((i=e.type)!=null?i:"string"){case"string":case"date":case"datetime":case"time":case"link":case"enum":case"any":return t;case"integer":{let s=Number.parseInt(t,10);if(!Number.isInteger(s))throw new Error("Expected integer input");return s}case"number":{let s=Number.parseFloat(t);if(Number.isNaN(s))throw new Error("Expected numeric input");return s}case"boolean":{let s=t.toLowerCase();if(["true","1","yes","y"].includes(s))return!0;if(["false","0","no","n"].includes(s))return!1;throw new Error("Expected boolean input: true/false")}case"list":{let s=t.split(",").map(o=>o.trim()).filter(o=>o.length>0);return e.items?s.map(o=>tf(o,e.items)):s}case"object":{let s=(0,me.parseYaml)(t);if(!re(s))throw new Error("Expected YAML object value");return s}case"tags":return t.split(",").map(s=>s.trim()).filter(s=>s.length>0);default:return t}}function rb(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 gb(r,e){let t=(0,me.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 RR(r,e){if(!r.path_pattern||r.path_pattern.trim().length===0)return null;let t=(0,me.normalizePath)(Zu(r.path_pattern,e));return t.endsWith(".md")?t:null}async function _b(r,e,t){var d;let n=RR(e,t),i=hR(e,t),s=n?(d=n.split("/").pop())!=null?d:n:mR(e,t),o=Rs(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;let l=a.lastIndexOf("/");return l>0&&await gb(r,a.slice(0,l)),a}async function bb(r,e,t,n=""){let i=Rs(e),s=i.lastIndexOf("/");if(s>0&&await gb(r,i.slice(0,s)),await r.adapter.exists(i))throw new Error(`File already exists: ${i}`);let o=`${mt(t,n)} +`;return r.create(i,o)}function $a(r){return aR(r)}var oe=require("obsidian"),k0=fn(Wu(),1);var Sa=Symbol.for("yaml.alias"),Ea=Symbol.for("yaml.document"),jt=Symbol.for("yaml.map"),rf=Symbol.for("yaml.pair"),yt=Symbol.for("yaml.scalar"),$r=Symbol.for("yaml.seq"),Ze=Symbol.for("yaml.node.type"),Dt=r=>!!r&&typeof r=="object"&&r[Ze]===Sa,sr=r=>!!r&&typeof r=="object"&&r[Ze]===Ea,qt=r=>!!r&&typeof r=="object"&&r[Ze]===jt,ne=r=>!!r&&typeof r=="object"&&r[Ze]===rf,G=r=>!!r&&typeof r=="object"&&r[Ze]===yt,Ft=r=>!!r&&typeof r=="object"&&r[Ze]===$r;function le(r){if(r&&typeof r=="object")switch(r[Ze]){case jt:case $r:return!0}return!1}function se(r){if(r&&typeof r=="object")switch(r[Ze]){case Sa:case jt:case yt:case $r:return!0}return!1}var Aa=r=>(G(r)||le(r))&&!!r.anchor;var lt=Symbol("break visit"),wb=Symbol("skip children"),or=Symbol("remove node");function ar(r,e){let t=vb(e);sr(r)?mi(null,r.contents,t,Object.freeze([r]))===or&&(r.contents=null):mi(null,r,t,Object.freeze([]))}ar.BREAK=lt;ar.SKIP=wb;ar.REMOVE=or;function mi(r,e,t,n){let i=$b(r,e,t,n);if(se(i)||ne(i))return Sb(r,n,i),mi(r,i,t,n);if(typeof i!="symbol"){if(le(e)){n=Object.freeze(n.concat(e));for(let s=0;sr.replace(/[!,[\]{}]/g,e=>TR[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+CR(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&&se(e.contents)){let s={};ar(e.contents,(o,a)=>{se(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 xa(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 nf(r){let e=new Set;return ar(r,{Value(t,n){n.anchor&&e.add(n.anchor)}}),e}function sf(r,e){for(let t=1;;++t){let n=`${r}${t}`;if(!e.has(n))return n}}function Eb(r,e){let t=[],n=new Map,i=null;return{onAnchor:s=>{t.push(s),i!=null||(i=nf(r));let o=sf(e,i);return i.add(o),o},setAnchors:()=>{for(let s of t){let o=n.get(s);if(typeof o=="object"&&o.anchor&&(G(o.node)||le(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 Qr(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||!Aa(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!=null&&t.keep)?Number(r):r}var Zr=class{constructor(e){Object.defineProperty(this,Ze,{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(!sr(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"?Qr(s,{"":a},"",a):a}};var Sr=class extends Zr{constructor(e){super(Sa),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,t){if((t==null?void 0:t.maxAliasCount)===0)throw new ReferenceError("Alias resolution is disabled");let n;t!=null&&t.aliasResolveCache?n=t.aliasResolveCache:(n=[],ar(e,{Node:(s,o)=>{(Dt(o)||Aa(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)}return i}toJSON(e,t){if(!t)return{source:this.source};let{anchors:n,doc:i,maxAliasCount:s}=t,o=this.resolve(i,t);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let a=n.get(o);if(a||(Te(o,null,t),a=n.get(o)),(a==null?void 0:a.res)===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(s>=0&&(a.count+=1,a.aliasCount===0&&(a.aliasCount=Pa(i,o,n)),a.count*a.aliasCount>s)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return a.res}toString(e,t,n){let i=`*${this.source}`;if(e){if(xa(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 Pa(r,e,t){if(Dt(e)){let n=e.resolve(r),i=t&&n&&t.get(n);return i?i.count*i.aliasCount:0}else if(le(e)){let n=0;for(let i of e.items){let s=Pa(r,i,t);s>n&&(n=s)}return n}else if(ne(e)){let n=Pa(r,e.key,t),i=Pa(r,e.value,t);return Math.max(n,i)}return 1}var Ia=r=>!r||typeof r!="function"&&typeof r!="object",q=class extends Zr{constructor(e){super(yt),this.value=e}toJSON(e,t){return t!=null&&t.keep?this.value:Te(this.value,e,t)}toString(){return String(this.value)}};q.BLOCK_FOLDED="BLOCK_FOLDED";q.BLOCK_LITERAL="BLOCK_LITERAL";q.PLAIN="PLAIN";q.QUOTE_DOUBLE="QUOTE_DOUBLE";q.QUOTE_SINGLE="QUOTE_SINGLE";var MR="tag:yaml.org,2002:";function NR(r,e,t){var n;if(e){let i=t.filter(o=>o.tag===e),s=(n=i.find(o=>!o.format))!=null?n:i[0];if(!s)throw new Error(`Tag ${e} not found`);return s}return t.find(i=>{var s;return((s=i.identify)==null?void 0:s.call(i,r))&&!i.format})}function Er(r,e,t){var u,f,p,y;if(sr(r)&&(r=r.contents),se(r))return r;if(ne(r)){let h=(f=(u=t.schema[jt]).createNode)==null?void 0:f.call(u,t.schema,null,t);return h.items.push(r),h}(r instanceof String||r instanceof Number||r instanceof Boolean||typeof BigInt!="undefined"&&r instanceof BigInt)&&(r=r.valueOf());let{aliasDuplicateObjects:n,onAnchor:i,onTagObj:s,schema:o,sourceObjects:a}=t,c;if(n&&r&&typeof r=="object"){if(c=a.get(r),c)return(p=c.anchor)!=null||(c.anchor=i(r)),new Sr(c.anchor);c={anchor:null,node:null},a.set(r,c)}e!=null&&e.startsWith("!!")&&(e=MR+e.slice(2));let l=NR(r,e,o.tags);if(!l){if(r&&typeof r.toJSON=="function"&&(r=r.toJSON()),!r||typeof r!="object"){let h=new q(r);return c&&(c.node=h),h}l=r instanceof Map?o[jt]:Symbol.iterator in Object(r)?o[$r]:o[jt]}s&&(s(l),delete t.onTagObj);let d=l!=null&&l.createNode?l.createNode(t.schema,r,t):typeof((y=l==null?void 0:l.nodeClass)==null?void 0:y.from)=="function"?l.nodeClass.from(t.schema,r,t):new q(r);return e?d.tag=e:l.default||(d.tag=l.tag),c&&(c.node=d),d}function Cs(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 Er(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 _i=r=>r==null||typeof r=="object"&&!!r[Symbol.iterator]().next().done,gi=class extends Zr{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=>se(n)||ne(n)?n.clone(e):n),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(_i(e))this.add(t);else{let[n,...i]=e,s=this.get(n,!0);if(le(s))s.addIn(i,t);else if(s===void 0&&this.schema)this.set(n,Cs(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(le(i))return i.deleteIn(n);throw new Error(`Expected YAML collection at ${t}. Remaining path: ${n}`)}getIn(e,t){let[n,...i]=e,s=this.get(n,!0);return i.length===0?!t&&G(s)?s.value:s:le(s)?s.getIn(i,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!ne(t))return!1;let n=t.value;return n==null||e&&G(n)&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn(e){let[t,...n]=e;if(n.length===0)return this.has(t);let i=this.get(t,!0);return le(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(le(s))s.setIn(i,t);else if(s===void 0&&this.schema)this.set(n,Cs(this.schema,i,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${i}`)}}};var Ab=r=>r.replace(/^(?!$)(?: $)?/gm,"#");function It(r,e){return/^\n+$/.test(r)?r.substring(1):e?r.replace(/^(?! *$)/gm,e):r}var lr=(r,e,t)=>r.endsWith(` +`)?It(t,e):t.includes(` `)?` -`+Ot(t,e):(r.endsWith(" ")?"":" ")+t;var of="flow",Ia="block",Ms="quoted";function Cs(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):u=i-n);let f,p,y=!1,h=-1,m=-1,g=-1;t===Ia&&(h=kb(r,h,e.length),h!==-1&&(u=h+c));for(let w;w=r[h+=1];){if(t===Ms&&w==="\\"){switch(m=h,r[h+1]){case"x":h+=3;break;case"u":h+=5;break;case"U":h+=9;break;default:h+=1}g=h}if(w===` -`)t===Ia&&(h=kb(r,h,e.length)),u=h+e.length+c,f=void 0;else{if(w===" "&&p&&p!==" "&&p!==` -`&&p!==" "){let k=r[h+1];k&&k!==" "&&k!==` -`&&k!==" "&&(f=h)}if(h>=u)if(f)l.push(f),u=f+c,f=void 0;else if(t===Ms){for(;p===" "||p===" ";)p=w,w=r[h+=1],y=!0;let k=h>g+1?h-2:m-1;if(d[k])return r;l.push(k),d[k]=!0,u=k+c,f=void 0}else y=!0}p=w}if(y&&a&&a(),l.length===0)return r;o&&o();let _=r.slice(0,l[0]);for(let w=0;w({indentAtStart:e?r.indent.length:r.indentAtStart,lineWidth:r.options.lineWidth,minContentWidth:r.options.minContentWidth}),Ta=r=>/^(%|---|\.\.\.)/m.test(r);function UR(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 Ns(r,e){let t=JSON.stringify(r);if(e.options.doubleQuotedAsJSON)return t;let{implicitKey:n}=e,i=e.options.doubleQuotedMinMultiLineLength,s=e.indent||(Ta(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 d=t.substr(c+2,4);switch(d){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:d.substr(0,2)==="00"?o+="\\x"+d.substr(2):o+=t.substr(c,6)}c+=5,a=c+1}break;case"n":if(n||t[c+2]==='"'||t.lengthi-Math.max(2,s)?l.push(0):u=i-n);let f,p,y=!1,h=-1,m=-1,g=-1;t===Oa&&(h=kb(r,h,e.length),h!==-1&&(u=h+c));for(let w;w=r[h+=1];){if(t===Ms&&w==="\\"){switch(m=h,r[h+1]){case"x":h+=3;break;case"u":h+=5;break;case"U":h+=9;break;default:h+=1}g=h}if(w===` +`)t===Oa&&(h=kb(r,h,e.length)),u=h+e.length+c,f=void 0;else{if(w===" "&&p&&p!==" "&&p!==` +`&&p!==" "){let x=r[h+1];x&&x!==" "&&x!==` +`&&x!==" "&&(f=h)}if(h>=u)if(f)l.push(f),u=f+c,f=void 0;else if(t===Ms){for(;p===" "||p===" ";)p=w,w=r[h+=1],y=!0;let x=h>g+1?h-2:m-1;if(d[x])return r;l.push(x),d[x]=!0,u=x+c,f=void 0}else y=!0}p=w}if(y&&a&&a(),l.length===0)return r;o&&o();let _=r.slice(0,l[0]);for(let w=0;w({indentAtStart:e?r.indent.length:r.indentAtStart,lineWidth:r.options.lineWidth,minContentWidth:r.options.minContentWidth}),Ca=r=>/^(%|---|\.\.\.)/m.test(r);function LR(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 Ls(r,e){let t=JSON.stringify(r);if(e.options.doubleQuotedAsJSON)return t;let{implicitKey:n}=e,i=e.options.doubleQuotedMinMultiLineLength,s=e.indent||(Ca(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 d=t.substr(c+2,4);switch(d){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:d.substr(0,2)==="00"?o+="\\x"+d.substr(2):o+=t.substr(c,6)}c+=5,a=c+1}break;case"n":if(n||t[c+2]==='"'||t.length `;let u,f;for(f=t.length;f>0;--f){let v=t[f-1];if(v!==` `&&v!==" "&&v!==" ")break}let p=t.substring(f),y=p.indexOf(` `);y===-1?u="-":t===p||y!==p.length-1?(u="+",s&&s()):u="",p&&(t=t.slice(0,-p.length),p[p.length-1]===` `&&(p=p.slice(0,-1)),p=p.replace(cf,`$&${l}`));let h=!1,m,g=-1;for(m=0;m{P=!0});let $=Cs(`${_}${v}${p}`,l,Ia,O);if(!P)return`>${k} -${l}${$}`}return t=t.replace(/\n+/g,`$&${l}`),`|${k} -${l}${_}${t}${p}`}function VR(r,e,t,n){let{type:i,value:s}=r,{actualString:o,implicitKey:a,indent:c,indentStep:l,inFlow:d}=e;if(a&&s.includes(` -`)||d&&/[[\]{},]/.test(s))return gi(s,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(s))return a||d||!s.includes(` -`)?gi(s,e):Oa(r,e,t,n);if(!a&&!d&&i!==q.PLAIN&&s.includes(` -`))return Oa(r,e,t,n);if(Ta(s)){if(c==="")return e.forceBlockIndent=!0,Oa(r,e,t,n);if(a&&c===l)return gi(s,e)}let u=s.replace(/\n+/g,`$& -${c}`);if(o){let f=h=>{var m;return h.default&&h.tag!=="tag:yaml.org,2002:str"&&((m=h.test)==null?void 0:m.test(u))},{compat:p,tags:y}=e.doc.schema;if(y.some(f)||p!=null&&p.some(f))return gi(s,e)}return a?u:Cs(u,c,of,Ra(e,!1))}function En(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!==q.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=q.QUOTE_DOUBLE);let c=d=>{switch(d){case q.BLOCK_FOLDED:case q.BLOCK_LITERAL:return i||s?gi(o.value,e):Oa(o,e,t,n);case q.QUOTE_DOUBLE:return Ns(o.value,e);case q.QUOTE_SINGLE:return af(o.value,e);case q.PLAIN:return VR(o,e,t,n);default:return null}},l=c(a);if(l===null){let{defaultKeyType:d,defaultStringType:u}=e.options,f=i&&d||u;if(l=c(f),l===null)throw new Error(`Unsupported default string type ${f}`)}return l}function Ma(r,e){let t=Object.assign({blockQuote:!0,commentString:xb,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 BR(r,e){var i,s,o,a;if(e.tag){let c=r.filter(l=>l.tag===e.tag);if(c.length>0)return(i=c.find(l=>l.format===e.format))!=null?i:c[0]}let t,n;if(G(e)){n=e.value;let c=r.filter(l=>{var d;return(d=l.identify)==null?void 0:d.call(l,n)});if(c.length>1){let l=c.filter(d=>d.test);l.length>0&&(c=l)}t=(s=c.find(l=>l.format===e.format))!=null?s:c.find(l=>!l.format)}else n=e,t=r.find(c=>c.nodeClass&&n instanceof c.nodeClass);if(!t){let c=(a=(o=n==null?void 0:n.constructor)==null?void 0:o.name)!=null?a:n===null?"null":typeof n;throw new Error(`Tag not resolved for ${c} value`)}return t}function zR(r,e,{anchors:t,doc:n}){var a;if(!n.directives)return"";let i=[],s=(G(r)||le(r))&&r.anchor;s&&xa(s)&&(t.add(s),i.push(`&${s}`));let o=(a=r.tag)!=null?a:e.default?null:e.tag;return o&&i.push(n.directives.tagString(o)),i.join(" ")}function Ar(r,e,t,n){var c,l;if(ne(r))return r.toString(e,t,n);if(qt(r)){if(e.doc.directives)return r.toString(e);if((c=e.resolvedAliases)!=null&&c.has(r))throw new TypeError("Cannot stringify circular structure without alias nodes");e.resolvedAliases?e.resolvedAliases.add(r):e.resolvedAliases=new Set([r]),r=r.resolve(e.doc)}let i,s=se(r)?r:e.doc.createNode(r,{onTagObj:d=>i=d});i!=null||(i=BR(e.doc.schema.tags,s));let o=zR(s,i,e);o.length>0&&(e.indentAtStart=((l=e.indentAtStart)!=null?l:0)+o.length+1);let a=typeof i.stringify=="function"?i.stringify(s,e,t,n):G(s)?En(s,e,t,n):s.toString(e,t,n);return o?G(s)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o} -${e.indent}${a}`:a}function Pb({key:r,value:e},t,n,i){var O,$;let{allNullValues:s,doc:o,indent:a,indentStep:c,options:{commentString:l,indentSeq:d,simpleKeys:u}}=t,f=se(r)&&r.comment||null;if(u){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(le(r)||!se(r)&&typeof r=="object"){let R="With simple keys, collection cannot be used as a key value";throw new Error(R)}}let p=!u&&(!r||f&&e==null&&!t.inFlow||le(r)||(G(r)?r.type===q.BLOCK_FOLDED||r.type===q.BLOCK_LITERAL:typeof r=="object"));t=Object.assign({},t,{allNullValues:!1,implicitKey:!p&&(u||!s),indent:a+c});let y=!1,h=!1,m=Ar(r,t,()=>y=!0,()=>h=!0);if(!p&&!t.inFlow&&m.length>1024){if(u)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 y&&n&&n(),m===""?"?":p?`? ${m}`:m}else if(s&&!u||e==null&&p)return m=`? ${m}`,f&&!y?m+=dr(m,t.indent,l(f)):h&&i&&i(),m;y&&(f=null),p?(f&&(m+=dr(m,t.indent,l(f))),m=`? ${m} -${a}:`):(m=`${m}:`,f&&(m+=dr(m,t.indent,l(f))));let g,_,w;se(e)?(g=!!e.spaceBefore,_=e.commentBefore,w=e.comment):(g=!1,_=null,w=null,e&&typeof e=="object"&&(e=o.createNode(e))),t.implicitKey=!1,!p&&!f&&G(e)&&(t.indentAtStart=m.length+1),h=!1,!d&&c.length>=2&&!t.inFlow&&!p&&Ut(e)&&!e.flow&&!e.tag&&!e.anchor&&(t.indent=t.indent.substring(2));let k=!1,v=Ar(e,t,()=>k=!0,()=>h=!0),P=" ";if(f||g||_){if(P=g?` +`)g=m;else break}let _=t.substring(0,g{P=!0});let $=Ns(`${_}${v}${p}`,l,Oa,O);if(!P)return`>${x} +${l}${$}`}return t=t.replace(/\n+/g,`$&${l}`),`|${x} +${l}${_}${t}${p}`}function jR(r,e,t,n){let{type:i,value:s}=r,{actualString:o,implicitKey:a,indent:c,indentStep:l,inFlow:d}=e;if(a&&s.includes(` +`)||d&&/[[\]{},]/.test(s))return bi(s,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(s))return a||d||!s.includes(` +`)?bi(s,e):Ra(r,e,t,n);if(!a&&!d&&i!==q.PLAIN&&s.includes(` +`))return Ra(r,e,t,n);if(Ca(s)){if(c==="")return e.forceBlockIndent=!0,Ra(r,e,t,n);if(a&&c===l)return bi(s,e)}let u=s.replace(/\n+/g,`$& +${c}`);if(o){let f=h=>{var m;return h.default&&h.tag!=="tag:yaml.org,2002:str"&&((m=h.test)==null?void 0:m.test(u))},{compat:p,tags:y}=e.doc.schema;if(y.some(f)||p!=null&&p.some(f))return bi(s,e)}return a?u:Ns(u,c,of,Ta(e,!1))}function kn(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!==q.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=q.QUOTE_DOUBLE);let c=d=>{switch(d){case q.BLOCK_FOLDED:case q.BLOCK_LITERAL:return i||s?bi(o.value,e):Ra(o,e,t,n);case q.QUOTE_DOUBLE:return Ls(o.value,e);case q.QUOTE_SINGLE:return af(o.value,e);case q.PLAIN:return jR(o,e,t,n);default:return null}},l=c(a);if(l===null){let{defaultKeyType:d,defaultStringType:u}=e.options,f=i&&d||u;if(l=c(f),l===null)throw new Error(`Unsupported default string type ${f}`)}return l}function Ma(r,e){let t=Object.assign({blockQuote:!0,commentString:Ab,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},r.schema.toStringOptions,e),n;switch(t.collectionStyle){case"block":n=!1;break;case"flow":n=!0;break;default:n=null}return{anchors:new Set,doc:r,flowCollectionPadding:t.flowCollectionPadding?" ":"",indent:"",indentStep:typeof t.indent=="number"?" ".repeat(t.indent):" ",inFlow:n,options:t}}function DR(r,e){var i,s,o,a;if(e.tag){let c=r.filter(l=>l.tag===e.tag);if(c.length>0)return(i=c.find(l=>l.format===e.format))!=null?i:c[0]}let t,n;if(G(e)){n=e.value;let c=r.filter(l=>{var d;return(d=l.identify)==null?void 0:d.call(l,n)});if(c.length>1){let l=c.filter(d=>d.test);l.length>0&&(c=l)}t=(s=c.find(l=>l.format===e.format))!=null?s:c.find(l=>!l.format)}else n=e,t=r.find(c=>c.nodeClass&&n instanceof c.nodeClass);if(!t){let c=(a=(o=n==null?void 0:n.constructor)==null?void 0:o.name)!=null?a:n===null?"null":typeof n;throw new Error(`Tag not resolved for ${c} value`)}return t}function qR(r,e,{anchors:t,doc:n}){var a;if(!n.directives)return"";let i=[],s=(G(r)||le(r))&&r.anchor;s&&xa(s)&&(t.add(s),i.push(`&${s}`));let o=(a=r.tag)!=null?a:e.default?null:e.tag;return o&&i.push(n.directives.tagString(o)),i.join(" ")}function Ar(r,e,t,n){var c,l;if(ne(r))return r.toString(e,t,n);if(Dt(r)){if(e.doc.directives)return r.toString(e);if((c=e.resolvedAliases)!=null&&c.has(r))throw new TypeError("Cannot stringify circular structure without alias nodes");e.resolvedAliases?e.resolvedAliases.add(r):e.resolvedAliases=new Set([r]),r=r.resolve(e.doc)}let i,s=se(r)?r:e.doc.createNode(r,{onTagObj:d=>i=d});i!=null||(i=DR(e.doc.schema.tags,s));let o=qR(s,i,e);o.length>0&&(e.indentAtStart=((l=e.indentAtStart)!=null?l:0)+o.length+1);let a=typeof i.stringify=="function"?i.stringify(s,e,t,n):G(s)?kn(s,e,t,n):s.toString(e,t,n);return o?G(s)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o} +${e.indent}${a}`:a}function xb({key:r,value:e},t,n,i){var O,$;let{allNullValues:s,doc:o,indent:a,indentStep:c,options:{commentString:l,indentSeq:d,simpleKeys:u}}=t,f=se(r)&&r.comment||null;if(u){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(le(r)||!se(r)&&typeof r=="object"){let R="With simple keys, collection cannot be used as a key value";throw new Error(R)}}let p=!u&&(!r||f&&e==null&&!t.inFlow||le(r)||(G(r)?r.type===q.BLOCK_FOLDED||r.type===q.BLOCK_LITERAL:typeof r=="object"));t=Object.assign({},t,{allNullValues:!1,implicitKey:!p&&(u||!s),indent:a+c});let y=!1,h=!1,m=Ar(r,t,()=>y=!0,()=>h=!0);if(!p&&!t.inFlow&&m.length>1024){if(u)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 y&&n&&n(),m===""?"?":p?`? ${m}`:m}else if(s&&!u||e==null&&p)return m=`? ${m}`,f&&!y?m+=lr(m,t.indent,l(f)):h&&i&&i(),m;y&&(f=null),p?(f&&(m+=lr(m,t.indent,l(f))),m=`? ${m} +${a}:`):(m=`${m}:`,f&&(m+=lr(m,t.indent,l(f))));let g,_,w;se(e)?(g=!!e.spaceBefore,_=e.commentBefore,w=e.comment):(g=!1,_=null,w=null,e&&typeof e=="object"&&(e=o.createNode(e))),t.implicitKey=!1,!p&&!f&&G(e)&&(t.indentAtStart=m.length+1),h=!1,!d&&c.length>=2&&!t.inFlow&&!p&&Ft(e)&&!e.flow&&!e.tag&&!e.anchor&&(t.indent=t.indent.substring(2));let x=!1,v=Ar(e,t,()=>x=!0,()=>h=!0),P=" ";if(f||g||_){if(P=g?` `:"",_){let R=l(_);P+=` -${Ot(R,t.indent)}`}v===""&&!t.inFlow?P===` +${It(R,t.indent)}`}v===""&&!t.inFlow?P===` `&&w&&(P=` `):P+=` ${t.indent}`}else if(!p&&le(e)){let R=v[0],S=v.indexOf(` -`),V=S!==-1,B=($=(O=t.inFlow)!=null?O:e.flow)!=null?$:e.items.length===0;if(V||!B){let T=!1;if(V&&(R==="&"||R==="!")){let E=v.indexOf(" ");R==="&"&&E!==-1&&Er===Na||typeof r=="symbol"&&r.description===Na,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new q(Symbol(Na)),{addToJSMap:df}),stringify:()=>Na},Ib=(r,e)=>(Vt.identify(e)||G(e)&&(!e.type||e.type===q.PLAIN)&&Vt.identify(e.value))&&(r==null?void 0:r.doc.schema.tags.some(t=>t.tag===Vt.tag&&t.default));function df(r,e,t){let n=Ob(r,t);if(Ut(n))for(let i of n.items)lf(r,e,i);else if(Array.isArray(n))for(let i of n)lf(r,e,i);else lf(r,e,n)}function lf(r,e,t){let n=Ob(r,t);if(!Ft(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 Ob(r,e){return r&&qt(e)?e.resolve(r.doc,r):e}function La(r,e,{key:t,value:n}){if(se(t)&&t.addToJSMap)t.addToJSMap(r,e,n);else if(Ib(r,t))df(r,e,n);else{let i=Me(t,"",r);if(e instanceof Map)e.set(i,Me(n,i,r));else if(e instanceof Set)e.add(i);else{let s=HR(t,i,r),o=Me(n,s,r);s in e?Object.defineProperty(e,s,{value:o,writable:!0,enumerable:!0,configurable:!0}):e[s]=o}}return e}function HR(r,e,t){if(e===null)return"";if(typeof e!="object")return String(e);if(se(r)&&(t!=null&&t.doc)){let n=Ma(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)+'..."'),Ca(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 _i(r,e,t){let n=Er(r,void 0,t),i=Er(e,void 0,t);return new Se(n,i)}var Se=class r{constructor(e,t=null){Object.defineProperty(this,et,{value:rf}),this.key=e,this.value=t}clone(e){let{key:t,value:n}=this;return se(t)&&(t=t.clone(e)),se(n)&&(n=n.clone(e)),new r(t,n)}toJSON(e,t){let n=t!=null&&t.mapAsMap?new Map:{};return La(t,n,this)}toString(e,t,n){return e!=null&&e.doc?Pb(this,e,t,n):JSON.stringify(this)}};function Da(r,e,t){var s;return(((s=e.inFlow)!=null?s:r.flow)?WR:KR)(r,e,t)}function KR({comment:r,items:e},t,{blockItemPrefix:n,flowChars:i,itemIndent:s,onChompKeep:o,onComment:a}){let{indent:c,options:{commentString:l}}=t,d=Object.assign({},t,{indent:s,type:null}),u=!1,f=[];for(let y=0;ym=null,()=>u=!0);m&&(g+=dr(g,s,l(m))),u&&m&&(u=!1),f.push(n+g)}let p;if(f.length===0)p=i.start+i.end;else{p=f[0];for(let y=1;yr===La||typeof r=="symbol"&&r.description===La,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new q(Symbol(La)),{addToJSMap:df}),stringify:()=>La},Pb=(r,e)=>(Vt.identify(e)||G(e)&&(!e.type||e.type===q.PLAIN)&&Vt.identify(e.value))&&(r==null?void 0:r.doc.schema.tags.some(t=>t.tag===Vt.tag&&t.default));function df(r,e,t){let n=Ib(r,t);if(Ft(n))for(let i of n.items)lf(r,e,i);else if(Array.isArray(n))for(let i of n)lf(r,e,i);else lf(r,e,n)}function lf(r,e,t){let n=Ib(r,t);if(!qt(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 Ib(r,e){return r&&Dt(e)?e.resolve(r.doc,r):e}function ja(r,e,{key:t,value:n}){if(se(t)&&t.addToJSMap)t.addToJSMap(r,e,n);else if(Pb(r,t))df(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=FR(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 FR(r,e,t){if(e===null)return"";if(typeof e!="object")return String(e);if(se(r)&&(t!=null&&t.doc)){let n=Ma(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)+'..."'),Na(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 wi(r,e,t){let n=Er(r,void 0,t),i=Er(e,void 0,t);return new Se(n,i)}var Se=class r{constructor(e,t=null){Object.defineProperty(this,Ze,{value:rf}),this.key=e,this.value=t}clone(e){let{key:t,value:n}=this;return se(t)&&(t=t.clone(e)),se(n)&&(n=n.clone(e)),new r(t,n)}toJSON(e,t){let n=t!=null&&t.mapAsMap?new Map:{};return ja(t,n,this)}toString(e,t,n){return e!=null&&e.doc?xb(this,e,t,n):JSON.stringify(this)}};function qa(r,e,t){var s;return(((s=e.inFlow)!=null?s:r.flow)?UR:VR)(r,e,t)}function VR({comment:r,items:e},t,{blockItemPrefix:n,flowChars:i,itemIndent:s,onChompKeep:o,onComment:a}){let{indent:c,options:{commentString:l}}=t,d=Object.assign({},t,{indent:s,type:null}),u=!1,f=[];for(let y=0;ym=null,()=>u=!0);m&&(g+=lr(g,s,l(m))),u&&m&&(u=!1),f.push(n+g)}let p;if(f.length===0)p=i.start+i.end;else{p=f[0];for(let y=1;ym=null);l||(l=u.length>d||g.includes(` -`)),y0&&(l||(l=u.reduce((_,w)=>_+w.length+2,2)+(g.length+2)>e.options.lineWidth)),l&&(g+=",")),m&&(g+=dr(g,n,a(m))),u.push(g),d=u.length}let{start:f,end:p}=t;if(u.length===0)return f+p;if(!l){let y=u.reduce((h,m)=>h+m.length+2,2);l=e.options.lineWidth>0&&y>e.options.lineWidth}if(l){let y=f;for(let h of u)y+=h?` +`+It(l(r),c),a&&a()):u&&o&&o(),p}function UR({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,d=0,u=[];for(let y=0;ym=null);l||(l=u.length>d||g.includes(` +`)),y0&&(l||(l=u.reduce((_,w)=>_+w.length+2,2)+(g.length+2)>e.options.lineWidth)),l&&(g+=",")),m&&(g+=lr(g,n,a(m))),u.push(g),d=u.length}let{start:f,end:p}=t;if(u.length===0)return f+p;if(!l){let y=u.reduce((h,m)=>h+m.length+2,2);l=e.options.lineWidth>0&&y>e.options.lineWidth}if(l){let y=f;for(let h of u)y+=h?` ${s}${i}${h}`:` `;return`${y} -${i}${p}`}else return`${f}${o}${u.join(" ")}${o}${p}`}function ja({indent:r,options:{commentString:e}},t,n,i){if(n&&i&&(n=n.replace(/^\n+/,"")),n){let s=Ot(e(n),r);t.push(s.trimStart())}}function Qr(r,e){let t=G(e)?e.value:e;for(let n of r)if(ne(n)&&(n.key===e||n.key===t||G(n.key)&&n.key.value===t))return n}var Pe=class extends mi{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(Dt,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(_i(c,l,n))};if(t instanceof Map)for(let[c,l]of t)a(c,l);else if(t&&typeof t=="object")for(let c of Object.keys(t))a(c,t[c]);return typeof e.sortMapEntries=="function"&&o.items.sort(e.sortMapEntries),o}add(e,t){var o;let n;ne(e)?n=e:!e||typeof e!="object"||!("key"in e)?n=new Se(e,e==null?void 0:e.value):n=new Se(e.key,e.value);let i=Qr(this.items,n.key),s=(o=this.schema)==null?void 0:o.sortMapEntries;if(i){if(!t)throw new Error(`Key ${n.key} already set`);G(i.value)&&Pa(n.value)?i.value.value=n.value:i.value=n.value}else if(s){let a=this.items.findIndex(c=>s(n,c)<0);a===-1?this.items.push(n):this.items.splice(a,0,n)}else this.items.push(n)}delete(e){let t=Qr(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){var s;let n=Qr(this.items,e),i=n==null?void 0:n.value;return(s=!t&&G(i)?i.value:i)!=null?s:void 0}has(e){return!!Qr(this.items,e)}set(e,t){this.add(new Se(e,t),!0)}toJSON(e,t,n){let i=n?new n:t!=null&&t.mapAsMap?new Map:{};t!=null&&t.onCreate&&t.onCreate(i);for(let s of this.items)La(t,i,s);return i}toString(e,t,n){if(!e)return JSON.stringify(this);for(let i of this.items)if(!ne(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})),Da(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:n,onComment:t})}};var Bt={collection:"map",default:!0,nodeClass:Pe,tag:"tag:yaml.org,2002:map",resolve(r,e){return Ft(r)||e("Expected a mapping for this tag"),r},createNode:(r,e,t)=>Pe.from(r,e,t)};var Ke=class extends mi{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super($r,e),this.items=[]}add(e){this.items.push(e)}delete(e){let t=qa(e);return typeof t!="number"?!1:this.items.splice(t,1).length>0}get(e,t){let n=qa(e);if(typeof n!="number")return;let i=this.items[n];return!t&&G(i)?i.value:i}has(e){let t=qa(e);return typeof t=="number"&&t=0?e:null}var zt={collection:"seq",default:!0,nodeClass:Ke,tag:"tag:yaml.org,2002:seq",resolve(r,e){return Ut(r)||e("Expected a sequence for this tag"),r},createNode:(r,e,t)=>Ke.from(r,e,t)};var Zr={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),En(r,e,t,n)}};var An={identify:r=>r==null,createNode:()=>new q(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new q(null),stringify:({source:r},e)=>typeof r=="string"&&An.test.test(r)?r:e.options.nullStr};var Ls={identify:r=>typeof r=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:r=>new q(r[0]==="t"||r[0]==="T"),stringify({source:r,value:e},t){if(r&&Ls.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 We({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 Fa={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:We},Ua={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():We(r)}},Va={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 q(parseFloat(r)),t=r.indexOf(".");return t!==-1&&r[r.length-1]==="0"&&(e.minFractionDigits=r.length-t-1),e},stringify:We};var Ba=r=>typeof r=="bigint"||Number.isInteger(r),uf=(r,e,t,{intAsBigInt:n})=>n?BigInt(r):parseInt(r.substring(e),t);function Rb(r,e,t){let{value:n}=r;return Ba(n)&&n>=0?t+n.toString(e):We(r)}var za={identify:r=>Ba(r)&&r>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(r,e,t)=>uf(r,2,8,t),stringify:r=>Rb(r,8,"0o")},Ha={identify:Ba,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(r,e,t)=>uf(r,0,10,t),stringify:We},Ka={identify:r=>Ba(r)&&r>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(r,e,t)=>uf(r,2,16,t),stringify:r=>Rb(r,16,"0x")};var Tb=[Bt,zt,Zr,An,Ls,za,Ha,Ka,Fa,Ua,Va];function Mb(r){return typeof r=="bigint"||Number.isInteger(r)}var Wa=({value:r})=>JSON.stringify(r),GR=[{identify:r=>typeof r=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:r=>r,stringify:Wa},{identify:r=>r==null,createNode:()=>new q(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Wa},{identify:r=>typeof r=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:r=>r==="true",stringify:Wa},{identify:Mb,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})=>Mb(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:Wa}],JR={default:!0,tag:"",test:/^/,resolve(r,e){return e(`Unresolved plain scalar ${JSON.stringify(r)}`),r}},Cb=[Bt,zt].concat(GR,JR);var js={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 s=i.items[0]||new Se(new q(null));if(i.commentBefore&&(s.key.commentBefore=s.key.commentBefore?`${i.commentBefore} +${i}${p}`}else return`${f}${o}${u.join(" ")}${o}${p}`}function Da({indent:r,options:{commentString:e}},t,n,i){if(n&&i&&(n=n.replace(/^\n+/,"")),n){let s=It(e(n),r);t.push(s.trimStart())}}function en(r,e){let t=G(e)?e.value:e;for(let n of r)if(ne(n)&&(n.key===e||n.key===t||G(n.key)&&n.key.value===t))return n}var xe=class extends gi{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(jt,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(wi(c,l,n))};if(t instanceof Map)for(let[c,l]of t)a(c,l);else if(t&&typeof t=="object")for(let c of Object.keys(t))a(c,t[c]);return typeof e.sortMapEntries=="function"&&o.items.sort(e.sortMapEntries),o}add(e,t){var o;let n;ne(e)?n=e:!e||typeof e!="object"||!("key"in e)?n=new Se(e,e==null?void 0:e.value):n=new Se(e.key,e.value);let i=en(this.items,n.key),s=(o=this.schema)==null?void 0:o.sortMapEntries;if(i){if(!t)throw new Error(`Key ${n.key} already set`);G(i.value)&&Ia(n.value)?i.value.value=n.value:i.value=n.value}else if(s){let a=this.items.findIndex(c=>s(n,c)<0);a===-1?this.items.push(n):this.items.splice(a,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){var s;let n=en(this.items,e),i=n==null?void 0:n.value;return(s=!t&&G(i)?i.value:i)!=null?s:void 0}has(e){return!!en(this.items,e)}set(e,t){this.add(new Se(e,t),!0)}toJSON(e,t,n){let i=n?new n:t!=null&&t.mapAsMap?new Map:{};t!=null&&t.onCreate&&t.onCreate(i);for(let s of this.items)ja(t,i,s);return i}toString(e,t,n){if(!e)return JSON.stringify(this);for(let i of this.items)if(!ne(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})),qa(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:n,onComment:t})}};var Ut={collection:"map",default:!0,nodeClass:xe,tag:"tag:yaml.org,2002:map",resolve(r,e){return qt(r)||e("Expected a mapping for this tag"),r},createNode:(r,e,t)=>xe.from(r,e,t)};var He=class extends gi{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super($r,e),this.items=[]}add(e){this.items.push(e)}delete(e){let t=Fa(e);return typeof t!="number"?!1:this.items.splice(t,1).length>0}get(e,t){let n=Fa(e);if(typeof n!="number")return;let i=this.items[n];return!t&&G(i)?i.value:i}has(e){let t=Fa(e);return typeof t=="number"&&t=0?e:null}var Bt={collection:"seq",default:!0,nodeClass:He,tag:"tag:yaml.org,2002:seq",resolve(r,e){return Ft(r)||e("Expected a sequence for this tag"),r},createNode:(r,e,t)=>He.from(r,e,t)};var tn={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),kn(r,e,t,n)}};var xn={identify:r=>r==null,createNode:()=>new q(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new q(null),stringify:({source:r},e)=>typeof r=="string"&&xn.test.test(r)?r:e.options.nullStr};var js={identify:r=>typeof r=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:r=>new q(r[0]==="t"||r[0]==="T"),stringify({source:r,value:e},t){if(r&&js.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 Ke({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 Va={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:Ke},Ua={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():Ke(r)}},Ba={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 q(parseFloat(r)),t=r.indexOf(".");return t!==-1&&r[r.length-1]==="0"&&(e.minFractionDigits=r.length-t-1),e},stringify:Ke};var za=r=>typeof r=="bigint"||Number.isInteger(r),uf=(r,e,t,{intAsBigInt:n})=>n?BigInt(r):parseInt(r.substring(e),t);function Ob(r,e,t){let{value:n}=r;return za(n)&&n>=0?t+n.toString(e):Ke(r)}var Ha={identify:r=>za(r)&&r>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(r,e,t)=>uf(r,2,8,t),stringify:r=>Ob(r,8,"0o")},Ka={identify:za,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(r,e,t)=>uf(r,0,10,t),stringify:Ke},Wa={identify:r=>za(r)&&r>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(r,e,t)=>uf(r,2,16,t),stringify:r=>Ob(r,16,"0x")};var Rb=[Ut,Bt,tn,xn,js,Ha,Ka,Wa,Va,Ua,Ba];function Tb(r){return typeof r=="bigint"||Number.isInteger(r)}var Ga=({value:r})=>JSON.stringify(r),BR=[{identify:r=>typeof r=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:r=>r,stringify:Ga},{identify:r=>r==null,createNode:()=>new q(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Ga},{identify:r=>typeof r=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:r=>r==="true",stringify:Ga},{identify:Tb,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})=>Tb(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:Ga}],zR={default:!0,tag:"",test:/^/,resolve(r,e){return e(`Unresolved plain scalar ${JSON.stringify(r)}`),r}},Cb=[Ut,Bt].concat(BR,zR);var Ds={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 s=i.items[0]||new Se(new q(null));if(i.commentBefore&&(s.key.commentBefore=s.key.commentBefore?`${i.commentBefore} ${s.key.commentBefore}`:i.commentBefore),i.comment){let o=(t=s.value)!=null?t:s.key;o.comment=o.comment?`${i.comment} -${o.comment}`:i.comment}i=s}r.items[n]=ne(i)?i:new Se(i)}}else e("Expected a sequence for this tag");return r}function pf(r,e,t){let{replacer:n}=t,i=new Ke(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(_i(a,c,t))}return i}var Ds={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:ff,createNode:pf};var bi=class r extends Ke{constructor(){super(),this.add=Pe.prototype.add.bind(this),this.delete=Pe.prototype.delete.bind(this),this.get=Pe.prototype.get.bind(this),this.has=Pe.prototype.has.bind(this),this.set=Pe.prototype.set.bind(this),this.tag=r.tag}toJSON(e,t){if(!t)return super.toJSON(e);let n=new Map;t!=null&&t.onCreate&&t.onCreate(n);for(let i of this.items){let s,o;if(ne(i)?(s=Me(i.key,"",t),o=Me(i.value,s,t)):s=Me(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=pf(e,t,n),s=new this;return s.items=i.items,s}};bi.tag="tag:yaml.org,2002:omap";var qs={collection:"seq",identify:r=>r instanceof Map,nodeClass:bi,default:!1,tag:"tag:yaml.org,2002:omap",resolve(r,e){let t=ff(r,e),n=[];for(let{key:i}of t.items)G(i)&&(n.includes(i.value)?e(`Ordered maps must not include duplicate keys: ${i.value}`):n.push(i.value));return Object.assign(new bi,t)},createNode:(r,e,t)=>bi.from(r,e,t)};function Nb({value:r,source:e},t){return e&&(r?hf:mf).test.test(e)?e:r?t.options.trueStr:t.options.falseStr}var hf={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 q(!0),stringify:Nb},mf={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 q(!1),stringify:Nb};var Lb={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:We},jb={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():We(r)}},Db={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 q(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:We};var Fs=r=>typeof r=="bigint"||Number.isInteger(r);function Ga(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 yf(r,e,t){let{value:n}=r;if(Fs(n)){let i=n.toString(e);return n<0?"-"+t+i.substr(1):t+i}return We(r)}var qb={identify:Fs,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(r,e,t)=>Ga(r,2,2,t),stringify:r=>yf(r,2,"0b")},Fb={identify:Fs,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(r,e,t)=>Ga(r,1,8,t),stringify:r=>yf(r,8,"0")},Ub={identify:Fs,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(r,e,t)=>Ga(r,0,10,t),stringify:We},Vb={identify:Fs,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(r,e,t)=>Ga(r,2,16,t),stringify:r=>yf(r,16,"0x")};var wi=class r extends Pe{constructor(e){super(e),this.tag=r.tag}add(e){let t;ne(e)?t=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?t=new Se(e.key,null):t=new Se(e,null),Qr(this.items,t.key)||this.items.push(t)}get(e,t){let n=Qr(this.items,e);return!t&&ne(n)?G(n.key)?n.key.value:n.key:n}set(e,t){if(typeof t!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof t}`);let n=Qr(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new Se(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(_i(o,null,n));return s}};wi.tag="tag:yaml.org,2002:set";var Us={collection:"map",identify:r=>r instanceof Set,nodeClass:wi,default:!1,tag:"tag:yaml.org,2002:set",createNode:(r,e,t)=>wi.from(r,e,t),resolve(r,e){if(Ft(r)){if(r.hasAllNullValues(!0))return Object.assign(new wi,r);e("Set items must all have null values")}else e("Expected a mapping for this tag");return r}};function gf(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 Bb(r){let{value:e}=r,t=o=>o;if(typeof e=="bigint")t=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return We(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 Ja={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})=>gf(r,t),stringify:Bb},Ya={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=>gf(r,!1),stringify:Bb},vi={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(vi.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),d=e[8];if(d&&d!=="Z"){let u=gf(d,!1);Math.abs(u)<30&&(u*=60),l-=6e4*u}return new Date(l)},stringify:({value:r})=>{var e;return(e=r==null?void 0:r.toISOString().replace(/(T00:00:00)?\.000Z$/,""))!=null?e:""}};var _f=[Bt,zt,Zr,An,hf,mf,qb,Fb,Ub,Vb,Lb,jb,Db,js,Vt,qs,Ds,Us,Ja,Ya,vi];var zb=new Map([["core",Tb],["failsafe",[Bt,zt,Zr]],["json",Cb],["yaml11",_f],["yaml-1.1",_f]]),Hb={binary:js,bool:Ls,float:Va,floatExp:Ua,floatNaN:Fa,floatTime:Ya,int:Ha,intHex:Ka,intOct:za,intTime:Ja,map:Bt,merge:Vt,null:An,omap:qs,pairs:Ds,seq:zt,set:Us,timestamp:vi},Kb={"tag:yaml.org,2002:binary":js,"tag:yaml.org,2002:merge":Vt,"tag:yaml.org,2002:omap":qs,"tag:yaml.org,2002:pairs":Ds,"tag:yaml.org,2002:set":Us,"tag:yaml.org,2002:timestamp":vi};function Xa(r,e,t){let n=zb.get(e);if(n&&!r)return t&&!n.includes(Vt)?n.concat(Vt):n.slice();let i=n;if(!i)if(Array.isArray(r))i=[];else{let s=Array.from(zb.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(Vt)),i.reduce((s,o)=>{let a=typeof o=="string"?Hb[o]:o;if(!a){let c=JSON.stringify(o),l=Object.keys(Hb).map(d=>JSON.stringify(d)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return s.includes(a)||s.push(a),s},[])}var YR=(r,e)=>r.keye.key?1:0,Vs=class r{constructor({compat:e,customTags:t,merge:n,resolveKnownTags:i,schema:s,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?Xa(e,"compat"):e?Xa(null,e):null,this.name=typeof s=="string"&&s||"core",this.knownTags=i?Kb:{},this.tags=Xa(t,this.name,n),this.toStringOptions=a!=null?a:null,Object.defineProperty(this,Dt,{value:Bt}),Object.defineProperty(this,gt,{value:Zr}),Object.defineProperty(this,$r,{value:zt}),this.sortMapEntries=typeof o=="function"?o:o===!0?YR:null}clone(){let e=Object.create(r.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};function Wb(r,e){var c;let t=[],n=e.directives===!0;if(e.directives!==!1&&r.directives){let l=r.directives.toString(r);l?(t.push(l),n=!0):r.directives.docStart&&(n=!0)}n&&t.push("---");let i=Ma(r,e),{commentString:s}=i.options;if(r.commentBefore){t.length!==1&&t.unshift("");let l=s(r.commentBefore);t.unshift(Ot(l,""))}let o=!1,a=null;if(r.contents){if(se(r.contents)){if(r.contents.spaceBefore&&n&&t.push(""),r.contents.commentBefore){let u=s(r.contents.commentBefore);t.push(Ot(u,""))}i.forceBlockIndent=!!r.comment,a=r.contents.comment}let l=a?void 0:()=>o=!0,d=Ar(r.contents,i,()=>a=null,l);a&&(d+=dr(d,"",s(a))),(d[0]==="|"||d[0]===">")&&t[t.length-1]==="---"?t[t.length-1]=`--- ${d}`:t.push(d)}else t.push(Ar(r.contents,i));if((c=r.directives)!=null&&c.docEnd)if(r.comment){let l=s(r.comment);l.includes(` -`)?(t.push("..."),t.push(Ot(l,""))):t.push(`... ${l}`)}else t.push("...");else{let l=r.comment;l&&o&&(l=l.replace(/^\n+/,"")),l&&((!o||a)&&t[t.length-1]!==""&&t.push(""),t.push(Ot(s(l),"")))}return t.join(` +${o.comment}`:i.comment}i=s}r.items[n]=ne(i)?i:new Se(i)}}else e("Expected a sequence for this tag");return r}function pf(r,e,t){let{replacer:n}=t,i=new He(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(wi(a,c,t))}return i}var qs={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:ff,createNode:pf};var vi=class r extends He{constructor(){super(),this.add=xe.prototype.add.bind(this),this.delete=xe.prototype.delete.bind(this),this.get=xe.prototype.get.bind(this),this.has=xe.prototype.has.bind(this),this.set=xe.prototype.set.bind(this),this.tag=r.tag}toJSON(e,t){if(!t)return super.toJSON(e);let n=new Map;t!=null&&t.onCreate&&t.onCreate(n);for(let i of this.items){let s,o;if(ne(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=pf(e,t,n),s=new this;return s.items=i.items,s}};vi.tag="tag:yaml.org,2002:omap";var Fs={collection:"seq",identify:r=>r instanceof Map,nodeClass:vi,default:!1,tag:"tag:yaml.org,2002:omap",resolve(r,e){let t=ff(r,e),n=[];for(let{key:i}of t.items)G(i)&&(n.includes(i.value)?e(`Ordered maps must not include duplicate keys: ${i.value}`):n.push(i.value));return Object.assign(new vi,t)},createNode:(r,e,t)=>vi.from(r,e,t)};function Mb({value:r,source:e},t){return e&&(r?hf:mf).test.test(e)?e:r?t.options.trueStr:t.options.falseStr}var hf={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 q(!0),stringify:Mb},mf={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 q(!1),stringify:Mb};var Nb={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:Ke},Lb={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:r=>parseFloat(r.replace(/_/g,"")),stringify(r){let e=Number(r.value);return isFinite(e)?e.toExponential():Ke(r)}},jb={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 q(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:Ke};var Vs=r=>typeof r=="bigint"||Number.isInteger(r);function Ja(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 yf(r,e,t){let{value:n}=r;if(Vs(n)){let i=n.toString(e);return n<0?"-"+t+i.substr(1):t+i}return Ke(r)}var Db={identify:Vs,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(r,e,t)=>Ja(r,2,2,t),stringify:r=>yf(r,2,"0b")},qb={identify:Vs,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(r,e,t)=>Ja(r,1,8,t),stringify:r=>yf(r,8,"0")},Fb={identify:Vs,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(r,e,t)=>Ja(r,0,10,t),stringify:Ke},Vb={identify:Vs,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(r,e,t)=>Ja(r,2,16,t),stringify:r=>yf(r,16,"0x")};var $i=class r extends xe{constructor(e){super(e),this.tag=r.tag}add(e){let t;ne(e)?t=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?t=new Se(e.key,null):t=new Se(e,null),en(this.items,t.key)||this.items.push(t)}get(e,t){let n=en(this.items,e);return!t&&ne(n)?G(n.key)?n.key.value:n.key:n}set(e,t){if(typeof t!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof t}`);let n=en(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new Se(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(wi(o,null,n));return s}};$i.tag="tag:yaml.org,2002:set";var Us={collection:"map",identify:r=>r instanceof Set,nodeClass:$i,default:!1,tag:"tag:yaml.org,2002:set",createNode:(r,e,t)=>$i.from(r,e,t),resolve(r,e){if(qt(r)){if(r.hasAllNullValues(!0))return Object.assign(new $i,r);e("Set items must all have null values")}else e("Expected a mapping for this tag");return r}};function gf(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 Ub(r){let{value:e}=r,t=o=>o;if(typeof e=="bigint")t=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return Ke(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 Ya={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})=>gf(r,t),stringify:Ub},Xa={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=>gf(r,!1),stringify:Ub},Si={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(Si.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),d=e[8];if(d&&d!=="Z"){let u=gf(d,!1);Math.abs(u)<30&&(u*=60),l-=6e4*u}return new Date(l)},stringify:({value:r})=>{var e;return(e=r==null?void 0:r.toISOString().replace(/(T00:00:00)?\.000Z$/,""))!=null?e:""}};var _f=[Ut,Bt,tn,xn,hf,mf,Db,qb,Fb,Vb,Nb,Lb,jb,Ds,Vt,Fs,qs,Us,Ya,Xa,Si];var Bb=new Map([["core",Rb],["failsafe",[Ut,Bt,tn]],["json",Cb],["yaml11",_f],["yaml-1.1",_f]]),zb={binary:Ds,bool:js,float:Ba,floatExp:Ua,floatNaN:Va,floatTime:Xa,int:Ka,intHex:Wa,intOct:Ha,intTime:Ya,map:Ut,merge:Vt,null:xn,omap:Fs,pairs:qs,seq:Bt,set:Us,timestamp:Si},Hb={"tag:yaml.org,2002:binary":Ds,"tag:yaml.org,2002:merge":Vt,"tag:yaml.org,2002:omap":Fs,"tag:yaml.org,2002:pairs":qs,"tag:yaml.org,2002:set":Us,"tag:yaml.org,2002:timestamp":Si};function Qa(r,e,t){let n=Bb.get(e);if(n&&!r)return t&&!n.includes(Vt)?n.concat(Vt):n.slice();let i=n;if(!i)if(Array.isArray(r))i=[];else{let s=Array.from(Bb.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(Vt)),i.reduce((s,o)=>{let a=typeof o=="string"?zb[o]:o;if(!a){let c=JSON.stringify(o),l=Object.keys(zb).map(d=>JSON.stringify(d)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return s.includes(a)||s.push(a),s},[])}var HR=(r,e)=>r.keye.key?1:0,Bs=class r{constructor({compat:e,customTags:t,merge:n,resolveKnownTags:i,schema:s,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?Qa(e,"compat"):e?Qa(null,e):null,this.name=typeof s=="string"&&s||"core",this.knownTags=i?Hb:{},this.tags=Qa(t,this.name,n),this.toStringOptions=a!=null?a:null,Object.defineProperty(this,jt,{value:Ut}),Object.defineProperty(this,yt,{value:tn}),Object.defineProperty(this,$r,{value:Bt}),this.sortMapEntries=typeof o=="function"?o:o===!0?HR:null}clone(){let e=Object.create(r.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};function Kb(r,e){var c;let t=[],n=e.directives===!0;if(e.directives!==!1&&r.directives){let l=r.directives.toString(r);l?(t.push(l),n=!0):r.directives.docStart&&(n=!0)}n&&t.push("---");let i=Ma(r,e),{commentString:s}=i.options;if(r.commentBefore){t.length!==1&&t.unshift("");let l=s(r.commentBefore);t.unshift(It(l,""))}let o=!1,a=null;if(r.contents){if(se(r.contents)){if(r.contents.spaceBefore&&n&&t.push(""),r.contents.commentBefore){let u=s(r.contents.commentBefore);t.push(It(u,""))}i.forceBlockIndent=!!r.comment,a=r.contents.comment}let l=a?void 0:()=>o=!0,d=Ar(r.contents,i,()=>a=null,l);a&&(d+=lr(d,"",s(a))),(d[0]==="|"||d[0]===">")&&t[t.length-1]==="---"?t[t.length-1]=`--- ${d}`:t.push(d)}else t.push(Ar(r.contents,i));if((c=r.directives)!=null&&c.docEnd)if(r.comment){let l=s(r.comment);l.includes(` +`)?(t.push("..."),t.push(It(l,""))):t.push(`... ${l}`)}else t.push("...");else{let l=r.comment;l&&o&&(l=l.replace(/^\n+/,"")),l&&((!o||a)&&t[t.length-1]!==""&&t.push(""),t.push(It(s(l),"")))}return t.join(` `)+` -`}var en=class r{constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,et,{value:Sa});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!=null&&n._directives?(this.directives=n._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new lr({version:o}),this.setSchema(o,n),this.contents=e===void 0?null:this.createNode(e,i,n)}clone(){let e=Object.create(r.prototype,{[et]:{value:Sa}});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=se(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){$i(this.contents)&&this.contents.add(e)}addIn(e,t){$i(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){let n=nf(this);e.anchor=!t||n.has(t)?sf(t||"a",n):t}return new Sr(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 m=_=>typeof _=="number"||_ instanceof String||_ instanceof Number,g=t.filter(m).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:d}=n!=null?n:{},{onAnchor:u,setAnchors:f,sourceObjects:p}=Ab(this,o||"a"),y={aliasDuplicateObjects:s!=null?s:!0,keepUndefined:c!=null?c:!1,onAnchor:u,onTagObj:l,replacer:i,schema:this.schema,sourceObjects:p},h=Er(e,d,y);return a&&le(h)&&(h.flow=!0),f(),h}createPair(e,t,n={}){let i=this.createNode(e,null,n),s=this.createNode(t,null,n);return new Se(i,s)}delete(e){return $i(this.contents)?this.contents.delete(e):!1}deleteIn(e){return yi(e)?this.contents==null?!1:(this.contents=null,!0):$i(this.contents)?this.contents.deleteIn(e):!1}get(e,t){return le(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return yi(e)?!t&&G(this.contents)?this.contents.value:this.contents:le(this.contents)?this.contents.getIn(e,t):void 0}has(e){return le(this.contents)?this.contents.has(e):!1}hasIn(e){return yi(e)?this.contents!==void 0:le(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=Ts(this.schema,[e],t):$i(this.contents)&&this.contents.set(e,t)}setIn(e,t){yi(e)?this.contents=t:this.contents==null?this.contents=Ts(this.schema,Array.from(e),t):$i(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 lr({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 lr({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 Vs(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=Me(this.contents,t!=null?t:"",a);if(typeof s=="function")for(let{count:l,res:d}of a.anchors.values())s(d,l);return typeof o=="function"?Yr(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 Wb(this,e)}};function $i(r){if(le(r))return!0;throw new Error("Expected a YAML collection as document contents")}var Bs=class extends Error{constructor(e,t,n,i){super(),this.name=e,this.code=n,this.message=i,this.pos=t}},Ht=class extends Bs{constructor(e,t,n){super("YAMLParseError",e,t,n)}},zs=class extends Bs{constructor(e,t,n){super("YAMLWarning",e,t,n)}},bf=(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 rn=class r{constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,Ze,{value:Ea});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!=null&&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,{[Ze]:{value:Ea}});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=se(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){Ei(this.contents)&&this.contents.add(e)}addIn(e,t){Ei(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){let n=nf(this);e.anchor=!t||n.has(t)?sf(t||"a",n):t}return new Sr(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 m=_=>typeof _=="number"||_ instanceof String||_ instanceof Number,g=t.filter(m).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:d}=n!=null?n:{},{onAnchor:u,setAnchors:f,sourceObjects:p}=Eb(this,o||"a"),y={aliasDuplicateObjects:s!=null?s:!0,keepUndefined:c!=null?c:!1,onAnchor:u,onTagObj:l,replacer:i,schema:this.schema,sourceObjects:p},h=Er(e,d,y);return a&&le(h)&&(h.flow=!0),f(),h}createPair(e,t,n={}){let i=this.createNode(e,null,n),s=this.createNode(t,null,n);return new Se(i,s)}delete(e){return Ei(this.contents)?this.contents.delete(e):!1}deleteIn(e){return _i(e)?this.contents==null?!1:(this.contents=null,!0):Ei(this.contents)?this.contents.deleteIn(e):!1}get(e,t){return le(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return _i(e)?!t&&G(this.contents)?this.contents.value:this.contents:le(this.contents)?this.contents.getIn(e,t):void 0}has(e){return le(this.contents)?this.contents.has(e):!1}hasIn(e){return _i(e)?this.contents!==void 0:le(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=Cs(this.schema,[e],t):Ei(this.contents)&&this.contents.set(e,t)}setIn(e,t){_i(e)?this.contents=t:this.contents==null?this.contents=Cs(this.schema,Array.from(e),t):Ei(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 Bs(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!=null?t:"",a);if(typeof s=="function")for(let{count:l,res:d}of a.anchors.values())s(d,l);return typeof o=="function"?Qr(o,{"":c},"",c):c}toJSON(e,t){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:t})}toString(e={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){let t=JSON.stringify(e.indent);throw new Error(`"indent" option must be a positive integer, not ${t}`)}return Kb(this,e)}};function Ei(r){if(le(r))return!0;throw new Error("Expected a YAML collection as document contents")}var zs=class extends Error{constructor(e,t,n,i){super(),this.name=e,this.code=n,this.message=i,this.pos=t}},zt=class extends zs{constructor(e,t,n){super("YAMLParseError",e,t,n)}},Hs=class extends zs{constructor(e,t,n){super("YAMLWarning",e,t,n)}},bf=(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==null?void 0:c.line)===n&&c.col>i&&(a=Math.max(1,Math.min(c.col-i,80-s)));let l=" ".repeat(s)+"^".repeat(a);t.message+=`: ${o} ${l} -`}};function ur(r,{flow:e,indicator:t,next:n,offset:i,onError:s,parentIndent:o,startOnNewline:a}){let c=!1,l=a,d=a,u="",f="",p=!1,y=!1,h=null,m=null,g=null,_=null,w=null,k=null,v=null;for(let $ of r)switch(y&&($.type!=="space"&&$.type!=="newline"&&$.type!=="comma"&&s($.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),y=!1),h&&(l&&$.type!=="comment"&&$.type!=="newline"&&s(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),h=null),$.type){case"space":!e&&(t!=="doc-start"||(n==null?void 0:n.type)!=="flow-collection")&&$.source.includes(" ")&&(h=$),d=!0;break;case"comment":{d||s($,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let R=$.source.substring(1)||" ";u?u+=f+R:u=R,f="",l=!1;break}case"newline":l?u?u+=$.source:(!k||t!=="seq-item-ind")&&(c=!0):f+=$.source,l=!0,p=!0,(m||g)&&(_=$),d=!0;break;case"anchor":m&&s($,"MULTIPLE_ANCHORS","A node can have at most one anchor"),$.source.endsWith(":")&&s($.offset+$.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),m=$,v!=null||(v=$.offset),l=!1,d=!1,y=!0;break;case"tag":{g&&s($,"MULTIPLE_TAGS","A node can have at most one tag"),g=$,v!=null||(v=$.offset),l=!1,d=!1,y=!0;break}case t:(m||g)&&s($,"BAD_PROP_ORDER",`Anchors and tags must be after the ${$.source} indicator`),k&&s($,"UNEXPECTED_TOKEN",`Unexpected ${$.source} in ${e!=null?e:"collection"}`),k=$,l=t==="seq-item-ind"||t==="explicit-key-ind",d=!1;break;case"comma":if(e){w&&s($,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),w=$,l=!1,d=!1;break}default:s($,"UNEXPECTED_TOKEN",`Unexpected ${$.type} token`),l=!1,d=!1}let P=r[r.length-1],O=P?P.offset+P.source.length:i;return y&&n&&n.type!=="space"&&n.type!=="newline"&&n.type!=="comma"&&(n.type!=="scalar"||n.source!=="")&&s(n.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),h&&(l&&h.indent<=o||(n==null?void 0:n.type)==="block-map"||(n==null?void 0:n.type)==="block-seq")&&s(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:w,found:k,spaceBefore:c,comment:u,hasNewline:p,anchor:m,tag:g,newlineAfterProp:_,end:O,start:v!=null?v:O}}function tn(r){if(!r)return null;switch(r.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(r.source.includes(` -`))return!0;if(r.end){for(let e of r.end)if(e.type==="newline")return!0}return!1;case"flow-collection":for(let e of r.items){for(let t of e.start)if(t.type==="newline")return!0;if(e.sep){for(let t of e.sep)if(t.type==="newline")return!0}if(tn(e.key)||tn(e.value))return!0}return!1;default:return!0}}function Hs(r,e,t){if((e==null?void 0:e.type)==="flow-collection"){let n=e.end[0];n.indent===r&&(n.source==="]"||n.source==="}")&&tn(e)&&t(n,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}function Qa(r,e,t){let{uniqueKeys:n}=r.options;if(n===!1)return!1;let i=typeof n=="function"?n:(s,o)=>s===o||G(s)&&G(o)&&s.value===o.value;return e.some(s=>i(s.key,t))}var Gb="All mapping items must start at the same column";function Jb({composeNode:r,composeEmptyNode:e},t,n,i,s){var d,u;let o=(d=s==null?void 0:s.nodeClass)!=null?d:Pe,a=new o(t.schema);t.atRoot&&(t.atRoot=!1);let c=n.offset,l=null;for(let f of n.items){let{start:p,key:y,sep:h,value:m}=f,g=ur(p,{indicator:"explicit-key-ind",next:y!=null?y:h==null?void 0:h[0],offset:c,onError:i,parentIndent:n.indent,startOnNewline:!0}),_=!g.found;if(_){if(y&&(y.type==="block-seq"?i(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in y&&y.indent!==n.indent&&i(c,"BAD_INDENT",Gb)),!g.anchor&&!g.tag&&!h){l=g.end,g.comment&&(a.comment?a.comment+=` -`+g.comment:a.comment=g.comment);continue}(g.newlineAfterProp||tn(y))&&i(y!=null?y:p[p.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else((u=g.found)==null?void 0:u.indent)!==n.indent&&i(c,"BAD_INDENT",Gb);t.atKey=!0;let w=g.end,k=y?r(t,y,g,i):e(t,w,p,null,g,i);t.schema.compat&&Hs(n.indent,y,i),t.atKey=!1,Qa(t,a.items,k)&&i(w,"DUPLICATE_KEY","Map keys must be unique");let v=ur(h!=null?h:[],{indicator:"map-value-ind",next:m,offset:k.range[2],onError:i,parentIndent:n.indent,startOnNewline:!y||y.type==="block-scalar"});if(c=v.end,v.found){_&&((m==null?void 0:m.type)==="block-map"&&!v.hasNewline&&i(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),t.options.strict&&g.startr&&(r.type==="block-map"||r.type==="block-seq");function Xb({composeNode:r,composeEmptyNode:e},t,n,i,s){var m,g,_;let o=n.start.source==="{",a=o?"flow map":"flow sequence",c=(m=s==null?void 0:s.nodeClass)!=null?m:o?Pe:Ke,l=new c(t.schema);l.flow=!0;let d=t.atRoot;d&&(t.atRoot=!1),t.atKey&&(t.atKey=!1);let u=n.offset+n.start.source.length;for(let w=0;w0){let w=fr(y,h,t.options.strict,i);w.comment&&(l.comment?l.comment+=` -`+w.comment:l.comment=w.comment),l.range=[n.offset,h,w.offset]}else l.range=[n.offset,h,h];return l}function $f(r,e,t,n,i,s){let o=t.type==="block-map"?Jb(r,e,t,n,s):t.type==="block-seq"?Yb(r,e,t,n,s):Xb(r,e,t,n,s),a=o.constructor;return i==="!"||i===a.tagName?(o.tag=a.tagName,o):(i&&(o.tag=i),o)}function Qb(r,e,t,n,i){var f,p,y;let s=n.tag,o=s?e.directives.tagName(s.source,h=>i(s,"TAG_RESOLVE_FAILED",h)):null;if(t.type==="block-seq"){let{anchor:h,newlineAfterProp:m}=n,g=h&&s?h.offset>s.offset?h:s:h!=null?h:s;g&&(!m||m.offseth.tag===o&&h.collection===a);if(!c){let h=e.schema.knownTags[o];if((h==null?void 0:h.collection)===a)e.schema.tags.push(Object.assign({},h,{default:!1})),c=h;else return h?i(s,"BAD_COLLECTION_TYPE",`${h.tag} used for ${a} collection, but expects ${(f=h.collection)!=null?f:"scalar"}`,!0):i(s,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),$f(r,e,t,i,o)}let l=$f(r,e,t,i,o,c),d=(y=(p=c.resolve)==null?void 0:p.call(c,l,h=>i(s,"TAG_RESOLVE_FAILED",h),e.options))!=null?y:l,u=se(d)?d:new q(d);return u.range=l.range,u.tag=o,c!=null&&c.format&&(u.format=c.format),u}function Sf(r,e,t){let n=e.offset,i=XR(e,r.options.strict,t);if(!i)return{value:"",type:null,comment:"",range:[n,n,n]};let s=i.mode===">"?q.BLOCK_FOLDED:q.BLOCK_LITERAL,o=e.source?QR(e.source):[],a=o.length;for(let h=o.length-1;h>=0;--h){let m=o[h][1];if(m===""||m==="\r")a=h;else break}if(a===0){let h=i.chomp==="+"&&o.length>0?` +`}};function dr(r,{flow:e,indicator:t,next:n,offset:i,onError:s,parentIndent:o,startOnNewline:a}){let c=!1,l=a,d=a,u="",f="",p=!1,y=!1,h=null,m=null,g=null,_=null,w=null,x=null,v=null;for(let $ of r)switch(y&&($.type!=="space"&&$.type!=="newline"&&$.type!=="comma"&&s($.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),y=!1),h&&(l&&$.type!=="comment"&&$.type!=="newline"&&s(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),h=null),$.type){case"space":!e&&(t!=="doc-start"||(n==null?void 0:n.type)!=="flow-collection")&&$.source.includes(" ")&&(h=$),d=!0;break;case"comment":{d||s($,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let R=$.source.substring(1)||" ";u?u+=f+R:u=R,f="",l=!1;break}case"newline":l?u?u+=$.source:(!x||t!=="seq-item-ind")&&(c=!0):f+=$.source,l=!0,p=!0,(m||g)&&(_=$),d=!0;break;case"anchor":m&&s($,"MULTIPLE_ANCHORS","A node can have at most one anchor"),$.source.endsWith(":")&&s($.offset+$.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),m=$,v!=null||(v=$.offset),l=!1,d=!1,y=!0;break;case"tag":{g&&s($,"MULTIPLE_TAGS","A node can have at most one tag"),g=$,v!=null||(v=$.offset),l=!1,d=!1,y=!0;break}case t:(m||g)&&s($,"BAD_PROP_ORDER",`Anchors and tags must be after the ${$.source} indicator`),x&&s($,"UNEXPECTED_TOKEN",`Unexpected ${$.source} in ${e!=null?e:"collection"}`),x=$,l=t==="seq-item-ind"||t==="explicit-key-ind",d=!1;break;case"comma":if(e){w&&s($,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),w=$,l=!1,d=!1;break}default:s($,"UNEXPECTED_TOKEN",`Unexpected ${$.type} token`),l=!1,d=!1}let P=r[r.length-1],O=P?P.offset+P.source.length:i;return y&&n&&n.type!=="space"&&n.type!=="newline"&&n.type!=="comma"&&(n.type!=="scalar"||n.source!=="")&&s(n.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),h&&(l&&h.indent<=o||(n==null?void 0:n.type)==="block-map"||(n==null?void 0:n.type)==="block-seq")&&s(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:w,found:x,spaceBefore:c,comment:u,hasNewline:p,anchor:m,tag:g,newlineAfterProp:_,end:O,start:v!=null?v:O}}function nn(r){if(!r)return null;switch(r.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(r.source.includes(` +`))return!0;if(r.end){for(let e of r.end)if(e.type==="newline")return!0}return!1;case"flow-collection":for(let e of r.items){for(let t of e.start)if(t.type==="newline")return!0;if(e.sep){for(let t of e.sep)if(t.type==="newline")return!0}if(nn(e.key)||nn(e.value))return!0}return!1;default:return!0}}function Ks(r,e,t){if((e==null?void 0:e.type)==="flow-collection"){let n=e.end[0];n.indent===r&&(n.source==="]"||n.source==="}")&&nn(e)&&t(n,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}function Za(r,e,t){let{uniqueKeys:n}=r.options;if(n===!1)return!1;let i=typeof n=="function"?n:(s,o)=>s===o||G(s)&&G(o)&&s.value===o.value;return e.some(s=>i(s.key,t))}var Wb="All mapping items must start at the same column";function Gb({composeNode:r,composeEmptyNode:e},t,n,i,s){var d,u;let o=(d=s==null?void 0:s.nodeClass)!=null?d:xe,a=new o(t.schema);t.atRoot&&(t.atRoot=!1);let c=n.offset,l=null;for(let f of n.items){let{start:p,key:y,sep:h,value:m}=f,g=dr(p,{indicator:"explicit-key-ind",next:y!=null?y:h==null?void 0:h[0],offset:c,onError:i,parentIndent:n.indent,startOnNewline:!0}),_=!g.found;if(_){if(y&&(y.type==="block-seq"?i(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in y&&y.indent!==n.indent&&i(c,"BAD_INDENT",Wb)),!g.anchor&&!g.tag&&!h){l=g.end,g.comment&&(a.comment?a.comment+=` +`+g.comment:a.comment=g.comment);continue}(g.newlineAfterProp||nn(y))&&i(y!=null?y:p[p.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else((u=g.found)==null?void 0:u.indent)!==n.indent&&i(c,"BAD_INDENT",Wb);t.atKey=!0;let w=g.end,x=y?r(t,y,g,i):e(t,w,p,null,g,i);t.schema.compat&&Ks(n.indent,y,i),t.atKey=!1,Za(t,a.items,x)&&i(w,"DUPLICATE_KEY","Map keys must be unique");let v=dr(h!=null?h:[],{indicator:"map-value-ind",next:m,offset:x.range[2],onError:i,parentIndent:n.indent,startOnNewline:!y||y.type==="block-scalar"});if(c=v.end,v.found){_&&((m==null?void 0:m.type)==="block-map"&&!v.hasNewline&&i(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),t.options.strict&&g.startr&&(r.type==="block-map"||r.type==="block-seq");function Yb({composeNode:r,composeEmptyNode:e},t,n,i,s){var m,g,_;let o=n.start.source==="{",a=o?"flow map":"flow sequence",c=(m=s==null?void 0:s.nodeClass)!=null?m:o?xe:He,l=new c(t.schema);l.flow=!0;let d=t.atRoot;d&&(t.atRoot=!1),t.atKey&&(t.atKey=!1);let u=n.offset+n.start.source.length;for(let w=0;w0){let w=ur(y,h,t.options.strict,i);w.comment&&(l.comment?l.comment+=` +`+w.comment:l.comment=w.comment),l.range=[n.offset,h,w.offset]}else l.range=[n.offset,h,h];return l}function $f(r,e,t,n,i,s){let o=t.type==="block-map"?Gb(r,e,t,n,s):t.type==="block-seq"?Jb(r,e,t,n,s):Yb(r,e,t,n,s),a=o.constructor;return i==="!"||i===a.tagName?(o.tag=a.tagName,o):(i&&(o.tag=i),o)}function Xb(r,e,t,n,i){var f,p,y;let s=n.tag,o=s?e.directives.tagName(s.source,h=>i(s,"TAG_RESOLVE_FAILED",h)):null;if(t.type==="block-seq"){let{anchor:h,newlineAfterProp:m}=n,g=h&&s?h.offset>s.offset?h:s:h!=null?h:s;g&&(!m||m.offseth.tag===o&&h.collection===a);if(!c){let h=e.schema.knownTags[o];if((h==null?void 0:h.collection)===a)e.schema.tags.push(Object.assign({},h,{default:!1})),c=h;else return h?i(s,"BAD_COLLECTION_TYPE",`${h.tag} used for ${a} collection, but expects ${(f=h.collection)!=null?f:"scalar"}`,!0):i(s,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),$f(r,e,t,i,o)}let l=$f(r,e,t,i,o,c),d=(y=(p=c.resolve)==null?void 0:p.call(c,l,h=>i(s,"TAG_RESOLVE_FAILED",h),e.options))!=null?y:l,u=se(d)?d:new q(d);return u.range=l.range,u.tag=o,c!=null&&c.format&&(u.format=c.format),u}function Sf(r,e,t){let n=e.offset,i=KR(e,r.options.strict,t);if(!i)return{value:"",type:null,comment:"",range:[n,n,n]};let s=i.mode===">"?q.BLOCK_FOLDED:q.BLOCK_LITERAL,o=e.source?WR(e.source):[],a=o.length;for(let h=o.length-1;h>=0;--h){let m=o[h][1];if(m===""||m==="\r")a=h;else break}if(a===0){let h=i.chomp==="+"&&o.length>0?` `.repeat(Math.max(1,o.length-1)):"",m=n+i.length;return e.source&&(m+=e.source.length),{value:h,type:s,comment:i.comment,range:[n,m,m]}}let c=e.indent+i.indent,l=e.offset+i.length,d=0;for(let h=0;hc&&(c=m.length);else{m.length=a;--h)o[h][0].length>c&&(a=h+1);let u="",f="",p=!1;for(let h=0;hc||g[0]===" "?(f===" "?f=` `:!p&&f===` `&&(f=` @@ -105,74 +105,74 @@ ${l} `+o[h][0].slice(c);u[u.length-1]!==` `&&(u+=` `);break;default:u+=` -`}let y=n+i.length+e.source.length;return{value:u,type:s,comment:i.comment,range:[n,y,y]}}function XR({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,y);switch(i){case"scalar":a=q.PLAIN,c=ZR(s,l);break;case"single-quoted-scalar":a=q.QUOTE_SINGLE,c=eT(s,l);break;case"double-quoted-scalar":a=q.QUOTE_DOUBLE,c=tT(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 d=n+s.length,u=fr(o,d,e,t);return{value:c,type:a,comment:u.comment,range:[n,d,u.offset]}}function ZR(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}`),Zb(r)}function eT(r,e){return(r[r.length-1]!=="'"||r.length===1)&&e(r.length,"MISSING_CHAR","Missing closing 'quote"),Zb(r.slice(1,-1)).replace(/''/g,"'")}function Zb(r){var c;let e,t;try{e=new RegExp(`(.*?)(?t(n+f,p,y);switch(i){case"scalar":a=q.PLAIN,c=GR(s,l);break;case"single-quoted-scalar":a=q.QUOTE_SINGLE,c=JR(s,l);break;case"double-quoted-scalar":a=q.QUOTE_DOUBLE,c=YR(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 d=n+s.length,u=ur(o,d,e,t);return{value:c,type:a,comment:u.comment,range:[n,d,u.offset]}}function GR(r,e){let t="";switch(r[0]){case" ":t="a tab character";break;case",":t="flow indicator character ,";break;case"%":t="directive indicator character %";break;case"|":case">":{t=`block scalar indicator ${r[0]}`;break}case"@":case"`":{t=`reserved character ${r[0]}`;break}}return t&&e(0,"BAD_SCALAR_START",`Plain value cannot start with ${t}`),Qb(r)}function JR(r,e){return(r[r.length-1]!=="'"||r.length===1)&&e(r.length,"MISSING_CHAR","Missing closing 'quote"),Qb(r.slice(1,-1)).replace(/''/g,"'")}function Qb(r){var c;let e,t;try{e=new RegExp(`(.*?)(?s?r.slice(s,n+1):i)}else t+=i}return(r[r.length-1]!=='"'||r.length===1)&&e(r.length,"MISSING_CHAR",'Missing closing "quote'),t}function rT(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 XR(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 nT={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:` -`,r:"\r",t:" ",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function iT(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(a){let c=r.substr(e-2,t+2);return n(e-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${c}`),c}}function Af(r,e,t,n){let{value:i,type:s,comment:o,range:a}=e.type==="block-scalar"?Sf(r,e,n):Ef(e,r.options.strict,n),c=t?r.directives.tagName(t.source,u=>n(t,"TAG_RESOLVE_FAILED",u)):null,l;r.options.stringKeys&&r.atKey?l=r.schema[gt]:c?l=sT(r.schema,i,c,t,n):e.type==="scalar"?l=oT(r,i,e,n):l=r.schema[gt];let d;try{let u=l.resolve(i,f=>n(t!=null?t:e,"TAG_RESOLVE_FAILED",f),r.options);d=G(u)?u:new q(u)}catch(u){let f=u instanceof Error?u.message:String(u);n(t!=null?t:e,"TAG_RESOLVE_FAILED",f),d=new q(i)}return d.range=a,d.source=i,s&&(d.type=s),c&&(d.tag=c),l.format&&(d.format=l.format),o&&(d.comment=o),d}function sT(r,e,t,n,i){var a;if(t==="!")return r[gt];let s=[];for(let c of r.tags)if(!c.collection&&c.tag===t)if(c.default&&c.test)s.push(c);else return c;for(let c of s)if((a=c.test)!=null&&a.test(e))return c;let o=r.knownTags[t];return o&&!o.collection?(r.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(i(n,"TAG_RESOLVE_FAILED",`Unresolved tag: ${t}`,t!=="tag:yaml.org,2002:str"),r[gt])}function oT({atKey:r,directives:e,schema:t},n,i,s){var a;let o=t.tags.find(c=>{var l;return(c.default===!0||r&&c.default==="key")&&((l=c.test)==null?void 0:l.test(n))})||t[gt];if(t.compat){let c=(a=t.compat.find(l=>{var d;return l.default&&((d=l.test)==null?void 0:d.test(n))}))!=null?a:t[gt];if(o.tag!==c.tag){let l=e.tagString(o.tag),d=e.tagString(c.tag),u=`Value may be parsed as either ${l} or ${d}`;s(i,"TAG_RESOLVE_FAILED",u,!0)}}return o}function ew(r,e,t){if(e){t!=null||(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==null?void 0:i.type)==="space";)r+=i.source.length,i=e[++n];break}}return r}var aT={composeNode:xf,composeEmptyNode:Za};function xf(r,e,t,n){let i=r.atKey,{spaceBefore:s,comment:o,anchor:a,tag:c}=t,l,d=!0;switch(e.type){case"alias":l=cT(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=Af(r,e,c,n),a&&(l.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=Qb(aT,r,e,t,n),a&&(l.anchor=a.source.substring(1))}catch(u){let f=u instanceof Error?u.message:String(u);n(e,"RESOURCE_EXHAUSTION",f)}break;default:{let u=e.type==="error"?e.message:`Unsupported token (type: ${e.type})`;n(e,"UNEXPECTED_TOKEN",u),d=!1}}return l!=null||(l=Za(r,e.offset,void 0,null,t,n)),a&&l.anchor===""&&n(a,"BAD_ALIAS","Anchor cannot be an empty string"),i&&r.options.stringKeys&&(!G(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&n(c!=null?c:e,"NON_STRING_KEY","With stringKeys, all keys must be strings"),s&&(l.spaceBefore=!0),o&&(e.type==="scalar"&&e.source===""?l.comment=o:l.commentBefore=o),r.options.keepSourceTokens&&d&&(l.srcToken=e),l}function Za(r,e,t,n,{spaceBefore:i,comment:s,anchor:o,tag:a,end:c},l){let d={type:"scalar",offset:ew(e,t,n),indent:-1,source:""},u=Af(r,d,a,l);return o&&(u.anchor=o.source.substring(1),u.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),i&&(u.spaceBefore=!0),s&&(u.comment=s,u.range[2]=c),u}function cT({options:r},{offset:e,source:t,end:n},i){let s=new Sr(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=fr(n,o,r.strict,i);return s.range=[e,o,a.offset],a.comment&&(s.comment=a.comment),s}function tw(r,e,{offset:t,start:n,value:i,end:s},o){let a=Object.assign({_directives:e},r),c=new en(void 0,a),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},d=ur(n,{indicator:"doc-start",next:i!=null?i:s==null?void 0:s[0],offset:t,onError:o,parentIndent:0,startOnNewline:!0});d.found&&(c.directives.docStart=!0,i&&(i.type==="block-map"||i.type==="block-seq")&&!d.hasNewline&&o(d.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=i?xf(l,i,d,o):Za(l,d.end,n,null,d,o);let u=c.contents.range[2],f=fr(s,u,!1,o);return f.comment&&(c.comment=f.comment),c.range=[t,u,f.offset],c}function Ks(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 rw(r){var i;let e="",t=!1,n=!1;for(let s=0;sn(t,"TAG_RESOLVE_FAILED",u)):null,l;r.options.stringKeys&&r.atKey?l=r.schema[yt]:c?l=eT(r.schema,i,c,t,n):e.type==="scalar"?l=tT(r,i,e,n):l=r.schema[yt];let d;try{let u=l.resolve(i,f=>n(t!=null?t:e,"TAG_RESOLVE_FAILED",f),r.options);d=G(u)?u:new q(u)}catch(u){let f=u instanceof Error?u.message:String(u);n(t!=null?t:e,"TAG_RESOLVE_FAILED",f),d=new q(i)}return d.range=a,d.source=i,s&&(d.type=s),c&&(d.tag=c),l.format&&(d.format=l.format),o&&(d.comment=o),d}function eT(r,e,t,n,i){var a;if(t==="!")return r[yt];let s=[];for(let c of r.tags)if(!c.collection&&c.tag===t)if(c.default&&c.test)s.push(c);else return c;for(let c of s)if((a=c.test)!=null&&a.test(e))return c;let o=r.knownTags[t];return o&&!o.collection?(r.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(i(n,"TAG_RESOLVE_FAILED",`Unresolved tag: ${t}`,t!=="tag:yaml.org,2002:str"),r[yt])}function tT({atKey:r,directives:e,schema:t},n,i,s){var a;let o=t.tags.find(c=>{var l;return(c.default===!0||r&&c.default==="key")&&((l=c.test)==null?void 0:l.test(n))})||t[yt];if(t.compat){let c=(a=t.compat.find(l=>{var d;return l.default&&((d=l.test)==null?void 0:d.test(n))}))!=null?a:t[yt];if(o.tag!==c.tag){let l=e.tagString(o.tag),d=e.tagString(c.tag),u=`Value may be parsed as either ${l} or ${d}`;s(i,"TAG_RESOLVE_FAILED",u,!0)}}return o}function Zb(r,e,t){if(e){t!=null||(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==null?void 0:i.type)==="space";)r+=i.source.length,i=e[++n];break}}return r}var rT={composeNode:kf,composeEmptyNode:ec};function kf(r,e,t,n){let i=r.atKey,{spaceBefore:s,comment:o,anchor:a,tag:c}=t,l,d=!0;switch(e.type){case"alias":l=nT(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=Af(r,e,c,n),a&&(l.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=Xb(rT,r,e,t,n),a&&(l.anchor=a.source.substring(1))}catch(u){let f=u instanceof Error?u.message:String(u);n(e,"RESOURCE_EXHAUSTION",f)}break;default:{let u=e.type==="error"?e.message:`Unsupported token (type: ${e.type})`;n(e,"UNEXPECTED_TOKEN",u),d=!1}}return l!=null||(l=ec(r,e.offset,void 0,null,t,n)),a&&l.anchor===""&&n(a,"BAD_ALIAS","Anchor cannot be an empty string"),i&&r.options.stringKeys&&(!G(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&n(c!=null?c:e,"NON_STRING_KEY","With stringKeys, all keys must be strings"),s&&(l.spaceBefore=!0),o&&(e.type==="scalar"&&e.source===""?l.comment=o:l.commentBefore=o),r.options.keepSourceTokens&&d&&(l.srcToken=e),l}function ec(r,e,t,n,{spaceBefore:i,comment:s,anchor:o,tag:a,end:c},l){let d={type:"scalar",offset:Zb(e,t,n),indent:-1,source:""},u=Af(r,d,a,l);return o&&(u.anchor=o.source.substring(1),u.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),i&&(u.spaceBefore=!0),s&&(u.comment=s,u.range[2]=c),u}function nT({options:r},{offset:e,source:t,end:n},i){let s=new Sr(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=ur(n,o,r.strict,i);return s.range=[e,o,a.offset],a.comment&&(s.comment=a.comment),s}function ew(r,e,{offset:t,start:n,value:i,end:s},o){let a=Object.assign({_directives:e},r),c=new rn(void 0,a),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},d=dr(n,{indicator:"doc-start",next:i!=null?i:s==null?void 0:s[0],offset:t,onError:o,parentIndent:0,startOnNewline:!0});d.found&&(c.directives.docStart=!0,i&&(i.type==="block-map"||i.type==="block-seq")&&!d.hasNewline&&o(d.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=i?kf(l,i,d,o):ec(l,d.end,n,null,d,o);let u=c.contents.range[2],f=ur(s,u,!1,o);return f.comment&&(c.comment=f.comment),c.range=[t,u,f.offset],c}function Ws(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 tw(r){var i;let e="",t=!1,n=!1;for(let s=0;s{let o=Ks(t);s?this.warnings.push(new zs(o,n,i)):this.errors.push(new Ht(o,n,i))},this.directives=new lr({version:e.version||"1.2"}),this.options=e}decorate(e,t){let{comment:n,afterEmptyLine:i}=rw(this.prelude);if(n){let s=e.contents;if(t)e.comment=e.comment?`${e.comment} +`)+(o.substring(1)||" "),t=!0,n=!1;break;case"%":((i=r[s+1])==null?void 0:i[0])!=="#"&&(s+=1),t=!1;break;default:t||(n=!0),t=!1}}return{comment:e,afterEmptyLine:n}}var Gs=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(t,n,i,s)=>{let o=Ws(t);s?this.warnings.push(new Hs(o,n,i)):this.errors.push(new zt(o,n,i))},this.directives=new cr({version:e.version||"1.2"}),this.options=e}decorate(e,t){let{comment:n,afterEmptyLine:i}=tw(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(le(s)&&!s.flow&&s.items.length>0){let o=s.items[0];ne(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=Ks(e);s[0]+=t,this.onError(s,"BAD_DIRECTIVE",n,i)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{let t=tw(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 Ht(Ks(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 Ht(Ks(e),"UNEXPECTED_TOKEN",n));break}this.doc.directives.docEnd=!0;let t=fr(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 Ht(Ks(e),"UNEXPECTED_TOKEN",`Unsupported token ${e.type}`))}}*end(e=!1,t=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){let n=Object.assign({_directives:this.directives},this.options),i=new en(void 0,n);this.atDirectives&&this.onError(t,"MISSING_CHAR","Missing directives-end indicator line"),i.range=[0,t,t],this.decorate(i,!1),yield i}}};var kf=Symbol("break visit"),lT=Symbol("skip children"),nw=Symbol("remove item");function xn(r,e){"type"in r&&r.type==="document"&&(r={start:r.start,value:r.value}),iw(Object.freeze([]),r,e)}xn.BREAK=kf;xn.SKIP=lT;xn.REMOVE=nw;xn.itemAtPath=(r,e)=>{let t=r;for(let[n,i]of e){let s=t==null?void 0:t[n];if(s&&"items"in s)t=s.items[i];else return}return t};xn.parentCollection=(r,e)=>{let t=xn.itemAtPath(r,e.slice(0,-1)),n=e[e.length-1][0],i=t==null?void 0:t[n];if(i&&"items"in i)return i;throw new Error("Parent collection not found")};function iw(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 s=Ws(e);s[0]+=t,this.onError(s,"BAD_DIRECTIVE",n,i)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{let t=ew(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 zt(Ws(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 zt(Ws(e),"UNEXPECTED_TOKEN",n));break}this.doc.directives.docEnd=!0;let t=ur(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 zt(Ws(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 rn(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 xf=Symbol("break visit"),iT=Symbol("skip children"),rw=Symbol("remove item");function Pn(r,e){"type"in r&&r.type==="document"&&(r={start:r.start,value:r.value}),nw(Object.freeze([]),r,e)}Pn.BREAK=xf;Pn.SKIP=iT;Pn.REMOVE=rw;Pn.itemAtPath=(r,e)=>{let t=r;for(let[n,i]of e){let s=t==null?void 0:t[n];if(s&&"items"in s)t=s.items[i];else return}return t};Pn.parentCollection=(r,e)=>{let t=Pn.itemAtPath(r,e.slice(0,-1)),n=e[e.length-1][0],i=t==null?void 0:t[n];if(i&&"items"in i)return i;throw new Error("Parent collection not found")};function nw(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 Kt(r){switch(r){case void 0:case" ":case` -`:case"\r":case" ":return!0;default:return!1}}var ow=new Set("0123456789ABCDEFabcdef"),uT=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),tc=new Set(",[]{}"),fT=new Set(` ,[]{} -\r `),Rf=r=>!r||fT.has(r),Gs=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,t=!1){var i;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=(i=this.next)!=null?i:"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===` +`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(r[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}function Ht(r){switch(r){case void 0:case" ":case` +`:case"\r":case" ":return!0;default:return!1}}var sw=new Set("0123456789ABCDEFabcdef"),oT=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),rc=new Set(",[]{}"),aT=new Set(` ,[]{} +\r `),Rf=r=>!r||aT.has(r),Js=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,t=!1){var i;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=(i=this.next)!=null?i:"stream";for(;n&&(t||this.hasChars(1));)n=yield*this.parseNext(n)}atLineEnd(){let e=this.pos,t=this.buffer[e];for(;t===" "||t===" ";)t=this.buffer[++e];return!t||t==="#"||t===` `?!0:t==="\r"?this.buffer[e+1]===` `:!1}charAt(e){return this.buffer[this.pos+e]}continueScalar(e){let t=this.buffer[e];if(this.indentNext>0){let n=0;for(;t===" ";)t=this.buffer[++n+e];if(t==="\r"){let i=this.buffer[n+e+1];if(i===` `||!i&&!this.atEnd)return e+n+1}return t===` -`||n>=this.indentNext||!t&&!this.atEnd?e+n:-1}if(t==="-"||t==="."){let n=this.buffer.substr(e,3);if((n==="---"||n==="...")&&Kt(this.buffer[e+3]))return-1}return e}getLine(){let e=this.lineEndPos;return(typeof e!="number"||e!==-1&&ethis.indentValue&&!Kt(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[e,t]=this.peek(2);if(!t&&!this.atEnd)return this.setNext("block-start");if((e==="-"||e==="?"||e===":")&&Kt(t)){let n=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=n,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let e=this.getLine();if(e===null)return this.setNext("doc");let t=yield*this.pushIndicators();switch(e[t]){case"#":yield*this.pushCount(e.length-t);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(Rf),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return t+=yield*this.parseBlockScalarHeader(),t+=yield*this.pushSpaces(!0),yield*this.pushCount(e.length-t),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let e,t,n=-1;do e=yield*this.pushNewline(),e>0?(t=yield*this.pushSpaces(!1),this.indentValue=n=t):t=0,t+=yield*this.pushSpaces(!0);while(e+t>0);let i=this.getLine();if(i===null)return this.setNext("flow");if((n!==-1&&n=this.indentNext||!t&&!this.atEnd?e+n:-1}if(t==="-"||t==="."){let n=this.buffer.substr(e,3);if((n==="---"||n==="...")&&Ht(this.buffer[e+3]))return-1}return e}getLine(){let e=this.lineEndPos;return(typeof e!="number"||e!==-1&&ethis.indentValue&&!Ht(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[e,t]=this.peek(2);if(!t&&!this.atEnd)return this.setNext("block-start");if((e==="-"||e==="?"||e===":")&&Ht(t)){let n=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=n,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let e=this.getLine();if(e===null)return this.setNext("doc");let t=yield*this.pushIndicators();switch(e[t]){case"#":yield*this.pushCount(e.length-t);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(Rf),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return t+=yield*this.parseBlockScalarHeader(),t+=yield*this.pushSpaces(!0),yield*this.pushCount(e.length-t),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let e,t,n=-1;do e=yield*this.pushNewline(),e>0?(t=yield*this.pushSpaces(!1),this.indentValue=n=t):t=0,t+=yield*this.pushSpaces(!0);while(e+t>0);let i=this.getLine();if(i===null)return this.setNext("flow");if((n!==-1&&n"0"&&t<="9")this.blockScalarIndent=Number(t)-1;else if(t!=="-")break}return yield*this.pushUntil(t=>Kt(t)||t==="#")}*parseBlockScalar(){let e=this.pos-1,t=0,n;e:for(let s=this.pos;n=this.buffer[s];++s)switch(n){case" ":t+=1;break;case` +`,s)}i!==-1&&(t=i-(n[i-1]==="\r"?2:1))}if(t===-1){if(!this.atEnd)return this.setNext("quoted-scalar");t=this.buffer.length}return yield*this.pushToIndex(t+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let e=this.pos;for(;;){let t=this.buffer[++e];if(t==="+")this.blockScalarKeep=!0;else if(t>"0"&&t<="9")this.blockScalarIndent=Number(t)-1;else if(t!=="-")break}return yield*this.pushUntil(t=>Ht(t)||t==="#")}*parseBlockScalar(){let e=this.pos-1,t=0,n;e:for(let s=this.pos;n=this.buffer[s];++s)switch(n){case" ":t+=1;break;case` `:e=s,t=0;break;case"\r":{let o=this.buffer[s+1];if(!o&&!this.atEnd)return this.setNext("block-scalar");if(o===` `)break}default:break e}if(!n&&!this.atEnd)return this.setNext("block-scalar");if(t>=this.indentNext){this.blockScalarIndent===-1?this.indentNext=t:this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let s=this.continueScalar(e+1);if(s===-1)break;e=this.buffer.indexOf(` `,s)}while(e!==-1);if(e===-1){if(!this.atEnd)return this.setNext("block-scalar");e=this.buffer.length}}let i=e+1;for(n=this.buffer[i];n===" ";)n=this.buffer[++i];if(n===" "){for(;n===" "||n===" "||n==="\r"||n===` `;)n=this.buffer[++i];e=i-1}else if(!this.blockScalarKeep)do{let s=e-1,o=this.buffer[s];o==="\r"&&(o=this.buffer[--s]);let a=s;for(;o===" ";)o=this.buffer[--s];if(o===` -`&&s>=this.pos&&s+1+t>a)e=s;else break}while(!0);return yield ec,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(Kt(s)||e&&tc.has(s))break;t=n}else if(Kt(i)){let s=this.buffer[n+1];if(i==="\r"&&(s===` +`&&s>=this.pos&&s+1+t>a)e=s;else break}while(!0);return yield tc,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(Ht(s)||e&&rc.has(s))break;t=n}else if(Ht(i)){let s=this.buffer[n+1];if(i==="\r"&&(s===` `?(n+=1,i=` -`,s=this.buffer[n+1]):t=n),s==="#"||e&&tc.has(s))break;if(i===` -`){let o=this.continueScalar(n+1);if(o===-1)break;n=Math.max(n,o-2)}}else{if(e&&tc.has(i))break;t=n}return!i&&!this.atEnd?this.setNext("plain-scalar"):(yield ec,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(Rf),e+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let t=this.flowLevel>0,n=this.charAt(1);if(Kt(n)||t&&tc.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(;!Kt(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(uT.has(t))t=this.buffer[++e];else if(t==="%"&&ow.has(this.buffer[e+1])&&ow.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===` +`,s=this.buffer[n+1]):t=n),s==="#"||e&&rc.has(s))break;if(i===` +`){let o=this.continueScalar(n+1);if(o===-1)break;n=Math.max(n,o-2)}}else{if(e&&rc.has(i))break;t=n}return!i&&!this.atEnd?this.setNext("plain-scalar"):(yield tc,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(Rf),e+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let t=this.flowLevel>0,n=this.charAt(1);if(Ht(n)||t&&rc.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(;!Ht(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(oT.has(t))t=this.buffer[++e];else if(t==="%"&&sw.has(this.buffer[e+1])&&sw.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 Js=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(;((t=r[++e])==null?void 0:t.type)==="space";);return r.splice(e,r.length)}function nc(r,e){if(e.length<1e5)Array.prototype.push.apply(r,e);else for(let t=0;t0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let e=this.peek(1);if(this.type==="doc-end"&&(e==null?void 0:e.type)!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!e)return yield*this.stream();switch(e.type){case"document":return yield*this.document(e);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(e);case"block-scalar":return yield*this.blockScalar(e);case"block-map":return yield*this.blockMap(e);case"block-seq":return yield*this.blockSequence(e);case"flow-collection":return yield*this.flowCollection(e);case"doc-end":return yield*this.documentEnd(e)}yield*this.pop()}peek(e){return this.stack[this.stack.length-e]}*pop(e){let t=e!=null?e:this.stack.pop();if(!t)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield t;else{let n=this.peek(1);switch(t.type==="block-scalar"?t.indent="indent"in n?n.indent:0:t.type==="flow-collection"&&n.type==="document"&&(t.indent=0),t.type==="flow-collection"&&cw(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&&aw(i.start)===-1&&(t.indent===0||i.start.every(s=>s.type!=="comment"||s.indent0&&(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 Ys=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(;((t=r[++e])==null?void 0:t.type)==="space";);return r.splice(e,r.length)}function ic(r,e){if(e.length<1e5)Array.prototype.push.apply(r,e);else for(let t=0;t0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let e=this.peek(1);if(this.type==="doc-end"&&(e==null?void 0:e.type)!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!e)return yield*this.stream();switch(e.type){case"document":return yield*this.document(e);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(e);case"block-scalar":return yield*this.blockScalar(e);case"block-map":return yield*this.blockMap(e);case"block-seq":return yield*this.blockSequence(e);case"flow-collection":return yield*this.flowCollection(e);case"doc-end":return yield*this.documentEnd(e)}yield*this.pop()}peek(e){return this.stack[this.stack.length-e]}*pop(e){let t=e!=null?e:this.stack.pop();if(!t)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield t;else{let n=this.peek(1);switch(t.type==="block-scalar"?t.indent="indent"in n?n.indent:0:t.type==="flow-collection"&&n.type==="document"&&(t.indent=0),t.type==="flow-collection"&&aw(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&&ow(i.start)===-1&&(t.indent===0||i.start.every(s=>s.type!=="comment"||s.indent=e.indent){let i=!this.onKeyLine&&this.indent===e.indent,s=i&&(t.sep||t.explicitKey)&&this.type!=="seq-item-ind",o=[];if(s&&t.sep&&!t.value){let a=[];for(let c=0;ce.indent&&(a.length=0);break;default:a.length=0}}a.length>=2&&(o=t.sep.splice(a[1]))}switch(this.type){case"anchor":case"tag":s||t.value?(o.push(this.sourceToken),e.items.push({start:o}),this.onKeyLine=!0):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"explicit-key-ind":!t.sep&&!t.explicitKey?(t.start.push(this.sourceToken),t.explicitKey=!0):s||t.value?(o.push(this.sourceToken),e.items.push({start:o,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(t.explicitKey)if(t.sep)if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(rn(t.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]});else if(lw(t.key)&&!rn(t.sep,"newline")){let a=Si(t.start),c=t.key,l=t.sep;l.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:a,key:c,sep:l}]})}else o.length>0?t.sep=t.sep.concat(o,this.sourceToken):t.sep.push(this.sourceToken);else if(rn(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{let a=Si(t.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:a,key:null,sep:[this.sourceToken]}]})}else t.sep?t.value||s?e.items.push({start:o,key:null,sep:[this.sourceToken]}):rn(t.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let a=this.flowScalar(this.type);s||t.value?(e.items.push({start:o,key:a,sep:[]}),this.onKeyLine=!0):t.sep?this.stack.push(a):(Object.assign(t,{key:a,sep:[]}),this.onKeyLine=!0);return}default:{let a=this.startBlockValue(e);if(a){if(a.type==="block-seq"){if(!t.explicitKey&&t.sep&&!rn(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 i&&e.items.push({start:o});this.stack.push(a);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){var n;let t=e.items[e.items.length-1];switch(this.type){case"newline":if(t.value){let i="end"in t.value?t.value.end:void 0,s=Array.isArray(i)?i[i.length-1]:void 0;(s==null?void 0:s.type)==="comment"?i==null||i.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],s=(n=i==null?void 0:i.value)==null?void 0:n.end;if(Array.isArray(s)){nc(s,t.start),s.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return;case"anchor":case"tag":if(t.value||this.indent<=e.indent)break;t.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==e.indent)break;t.value||rn(t.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return}if(this.indent>e.indent){let i=this.startBlockValue(e);if(i){this.stack.push(i);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let t=e.items[e.items.length-1];if(this.type==="flow-error-end"){let n;do yield*this.pop(),n=this.peek(1);while((n==null?void 0:n.type)==="flow-collection")}else if(e.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!t||t.sep?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return;case"map-value-ind":!t||t.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!t||t.value?e.items.push({start:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let 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=rc(n),s=Si(i);cw(e);let o=e.end.splice(1,e.end.length);o.push(this.sourceToken);let a={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:s,key:e,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let t=this.source.indexOf(` +`,t)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){var n;let t=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,t.value){let i="end"in t.value?t.value.end:void 0,s=Array.isArray(i)?i[i.length-1]:void 0;(s==null?void 0:s.type)==="comment"?i==null||i.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else{if(this.atIndentedComment(t.start,e.indent)){let i=e.items[e.items.length-2],s=(n=i==null?void 0:i.value)==null?void 0:n.end;if(Array.isArray(s)){ic(s,t.start),s.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let i=!this.onKeyLine&&this.indent===e.indent,s=i&&(t.sep||t.explicitKey)&&this.type!=="seq-item-ind",o=[];if(s&&t.sep&&!t.value){let a=[];for(let c=0;ce.indent&&(a.length=0);break;default:a.length=0}}a.length>=2&&(o=t.sep.splice(a[1]))}switch(this.type){case"anchor":case"tag":s||t.value?(o.push(this.sourceToken),e.items.push({start:o}),this.onKeyLine=!0):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"explicit-key-ind":!t.sep&&!t.explicitKey?(t.start.push(this.sourceToken),t.explicitKey=!0):s||t.value?(o.push(this.sourceToken),e.items.push({start:o,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(t.explicitKey)if(t.sep)if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(sn(t.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]});else if(cw(t.key)&&!sn(t.sep,"newline")){let a=Ai(t.start),c=t.key,l=t.sep;l.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:a,key:c,sep:l}]})}else o.length>0?t.sep=t.sep.concat(o,this.sourceToken):t.sep.push(this.sourceToken);else if(sn(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{let a=Ai(t.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:a,key:null,sep:[this.sourceToken]}]})}else t.sep?t.value||s?e.items.push({start:o,key:null,sep:[this.sourceToken]}):sn(t.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let a=this.flowScalar(this.type);s||t.value?(e.items.push({start:o,key:a,sep:[]}),this.onKeyLine=!0):t.sep?this.stack.push(a):(Object.assign(t,{key:a,sep:[]}),this.onKeyLine=!0);return}default:{let a=this.startBlockValue(e);if(a){if(a.type==="block-seq"){if(!t.explicitKey&&t.sep&&!sn(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 i&&e.items.push({start:o});this.stack.push(a);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){var n;let t=e.items[e.items.length-1];switch(this.type){case"newline":if(t.value){let i="end"in t.value?t.value.end:void 0,s=Array.isArray(i)?i[i.length-1]:void 0;(s==null?void 0:s.type)==="comment"?i==null||i.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],s=(n=i==null?void 0:i.value)==null?void 0:n.end;if(Array.isArray(s)){ic(s,t.start),s.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return;case"anchor":case"tag":if(t.value||this.indent<=e.indent)break;t.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==e.indent)break;t.value||sn(t.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return}if(this.indent>e.indent){let i=this.startBlockValue(e);if(i){this.stack.push(i);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let t=e.items[e.items.length-1];if(this.type==="flow-error-end"){let n;do yield*this.pop(),n=this.peek(1);while((n==null?void 0:n.type)==="flow-collection")}else if(e.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!t||t.sep?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return;case"map-value-ind":!t||t.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!t||t.value?e.items.push({start:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let 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=nc(n),s=Ai(i);aw(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=rc(e),n=Si(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=rc(e),n=Si(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 pT(r){let e=r.prettyErrors!==!1;return{lineCounter:r.lineCounter||e&&new Js||null,prettyErrors:e}}function dw(r,e={}){let{lineCounter:t,prettyErrors:n}=pT(e),i=new Ys(t==null?void 0:t.addNewLine),s=new Ws(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 Ht(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&t&&(o.errors.forEach(bf(r,t)),o.warnings.forEach(bf(r,t))),o}function Ei(r,e,t){let n;typeof e=="function"?n=e:t===void 0&&e&&typeof e=="object"&&(t=e);let i=dw(r,t);if(!i)return null;if(i.warnings.forEach(s=>Ca(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 yT=r=>r/2**32|0,gT=r=>r>>>0;function uw(r,e,t,n){let i=yT(t),s=gT(t);r.setUint32(e,n?s:i,n),r.setUint32(e+4,n?i:s,n)}function fw(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in r&&r.BYTES_PER_ELEMENT===1}var Tf=r=>r?`"${r}" `:"";function _T(r,e=""){if(typeof r!="number")throw new TypeError(Tf(e)+"expected number, got "+typeof r);if(!Number.isSafeInteger(r)||r<0)throw new RangeError(Tf(e)+"expected integer >= 0, got "+r);return r}function ic(r,e,t=""){if(fw(r)&&(e===void 0||r.length===e))return r;e!==void 0&&_T(e,"length");let n=fw(r),i=e!==void 0?` of length ${e}`:"",s=n?`length=${r.length}`:`type=${typeof r}`,o=Tf(t)+"expected Uint8Array"+i+", got "+s;throw n?new RangeError(o):new TypeError(o)}var pw=(r,e)=>{if(r===null||typeof r!="object"||Array.isArray(r))throw new TypeError((e==="object"?"":`"${e}" `)+"expected object, got type="+typeof r)};function Mf(r,e=!0){if(r.destroyed)throw new Error("hash was destroyed");if(e&&r.finished)throw new Error("digest() was already called")}function hw(r,e){ic(r,void 0,"output");let t=e.outputLen;if(!(r.length>=t))throw new RangeError('"output" expected length >= '+t)}function Ai(...r){for(let e=0;e>>e}function oc(r,e){return r<>>32-e>>>0}var bT=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",wT=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function Le(r){if(ic(r),bT)return r.toHex();let e="";for(let t=0;t='+t)}function on(...r){for(let e=0;e>>e}function ac(r,e){return r<>>32-e>>>0}var fT=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",pT=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function Ne(r){if(sc(r),fT)return r.toHex();let e="";for(let t=0;tr(s).update(i).digest(),n=r(void 0);return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.canXOF=n.canXOF,t.create=i=>r(i),Object.assign(t,e),Object.freeze(t)}var uw=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function lc(r,e,t){return r&e^~r&t}function dc(r,e,t){return r&e^r&t^e&t}var xi=class{constructor(e,t,n,i){I(this,"blockLen");I(this,"outputLen");I(this,"canXOF",!1);I(this,"padOffset");I(this,"isLE");I(this,"buffer");I(this,"view");I(this,"finished",!1);I(this,"length",0);I(this,"pos",0);I(this,"destroyed",!1);this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=i,this.buffer=new Uint8Array(e),this.view=oc(this.buffer)}update(e){Tf(this),sc(e);let{view:t,buffer:n,blockLen:i}=this,s=e.length;for(let o=0;oi-o&&(this.process(n,0),o=0);for(let u=o;ud.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u>>3,h=Kt(p,17)^Kt(p,19)^p>>>10;an[u]=h+an[u-7]+y+an[u-16]|0}let{A:n,B:i,C:s,D:o,E:a,F:c,G:l,H:d}=this;for(let u=0;u<64;u++){let f=Kt(a,6)^Kt(a,11)^Kt(a,25),p=d+f+lc(a,c,l)+hT[u]+an[u]|0,h=(Kt(n,2)^Kt(n,13)^Kt(n,22))+dc(n,i,s)|0;d=l,l=c,c=a,a=o+p|0,o=s,s=i,i=n,n=p+h|0}n=n+this.A|0,i=i+this.B|0,s=s+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,d=d+this.H|0,this.set(n,i,s,o,a,c,l,d)}roundClean(){on(an)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),on(this.buffer)}},Mf=class extends Cf{constructor(){super(32);I(this,"A",kr[0]|0);I(this,"B",kr[1]|0);I(this,"C",kr[2]|0);I(this,"D",kr[3]|0);I(this,"E",kr[4]|0);I(this,"F",kr[5]|0);I(this,"G",kr[6]|0);I(this,"H",kr[7]|0)}};var We=cc(()=>new Mf,uw(1));var b=class extends Error{constructor(t,n){super(n);I(this,"code");this.code=t}};var Pr=new TextEncoder,mT=new Set(["null","true","false"]),xr=Symbol("invalid-json-projection");function yT(r){return Ne(We(Pr.encode(r)))}function pw(r){return`sha256:${yT(r)}`}function uc(r){if(typeof r.document!="string")throw new b("invalid_authority_record",`Authority record ${r.path} omitted its exact Markdown document.`);return r.document}function hw(r,e){let t=0,n=!1;for(let s in e.frontmatter){if(!Object.prototype.hasOwnProperty.call(e.frontmatter,s))continue;if(!n&&(n=!0,t=dt(r,`--- +`,t),t<0))return!1;let o=e.frontmatter[s];if(!/^[A-Za-z_][A-Za-z0-9_-]*$/u.test(s))return null;let a=fw(o);if(a!==null){if(t=dt(r,s,t),t<0||(t=dt(r,": ",t),t<0)||(t=dt(r,a,t),t<0)||(t=dt(r,` +`,t),t<0))return!1;continue}if(!Array.isArray(o))return null;if(o.length===0){if(t=dt(r,s,t),t<0||(t=dt(r,`: [] +`,t),t<0))return!1;continue}if(t=dt(r,s,t),t<0||(t=dt(r,`: +`,t),t<0))return!1;for(let c of o){let l=fw(c);if(l===null)return null;if(t=dt(r," - ",t),t<0||(t=dt(r,l,t),t<0)||(t=dt(r,` +`,t),t<0))return!1}}if(!n)return r===e.body;if(t=dt(r,`--- `,t),t<0)return!1;if(!e.body)return t===r.length;let i=e.body.startsWith(` -`)?e.body.slice(1):e.body;return t=ut(r,` -`,t),t>=0&&r.startsWith(i,t)&&t+i.length===r.length}function uc(r,e){var i;let t=r.match(/^---[ \t]*\r?\n([\s\S]*?)^---[ \t]*(?:\r?\n|$)([\s\S]*)$/m);if(!t)return{frontmatter:{},body:r};let n;try{n=Ei(t[1])}catch(s){return{frontmatter:{},body:r}}return n===null&&t[1].trim()===""&&(n={}),!n||typeof n!="object"||Array.isArray(n)?{frontmatter:{},body:r}:{frontmatter:n,body:(i=t[2])!=null?i:""}}function gw(r){return typeof r=="boolean"||r===null||typeof r=="number"&&Number.isSafeInteger(r)?String(r):typeof r!="string"||!/^[A-Za-z][A-Za-z0-9 _.-]*$/u.test(r)||r.length<=5&&ST.has(r.toLowerCase())?null:r}function ut(r,e,t){return r.startsWith(e,t)?t+e.length:-1}function fc(r){let e=Ge.create().update(xr.encode(`mdbase-authority-manifest-v2 -`));for(let t of[...r].sort((n,i)=>n.kind!==i.kind?n.kinde.type==="file_put"||e.type==="file_remove"))throw new b("file_sync_unsupported","This replica cannot materialize collection file changes yet. Upgrade it before continuing sync.")}function ww(r){xT([r])}Ee();Ee();var J=class extends b{constructor(t,n,i,s){super(t,n);I(this,"status");this.status=i,this.name="AuthorityAdoptionError",(s==null?void 0:s.cause)!==void 0&&(this.cause=s.cause)}},kr=class extends J{constructor(t,n){super("authority_adoption_outcome_unknown",t,void 0,n);I(this,"sourceMustRemainFenced",!0);this.name="AuthorityAdoptionOutcomeUnknownError"}};var ki=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function kn(r,e){if(!ki.test(r))throw new J("invalid_authority_adoption",`${e} must be a UUID.`);return r.toLowerCase()}var Xs=Uint32Array.from([1732584193,4023233417,2562383102,271733878,3285377520]),sn=new Uint32Array(80),jf=class extends xi{constructor(){super(64,20,8,!1);I(this,"A",Xs[0]|0);I(this,"B",Xs[1]|0);I(this,"C",Xs[2]|0);I(this,"D",Xs[3]|0);I(this,"E",Xs[4]|0)}get(){let{A:t,B:n,C:i,D:s,E:o}=this;return[t,n,i,s,o]}set(t,n,i,s,o){this.A=t|0,this.B=n|0,this.C=i|0,this.D=s|0,this.E=o|0}_cloneInto(t){return(t||(t=new this.constructor)).set(...this.get()),this._cloneIntoMeta(t)}process(t,n){for(let l=0;l<16;l++,n+=4)sn[l]=t.getUint32(n,!1);for(let l=16;l<80;l++)sn[l]=oc(sn[l-3]^sn[l-8]^sn[l-14]^sn[l-16],1);let{A:i,B:s,C:o,D:a,E:c}=this;for(let l=0;l<80;l++){let d,u;l<20?(d=cc(s,o,a),u=1518500249):l<40?(d=s^o^a,u=1859775393):l<60?(d=lc(s,o,a),u=2400959708):(d=s^o^a,u=3395469782);let f=oc(i,5)+d+c+u+sn[l]|0;c=a,a=o,o=oc(s,30),s=i,i=f}i=i+this.A|0,s=s+this.B|0,o=o+this.C|0,a=a+this.D|0,c=c+this.E|0,this.set(i,s,o,a,c)}roundClean(){Ai(sn)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0),Ai(this.buffer)}},hc=ac(()=>new jf);var kT=1e4,PT=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,IT=new TextEncoder;async function $w(r,e,t,n,i){var h,m,g;let s=RT(n,t.media_type);if(s.size!==t.size||await TT(s,i.signal)!==t.content_digest)throw new J("authority_adoption_file_changed",`File bytes no longer match the fenced snapshot for ${t.path}.`);let o=MT(e.import_id,t),a=await Df(r,`${e.files_url}/uploads`,e.access_token,{protocol_version:1,type:"open_authority_import_file_upload",transfer_id:o,file_id:t.file_id},i.signal);if(NT(a,o,t.size),a.strategy.kind!=="object_put"&&a.strategy.kind!=="object_multipart")throw ft("Connect returned an incompatible authority import file strategy.");let c=a.strategy.kind==="object_put"?Math.max(1,t.size):a.strategy.part_size,l=a.strategy.kind==="object_put"?1:Math.ceil(t.size/c);if(l>kT)throw ft("Authority import returned too many file parts.");let d=new Set(a.received),u=new Map(((h=a.uploaded_parts)!=null?h:[]).map(_=>[_.part_number-1,_]));if(a.received.length===l&&await vw(r,e,t,o,[...u.values()],i.signal))return;let f=Array(l);for(let[_,w]of u)f[_]=w;let p=[...d].reduce((_,w)=>_+Math.min(c,Math.max(0,t.size-w*c)),0);for(let _=0;__!==void 0);if(!await vw(r,e,t,o,y,i.signal))throw new J("authority_adoption_file_upload_incomplete",`Connect could not commit ${t.path}.`)}async function vw(r,e,t,n,i,s){try{let o=await Df(r,`${e.files_url}/uploads/${encodeURIComponent(n)}/commit`,e.access_token,{protocol_version:1,type:"commit_file_upload",transfer_id:n,...i.length>0?{parts:i}:{}},s);if(o.protocol_version!==1||o.type!=="file_upload_committed"||o.transfer_id!==n||!qT(o.file,t))throw ft("Connect returned an invalid authority import file receipt.");return!0}catch(o){if(i.length===0&&o instanceof J&&o.code==="file_upload_incomplete")return!1;throw o}}async function Df(r,e,t,n,i){let s;try{s=await r({url:e,method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/json"},body:n,...i?{signal:i}:{}})}catch(o){throw mc(i),new J("authority_adoption_unreachable","Connect could not be reached for collection adoption.")}if(s.status<200||s.status>=300)throw FT(s);return s.body}async function OT(r,e,t,n){jT(e.url);let i;try{i=await r({url:e.url,method:"PUT",headers:DT(e.headers),body:t,rawBody:!0,...n?{signal:n}:{}})}catch(s){throw mc(n),new J("authority_adoption_unreachable","Connect could not be reached for collection adoption.")}if(i.status<200||i.status>=300)throw new J("authority_adoption_object_upload_failed","Object storage rejected an authority import file part.",i.status);return i}function RT(r,e){if(r instanceof Blob)return r;if(r instanceof ArrayBuffer)return new Blob([r],{type:e});let t=new Uint8Array(r.buffer,r.byteOffset,r.byteLength).slice();return new Blob([t],{type:e})}async function TT(r,e){let t=Ge.create(),n=r.stream().getReader();try{for(;;){mc(e);let i=await n.read();if(i.done)break;t.update(i.value)}}finally{n.releaseLock()}return`sha256:${Le(t.digest())}`}function MT(r,e){let t=CT(r),n=IT.encode(`mdbase-authority-import-file-v1\0${e.file_id}\0${e.revision}\0${e.content_digest}`),i=hc(new Uint8Array([...t,...n])).slice(0,16);i[6]=i[6]&15|80,i[8]=i[8]&63|128;let s=Le(i);return`${s.slice(0,8)}-${s.slice(8,12)}-${s.slice(12,16)}-${s.slice(16,20)}-${s.slice(20)}`}function CT(r){if(!PT.test(r))throw ft("Authority import ID is invalid.");return Uint8Array.from(r.replaceAll("-","").match(/../g).map(e=>Number.parseInt(e,16)))}function NT(r,e,t){var a;let n=r==null?void 0:r.strategy;if((r==null?void 0:r.protocol_version)!==1||r.type!=="file_transfer"||r.transfer_id!==e||r.direction!=="upload"||r.protection!=="transport_tls"||r.total_size!==t||!Array.isArray(r.received)||!n||!["object_put","object_multipart"].includes(n.kind)||n.kind==="object_multipart"&&(!Number.isSafeInteger(n.part_size)||n.part_size<=0))throw ft("Connect returned an invalid authority import file session.");if(n.kind!=="object_put"&&n.kind!=="object_multipart")throw ft("Connect returned an invalid authority import file strategy.");let i=n.kind==="object_put"?Math.max(1,t):n.part_size,s=n.kind==="object_put"?1:Math.ceil(t/i);if(new Set(r.received).size!==r.received.length||r.received.some(c=>!Number.isSafeInteger(c)||c<0||c>=s))throw ft("Connect returned invalid authority import file progress.");let o=(a=r.uploaded_parts)!=null?a:[];if(!Array.isArray(o)||o.some((c,l)=>!Number.isSafeInteger(c==null?void 0:c.part_number)||c.part_number<1||c.part_number>s||typeof c.etag!="string"||c.etag.length===0||c.etag.length>255||l>0&&o[l-1].part_number>=c.part_number)||(n.kind==="object_multipart"?o.length!==r.received.length||o.some((c,l)=>c.part_number-1!==r.received[l]):o.length!==0))throw ft("Connect returned invalid authority import part receipts.")}function LT(r,e,t,n,i){if((r==null?void 0:r.protocol_version)!==1||r.type!=="file_part"||r.transfer_id!==e||r.part_index!==t||r.offset!==n||r.content_length!==i||r.method.toUpperCase()!=="PUT"||!Number.isFinite(Date.parse(r.expires_at))||!qf(r.headers))throw ft("Connect returned an invalid prepared authority import file part.")}function jT(r){let e;try{e=new URL(r)}catch(t){throw ft("Connect returned an invalid object storage URL.")}if(e.protocol!=="https:"&&!(e.protocol==="http:"&&["localhost","127.0.0.1","[::1]","::1"].includes(e.hostname))||e.username||e.password||e.hash)throw ft("Connect returned an unsafe object storage URL.")}function DT(r){let e={};for(let[t,n]of Object.entries(r)){if(["authorization","cookie","host","proxy-authorization"].includes(t.toLowerCase()))throw ft("Connect returned unsafe object storage headers.");if(/\r|\n/.test(t)||/\r|\n/.test(n))throw ft("Connect returned invalid object storage headers.");e[t]=n}return e}function qT(r,e){return r.file_id===e.file_id&&r.path===e.path&&r.revision===e.revision&&r.content_digest===e.content_digest&&r.size===e.size&&r.media_type===e.media_type&&r.media_class===e.media_class&&r.modified_at===e.modified_at}function FT(r){let e=qf(r.body)&&qf(r.body.error)?r.body.error:{};return new J(typeof e.code=="string"?e.code:"authority_adoption_request_failed",typeof e.message=="string"?e.message:`Collection adoption request failed with status ${r.status}.`,r.status)}function ft(r){return new J("invalid_authority_adoption_response",r)}function mc(r){if(r!=null&&r.aborted)throw new J("authority_adoption_cancelled","Collection adoption was cancelled.")}function qf(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}var Ff=1500,UT=250,VT=3e4,Pw=1440*60*1e3,Pr=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,yc=class{constructor(e={}){I(this,"request");I(this,"now");I(this,"wait");var t,n,i;this.request=(t=e.request)!=null?t:BT,this.now=(n=e.now)!=null?n:Date.now,this.wait=(i=e.wait)!=null?i:WT}async begin(e,t={}){Pn(t.signal);let n=Ir(e.controlUrl),i=e.mirrorName.trim();if(!i||i.length>200)throw new Je("invalid_mirror_name","Mirror name must contain between 1 and 200 characters.");if(!["read_only","read_write"].includes(e.mode))throw new Je("invalid_mirror_mode","Mirror mode must be read-only or read-write.");if(e.collectionId!==void 0&&!Pr.test(e.collectionId))throw new Je("invalid_collection_id","Collection ID must be a UUID.");let s;try{s=await this.request({url:`${n}/v1/mirror-pairing-requests`,method:"POST",headers:{"content-type":"application/json"},body:{mirror_name:i,mode:e.mode,...e.collectionId?{collection_id:e.collectionId}:{}},...t.signal?{signal:t.signal}:{}})}catch(c){throw Pn(t.signal),xw()}let o=Aw(s,201);if(!Pi(o)||!Pr.test(_t(o.pairing_id))||!Qs(o.pairing_secret)||!GT(o.expires_in)||Number(o.expires_in)*1e3>Pw)throw Gt("Connect returned an invalid mirror approval.");let a=Ow(n,_t(o.verification_uri),_t(o.pairing_id));return{controlUrl:n,pairingId:_t(o.pairing_id),refreshCredential:_t(o.pairing_secret),verificationUri:a,expiresAt:new Date(this.now()+Number(o.expires_in)*1e3).toISOString(),requested:{mirrorName:i,mode:e.mode,...e.collectionId?{collectionId:e.collectionId}:{}}}}async enroll(e,t){let n=await this.begin(e,t),{refreshCredential:i,...s}=n;return await t.onVerification(s),this.waitForApproval(n,t)}async waitForApproval(e,t={}){var o,a;zT(e,this.now());let n=kw(t.pollIntervalMs),i=Date.parse(e.expiresAt),s=0;for(;this.now()=500){let l=Uf(c);if(await this.retry(i,(a=c.retryAfterMs)!=null?a:n,t,s,{code:l.code,message:l.message})===null)break;continue}throw Uf(c)}throw new Je("mirror_enrollment_expired","Mirror approval expired before it was completed.")}async renew(e,t={}){HT(e),Pn(t.signal);let n;try{n=await this.request({url:Ew(e.controlUrl,e.enrollmentId,"renew"),method:"POST",headers:{authorization:`Bearer ${e.refreshCredential}`},...t.signal?{signal:t.signal}:{}})}catch(s){throw Pn(t.signal),xw()}let i={controlUrl:e.controlUrl,pairingId:e.enrollmentId,refreshCredential:e.refreshCredential,verificationUri:`${e.controlUrl}/mirror/${e.enrollmentId}`,expiresAt:new Date(this.now()+6e4).toISOString(),requested:{mirrorName:e.name,mode:e.mode,collectionId:e.collectionId}};return Sw(i,Aw(n,200),{replicaId:e.replicaId})}async retry(e,t,n,i,s){var l;let o=e-this.now();if(o<=0)return null;let a=Math.min(kw(t),o),c=new Date(this.now()+a).toISOString();return(l=n.onStatus)==null||l.call(n,{state:s?"retrying":"waiting_for_approval",attempt:i,expiresAt:new Date(e).toISOString(),retryAt:c,...s?{error:s}:{}}),await this.wait(a,n.signal),c}},Je=class extends b{constructor(t,n,i){super(t,n);I(this,"status");this.status=i,this.name="MirrorEnrollmentError"}};function Ir(r){let e;try{e=new URL(r)}catch(n){throw new Je("invalid_connect_url","Connect URL must be an absolute HTTPS origin.")}if(e.pathname!=="/"||e.search||e.hash||e.username||e.password)throw new Je("invalid_connect_url","Connect URL must be an origin without credentials, path, query, or fragment.");let t=["localhost","127.0.0.1","[::1]","::1"].includes(e.hostname);if(e.protocol!=="https:"&&!(e.protocol==="http:"&&t))throw new Je("invalid_connect_url","Connect URL must use HTTPS outside loopback development.");return e.origin}async function BT(r){let e=await fetch(r.url,{method:r.method,headers:r.headers,...r.body===void 0?{}:{body:JSON.stringify(r.body)},...r.signal?{signal:r.signal}:{}}),t=await e.json().catch(()=>null),n=e.headers.get("retry-after");return{status:e.status,body:t,...n===null?{}:{retryAfterMs:KT(n)}}}function Sw(r,e,t){if(!Pi(e)||e.status!=="paired"||!Pi(e.replica))throw Gt("Connect returned an invalid mirror enrollment.");let n=e.replica,i=_t(n.id),s=_t(n.collection_id),o=_t(n.name).trim(),a=n.mode,c=_t(e.token),l=_t(e.token_expires_at);if(!Pr.test(i)||!Pr.test(s)||!o||!["read_only","read_write"].includes(String(a))||!Qs(c)||!Tw(l))throw Gt("Connect returned invalid mirror credentials.");if(a!==r.requested.mode)throw Gt("Connect returned a mirror with a different access mode.");if(r.requested.collectionId&&s!==r.requested.collectionId)throw Gt("Connect returned a different collection.");if(t.mirrorName!==void 0&&o!==t.mirrorName)throw Gt("Connect returned a mirror with a different name.");if(t.replicaId!==void 0&&i!==t.replicaId)throw Gt("Connect returned a different mirror replica.");let d;try{d=Iw(_t(e.sync_url),s)}catch(u){throw Gt("Connect returned an invalid authority sync URL.")}return{controlUrl:Ir(r.controlUrl),syncUrl:d,collectionId:s,replicaId:i,mode:a,name:o,enrollmentId:r.pairingId,accessToken:c,refreshCredential:r.refreshCredential,accessTokenExpiresAt:l}}function zT(r,e){Ir(r.controlUrl);let t=Date.parse(r.expiresAt);if(!Pr.test(r.pairingId)||!Qs(r.refreshCredential)||!Number.isFinite(t)||t-e>Pw||!r.requested.mirrorName.trim()||r.requested.mirrorName.length>200||!["read_only","read_write"].includes(r.requested.mode)||r.requested.collectionId!==void 0&&!Pr.test(r.requested.collectionId))throw new Je("invalid_mirror_enrollment_session","Mirror enrollment session is invalid.");Ow(r.controlUrl,r.verificationUri,r.pairingId)}function HT(r){if(Ir(r.controlUrl),Iw(r.syncUrl,r.collectionId),!Pr.test(r.collectionId)||!Pr.test(r.replicaId)||!Pr.test(r.enrollmentId)||!Qs(r.accessToken)||!Qs(r.refreshCredential)||!Tw(r.accessTokenExpiresAt)||!r.name.trim()||r.name.length>200||!["read_only","read_write"].includes(r.mode))throw new Je("invalid_mirror_enrollment","Stored mirror enrollment is invalid.")}function Iw(r,e){let t=new URL(r),n=`/v1/authorities/${encodeURIComponent(e)}/sync`;if(!(t.protocol==="https:"||t.protocol==="http:"&&["localhost","127.0.0.1","[::1]","::1"].includes(t.hostname))||t.username||t.password||t.pathname.replace(/\/$/,"")!==n||t.search||t.hash)throw new Error("invalid sync URL");return`${t.origin}${n}`}function Ow(r,e,t){let n;try{n=new URL(e)}catch(s){throw Gt("Connect returned an invalid mirror verification URI.")}let i=new URL(`/mirror/${encodeURIComponent(t)}`,r);if(n.origin!==i.origin||n.pathname!==i.pathname||n.search||n.hash||n.username||n.password)throw Gt("Connect returned an untrusted mirror verification URI.");return n.href}function Ew(r,e,t){return`${Ir(r)}/v1/mirror-pairing-requests/${encodeURIComponent(e)}/${t}`}function Aw(r,e){if(r.status!==e)throw Uf(r);return r.body}function Uf(r){let e=Pi(r.body)&&Pi(r.body.error)?r.body.error:{};return new Je(_t(e.code)||"mirror_enrollment_request_failed",_t(e.message)||`Mirror enrollment request failed with status ${r.status}.`,r.status)}function Gt(r){return new Je("invalid_mirror_enrollment_response",r)}function Rw(r){return{code:"mirror_enrollment_unreachable",message:"Connect could not be reached for mirror enrollment."}}function xw(){let r=Rw(void 0);return new Je(r.code,r.message)}function kw(r=Ff){return Number.isFinite(r)?Math.min(VT,Math.max(UT,Math.round(r))):Ff}function KT(r){let e=Number(r);if(Number.isFinite(e)&&e>=0)return e*1e3;let t=Date.parse(r);return Number.isFinite(t)?Math.max(0,t-Date.now()):Ff}function WT(r,e){return Pn(e),new Promise((t,n)=>{let i=setTimeout(o,r),s=()=>{clearTimeout(i),e==null||e.removeEventListener("abort",s),n(new Je("mirror_enrollment_cancelled","Mirror enrollment was cancelled."))};function o(){e==null||e.removeEventListener("abort",s),t()}e==null||e.addEventListener("abort",s,{once:!0})})}function Pn(r){if(r!=null&&r.aborted)throw new Je("mirror_enrollment_cancelled","Mirror enrollment was cancelled.")}function Tw(r){let e=Date.parse(r);return Number.isFinite(e)}function GT(r){return typeof r=="number"&&Number.isSafeInteger(r)&&r>0}function Qs(r){return typeof r=="string"&&r.length>=16}function _t(r){return typeof r=="string"?r:""}function Pi(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}Ee();var JT=/(?:^|\/)(?:\.{1,2}|)(?:\/|$)/u,YT=/[\p{Cc}:?<>|*"]/u,XT=/[. ](?:\/|$)/u,QT=/(?:^|\/)(?:CON|PRN|AUX|NUL|COM[1-9¹²³]|LPT[1-9¹²³])(?:\.|\/|$)/iu;function Jt(r){if(!r||r.startsWith("/")||r.includes("\\")||JT.test(r)||YT.test(r)||XT.test(r)||QT.test(r))throw new b("invalid_path",`Mirror received an unsafe path: ${r}.`)}function bt(r){return Jt(r),Ii(r)}function Ii(r){return/^[\x20-\x7e]+$/u.test(r)?/[A-Z]/u.test(r)?r.toLowerCase():r:r.normalize("NFC").toLowerCase().normalize("NFC")}Ee();var Cw=new Set(["image","audio","video","pdf","other"]),Mw=["image","audio","video","pdf","other"],ZT=new Set([".mdbase",".git","node_modules","_contracts","_schemas","_types","_views"]),eM=/^(?:CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\.|$)/iu,tM=/^sha256:[0-9a-f]{64}$/u,rM=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,nM=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/u;function In(r){var s,o;let e={file_classes:[...(s=r==null?void 0:r.file_classes)!=null?s:[]],excluded_folders:[...(o=r==null?void 0:r.excluded_folders)!=null?o:[]]};if(e.excluded_folders.length>100)throw new b("invalid_file_materialization","Selective sync supports at most 100 excluded folders.");let t=new Set;for(let a of e.file_classes){if(!Cw.has(a)||t.has(a))throw new b("invalid_file_materialization","Selected file media classes must be valid and unique.");t.add(a)}let n=new Set,i=new Set;for(let a of e.excluded_folders){Lw(a,!0);let c=bt(a);if(n.has(a)||i.has(c))throw new b("invalid_file_materialization","Excluded folders must be unique on portable filesystems.");n.add(a),i.add(c)}return e.file_classes.sort((a,c)=>Mw.indexOf(a)-Mw.indexOf(c)),e.excluded_folders.sort((a,c)=>bt(a).localeCompare(bt(c))),e}function On(r,e){let t=bt(e);return!r.excluded_folders.some(n=>{let i=bt(n);return t===i||t.startsWith(`${i}/`)})}function _c(r,e){return r.file_classes.includes(e.media_class)&&On(r,e.path)}function Vf(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 Nw(r,e){return r.file_classes.includes(Vf(e))&&On(r,e)}function pt(r){if(Lw(r.path,!1),typeof r.file_id!="string"||!rM.test(r.file_id)||typeof r.revision!="string"||!r.revision||r.revision.length>255||!tM.test(r.content_digest)||!Number.isSafeInteger(r.size)||r.size<0||!Cw.has(r.media_class)||typeof r.modified_at!="string"||!nM.test(r.modified_at)||!Number.isFinite(Date.parse(r.modified_at))||r.media_type!==void 0&&(typeof r.media_type!="string"||!r.media_type||r.media_type.length>255))throw new b("invalid_snapshot",`Collection file ${r.path} has invalid metadata.`)}function Lw(r,e){if(Jt(r),r.length>1024)throw new b("invalid_file_path","Collection file paths cannot exceed 1024 characters.");if(r.split("/").some(i=>i.startsWith(".")||/[<>"|?*]/u.test(i)||eM.test(i)||ZT.has(i.toLowerCase()))||!e&&/\.md$/iu.test(r))throw new b("invalid_file_path",`Collection file path ${r} is hidden, reserved, or non-portable.`)}async function jw(r,e,t){let n,i=new Set;do{let s=await r.fileSnapshot(e.snapshot_id,n);if(s.protocol_version!==1||s.type!=="file_snapshot_page"||s.snapshot_id!==e.snapshot_id||s.scope_epoch!==e.scope_epoch||s.cursor!==e.head)throw new b("invalid_snapshot","Authority file snapshot boundary changed during download.");for(let o of s.files)pt(o);if(await t(s.files),n=s.next_page,n!==void 0&&i.has(n))throw new b("invalid_snapshot","Authority file snapshot repeated a page cursor.");n!==void 0&&i.add(n)}while(n)}function Or(r,e){return(r==null?void 0:r.size)===e.size&&r.content_digest===e.content_digest}async function*gc(r,e){let t=Ge.create(),n=0;for await(let i of r){if(!(i instanceof Uint8Array)||i.byteLength===0){if(i instanceof Uint8Array&&i.byteLength===0)continue;throw new b("file_integrity_failed","A file transport returned invalid bytes.")}if(n+=i.byteLength,!Number.isSafeInteger(n)||n>e.size)throw new b("file_integrity_failed",`Downloaded bytes for ${e.path} are oversized.`);t.update(i),yield i}if(n!==e.size||`sha256:${Le(t.digest())}`!==e.content_digest)throw new b("file_integrity_failed",`Downloaded bytes for ${e.path} failed integrity verification.`)}async function*Dw(r,e,t){let n=Ge.create(),i=0;for await(let s of r){if(!(s instanceof Uint8Array))throw new b("file_integrity_failed",`Local bytes for ${t} are invalid.`);if(s.byteLength!==0){if(i+=s.byteLength,!Number.isSafeInteger(i)||i>e.size)throw new b("pending_local_changed",`Local file ${t} changed while being staged.`);n.update(s),yield s}}if(i!==e.size||`sha256:${Le(n.digest())}`!==e.content_digest)throw new b("pending_local_changed",`Local file ${t} changed while being staged.`)}async function bc(r,e,t){if(pt(t),await e.has(t.content_digest))try{for await(let n of gc(e.read(t.content_digest),t));return}catch(n){await e.remove(t.content_digest)}try{await e.write(t.content_digest,gc(r.downloadFile(t),t))}catch(n){throw await e.remove(t.content_digest).catch(()=>{}),n}if(!await e.has(t.content_digest))throw new b("file_integrity_failed","The verified file blob was not persisted.")}var on=new TextEncoder;function Hf(r){var u,f,p,y,h;let e=kn(r.collectionId,"Collection ID"),t=(u=r.sourceHead)!=null?u:0;if(!Number.isSafeInteger(t)||t<0)throw new J("invalid_authority_snapshot","Source head must be a non-negative integer.");let n=new Set,i=r.resources.map(m=>{let g=wc(m.path);if(n.add(g)||Bf(g),!["configuration","lock","contract","schema","type","view"].includes(m.kind))throw new J("invalid_authority_snapshot",`Unsupported collection resource kind for ${g}.`);return{path:g,kind:m.kind,revision:qw(m.document),document:m.document}}).sort(sM);if(((f=i[0])==null?void 0:f.path)!=="mdbase.yaml"||i[0].kind!=="configuration"||i.filter(({kind:m})=>m==="configuration").length!==1)throw new J("invalid_authority_snapshot","A portable snapshot requires one mdbase.yaml configuration resource.");let s=r.records.map(m=>{let g=wc(m.path);return n.add(g)||Bf(g),{record_id:m.recordId?kn(m.recordId,`Record ID for ${g}`):Uw(e,g),path:g,document:m.document}}).sort((m,g)=>zf(m.path,g.path)),o=new Set,a=((p=r.files)!=null?p:[]).map(m=>{let g=wc(m.path);n.add(g)||Bf(g);let _=kn(m.file_id,`File ID for ${g}`);if(!o.add(_))throw new J("invalid_authority_snapshot",`Collection snapshot contains file ID more than once: ${_}`);return iM(m,g),{...m,file_id:_,path:g}}).sort((m,g)=>zf(m.path,g.path)),c=Fw(i.flatMap(({path:m,revision:g})=>[m,g])),l=Fw([...i.flatMap(({path:m,revision:g})=>["resource",m,g]),...s.flatMap(m=>["record",m.path,qw(m.document)]),...a.flatMap(m=>{var g;return["file",m.path,m.file_id,m.revision,m.content_digest,String(m.size),(g=m.media_type)!=null?g:"",m.media_class]})]),d=fc([...i.map(({path:m,document:g})=>({kind:"resource",path:m,identity:"",document_hash:Le(Ge(on.encode(g)))})),...s.map(m=>({kind:"record",path:m.path,identity:m.record_id,document_hash:Le(Ge(on.encode(m.document)))})),...a.map(m=>({kind:"file",path:m.path,identity:m.file_id,document_hash:pc(m)}))]);return{protocol_version:1,collection_id:e,source_head:t,source_revision:l,manifest_digest:d,resources:{revision:c,spec_version:r.specVersion,types:(y=r.types)!=null?y:[],contracts:(h=r.contracts)!=null?h:[],documents:i},records:s,files:a}}function iM(r,e){try{pt({...r,path:e})}catch(t){throw new J("invalid_authority_snapshot",`File descriptor is invalid for ${e}.`)}if(r.media_class!==Vf(e))throw new J("invalid_authority_snapshot",`File media class does not match its path for ${e}.`)}function Uw(r,e){let t=oM(kn(r,"Collection ID")),i=hc(new Uint8Array([...t,...on.encode(wc(e))])).slice(0,16);i[6]=i[6]&15|80,i[8]=i[8]&63|128;let s=Le(i);return`${s.slice(0,8)}-${s.slice(8,12)}-${s.slice(12,16)}-${s.slice(16,20)}-${s.slice(20)}`}function qw(r){return`sha256:${Le(Ge(on.encode(r)))}`}function Fw(r){let e=Ge.create();for(let t of r){let n=BigInt(on.encode(t).length),i=new Uint8Array(8);new DataView(i.buffer).setBigUint64(0,n),e.update(i),e.update(on.encode(t))}return`sha256:${Le(e.digest())}`}function sM(r,e){return r.kind==="configuration"&&e.kind!=="configuration"?-1:e.kind==="configuration"&&r.kind!=="configuration"?1:zf(r.path,e.path)}function zf(r,e){let t=on.encode(r),n=on.encode(e),i=Math.min(t.length,n.length);for(let s=0;s!t||t==="."||t===".."))throw new J("invalid_authority_snapshot",`Collection path is unsafe: ${r}`);return e}function Bf(r){throw new J("invalid_authority_snapshot",`Collection snapshot contains the path more than once: ${r}`)}function oM(r){return Uint8Array.from(r.replaceAll("-","").match(/../g).map(e=>Number.parseInt(e,16)))}var aM=/^sha256:[a-f0-9]{64}$/,cM=/^[a-f0-9]{64}$/,Wf=1500,Gf=1440*60*1e3,lM=200,Vw=8*1024*1024,dM=new TextEncoder,vc=class{constructor(e={}){I(this,"request");I(this,"now");I(this,"wait");var t,n,i;this.request=(t=e.request)!=null?t:hM,this.now=(n=e.now)!=null?n:Date.now,this.wait=(i=e.wait)!=null?i:pM}async begin(e,t={}){var f,p;Tn(t.signal);let n=Ir(e.controlUrl),i=kn(e.collectionId,"Collection ID"),s=Kf(e.displayName,"Collection name"),o=Kf(e.sourceName,"Source name"),a=(f=e.retainMirror)!=null?f:!0,c=a?Kf((p=e.mirrorName)!=null?p:o,"Mirror name"):void 0,l;try{l=await this.request({url:`${n}/v1/authority-adoptions`,method:"POST",headers:{"content-type":"application/json"},body:{collection_id:i,display_name:s,source_name:o,retain_mirror:a,...c?{mirror_name:c}:{}},...t.signal?{signal:t.signal}:{}})}catch(y){throw Tn(t.signal),Kw()}let d=fM(l,201);if(!Rr(d)||!ki.test(tt(d.adoption_id))||!Jf(d.adoption_secret)||!_M(d.expires_in)||Number(d.expires_in)*1e3>Gf)throw rt("Connect returned an invalid collection adoption request.");let u=Xw(n,tt(d.verification_uri),tt(d.adoption_id));return{controlUrl:n,adoptionId:tt(d.adoption_id),credential:tt(d.adoption_secret),verificationUri:u,expiresAt:new Date(this.now()+Number(d.expires_in)*1e3).toISOString(),requested:{collectionId:i,displayName:s,sourceName:o,retainMirror:a,...c?{mirrorName:c}:{}}}}async start(e,t){let n=await this.begin(e,t),{credential:i,...s}=n;return await t.onVerification(s),{session:n,prepared:await this.waitForApproval(n,t)}}async waitForApproval(e,t={}){var o,a;Oi(e,this.now());let n=Ww(t.pollIntervalMs),i=Date.parse(e.expiresAt),s=0;for(;this.now()=500){let l=Rn(c);if(!await this.retry(i,(a=c.retryAfterMs)!=null?a:n,s,t,{code:l.code,message:l.message}))break;continue}throw Rn(c)}throw new J("authority_adoption_expired","Collection adoption approval expired before upload began.")}async exchange(e,t={}){Oi(e,this.now(),!0);let n=await this.controlRequest(e,"exchange","POST",{},t.signal);if(n.status===202)throw new J("authority_adoption_pending","Collection adoption is still awaiting approval.",202);if(n.status!==200)throw Rn(n);return zw(e,n.body)}async uploadSnapshot(e,t,n,i={}){Oi(e,this.now(),!0),Jw(e,t),Bw(e,n);let s={protocol_version:1,collection_id:n.collection_id,source_head:n.source_head,source_revision:n.source_revision,manifest_digest:n.manifest_digest,resources:n.resources,record_count:n.records.length,file_count:n.files.length,files:n.files};await this.importRequest(t.import.manifest_url,"PUT",t.import.access_token,s,i.signal);let o=0,a=[],c=0;for(let l of n.records){let d=dM.encode(JSON.stringify(l)).length;if(d>Vw)throw new J("authority_adoption_record_too_large",`Record ${l.path} is too large to adopt.`);a.length>0&&(a.length===lM||c+d>Vw)&&(await this.uploadPage(t.import,o,a,i.signal),o+=1,a=[],c=0),a.push(l),c+=d}a.length>0&&await this.uploadPage(t.import,o,a,i.signal);for(let l of n.files){if(!i.fileSource)throw new J("authority_adoption_file_source_required",`File bytes are required to adopt ${l.path}.`);let d=await i.fileSource(l);await $w(this.request,t.import,l,d,i)}await this.importRequest(t.import.finalize_url,"POST",t.import.access_token,void 0,i.signal)}async complete(e,t,n={}){Oi(e,this.now(),!0),Bw(e,t);let i;try{i=await this.controlRequest(e,"complete","POST",{manifest_digest:t.manifest_digest,source_revision:t.source_revision,source_head:t.source_head},n.signal)}catch(a){throw Tn(n.signal),new kr("Connect could not confirm whether hosted authority activated.",{cause:a})}if(i.status>=500)throw new kr("Connect could not confirm whether hosted authority activated.");if(i.status!==200)throw Rn(i);let s=i.body;if(!Rr(s)||s.status!=="completed")throw rt("Connect returned an invalid adoption completion.");let o=Yw(e,s.adoption);if(o.state!=="completed"||o.manifest_digest!==t.manifest_digest||o.source_revision!==t.source_revision||o.final_head!==t.source_head)throw rt("Connect completed a different adoption snapshot.");return{status:"completed",adoption:o}}async cancel(e,t={}){Oi(e,this.now(),!0);let n=await this.controlRequest(e,void 0,"DELETE",void 0,t.signal);if(n.status!==200)throw Rn(n)}mirrorEnrollmentSession(e,t){var n;if(Oi(e,this.now(),!0),t.status!=="completed"||t.adoption.collection_id!==e.requested.collectionId)throw rt("Completed adoption does not belong to this session.");return e.requested.retainMirror?{controlUrl:e.controlUrl,pairingId:e.adoptionId,refreshCredential:e.credential,verificationUri:`${e.controlUrl}/mirror/${e.adoptionId}`,expiresAt:new Date(this.now()+Gf).toISOString(),requested:{mirrorName:(n=e.requested.mirrorName)!=null?n:e.requested.sourceName,mode:"read_write",collectionId:e.requested.collectionId}}:null}async uploadPage(e,t,n,i){let s={protocol_version:1,page:t,records:n};await this.importRequest(e.records_url,"PUT",e.access_token,s,i)}async importRequest(e,t,n,i,s){let o;try{o=await this.request({url:e,method:t,headers:{authorization:`Bearer ${n}`,...i===void 0?{}:{"content-type":"application/json"}},...i===void 0?{}:{body:i},...s?{signal:s}:{}})}catch(a){throw Tn(s),Kw()}if(o.status<200||o.status>=300)throw Rn(o)}controlRequest(e,t,n,i,s){return this.request({url:Hw(e,t),method:n,headers:{authorization:`Bearer ${e.credential}`,...i===void 0?{}:{"content-type":"application/json"}},...i===void 0?{}:{body:i},...s?{signal:s}:{}})}async retry(e,t,n,i,s){var l;let o=e-this.now();if(o<=0)return!1;let a=Math.min(Ww(t),o),c=new Date(this.now()+a).toISOString();return(l=i.onStatus)==null||l.call(i,{state:s?"retrying":"waiting_for_approval",attempt:n,expiresAt:new Date(e).toISOString(),retryAt:c,...s?{error:s}:{}}),await this.wait(a,i.signal),!0}};function Oi(r,e,t=!1){Ir(r.controlUrl);let n=Date.parse(r.expiresAt);if(!ki.test(r.adoptionId)||!Jf(r.credential)||!Number.isFinite(n)||n-e>Gf||!t&&n<=e||!ki.test(r.requested.collectionId)||!r.requested.displayName.trim()||!r.requested.sourceName.trim())throw new J("invalid_authority_adoption_session","Stored collection adoption state is invalid.");Xw(r.controlUrl,r.verificationUri,r.adoptionId)}function Jw(r,e){if(e.status!=="ready"||e.adoption.id!==r.adoptionId||e.adoption.collection_id!==r.requested.collectionId)throw rt("Prepared adoption does not belong to this session.");let t=e.import;if(!ki.test(t.import_id)||!Jf(t.access_token))throw rt("Connect returned an invalid authority import capability.");let n=[[t.manifest_url,"manifest"],[t.records_url,"records"],[t.files_url,"files"],[t.finalize_url,"finalize"]],i;for(let[s,o]of n){let a=uM(s,t.import_id,o);if(!a||i!==void 0&&a.origin!==i)throw rt("Connect returned an invalid authority import capability.");i=a.origin}}function Bw(r,e){var t;if(e.protocol_version!==1||e.collection_id!==r.requested.collectionId||!Number.isSafeInteger(e.source_head)||e.source_head<0||!aM.test(e.source_revision)||!cM.test(e.manifest_digest)||((t=e.resources.documents)==null?void 0:t.length)===0||!Array.isArray(e.files))throw new J("invalid_authority_snapshot","Authority snapshot does not belong to this adoption.")}function zw(r,e){if(!Rr(e)||!["ready","activating","completed"].includes(tt(e.status)))throw rt("Connect returned an invalid adoption exchange.");let t=Yw(r,e.adoption);if(e.status==="completed")return{status:"completed",adoption:t};if(e.status==="activating")return{status:"activating",adoption:t};if(!Rr(e.import)||!Rr(e.staged))throw rt("Connect omitted the authority import capability.");let n=e.import,i=e.staged,s={status:"ready",adoption:t,import:{import_id:tt(n.import_id),manifest_url:tt(n.manifest_url),records_url:tt(n.records_url),files_url:tt(n.files_url),finalize_url:tt(n.finalize_url),access_token:tt(n.access_token)},staged:{state:i.state,manifest_digest:Gw(i.manifest_digest),source_revision:Gw(i.source_revision),source_head:gM(i.source_head)}};if(Jw(r,s),!["receiving","uploaded"].includes(s.staged.state))throw rt("Connect returned an invalid staged import state.");return s}function Yw(r,e){if(!Rr(e))throw rt("Connect omitted collection adoption state.");let t=e;if(t.id!==r.adoptionId||t.collection_id!==r.requested.collectionId||!["requested","approved","prepared","activating","completed","cancelled","expired"].includes(t.state)||!Number.isSafeInteger(t.authority_epoch)||t.authority_epoch<2||!yM(t.expires_at))throw rt("Connect returned invalid collection adoption state.");return t}function uM(r,e,t){try{let n=new URL(r);return(n.protocol==="https:"||n.protocol==="http:"&&["localhost","127.0.0.1","[::1]","::1"].includes(n.hostname))&&!n.username&&!n.password&&!n.search&&!n.hash&&n.pathname===`/v1/authority-imports/${e}/${t}`?n:null}catch(n){return null}}function Xw(r,e,t){let n;try{n=new URL(e)}catch(s){throw rt("Connect returned an invalid adoption verification URI.")}let i=new URL(`/adopt/${encodeURIComponent(t)}`,r);if(n.origin!==i.origin||n.pathname!==i.pathname||n.search||n.hash||n.username||n.password)throw rt("Connect returned an untrusted adoption verification URI.");return n.href}function Hw(r,e){let t=e?`/${e}`:"";return`${Ir(r.controlUrl)}/v1/authority-adoptions/${encodeURIComponent(r.adoptionId)}${t}`}function Kf(r,e){let t=r.trim();if(!t||t.length>200)throw new J("invalid_authority_adoption",`${e} must contain between 1 and 200 characters.`);return t}function fM(r,e){if(r.status!==e)throw Rn(r);return r.body}function Rn(r){let e=Rr(r.body)&&Rr(r.body.error)?r.body.error:{};return new J(tt(e.code)||"authority_adoption_request_failed",tt(e.message)||`Collection adoption request failed with status ${r.status}.`,r.status)}function rt(r){return new J("invalid_authority_adoption_response",r)}function Qw(r){return{code:"authority_adoption_unreachable",message:"Connect could not be reached for collection adoption."}}function Kw(){let r=Qw(void 0);return new J(r.code,r.message)}function Ww(r=Wf){return Number.isFinite(r)?Math.min(3e4,Math.max(250,Math.round(r))):Wf}function pM(r,e){return Tn(e),new Promise((t,n)=>{let i=setTimeout(o,r),s=()=>{clearTimeout(i),e==null||e.removeEventListener("abort",s),n(new J("authority_adoption_cancelled","Collection adoption was cancelled."))};function o(){e==null||e.removeEventListener("abort",s),t()}e==null||e.addEventListener("abort",s,{once:!0})})}function Tn(r){if(r!=null&&r.aborted)throw new J("authority_adoption_cancelled","Collection adoption was cancelled.")}async function hM(r){let e=await fetch(r.url,{method:r.method,headers:r.headers,redirect:"error",...r.body===void 0?{}:{body:r.rawBody?r.body:JSON.stringify(r.body)},...r.signal?{signal:r.signal}:{}}),t=await e.json().catch(()=>({})),n=e.headers.get("retry-after");return{status:e.status,body:t,headers:Object.fromEntries(e.headers.entries()),...n?{retryAfterMs:mM(n)}:{}}}function mM(r){let e=Number(r);if(Number.isFinite(e)&&e>=0)return e*1e3;let t=Date.parse(r);return Number.isFinite(t)?Math.max(0,t-Date.now()):Wf}function yM(r){return Number.isFinite(Date.parse(r))}function Gw(r){return r===null?null:tt(r)}function gM(r){return r===null?null:typeof r=="number"&&Number.isSafeInteger(r)&&r>=0?r:Number.NaN}function _M(r){return typeof r=="number"&&Number.isSafeInteger(r)&&r>0}function Jf(r){return typeof r=="string"&&r.length>=16}function tt(r){return typeof r=="string"?r:""}function Rr(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}Ee();Ee();var bM=new TextEncoder,eo=Object.freeze({digest:r=>Le(Ge(bM.encode(r))),randomId:()=>{var r;if(typeof((r=globalThis.crypto)==null?void 0:r.randomUUID)!="function")throw new b("mirror_random_unavailable","This runtime must provide crypto.randomUUID() or a MirrorRuntime adapter.");return globalThis.crypto.randomUUID()},now:()=>new Date().toISOString()});var Zs=class{constructor(){I(this,"held",!1)}async runExclusive(e){if(this.held)throw new b("mirror_folder_in_use","Another mdbase mirror process is already using this folder.");this.held=!0;try{return await e()}finally{this.held=!1}}};function Zw(r,e,t){var i,s,o,a,c,l;if(r.engine_version!==3)throw new b("mirror_state_upgrade_required","Rebuild this prerelease mirror with the exact-document sync engine.");if(r.protocol_version!==1||r.replica_id!==e)throw new Error;if((i=r.resources)!=null||(r.resources={}),(s=r.generation)!=null||(r.generation=0),(o=r.files)!=null||(r.files={}),r.selective_sync=In(r.selective_sync),(a=r.planned_conflicts)!=null||(r.planned_conflicts={}),(c=r.local_bindings)!=null||(r.local_bindings={}),(l=r.mode)!=null||(r.mode="read_only"),r.mode!==t)throw new b("mirror_mode_mismatch",`Mirror metadata belongs to a ${r.mode.replace("_","-")} replica.`);let n=[];for(let[d,u]of Object.entries(r.records))if(n.push(bt(u.path)),u.record&&(u.record.record_id!==d||u.record.path!==u.path))throw new Error;for(let[d,u]of Object.entries(r.resources)){if(Jt(d),d!==u.path)throw new Error;n.push(bt(u.path))}for(let[d,u]of Object.entries(r.files)){if(pt(u.file),u.file.file_id!==d)throw new Error;n.push(bt(u.file.path))}n.sort();for(let d=1;dl.kind==="configuration"&&l.path==="mdbase.yaml");if(n.length!==1)throw new b("invalid_snapshot","Hosted snapshot requires exactly one canonical mdbase.yaml resource.");let i=r0(n[0].document,e),s=(c=s0(n[0].document).settings)!=null?c:{},o=Ri(s.types_folder,"_types"),a=Ri(s.contracts_folder,"_contracts");for(let l of r){let d=l.path.split(".").at(-1),u=l.path.split("/"),f=u.some(y=>y.startsWith(".")),p=!1;if(l.kind==="configuration")p=l.path==="mdbase.yaml";else if(l.kind==="lock")p=l.path==="mdbase.lock.yaml"&&$M(l.document);else if(l.kind==="type")p=Yf(l.path,o)&&d==="md"&&e0(l.document,l.path)==="mdbase.type";else if(l.kind==="contract")p=Yf(l.path,a)&&d==="md"&&e0(l.document,l.path)==="mdbase.contract";else if(l.kind==="schema"){let y=vM(l.document);p=!f&&d==="json"&&u.some(h=>h==="schemas"||h==="_schemas")&&y!==null}else l.kind==="view"&&(p=!f&&d==="base");if(!p)throw new b("invalid_snapshot",`Hosted resource ${l.path} is not valid for kind ${l.kind}.`)}return i}function t0(r){return{reservedFolders:new Set(["_types","_contracts","_types/_migrations",".mdbase"]),resourcePaths:r}}function r0(r,e){var s;let t=(s=s0(r).settings)!=null?s:{},n=Ri(t.types_folder,"_types");return{reservedFolders:new Set([n,Ri(t.contracts_folder,"_contracts"),Ri(t.migrations_folder,`${n}/_migrations`),Ri(t.cache_folder,".mdbase",!0)]),resourcePaths:e}}async function n0(r,e){if(r.length===0)return t0(new Set);let t=await e();if(t===null)throw new b("invalid_mirror_state","Mirror collection configuration is missing.");return r0(t,new Set(r))}function an(r,e){if(Jt(r),/(?:^|\/)\./u.test(r)||e.resourcePaths.has(r)||wM(r,e.reservedFolders)||!r.endsWith(".md"))throw new b("invalid_record_path",`Mirror record path ${r} is outside the configured record namespace.`)}function wM(r,e){for(let t of e)if(Yf(r,t))return!0;return!1}function i0(r,e){return r.filter(t=>{try{return an(t,e),!0}catch(n){return!1}})}function s0(r){let e;try{e=Ei(r)}catch(n){throw new b("invalid_snapshot","Hosted mdbase.yaml is not valid YAML.")}if(!e||typeof e!="object"||Array.isArray(e))throw new b("invalid_snapshot","Hosted mdbase.yaml requires an object document.");let t=e;if(typeof t.spec_version!="string")throw new b("invalid_snapshot","Hosted mdbase.yaml requires spec_version.");return t}function Ri(r,e,t=!1){let n=typeof r=="string"?r:e;if(Jt(n),!t&&n.split("/").some(i=>i.startsWith(".")))throw new b("invalid_snapshot",`Collection control folder ${n} must not be hidden.`);return n}function Yf(r,e){return r===e||r.startsWith(`${e}/`)}function vM(r){try{let e=JSON.parse(r);return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null}catch(e){return null}}function $M(r){try{let e=Ei(r);return e!==null&&typeof e=="object"&&!Array.isArray(e)&&e.kind==="mdbase.type-pack-lock"&&e.lock_version===1&&Array.isArray(e.packs)}catch(e){return!1}}function e0(r,e){try{return uc(r,e).frontmatter.kind}catch(t){return null}}Ee();function wt(r){return Ii(r)}function o0(r,e,t,n,i=[]){let s=wt(r);for(let o of t)if(wt(o)===s)throw new b("invalid_record_path",`Mirror record path ${r} aliases authority resource ${o} on a supported filesystem.`);for(let[o,a]of n)if((o!==e||a.path!==r)&&wt(a.path)===s)throw new b("invalid_record_path",`Mirror record paths ${a.path} and ${r} alias on a supported filesystem.`);for(let[,o]of i)if(wt(o.file.path)===s)throw new b("invalid_record_path",`Mirror record path ${r} aliases collection file ${o.file.path} on a supported filesystem.`)}function a0(r,e,t){var i,s;let n=wt(r);for(let o of Object.values((i=t.resources)!=null?i:{}))if(wt(o.path)===n)throw new b("invalid_file_path",`Collection file ${r} aliases authority resource ${o.path}.`);for(let o of Object.values(t.records))if(wt(o.path)===n)throw new b("invalid_file_path",`Collection file ${r} aliases record ${o.path}.`);for(let[o,a]of Object.entries((s=t.files)!=null?s:{}))if((o!==e||a.file.path!==r)&&wt(a.file.path)===n)throw new b("invalid_file_path",`Collection files ${a.file.path} and ${r} alias on a supported filesystem.`)}function to(r){let e=new Map;for(let t of r){let n=wt(t),i=e.get(n);if(i!==void 0&&i!==t)throw new b("invalid_record_path",`Mirror paths ${i} and ${t} alias on a supported filesystem.`);e.set(n,t)}}Ee();var Sc=class{constructor(e,t,n){I(this,"pathPolicy");I(this,"digest");I(this,"recordIds",new Set);I(this,"physicalPaths",new Set);this.pathPolicy=e,this.digest=n;for(let i of t)this.physicalPaths.add(Ii(i.path))}validate(e){let t=e.document,n=e;if(an(n.path,this.pathPolicy),this.recordIds.has(n.record_id))throw new b("invalid_snapshot",`Hosted snapshot repeats record identity ${n.record_id}.`);this.recordIds.add(n.record_id);let i=Ii(n.path);if(this.physicalPaths.has(i))throw new b("invalid_snapshot",`Hosted record path ${n.path} aliases another snapshot path on a supported filesystem.`);this.physicalPaths.add(i);let s=this.digest(t);if(n.revision.length!==7+s.length||!n.revision.startsWith("sha256:")||!n.revision.endsWith(s))throw new b("invalid_snapshot",`Hosted record ${n.path} does not match its declared revision.`);if(bw(t,n)!==!0){let a;try{a=uc(t,n.path)}catch(c){throw new b("invalid_snapshot",`Hosted record ${n.path} is not valid Markdown.`)}if(!Xf(a.frontmatter,n.frontmatter)||!SM(a.body,n.body))throw new b("invalid_snapshot",`Hosted record ${n.path} does not match its declared document.`)}return{record:n,document:t,hash:s}}};async function c0(r,e,t){let n,i=new Set;do{let s=await r.snapshot(e.snapshot_id,n);if(s.protocol_version!==1||s.snapshot_id!==e.snapshot_id||s.scope_epoch!==e.scope_epoch||s.cursor!==e.head)throw new b("invalid_snapshot","Authority snapshot boundary changed during download.");if(await t(s.records),n=s.next_page,n!==void 0&&i.has(n))throw new b("invalid_snapshot","Authority snapshot repeated a page cursor.");n!==void 0&&i.add(n)}while(n)}function SM(r,e){return r===e||r.startsWith(` +`)?e.body.slice(1):e.body;return t=dt(r,` +`,t),t>=0&&r.startsWith(i,t)&&t+i.length===r.length}function fc(r,e){var s,o;let t=r.match(/^---[ \t]*\r?\n([\s\S]*?)^---[ \t]*(?:\r?\n|$)([\s\S]*)$/m);if(!t)return{frontmatter:{},body:r};let n;try{n=ki(t[1],{mapAsMap:!0})}catch(a){return{frontmatter:{},body:r}}if(n===null&&t[1].trim()==="")return{frontmatter:{},body:(s=t[2])!=null?s:""};let i=Nf(n,new Set);return i===xr||!gT(i)?{frontmatter:{},body:r}:{frontmatter:i,body:(o=t[2])!=null?o:""}}function Nf(r,e){if(r===null||typeof r=="string"||typeof r=="boolean")return r;if(typeof r=="number")return Number.isFinite(r)?r:xr;if(!r||typeof r!="object"||e.has(r))return xr;e.add(r);try{if(Array.isArray(r)){let n=[];for(let i of r){let s=Nf(i,e);if(s===xr)return xr;n.push(s)}return n}if(!(r instanceof Map))return xr;let t={};for(let[n,i]of r){if(typeof n!="string")return xr;let s=Nf(i,e);if(s===xr)return xr;Object.defineProperty(t,n,{value:s,enumerable:!0,configurable:!0,writable:!0})}return t}finally{e.delete(r)}}function gT(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function fw(r){return typeof r=="boolean"||r===null||typeof r=="number"&&Number.isSafeInteger(r)?String(r):typeof r!="string"||!/^[A-Za-z][A-Za-z0-9 _.-]*$/u.test(r)||r.length<=5&&mT.has(r.toLowerCase())?null:r}function dt(r,e,t){return r.startsWith(e,t)?t+e.length:-1}function pc(r){let e=We.create().update(Pr.encode(`mdbase-authority-manifest-v2 +`));for(let t of[...r].sort((n,i)=>n.kind!==i.kind?n.kinde.type==="file_put"||e.type==="file_remove"))throw new b("file_sync_unsupported","This replica cannot materialize collection file changes yet. Upgrade it before continuing sync.")}function mw(r){bT([r])}var J=class extends b{constructor(t,n,i,s){super(t,n);I(this,"status");this.status=i,this.name="AuthorityAdoptionError",(s==null?void 0:s.cause)!==void 0&&(this.cause=s.cause)}},Ir=class extends J{constructor(t,n){super("authority_adoption_outcome_unknown",t,void 0,n);I(this,"sourceMustRemainFenced",!0);this.name="AuthorityAdoptionOutcomeUnknownError"}};var Pi=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function In(r,e){if(!Pi.test(r))throw new J("invalid_authority_adoption",`${e} must be a UUID.`);return r.toLowerCase()}var Qs=Uint32Array.from([1732584193,4023233417,2562383102,271733878,3285377520]),cn=new Uint32Array(80),jf=class extends xi{constructor(){super(64,20,8,!1);I(this,"A",Qs[0]|0);I(this,"B",Qs[1]|0);I(this,"C",Qs[2]|0);I(this,"D",Qs[3]|0);I(this,"E",Qs[4]|0)}get(){let{A:t,B:n,C:i,D:s,E:o}=this;return[t,n,i,s,o]}set(t,n,i,s,o){this.A=t|0,this.B=n|0,this.C=i|0,this.D=s|0,this.E=o|0}process(t,n){for(let l=0;l<16;l++,n+=4)cn[l]=t.getUint32(n,!1);for(let l=16;l<80;l++)cn[l]=ac(cn[l-3]^cn[l-8]^cn[l-14]^cn[l-16],1);let{A:i,B:s,C:o,D:a,E:c}=this;for(let l=0;l<80;l++){let d,u;l<20?(d=lc(s,o,a),u=1518500249):l<40?(d=s^o^a,u=1859775393):l<60?(d=dc(s,o,a),u=2400959708):(d=s^o^a,u=3395469782);let f=ac(i,5)+d+c+u+cn[l]|0;c=a,a=o,o=ac(s,30),s=i,i=f}i=i+this.A|0,s=s+this.B|0,o=o+this.C|0,a=a+this.D|0,c=c+this.E|0,this.set(i,s,o,a,c)}roundClean(){on(cn)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0),on(this.buffer)}},mc=cc(()=>new jf);var wT=1e4,vT=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,$T=new TextEncoder;async function gw(r,e,t,n,i){var h,m,g;let s=ET(n,t.media_type);if(s.size!==t.size||await AT(s,i.signal)!==t.content_digest)throw new J("authority_adoption_file_changed",`File bytes no longer match the fenced snapshot for ${t.path}.`);let o=kT(e.import_id,t),a=await Df(r,`${e.files_url}/uploads`,e.access_token,{protocol_version:1,type:"open_authority_import_file_upload",transfer_id:o,file_id:t.file_id},i.signal);if(PT(a,o,t.size),a.strategy.kind!=="object_put"&&a.strategy.kind!=="object_multipart")throw ut("Connect returned an incompatible authority import file strategy.");let c=a.strategy.kind==="object_put"?Math.max(1,t.size):a.strategy.part_size,l=a.strategy.kind==="object_put"?1:Math.ceil(t.size/c);if(l>wT)throw ut("Authority import returned too many file parts.");let d=new Set(a.received),u=new Map(((h=a.uploaded_parts)!=null?h:[]).map(_=>[_.part_number-1,_]));if(a.received.length===l&&await yw(r,e,t,o,[...u.values()],i.signal))return;let f=Array(l);for(let[_,w]of u)f[_]=w;let p=[...d].reduce((_,w)=>_+Math.min(c,Math.max(0,t.size-w*c)),0);for(let _=0;__!==void 0);if(!await yw(r,e,t,o,y,i.signal))throw new J("authority_adoption_file_upload_incomplete",`Connect could not commit ${t.path}.`)}async function yw(r,e,t,n,i,s){try{let o=await Df(r,`${e.files_url}/uploads/${encodeURIComponent(n)}/commit`,e.access_token,{protocol_version:1,type:"commit_file_upload",transfer_id:n,...i.length>0?{parts:i}:{}},s);if(o.protocol_version!==1||o.type!=="file_upload_committed"||o.transfer_id!==n||!TT(o.file,t))throw ut("Connect returned an invalid authority import file receipt.");return!0}catch(o){if(i.length===0&&o instanceof J&&o.code==="file_upload_incomplete")return!1;throw o}}async function Df(r,e,t,n,i){let s;try{s=await r({url:e,method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/json"},body:n,...i?{signal:i}:{}})}catch(o){throw yc(i),new J("authority_adoption_unreachable","Connect could not be reached for collection adoption.")}if(s.status<200||s.status>=300)throw CT(s);return s.body}async function ST(r,e,t,n){OT(e.url);let i;try{i=await r({url:e.url,method:"PUT",headers:RT(e.headers),body:t,rawBody:!0,...n?{signal:n}:{}})}catch(s){throw yc(n),new J("authority_adoption_unreachable","Connect could not be reached for collection adoption.")}if(i.status<200||i.status>=300)throw new J("authority_adoption_object_upload_failed","Object storage rejected an authority import file part.",i.status);return i}function ET(r,e){if(r instanceof Blob)return r;if(r instanceof ArrayBuffer)return new Blob([r],{type:e});let t=new Uint8Array(r.buffer,r.byteOffset,r.byteLength).slice();return new Blob([t],{type:e})}async function AT(r,e){let t=We.create(),n=r.stream().getReader();try{for(;;){yc(e);let i=await n.read();if(i.done)break;t.update(i.value)}}finally{n.releaseLock()}return`sha256:${Ne(t.digest())}`}function kT(r,e){let t=xT(r),n=$T.encode(`mdbase-authority-import-file-v1\0${e.file_id}\0${e.revision}\0${e.content_digest}`),i=mc(new Uint8Array([...t,...n])).slice(0,16);i[6]=i[6]&15|80,i[8]=i[8]&63|128;let s=Ne(i);return`${s.slice(0,8)}-${s.slice(8,12)}-${s.slice(12,16)}-${s.slice(16,20)}-${s.slice(20)}`}function xT(r){if(!vT.test(r))throw ut("Authority import ID is invalid.");return Uint8Array.from(r.replaceAll("-","").match(/../g).map(e=>Number.parseInt(e,16)))}function PT(r,e,t){var a;let n=r==null?void 0:r.strategy;if((r==null?void 0:r.protocol_version)!==1||r.type!=="file_transfer"||r.transfer_id!==e||r.direction!=="upload"||r.protection!=="transport_tls"||r.total_size!==t||!Array.isArray(r.received)||!n||!["object_put","object_multipart"].includes(n.kind)||n.kind==="object_multipart"&&(!Number.isSafeInteger(n.part_size)||n.part_size<=0))throw ut("Connect returned an invalid authority import file session.");if(n.kind!=="object_put"&&n.kind!=="object_multipart")throw ut("Connect returned an invalid authority import file strategy.");let i=n.kind==="object_put"?Math.max(1,t):n.part_size,s=n.kind==="object_put"?1:Math.ceil(t/i);if(new Set(r.received).size!==r.received.length||r.received.some(c=>!Number.isSafeInteger(c)||c<0||c>=s))throw ut("Connect returned invalid authority import file progress.");let o=(a=r.uploaded_parts)!=null?a:[];if(!Array.isArray(o)||o.some((c,l)=>!Number.isSafeInteger(c==null?void 0:c.part_number)||c.part_number<1||c.part_number>s||typeof c.etag!="string"||c.etag.length===0||c.etag.length>255||l>0&&o[l-1].part_number>=c.part_number)||(n.kind==="object_multipart"?o.length!==r.received.length||o.some((c,l)=>c.part_number-1!==r.received[l]):o.length!==0))throw ut("Connect returned invalid authority import part receipts.")}function IT(r,e,t,n,i){if((r==null?void 0:r.protocol_version)!==1||r.type!=="file_part"||r.transfer_id!==e||r.part_index!==t||r.offset!==n||r.content_length!==i||r.method.toUpperCase()!=="PUT"||!Number.isFinite(Date.parse(r.expires_at))||!qf(r.headers))throw ut("Connect returned an invalid prepared authority import file part.")}function OT(r){let e;try{e=new URL(r)}catch(t){throw ut("Connect returned an invalid object storage URL.")}if(e.protocol!=="https:"&&!(e.protocol==="http:"&&["localhost","127.0.0.1","[::1]","::1"].includes(e.hostname))||e.username||e.password||e.hash)throw ut("Connect returned an unsafe object storage URL.")}function RT(r){let e={};for(let[t,n]of Object.entries(r)){if(["authorization","cookie","host","proxy-authorization"].includes(t.toLowerCase()))throw ut("Connect returned unsafe object storage headers.");if(/\r|\n/.test(t)||/\r|\n/.test(n))throw ut("Connect returned invalid object storage headers.");e[t]=n}return e}function TT(r,e){return r.file_id===e.file_id&&r.path===e.path&&r.revision===e.revision&&r.content_digest===e.content_digest&&r.size===e.size&&r.media_type===e.media_type&&r.media_class===e.media_class&&r.modified_at===e.modified_at}function CT(r){let e=qf(r.body)&&qf(r.body.error)?r.body.error:{};return new J(typeof e.code=="string"?e.code:"authority_adoption_request_failed",typeof e.message=="string"?e.message:`Collection adoption request failed with status ${r.status}.`,r.status)}function ut(r){return new J("invalid_authority_adoption_response",r)}function yc(r){if(r!=null&&r.aborted)throw new J("authority_adoption_cancelled","Collection adoption was cancelled.")}function qf(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}var Ff=1500,MT=250,NT=3e4,Sw=1440*60*1e3,Or=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,gc=class{constructor(e={}){I(this,"request");I(this,"now");I(this,"wait");var t,n,i;this.request=(t=e.request)!=null?t:LT,this.now=(n=e.now)!=null?n:Date.now,this.wait=(i=e.wait)!=null?i:FT}async begin(e,t={}){On(t.signal);let n=Rr(e.controlUrl),i=e.mirrorName.trim();if(!i||i.length>200)throw new Ge("invalid_mirror_name","Mirror name must contain between 1 and 200 characters.");if(!["read_only","read_write"].includes(e.mode))throw new Ge("invalid_mirror_mode","Mirror mode must be read-only or read-write.");if(e.collectionId!==void 0&&!Or.test(e.collectionId))throw new Ge("invalid_collection_id","Collection ID must be a UUID.");let s;try{s=await this.request({url:`${n}/v1/mirror-pairing-requests`,method:"POST",headers:{"content-type":"application/json"},body:{mirror_name:i,mode:e.mode,...e.collectionId?{collection_id:e.collectionId}:{}},...t.signal?{signal:t.signal}:{}})}catch(c){throw On(t.signal),vw()}let o=ww(s,201);if(!Ii(o)||!Or.test(gt(o.pairing_id))||!Zs(o.pairing_secret)||!VT(o.expires_in)||Number(o.expires_in)*1e3>Sw)throw Wt("Connect returned an invalid mirror approval.");let a=Aw(n,gt(o.verification_uri),gt(o.pairing_id));return{controlUrl:n,pairingId:gt(o.pairing_id),refreshCredential:gt(o.pairing_secret),verificationUri:a,expiresAt:new Date(this.now()+Number(o.expires_in)*1e3).toISOString(),requested:{mirrorName:i,mode:e.mode,...e.collectionId?{collectionId:e.collectionId}:{}}}}async enroll(e,t){let n=await this.begin(e,t),{refreshCredential:i,...s}=n;return await t.onVerification(s),this.waitForApproval(n,t)}async waitForApproval(e,t={}){var o,a;jT(e,this.now());let n=$w(t.pollIntervalMs),i=Date.parse(e.expiresAt),s=0;for(;this.now()=500){let l=Vf(c);if(await this.retry(i,(a=c.retryAfterMs)!=null?a:n,t,s,{code:l.code,message:l.message})===null)break;continue}throw Vf(c)}throw new Ge("mirror_enrollment_expired","Mirror approval expired before it was completed.")}async renew(e,t={}){DT(e),On(t.signal);let n;try{n=await this.request({url:bw(e.controlUrl,e.enrollmentId,"renew"),method:"POST",headers:{authorization:`Bearer ${e.refreshCredential}`},...t.signal?{signal:t.signal}:{}})}catch(s){throw On(t.signal),vw()}let i={controlUrl:e.controlUrl,pairingId:e.enrollmentId,refreshCredential:e.refreshCredential,verificationUri:`${e.controlUrl}/mirror/${e.enrollmentId}`,expiresAt:new Date(this.now()+6e4).toISOString(),requested:{mirrorName:e.name,mode:e.mode,collectionId:e.collectionId}};return _w(i,ww(n,200),{replicaId:e.replicaId})}async retry(e,t,n,i,s){var l;let o=e-this.now();if(o<=0)return null;let a=Math.min($w(t),o),c=new Date(this.now()+a).toISOString();return(l=n.onStatus)==null||l.call(n,{state:s?"retrying":"waiting_for_approval",attempt:i,expiresAt:new Date(e).toISOString(),retryAt:c,...s?{error:s}:{}}),await this.wait(a,n.signal),c}},Ge=class extends b{constructor(t,n,i){super(t,n);I(this,"status");this.status=i,this.name="MirrorEnrollmentError"}};function Rr(r){let e;try{e=new URL(r)}catch(n){throw new Ge("invalid_connect_url","Connect URL must be an absolute HTTPS origin.")}if(e.pathname!=="/"||e.search||e.hash||e.username||e.password)throw new Ge("invalid_connect_url","Connect URL must be an origin without credentials, path, query, or fragment.");let t=["localhost","127.0.0.1","[::1]","::1"].includes(e.hostname);if(e.protocol!=="https:"&&!(e.protocol==="http:"&&t))throw new Ge("invalid_connect_url","Connect URL must use HTTPS outside loopback development.");return e.origin}async function LT(r){let e=await fetch(r.url,{method:r.method,headers:r.headers,...r.body===void 0?{}:{body:JSON.stringify(r.body)},...r.signal?{signal:r.signal}:{}}),t=await e.json().catch(()=>null),n=e.headers.get("retry-after");return{status:e.status,body:t,...n===null?{}:{retryAfterMs:qT(n)}}}function _w(r,e,t){if(!Ii(e)||e.status!=="paired"||!Ii(e.replica))throw Wt("Connect returned an invalid mirror enrollment.");let n=e.replica,i=gt(n.id),s=gt(n.collection_id),o=gt(n.name).trim(),a=n.mode,c=gt(e.token),l=gt(e.token_expires_at);if(!Or.test(i)||!Or.test(s)||!o||!["read_only","read_write"].includes(String(a))||!Zs(c)||!xw(l))throw Wt("Connect returned invalid mirror credentials.");if(a!==r.requested.mode)throw Wt("Connect returned a mirror with a different access mode.");if(r.requested.collectionId&&s!==r.requested.collectionId)throw Wt("Connect returned a different collection.");if(t.mirrorName!==void 0&&o!==t.mirrorName)throw Wt("Connect returned a mirror with a different name.");if(t.replicaId!==void 0&&i!==t.replicaId)throw Wt("Connect returned a different mirror replica.");let d;try{d=Ew(gt(e.sync_url),s)}catch(u){throw Wt("Connect returned an invalid authority sync URL.")}return{controlUrl:Rr(r.controlUrl),syncUrl:d,collectionId:s,replicaId:i,mode:a,name:o,enrollmentId:r.pairingId,accessToken:c,refreshCredential:r.refreshCredential,accessTokenExpiresAt:l}}function jT(r,e){Rr(r.controlUrl);let t=Date.parse(r.expiresAt);if(!Or.test(r.pairingId)||!Zs(r.refreshCredential)||!Number.isFinite(t)||t-e>Sw||!r.requested.mirrorName.trim()||r.requested.mirrorName.length>200||!["read_only","read_write"].includes(r.requested.mode)||r.requested.collectionId!==void 0&&!Or.test(r.requested.collectionId))throw new Ge("invalid_mirror_enrollment_session","Mirror enrollment session is invalid.");Aw(r.controlUrl,r.verificationUri,r.pairingId)}function DT(r){if(Rr(r.controlUrl),Ew(r.syncUrl,r.collectionId),!Or.test(r.collectionId)||!Or.test(r.replicaId)||!Or.test(r.enrollmentId)||!Zs(r.accessToken)||!Zs(r.refreshCredential)||!xw(r.accessTokenExpiresAt)||!r.name.trim()||r.name.length>200||!["read_only","read_write"].includes(r.mode))throw new Ge("invalid_mirror_enrollment","Stored mirror enrollment is invalid.")}function Ew(r,e){let t=new URL(r),n=`/v1/authorities/${encodeURIComponent(e)}/sync`;if(!(t.protocol==="https:"||t.protocol==="http:"&&["localhost","127.0.0.1","[::1]","::1"].includes(t.hostname))||t.username||t.password||t.pathname.replace(/\/$/,"")!==n||t.search||t.hash)throw new Error("invalid sync URL");return`${t.origin}${n}`}function Aw(r,e,t){let n;try{n=new URL(e)}catch(s){throw Wt("Connect returned an invalid mirror verification URI.")}let i=new URL(`/mirror/${encodeURIComponent(t)}`,r);if(n.origin!==i.origin||n.pathname!==i.pathname||n.search||n.hash||n.username||n.password)throw Wt("Connect returned an untrusted mirror verification URI.");return n.href}function bw(r,e,t){return`${Rr(r)}/v1/mirror-pairing-requests/${encodeURIComponent(e)}/${t}`}function ww(r,e){if(r.status!==e)throw Vf(r);return r.body}function Vf(r){let e=Ii(r.body)&&Ii(r.body.error)?r.body.error:{};return new Ge(gt(e.code)||"mirror_enrollment_request_failed",gt(e.message)||`Mirror enrollment request failed with status ${r.status}.`,r.status)}function Wt(r){return new Ge("invalid_mirror_enrollment_response",r)}function kw(r){return{code:"mirror_enrollment_unreachable",message:"Connect could not be reached for mirror enrollment."}}function vw(){let r=kw(void 0);return new Ge(r.code,r.message)}function $w(r=Ff){return Number.isFinite(r)?Math.min(NT,Math.max(MT,Math.round(r))):Ff}function qT(r){let e=Number(r);if(Number.isFinite(e)&&e>=0)return e*1e3;let t=Date.parse(r);return Number.isFinite(t)?Math.max(0,t-Date.now()):Ff}function FT(r,e){return On(e),new Promise((t,n)=>{let i=setTimeout(o,r),s=()=>{clearTimeout(i),e==null||e.removeEventListener("abort",s),n(new Ge("mirror_enrollment_cancelled","Mirror enrollment was cancelled."))};function o(){e==null||e.removeEventListener("abort",s),t()}e==null||e.addEventListener("abort",s,{once:!0})})}function On(r){if(r!=null&&r.aborted)throw new Ge("mirror_enrollment_cancelled","Mirror enrollment was cancelled.")}function xw(r){let e=Date.parse(r);return Number.isFinite(e)}function VT(r){return typeof r=="number"&&Number.isSafeInteger(r)&&r>0}function Zs(r){return typeof r=="string"&&r.length>=16}function gt(r){return typeof r=="string"?r:""}function Ii(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}var UT=/(?:^|\/)(?:\.{1,2}|)(?:\/|$)/u,BT=/[\p{Cc}:?<>|*"]/u,zT=/[. ](?:\/|$)/u,HT=/(?:^|\/)(?:CON|PRN|AUX|NUL|COM[1-9¹²³]|LPT[1-9¹²³])(?:\.|\/|$)/iu;function Gt(r){if(!r||r.startsWith("/")||r.includes("\\")||UT.test(r)||BT.test(r)||zT.test(r)||HT.test(r))throw new b("invalid_path",`Mirror received an unsafe path: ${r}.`)}function _t(r){return Gt(r),Oi(r)}function Oi(r){return/^[\x20-\x7e]+$/u.test(r)?/[A-Z]/u.test(r)?r.toLowerCase():r:r.normalize("NFC").toLowerCase().normalize("NFC")}var Iw=new Set(["image","audio","video","pdf","other"]),Pw=["image","audio","video","pdf","other"],KT=new Set([".mdbase",".git","node_modules","_contracts","_schemas","_types","_views"]),WT=/^(?:CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\.|$)/iu,GT=/^sha256:[0-9a-f]{64}$/u,JT=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,YT=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/u;function Rn(r){var s,o;let e={file_classes:[...(s=r==null?void 0:r.file_classes)!=null?s:[]],excluded_folders:[...(o=r==null?void 0:r.excluded_folders)!=null?o:[]]};if(e.excluded_folders.length>100)throw new b("invalid_file_materialization","Selective sync supports at most 100 excluded folders.");let t=new Set;for(let a of e.file_classes){if(!Iw.has(a)||t.has(a))throw new b("invalid_file_materialization","Selected file media classes must be valid and unique.");t.add(a)}let n=new Set,i=new Set;for(let a of e.excluded_folders){Rw(a,!0);let c=_t(a);if(n.has(a)||i.has(c))throw new b("invalid_file_materialization","Excluded folders must be unique on portable filesystems.");n.add(a),i.add(c)}return e.file_classes.sort((a,c)=>Pw.indexOf(a)-Pw.indexOf(c)),e.excluded_folders.sort((a,c)=>_t(a).localeCompare(_t(c))),e}function Tn(r,e){let t=_t(e);return!r.excluded_folders.some(n=>{let i=_t(n);return t===i||t.startsWith(`${i}/`)})}function bc(r,e){return r.file_classes.includes(e.media_class)&&Tn(r,e.path)}function Uf(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 Ow(r,e){return r.file_classes.includes(Uf(e))&&Tn(r,e)}function ft(r){if(Rw(r.path,!1),typeof r.file_id!="string"||!JT.test(r.file_id)||typeof r.revision!="string"||!r.revision||r.revision.length>255||!GT.test(r.content_digest)||!Number.isSafeInteger(r.size)||r.size<0||!Iw.has(r.media_class)||typeof r.modified_at!="string"||!YT.test(r.modified_at)||!Number.isFinite(Date.parse(r.modified_at))||r.media_type!==void 0&&(typeof r.media_type!="string"||!r.media_type||r.media_type.length>255))throw new b("invalid_snapshot",`Collection file ${r.path} has invalid metadata.`)}function Rw(r,e){if(Gt(r),r.length>1024)throw new b("invalid_file_path","Collection file paths cannot exceed 1024 characters.");if(r.split("/").some(i=>i.startsWith(".")||/[<>"|?*]/u.test(i)||WT.test(i)||KT.has(i.toLowerCase()))||!e&&/\.md$/iu.test(r))throw new b("invalid_file_path",`Collection file path ${r} is hidden, reserved, or non-portable.`)}async function Tw(r,e,t){let n,i=new Set;do{let s=await r.fileSnapshot(e.snapshot_id,n);if(s.protocol_version!==1||s.type!=="file_snapshot_page"||s.snapshot_id!==e.snapshot_id||s.scope_epoch!==e.scope_epoch||s.cursor!==e.head)throw new b("invalid_snapshot","Authority file snapshot boundary changed during download.");for(let o of s.files)ft(o);if(await t(s.files),n=s.next_page,n!==void 0&&i.has(n))throw new b("invalid_snapshot","Authority file snapshot repeated a page cursor.");n!==void 0&&i.add(n)}while(n)}function Tr(r,e){return(r==null?void 0:r.size)===e.size&&r.content_digest===e.content_digest}async function*_c(r,e){let t=We.create(),n=0;for await(let i of r){if(!(i instanceof Uint8Array)||i.byteLength===0){if(i instanceof Uint8Array&&i.byteLength===0)continue;throw new b("file_integrity_failed","A file transport returned invalid bytes.")}if(n+=i.byteLength,!Number.isSafeInteger(n)||n>e.size)throw new b("file_integrity_failed",`Downloaded bytes for ${e.path} are oversized.`);t.update(i),yield i}if(n!==e.size||`sha256:${Ne(t.digest())}`!==e.content_digest)throw new b("file_integrity_failed",`Downloaded bytes for ${e.path} failed integrity verification.`)}async function*Cw(r,e,t){let n=We.create(),i=0;for await(let s of r){if(!(s instanceof Uint8Array))throw new b("file_integrity_failed",`Local bytes for ${t} are invalid.`);if(s.byteLength!==0){if(i+=s.byteLength,!Number.isSafeInteger(i)||i>e.size)throw new b("pending_local_changed",`Local file ${t} changed while being staged.`);n.update(s),yield s}}if(i!==e.size||`sha256:${Ne(n.digest())}`!==e.content_digest)throw new b("pending_local_changed",`Local file ${t} changed while being staged.`)}async function wc(r,e,t){if(ft(t),await e.has(t.content_digest))try{for await(let n of _c(e.read(t.content_digest),t));return}catch(n){await e.remove(t.content_digest)}try{await e.write(t.content_digest,_c(r.downloadFile(t),t))}catch(n){throw await e.remove(t.content_digest).catch(()=>{}),n}if(!await e.has(t.content_digest))throw new b("file_integrity_failed","The verified file blob was not persisted.")}var ln=new TextEncoder;function Hf(r){var u,f,p,y,h;let e=In(r.collectionId,"Collection ID"),t=(u=r.sourceHead)!=null?u:0;if(!Number.isSafeInteger(t)||t<0)throw new J("invalid_authority_snapshot","Source head must be a non-negative integer.");let n=new Set,i=r.resources.map(m=>{let g=vc(m.path);if(n.add(g)||Bf(g),!["configuration","lock","contract","schema","type","view"].includes(m.kind))throw new J("invalid_authority_snapshot",`Unsupported collection resource kind for ${g}.`);return{path:g,kind:m.kind,revision:Mw(m.document),document:m.document}}).sort(QT);if(((f=i[0])==null?void 0:f.path)!=="mdbase.yaml"||i[0].kind!=="configuration"||i.filter(({kind:m})=>m==="configuration").length!==1)throw new J("invalid_authority_snapshot","A portable snapshot requires one mdbase.yaml configuration resource.");let s=r.records.map(m=>{let g=vc(m.path);return n.add(g)||Bf(g),{record_id:m.recordId?In(m.recordId,`Record ID for ${g}`):Lw(e,g),path:g,document:m.document}}).sort((m,g)=>zf(m.path,g.path)),o=new Set,a=((p=r.files)!=null?p:[]).map(m=>{let g=vc(m.path);n.add(g)||Bf(g);let _=In(m.file_id,`File ID for ${g}`);if(!o.add(_))throw new J("invalid_authority_snapshot",`Collection snapshot contains file ID more than once: ${_}`);return XT(m,g),{...m,file_id:_,path:g}}).sort((m,g)=>zf(m.path,g.path)),c=Nw(i.flatMap(({path:m,revision:g})=>[m,g])),l=Nw([...i.flatMap(({path:m,revision:g})=>["resource",m,g]),...s.flatMap(m=>["record",m.path,Mw(m.document)]),...a.flatMap(m=>{var g;return["file",m.path,m.file_id,m.revision,m.content_digest,String(m.size),(g=m.media_type)!=null?g:"",m.media_class]})]),d=pc([...i.map(({path:m,document:g})=>({kind:"resource",path:m,identity:"",document_hash:Ne(We(ln.encode(g)))})),...s.map(m=>({kind:"record",path:m.path,identity:m.record_id,document_hash:Ne(We(ln.encode(m.document)))})),...a.map(m=>({kind:"file",path:m.path,identity:m.file_id,document_hash:hc(m)}))]);return{protocol_version:1,collection_id:e,source_head:t,source_revision:l,manifest_digest:d,resources:{revision:c,spec_version:r.specVersion,types:(y=r.types)!=null?y:[],contracts:(h=r.contracts)!=null?h:[],documents:i},records:s,files:a}}function XT(r,e){try{ft({...r,path:e})}catch(t){throw new J("invalid_authority_snapshot",`File descriptor is invalid for ${e}.`)}if(r.media_class!==Uf(e))throw new J("invalid_authority_snapshot",`File media class does not match its path for ${e}.`)}function Lw(r,e){let t=ZT(In(r,"Collection ID")),i=mc(new Uint8Array([...t,...ln.encode(vc(e))])).slice(0,16);i[6]=i[6]&15|80,i[8]=i[8]&63|128;let s=Ne(i);return`${s.slice(0,8)}-${s.slice(8,12)}-${s.slice(12,16)}-${s.slice(16,20)}-${s.slice(20)}`}function Mw(r){return`sha256:${Ne(We(ln.encode(r)))}`}function Nw(r){let e=We.create();for(let t of r){let n=BigInt(ln.encode(t).length),i=new Uint8Array(8);new DataView(i.buffer).setBigUint64(0,n),e.update(i),e.update(ln.encode(t))}return`sha256:${Ne(e.digest())}`}function QT(r,e){return r.kind==="configuration"&&e.kind!=="configuration"?-1:e.kind==="configuration"&&r.kind!=="configuration"?1:zf(r.path,e.path)}function zf(r,e){let t=ln.encode(r),n=ln.encode(e),i=Math.min(t.length,n.length);for(let s=0;s!t||t==="."||t===".."))throw new J("invalid_authority_snapshot",`Collection path is unsafe: ${r}`);return e}function Bf(r){throw new J("invalid_authority_snapshot",`Collection snapshot contains the path more than once: ${r}`)}function ZT(r){return Uint8Array.from(r.replaceAll("-","").match(/../g).map(e=>Number.parseInt(e,16)))}var eC=/^sha256:[a-f0-9]{64}$/,tC=/^[a-f0-9]{64}$/,Wf=1500,Gf=1440*60*1e3,rC=200,jw=8*1024*1024,nC=new TextEncoder,$c=class{constructor(e={}){I(this,"request");I(this,"now");I(this,"wait");var t,n,i;this.request=(t=e.request)!=null?t:aC,this.now=(n=e.now)!=null?n:Date.now,this.wait=(i=e.wait)!=null?i:oC}async begin(e,t={}){var f,p;Mn(t.signal);let n=Rr(e.controlUrl),i=In(e.collectionId,"Collection ID"),s=Kf(e.displayName,"Collection name"),o=Kf(e.sourceName,"Source name"),a=(f=e.retainMirror)!=null?f:!0,c=a?Kf((p=e.mirrorName)!=null?p:o,"Mirror name"):void 0,l;try{l=await this.request({url:`${n}/v1/authority-adoptions`,method:"POST",headers:{"content-type":"application/json"},body:{collection_id:i,display_name:s,source_name:o,retain_mirror:a,...c?{mirror_name:c}:{}},...t.signal?{signal:t.signal}:{}})}catch(y){throw Mn(t.signal),Vw()}let d=sC(l,201);if(!Cr(d)||!Pi.test(et(d.adoption_id))||!Jf(d.adoption_secret)||!uC(d.expires_in)||Number(d.expires_in)*1e3>Gf)throw tt("Connect returned an invalid collection adoption request.");let u=Kw(n,et(d.verification_uri),et(d.adoption_id));return{controlUrl:n,adoptionId:et(d.adoption_id),credential:et(d.adoption_secret),verificationUri:u,expiresAt:new Date(this.now()+Number(d.expires_in)*1e3).toISOString(),requested:{collectionId:i,displayName:s,sourceName:o,retainMirror:a,...c?{mirrorName:c}:{}}}}async start(e,t){let n=await this.begin(e,t),{credential:i,...s}=n;return await t.onVerification(s),{session:n,prepared:await this.waitForApproval(n,t)}}async waitForApproval(e,t={}){var o,a;Ri(e,this.now());let n=Uw(t.pollIntervalMs),i=Date.parse(e.expiresAt),s=0;for(;this.now()=500){let l=Cn(c);if(!await this.retry(i,(a=c.retryAfterMs)!=null?a:n,s,t,{code:l.code,message:l.message}))break;continue}throw Cn(c)}throw new J("authority_adoption_expired","Collection adoption approval expired before upload began.")}async exchange(e,t={}){Ri(e,this.now(),!0);let n=await this.controlRequest(e,"exchange","POST",{},t.signal);if(n.status===202)throw new J("authority_adoption_pending","Collection adoption is still awaiting approval.",202);if(n.status!==200)throw Cn(n);return qw(e,n.body)}async uploadSnapshot(e,t,n,i={}){Ri(e,this.now(),!0),zw(e,t),Dw(e,n);let s={protocol_version:1,collection_id:n.collection_id,source_head:n.source_head,source_revision:n.source_revision,manifest_digest:n.manifest_digest,resources:n.resources,record_count:n.records.length,file_count:n.files.length,files:n.files};await this.importRequest(t.import.manifest_url,"PUT",t.import.access_token,s,i.signal);let o=0,a=[],c=0;for(let l of n.records){let d=nC.encode(JSON.stringify(l)).length;if(d>jw)throw new J("authority_adoption_record_too_large",`Record ${l.path} is too large to adopt.`);a.length>0&&(a.length===rC||c+d>jw)&&(await this.uploadPage(t.import,o,a,i.signal),o+=1,a=[],c=0),a.push(l),c+=d}a.length>0&&await this.uploadPage(t.import,o,a,i.signal);for(let l of n.files){if(!i.fileSource)throw new J("authority_adoption_file_source_required",`File bytes are required to adopt ${l.path}.`);let d=await i.fileSource(l);await gw(this.request,t.import,l,d,i)}await this.importRequest(t.import.finalize_url,"POST",t.import.access_token,void 0,i.signal)}async complete(e,t,n={}){Ri(e,this.now(),!0),Dw(e,t);let i;try{i=await this.controlRequest(e,"complete","POST",{manifest_digest:t.manifest_digest,source_revision:t.source_revision,source_head:t.source_head},n.signal)}catch(a){throw Mn(n.signal),new Ir("Connect could not confirm whether hosted authority activated.",{cause:a})}if(i.status>=500)throw new Ir("Connect could not confirm whether hosted authority activated.");if(i.status!==200)throw Cn(i);let s=i.body;if(!Cr(s)||s.status!=="completed")throw tt("Connect returned an invalid adoption completion.");let o=Hw(e,s.adoption);if(o.state!=="completed"||o.manifest_digest!==t.manifest_digest||o.source_revision!==t.source_revision||o.final_head!==t.source_head)throw tt("Connect completed a different adoption snapshot.");return{status:"completed",adoption:o}}async cancel(e,t={}){Ri(e,this.now(),!0);let n=await this.controlRequest(e,void 0,"DELETE",void 0,t.signal);if(n.status!==200)throw Cn(n)}mirrorEnrollmentSession(e,t){var n;if(Ri(e,this.now(),!0),t.status!=="completed"||t.adoption.collection_id!==e.requested.collectionId)throw tt("Completed adoption does not belong to this session.");return e.requested.retainMirror?{controlUrl:e.controlUrl,pairingId:e.adoptionId,refreshCredential:e.credential,verificationUri:`${e.controlUrl}/mirror/${e.adoptionId}`,expiresAt:new Date(this.now()+Gf).toISOString(),requested:{mirrorName:(n=e.requested.mirrorName)!=null?n:e.requested.sourceName,mode:"read_write",collectionId:e.requested.collectionId}}:null}async uploadPage(e,t,n,i){let s={protocol_version:1,page:t,records:n};await this.importRequest(e.records_url,"PUT",e.access_token,s,i)}async importRequest(e,t,n,i,s){let o;try{o=await this.request({url:e,method:t,headers:{authorization:`Bearer ${n}`,...i===void 0?{}:{"content-type":"application/json"}},...i===void 0?{}:{body:i},...s?{signal:s}:{}})}catch(a){throw Mn(s),Vw()}if(o.status<200||o.status>=300)throw Cn(o)}controlRequest(e,t,n,i,s){return this.request({url:Fw(e,t),method:n,headers:{authorization:`Bearer ${e.credential}`,...i===void 0?{}:{"content-type":"application/json"}},...i===void 0?{}:{body:i},...s?{signal:s}:{}})}async retry(e,t,n,i,s){var l;let o=e-this.now();if(o<=0)return!1;let a=Math.min(Uw(t),o),c=new Date(this.now()+a).toISOString();return(l=i.onStatus)==null||l.call(i,{state:s?"retrying":"waiting_for_approval",attempt:n,expiresAt:new Date(e).toISOString(),retryAt:c,...s?{error:s}:{}}),await this.wait(a,i.signal),!0}};function Ri(r,e,t=!1){Rr(r.controlUrl);let n=Date.parse(r.expiresAt);if(!Pi.test(r.adoptionId)||!Jf(r.credential)||!Number.isFinite(n)||n-e>Gf||!t&&n<=e||!Pi.test(r.requested.collectionId)||!r.requested.displayName.trim()||!r.requested.sourceName.trim())throw new J("invalid_authority_adoption_session","Stored collection adoption state is invalid.");Kw(r.controlUrl,r.verificationUri,r.adoptionId)}function zw(r,e){if(e.status!=="ready"||e.adoption.id!==r.adoptionId||e.adoption.collection_id!==r.requested.collectionId)throw tt("Prepared adoption does not belong to this session.");let t=e.import;if(!Pi.test(t.import_id)||!Jf(t.access_token))throw tt("Connect returned an invalid authority import capability.");let n=[[t.manifest_url,"manifest"],[t.records_url,"records"],[t.files_url,"files"],[t.finalize_url,"finalize"]],i;for(let[s,o]of n){let a=iC(s,t.import_id,o);if(!a||i!==void 0&&a.origin!==i)throw tt("Connect returned an invalid authority import capability.");i=a.origin}}function Dw(r,e){var t;if(e.protocol_version!==1||e.collection_id!==r.requested.collectionId||!Number.isSafeInteger(e.source_head)||e.source_head<0||!eC.test(e.source_revision)||!tC.test(e.manifest_digest)||((t=e.resources.documents)==null?void 0:t.length)===0||!Array.isArray(e.files))throw new J("invalid_authority_snapshot","Authority snapshot does not belong to this adoption.")}function qw(r,e){if(!Cr(e)||!["ready","activating","completed"].includes(et(e.status)))throw tt("Connect returned an invalid adoption exchange.");let t=Hw(r,e.adoption);if(e.status==="completed")return{status:"completed",adoption:t};if(e.status==="activating")return{status:"activating",adoption:t};if(!Cr(e.import)||!Cr(e.staged))throw tt("Connect omitted the authority import capability.");let n=e.import,i=e.staged,s={status:"ready",adoption:t,import:{import_id:et(n.import_id),manifest_url:et(n.manifest_url),records_url:et(n.records_url),files_url:et(n.files_url),finalize_url:et(n.finalize_url),access_token:et(n.access_token)},staged:{state:i.state,manifest_digest:Bw(i.manifest_digest),source_revision:Bw(i.source_revision),source_head:dC(i.source_head)}};if(zw(r,s),!["receiving","uploaded"].includes(s.staged.state))throw tt("Connect returned an invalid staged import state.");return s}function Hw(r,e){if(!Cr(e))throw tt("Connect omitted collection adoption state.");let t=e;if(t.id!==r.adoptionId||t.collection_id!==r.requested.collectionId||!["requested","approved","prepared","activating","completed","cancelled","expired"].includes(t.state)||!Number.isSafeInteger(t.authority_epoch)||t.authority_epoch<2||!lC(t.expires_at))throw tt("Connect returned invalid collection adoption state.");return t}function iC(r,e,t){try{let n=new URL(r);return(n.protocol==="https:"||n.protocol==="http:"&&["localhost","127.0.0.1","[::1]","::1"].includes(n.hostname))&&!n.username&&!n.password&&!n.search&&!n.hash&&n.pathname===`/v1/authority-imports/${e}/${t}`?n:null}catch(n){return null}}function Kw(r,e,t){let n;try{n=new URL(e)}catch(s){throw tt("Connect returned an invalid adoption verification URI.")}let i=new URL(`/adopt/${encodeURIComponent(t)}`,r);if(n.origin!==i.origin||n.pathname!==i.pathname||n.search||n.hash||n.username||n.password)throw tt("Connect returned an untrusted adoption verification URI.");return n.href}function Fw(r,e){let t=e?`/${e}`:"";return`${Rr(r.controlUrl)}/v1/authority-adoptions/${encodeURIComponent(r.adoptionId)}${t}`}function Kf(r,e){let t=r.trim();if(!t||t.length>200)throw new J("invalid_authority_adoption",`${e} must contain between 1 and 200 characters.`);return t}function sC(r,e){if(r.status!==e)throw Cn(r);return r.body}function Cn(r){let e=Cr(r.body)&&Cr(r.body.error)?r.body.error:{};return new J(et(e.code)||"authority_adoption_request_failed",et(e.message)||`Collection adoption request failed with status ${r.status}.`,r.status)}function tt(r){return new J("invalid_authority_adoption_response",r)}function Ww(r){return{code:"authority_adoption_unreachable",message:"Connect could not be reached for collection adoption."}}function Vw(){let r=Ww(void 0);return new J(r.code,r.message)}function Uw(r=Wf){return Number.isFinite(r)?Math.min(3e4,Math.max(250,Math.round(r))):Wf}function oC(r,e){return Mn(e),new Promise((t,n)=>{let i=setTimeout(o,r),s=()=>{clearTimeout(i),e==null||e.removeEventListener("abort",s),n(new J("authority_adoption_cancelled","Collection adoption was cancelled."))};function o(){e==null||e.removeEventListener("abort",s),t()}e==null||e.addEventListener("abort",s,{once:!0})})}function Mn(r){if(r!=null&&r.aborted)throw new J("authority_adoption_cancelled","Collection adoption was cancelled.")}async function aC(r){let e=await fetch(r.url,{method:r.method,headers:r.headers,redirect:"error",...r.body===void 0?{}:{body:r.rawBody?r.body:JSON.stringify(r.body)},...r.signal?{signal:r.signal}:{}}),t=await e.json().catch(()=>({})),n=e.headers.get("retry-after");return{status:e.status,body:t,headers:Object.fromEntries(e.headers.entries()),...n?{retryAfterMs:cC(n)}:{}}}function cC(r){let e=Number(r);if(Number.isFinite(e)&&e>=0)return e*1e3;let t=Date.parse(r);return Number.isFinite(t)?Math.max(0,t-Date.now()):Wf}function lC(r){return Number.isFinite(Date.parse(r))}function Bw(r){return r===null?null:et(r)}function dC(r){return r===null?null:typeof r=="number"&&Number.isSafeInteger(r)&&r>=0?r:Number.NaN}function uC(r){return typeof r=="number"&&Number.isSafeInteger(r)&&r>0}function Jf(r){return typeof r=="string"&&r.length>=16}function et(r){return typeof r=="string"?r:""}function Cr(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}var fC=new TextEncoder,to=Object.freeze({digest:r=>Ne(We(fC.encode(r))),randomId:()=>{var r;if(typeof((r=globalThis.crypto)==null?void 0:r.randomUUID)!="function")throw new b("mirror_random_unavailable","This runtime must provide crypto.randomUUID() or a MirrorRuntime adapter.");return globalThis.crypto.randomUUID()},now:()=>new Date().toISOString()});var eo=class{constructor(){I(this,"held",!1)}async runExclusive(e){if(this.held)throw new b("mirror_folder_in_use","Another mdbase mirror process is already using this folder.");this.held=!0;try{return await e()}finally{this.held=!1}}};function Gw(r,e,t){var i,s,o,a,c,l;if(r.engine_version!==3)throw new b("mirror_state_upgrade_required","Rebuild this prerelease mirror with the plan-only exact-document sync engine.");if(r.protocol_version!==1||r.replica_id!==e)throw new Error;if((i=r.resources)!=null||(r.resources={}),(s=r.generation)!=null||(r.generation=0),(o=r.files)!=null||(r.files={}),r.selective_sync=Rn(r.selective_sync),(a=r.planned_conflicts)!=null||(r.planned_conflicts={}),(c=r.local_bindings)!=null||(r.local_bindings={}),(l=r.mode)!=null||(r.mode="read_only"),r.mode!==t)throw new b("mirror_mode_mismatch",`Mirror metadata belongs to a ${r.mode.replace("_","-")} replica.`);let n=[];for(let[d,u]of Object.entries(r.records))if(n.push(_t(u.path)),u.record&&(u.record.record_id!==d||u.record.path!==u.path))throw new Error;for(let[d,u]of Object.entries(r.resources)){if(Gt(d),d!==u.path)throw new Error;n.push(_t(u.path))}for(let[d,u]of Object.entries(r.files)){if(ft(u.file),u.file.file_id!==d)throw new Error;n.push(_t(u.file.path))}n.sort();for(let d=1;dl.kind==="configuration"&&l.path==="mdbase.yaml");if(n.length!==1)throw new b("invalid_snapshot","Hosted snapshot requires exactly one canonical mdbase.yaml resource.");let i=Xw(n[0].document,e),s=(c=e0(n[0].document).settings)!=null?c:{},o=Ti(s.types_folder,"_types"),a=Ti(s.contracts_folder,"_contracts");for(let l of r){let d=l.path.split(".").at(-1),u=l.path.split("/"),f=u.some(y=>y.startsWith(".")),p=!1;if(l.kind==="configuration")p=l.path==="mdbase.yaml";else if(l.kind==="lock")p=l.path==="mdbase.lock.yaml"&&mC(l.document);else if(l.kind==="type")p=Yf(l.path,o)&&d==="md"&&Jw(l.document,l.path)==="mdbase.type";else if(l.kind==="contract")p=Yf(l.path,a)&&d==="md"&&Jw(l.document,l.path)==="mdbase.contract";else if(l.kind==="schema"){let y=hC(l.document);p=!f&&d==="json"&&u.some(h=>h==="schemas"||h==="_schemas")&&y!==null}else l.kind==="view"&&(p=!f&&d==="base");if(!p)throw new b("invalid_snapshot",`Hosted resource ${l.path} is not valid for kind ${l.kind}.`)}return i}function Yw(r){return{reservedFolders:new Set(["_types","_contracts","_types/_migrations",".mdbase"]),resourcePaths:r}}function Xw(r,e){var s;let t=(s=e0(r).settings)!=null?s:{},n=Ti(t.types_folder,"_types");return{reservedFolders:new Set([n,Ti(t.contracts_folder,"_contracts"),Ti(t.migrations_folder,`${n}/_migrations`),Ti(t.cache_folder,".mdbase",!0)]),resourcePaths:e}}async function Qw(r,e){if(r.length===0)return Yw(new Set);let t=await e();if(t===null)throw new b("invalid_mirror_state","Mirror collection configuration is missing.");return Xw(t,new Set(r))}function dn(r,e){if(Gt(r),/(?:^|\/)\./u.test(r)||e.resourcePaths.has(r)||pC(r,e.reservedFolders)||!r.endsWith(".md"))throw new b("invalid_record_path",`Mirror record path ${r} is outside the configured record namespace.`)}function pC(r,e){for(let t of e)if(Yf(r,t))return!0;return!1}function Zw(r,e){return r.filter(t=>{try{return dn(t,e),!0}catch(n){return!1}})}function e0(r){let e;try{e=ki(r)}catch(n){throw new b("invalid_snapshot","Hosted mdbase.yaml is not valid YAML.")}if(!e||typeof e!="object"||Array.isArray(e))throw new b("invalid_snapshot","Hosted mdbase.yaml requires an object document.");let t=e;if(typeof t.spec_version!="string")throw new b("invalid_snapshot","Hosted mdbase.yaml requires spec_version.");return t}function Ti(r,e,t=!1){let n=typeof r=="string"?r:e;if(Gt(n),!t&&n.split("/").some(i=>i.startsWith(".")))throw new b("invalid_snapshot",`Collection control folder ${n} must not be hidden.`);return n}function Yf(r,e){return r===e||r.startsWith(`${e}/`)}function hC(r){try{let e=JSON.parse(r);return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null}catch(e){return null}}function mC(r){try{let e=ki(r);return e!==null&&typeof e=="object"&&!Array.isArray(e)&&e.kind==="mdbase.type-pack-lock"&&e.lock_version===1&&Array.isArray(e.packs)}catch(e){return!1}}function Jw(r,e){try{return fc(r,e).frontmatter.kind}catch(t){return null}}function bt(r){return Oi(r)}function t0(r,e,t,n,i=[]){let s=bt(r);for(let o of t)if(bt(o)===s)throw new b("invalid_record_path",`Mirror record path ${r} aliases authority resource ${o} on a supported filesystem.`);for(let[o,a]of n)if((o!==e||a.path!==r)&&bt(a.path)===s)throw new b("invalid_record_path",`Mirror record paths ${a.path} and ${r} alias on a supported filesystem.`);for(let[,o]of i)if(bt(o.file.path)===s)throw new b("invalid_record_path",`Mirror record path ${r} aliases collection file ${o.file.path} on a supported filesystem.`)}function r0(r,e,t){var i,s;let n=bt(r);for(let o of Object.values((i=t.resources)!=null?i:{}))if(bt(o.path)===n)throw new b("invalid_file_path",`Collection file ${r} aliases authority resource ${o.path}.`);for(let o of Object.values(t.records))if(bt(o.path)===n)throw new b("invalid_file_path",`Collection file ${r} aliases record ${o.path}.`);for(let[o,a]of Object.entries((s=t.files)!=null?s:{}))if((o!==e||a.file.path!==r)&&bt(a.file.path)===n)throw new b("invalid_file_path",`Collection files ${a.file.path} and ${r} alias on a supported filesystem.`)}function ro(r){let e=new Map;for(let t of r){let n=bt(t),i=e.get(n);if(i!==void 0&&i!==t)throw new b("invalid_record_path",`Mirror paths ${i} and ${t} alias on a supported filesystem.`);e.set(n,t)}}var Ec=class{constructor(e,t,n){I(this,"pathPolicy");I(this,"digest");I(this,"recordIds",new Set);I(this,"physicalPaths",new Set);this.pathPolicy=e,this.digest=n;for(let i of t)this.physicalPaths.add(Oi(i.path))}validate(e){let t=e.document,n=e;if(dn(n.path,this.pathPolicy),this.recordIds.has(n.record_id))throw new b("invalid_snapshot",`Hosted snapshot repeats record identity ${n.record_id}.`);this.recordIds.add(n.record_id);let i=Oi(n.path);if(this.physicalPaths.has(i))throw new b("invalid_snapshot",`Hosted record path ${n.path} aliases another snapshot path on a supported filesystem.`);this.physicalPaths.add(i);let s=this.digest(t);if(n.revision.length!==7+s.length||!n.revision.startsWith("sha256:")||!n.revision.endsWith(s))throw new b("invalid_snapshot",`Hosted record ${n.path} does not match its declared revision.`);if(hw(t,n)!==!0){let a;try{a=fc(t,n.path)}catch(c){throw new b("invalid_snapshot",`Hosted record ${n.path} is not valid Markdown.`)}if(!Xf(a.frontmatter,n.frontmatter)||!yC(a.body,n.body))throw new b("invalid_snapshot",`Hosted record ${n.path} does not match its declared document.`)}return{record:n,document:t,hash:s}}};async function n0(r,e,t){let n,i=new Set;do{let s=await r.snapshot(e.snapshot_id,n);if(s.protocol_version!==1||s.snapshot_id!==e.snapshot_id||s.scope_epoch!==e.scope_epoch||s.cursor!==e.head)throw new b("invalid_snapshot","Authority snapshot boundary changed during download.");if(await t(s.records),n=s.next_page,n!==void 0&&i.has(n))throw new b("invalid_snapshot","Authority snapshot repeated a page cursor.");n!==void 0&&i.add(n)}while(n)}function yC(r,e){return r===e||r.startsWith(` `)&&r.slice(1)===e||e.startsWith(` -`)&&e.slice(1)===r}function Xf(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)=>Xf(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)&&Xf(s,n[i]))}var Ti=class{constructor(e,t,n,i){I(this,"fileSystem");I(this,"runtime");I(this,"mode");I(this,"blobStore");this.fileSystem=e,this.runtime=t,this.mode=n,this.blobStore=i}async recordPathPolicy(e){var t;return n0(Object.keys((t=e.resources)!=null?t:{}),()=>this.fileSystem.read("mdbase.yaml"))}async put(e,t,n={}){var p,y,h,m;let{managedState:i=e,acceptedHash:s,materialized:o,inspectionPreflighted:a=!1}=n;a||an(t.path,await this.recordPathPolicy(e)),o===void 0&&!a&&o0(t.path,t.record_id,Object.keys((p=e.resources)!=null?p:{}),Object.entries(e.records),Object.entries((y=e.files)!=null?y:{}));let c=(h=o==null?void 0:o.document)!=null?h:dc(t),l=await this.fileSystem.read(t.path),d=i==null?void 0:i.records[t.record_id];if(l!==null&&l!==c){let g=this.runtime.digest(l);if(!(d!==void 0&&d.path===t.path&&g===d.hash)&&(s===void 0||g!==s))throw new ht(t.record_id,t.path)}d&&d.path!==t.path&&await this.remove(i,t.record_id,d.path);let u=this.runtime.digest(c);typeof s=="string"&&s===u&&l!==null&&this.runtime.digest(l)===u||await this.fileSystem.write(t.path,c),e.records[t.record_id]={path:t.path,revision:t.revision,hash:(m=o==null?void 0:o.hash)!=null?m:u,...this.mode==="read_write"?{record:t}:{}}}async putFile(e,t,n=e,i){var y,h,m,g;if(pt(t),!this.blobStore)throw new b("file_storage_unavailable","Selected collection files require a content-addressed blob store adapter.");a0(t.path,t.file_id,e),(y=e.files)!=null||(e.files={});let s=(h=n.files)==null?void 0:h[t.file_id],o=await this.fileSystem.inspectBinary(t.path),a=wt(t.path),c=Object.values((m=n.files)!=null?m:{}).find(_=>wt(_.file.path)===a),l=[...Object.values((g=n.resources)!=null?g:{}),...Object.values(n.records)].find(_=>wt(_.path)===a),d=l?await this.fileSystem.read(t.path):null,u=(s==null?void 0:s.file.path)===t.path&&Or(o,s.file),f=c!==void 0&&Or(o,c.file),p=l!==void 0&&d!==null&&this.runtime.digest(d)===l.hash;if(o!==null&&!Or(o,t)&&!u&&!f&&!p&&!(i!==void 0&&(o==null?void 0:o.size)===i.size&&o.content_digest===i.content_digest))throw new ht(t.file_id,t.path);if(s&&s.file.path!==t.path){let _=await this.fileSystem.inspectBinary(s.file.path);if(_!==null&&!Or(_,s.file))throw new ht(t.file_id,s.file.path)}Or(o,t)||await this.fileSystem.writeBinary(t.path,gc(this.blobStore.read(t.content_digest),t)),s&&s.file.path!==t.path&&await this.fileSystem.remove(s.file.path),e.files[t.file_id]={file:t}}async removeFile(e,t){var s;let n=(s=e.files)==null?void 0:s[t];if(!n)return;let i=await this.fileSystem.inspectBinary(n.file.path);if(i!==null&&!Or(i,n.file))throw new ht(t,n.file.path);i!==null&&await this.fileSystem.remove(n.file.path),delete e.files[t]}async remove(e,t,n,i={}){var c;let s=e.records[t],o=(c=s==null?void 0:s.path)!=null?c:n;i.inspectionPreflighted||an(o,await this.recordPathPolicy(e));let a=await this.fileSystem.read(o);if(a!==null&&s&&this.runtime.digest(a)!==s.hash)throw new ht(t,s.path);a!==null&&await this.fileSystem.remove(o),delete e.records[t]}async putResource(e,t,n){var o,a;let i=await this.fileSystem.read(t.path),s=(o=n==null?void 0:n.resources)==null?void 0:o[t.path];if(i!==null&&i!==t.document&&(!s||this.runtime.digest(i)!==s.hash))throw new ht(`resource:${t.path}`,t.path);await this.fileSystem.write(t.path,t.document),(a=e.resources)!=null||(e.resources={}),e.resources[t.path]={path:t.path,revision:t.revision,hash:this.runtime.digest(t.document)}}async removeResource(e,t,n){let i=await this.fileSystem.read(t);if(i!==null&&this.runtime.digest(i)!==n.hash)throw new ht(`resource:${t}`,t);i!==null&&await this.fileSystem.remove(t),e.resources&&delete e.resources[t]}};async function l0(r,e,t,n){var i,s;for(let o in r.records){if(!Object.hasOwn(r.records,o))continue;let a=r.records[o];an(a.path,e);let c=await t.read(a.path);if(c===null||n(c)!==a.hash)throw new ht(o,a.path)}for(let[o,a]of Object.entries((i=r.resources)!=null?i:{})){let c=await t.read(a.path);if(c===null||n(c)!==a.hash)throw new ht(`resource:${o}`,a.path)}for(let[o,a]of Object.entries((s=r.files)!=null?s:{})){let c=await t.inspectBinary(a.file.path);if(!Or(c,a.file))throw new ht(o,a.file.path)}}Ee();async function d0(r){var u,f,p,y,h;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 b("promotion_incomplete_file_projection","Moving the source of truth requires every collection file class with no excluded folders.");if(Object.keys((u=e.planned_conflicts)!=null?u:{}).length>0||e.batch!==void 0)throw new b("promotion_not_converged","Upload or resolve every local change before moving the source of truth.");await l0(e,i,n,s);let o=new Set(Object.keys((f=e.resources)!=null?f:{})),a=new Set(Object.values(e.records).map(m=>m.path)),c=(await n.listMarkdown(o)).filter(m=>!a.has(m));if(c.length>0)throw new b("promotion_unmanaged_files",`Synchronize unmanaged Markdown before promotion: ${c.join(", ")}.`);if(!n.listBinary)throw new b("promotion_file_scan_unavailable","Moving the source of truth requires binary file enumeration.");let l=new Set(Object.values((p=e.files)!=null?p:{}).map(m=>m.file.path)),d=(await n.listBinary(new Set([...o,...a]))).filter(m=>!l.has(m));if(d.length>0)throw new b("promotion_unmanaged_files",`Synchronize unmanaged files before moving the source of truth: ${d.join(", ")}.`);return{cursor:e.cursor,digest:fc([...Object.entries((y=e.resources)!=null?y:{}).map(([m,g])=>({kind:"resource",path:m,identity:"",document_hash:Lf(g.hash)})),...Object.entries(e.records).map(([m,g])=>({kind:"record",path:g.path,identity:m,document_hash:Lf(g.hash)})),...Object.values((h=e.files)!=null?h:{}).map(({file:m})=>({kind:"file",path:m.path,identity:m.file_id,document_hash:pc(m)}))])}}function cn(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+t.file_conflicts.length,issues:e.issues,...i?{failure:i}:{}}}function u0(r,e){return["planned","applying","cancelled","stale","blocked","failed"].includes(r.state)?r:r.conflicts.length>0||r.file_conflicts.length>0||r.local_issues.length>0||e.summary.blocking_issues>0||e.summary.conflicts>0?{...r,state:"attention"}:{...r,state:e.actions.some(t=>t.command!=="advance_checkpoint")?"changes_waiting":"up_to_date"}}function Tr(r,e){var a,c,l,d,u,f,p,y,h;if(!r)return{state:"not_initialized",mode:e,pending:0,pending_files:0,conflicts:[],file_conflicts:[],local_issues:[],cursor:null,last_synced_at:null};let t=[],n=[];for(let[m,g]of Object.entries((a=r.planned_conflicts)!=null?a:{})){if(g.entity==="file"){let k=g.local.state==="exact"?g.local.object.path:g.remote.state==="exact"?g.remote.object.path:"",v=n.findIndex(({file_id:P})=>P===m);v!==-1&&n.splice(v,1),n.push({file_id:m,path:k,code:"file_conflict",message:"Local and authority changes need a decision."});continue}let _=t.findIndex(({record_id:k})=>k===m);_!==-1&&t.splice(_,1);let w=g.local.state==="exact"?g.local.object.path:g.remote.state==="exact"?g.remote.object.path:null;t.push({record_id:m,path:w,kind:g.conflict_kind==="rejected"?"rejected":"conflicted",message:g.conflict_kind==="rejected"?"The authority rejected this local change.":"Local and authority changes need a decision."})}let i=[],s=r.batch?r.batch.plan.actions.slice(r.batch.next_action).filter(m=>m.command!=="advance_checkpoint").length:0,o=r.batch?r.batch.phase==="prepared"?"planned":r.batch.phase==="applying"||r.batch.phase==="effects_complete"?"applying":r.batch.phase==="cancelled"?"cancelled":((c=r.batch.failure)==null?void 0:c.code)==="sync_plan_stale"?"stale":"blocked":null;return{state:o!=null?o:t.length||n.length?"attention":"up_to_date",mode:e,pending:s,pending_files:r.batch?r.batch.plan.actions.slice(r.batch.next_action).filter(m=>m.command!=="advance_checkpoint"&&("target"in m&&m.target.entity==="file"||"source"in m&&m.source.entity==="file"||"entity"in m&&m.entity==="file")).length:0,conflicts:t,file_conflicts:n,local_issues:i,cursor:(d=(l=r.batch)==null?void 0:l.checkpoint_before.cursor)!=null?d:r.cursor,last_synced_at:(u=r.last_synced_at)!=null?u:null,generation:(f=r.generation)!=null?f:0,pending_checkpoint:(y=(p=r.batch)==null?void 0:p.checkpoint_after.cursor)!=null?y: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,...(h=r.batch)!=null&&h.failure?{failure:r.batch.failure}:{}}}Ee();Ee();async function EM(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 b("sync_protocol_incompatible",`Filesystem mirror requires exact-document v1 and its own ${t.replace("_","-")} replica.`);return n}async function Ec(r,e,t,n,i){var f;let s=await EM(r,e,t),o=(f=s.resources.documents)!=null?f:[],a=$c(o),c=new Sc(a,o,i.digest),l=[];await c0(e,s,async p=>{for(let y of p){let h=c.validate(y);On(n,h.record.path)&&l.push(h)}});let d=[],u=new Set;return await jw(e,s,async p=>{for(let y of p)if(_c(n,y)){if(u.has(y.file_id))throw new b("invalid_snapshot",`Hosted snapshot repeats file identity ${y.file_id}.`);u.add(y.file_id),d.push(y)}}),to([...o.map(p=>p.path),...l.map(({record:p})=>p.path),...d.map(p=>p.path)]),{session:s,resources:o,records:l,files:d}}var Ac="exact_document_plan_only_v1",xc="three_way_exact_document_v1",kc="portable_mirror_projection_v1";Ee();function Pc(r){return JSON.stringify(Qf(r))}function ro(r,e){return`sha256:${e(Pc(r))}`}function Qf(r){if(r===null||typeof r=="string"||typeof r=="boolean")return r;if(typeof r=="number"){if(!Number.isSafeInteger(r))throw new b("invalid_sync_plan","Sync plans contain only safe integer numeric values.");return r}if(Array.isArray(r))return r.map(Qf);if(typeof r=="object"){let e={};for(let t of Object.keys(r).sort()){let n=r[t];if(n===void 0)throw new b("invalid_sync_plan",`Sync plan field ${t} is undefined rather than an explicit state.`);e[t]=Qf(n)}return e}throw new b("invalid_sync_plan","Sync plans contain only canonical I-JSON values.")}function y0(r,e,t){let n=new Map(r.base.map(d=>[d.identity,d])),i=new Map(r.remote.map(d=>[d.identity,d])),s=new Map,o=new Map(r.local.map(d=>[d.object.path,d]));for(let d of r.local)!d.stable_identity||d.object.identity===""||(s.set(d.object.identity,d.object),o.delete(d.object.path));for(let[d,u]of n){let f=o.get(u.path);f&&(s.set(d,{...f.object,identity:d}),o.delete(u.path))}for(let[d,u]of i){if(s.has(d))continue;let f=o.get(u.path);f&&f.object.entity===u.entity&&(s.set(d,{...f.object,identity:d}),o.delete(u.path))}for(let[d,u]of n){if(s.has(d))continue;let f=[...o.values()].filter(y=>y.object.entity===u.entity&&y.object.payload_revision===u.payload_revision);if(f.length!==1)continue;let p=f[0];s.set(d,{...p.object,identity:d,revision:p.object.payload_revision===u.payload_revision?u.revision:p.object.revision}),o.delete(p.object.path)}for(let d of o.values()){let u=d.stable_identity?d.object.identity:CM(e,d.object,t);s.set(u,{...d.object,identity:u})}let a=new Set([...n.keys(),...s.keys(),...i.keys()]),c=new Map([...s.values()].map(d=>[d.path,d])),l=new Map([...i.values()].map(d=>[d.path,d]));return[...a].sort().map(d=>{var m,g,_,w,k;let u=n.get(d),f=s.get(d),p=i.get(d),y=(g=(m=p==null?void 0:p.path)!=null?m:f==null?void 0:f.path)!=null?g:u.path,h=(w=(_=f==null?void 0:f.path)!=null?_:p==null?void 0:p.path)!=null?w:u.path;return{entity:((k=f!=null?f:p)!=null?k:u).entity,identity:d,base:no(u),local:no(f),remote:no(p),local_target_owner:no(c.get(y)),remote_target_owner:no(l.get(h))}})}function g0(r,e){let t=[];for(let l of[...r.objects].sort(NM))RM(r,l,t);t=kM(t,r.objects,e),t=AM(t,r.objects);let n=t.map(l=>l.key);t.push({key:"checkpoint",depends_on_keys:n,command:"advance_checkpoint",reason:r.kind==="incremental"?"remote_change":r.kind,expected:r.boundary.checkpoint,next:{generation:r.boundary.checkpoint.generation+1,cursor:r.boundary.authority_cursor}});let i=new Map;for(let l of t){let{key:d,depends_on_keys:u,...f}=l;i.set(d,ro({action_scope:{replica_id:r.boundary.replica_id,scope_epoch:r.boundary.scope_epoch,generation:r.boundary.checkpoint.generation},key:d,...f},e))}let s=t.map(l=>{let{key:d,depends_on_keys:u,...f}=l,p={...f,action_id:i.get(d),depends_on:u.map(y=>i.get(y))};if((p.command==="put_remote"||p.command==="move_remote"||p.command==="delete_remote")&&(p.idempotency_key=p.action_id),p.command==="move_remote"){let y=u.find(h=>h===`${p.source.identity}:put-remote`);y&&(p.revision_from_dependency=i.get(y))}return p}),o=[...r.issues].sort(LM),a={uploads:s.filter(jM).length,downloads:s.filter(DM).length,conflicts:s.filter(l=>l.command==="record_conflict").length,blocking_issues:o.filter(l=>l.blocking).length},c={plan_version:1,engine_profile:Ac,protocol_profile:"exact_document_v1",planner_policy:xc,projection_policy:kc,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:s,issues:o,summary:a};return{...c,fingerprint:ro(c,e)}}function AM(r,e){var c;if(!r.some(l=>l.command==="move_remote"))return r;let t=[...r],n=new Set;for(let l of xM(t))for(let d of l){let u=t.find(f=>f.key===d);(u==null?void 0:u.command)==="move_remote"&&n.add(u.source.identity)}let i=tp(t),s=new Map(t.map(l=>[l.key,l])),o=!0;for(;o;){o=!1;for(let l of t){if(l.command!=="move_remote")continue;let d=l.expected_target_owner;if(d.state!=="exact"||d.object.identity===l.source.identity)continue;let u=s.get((c=i.get(pr(d.object)))!=null?c:""),f=u&&f0(u);(!u||f&&n.has(f))&&!n.has(l.source.identity)&&(n.add(l.source.identity),o=!0)}}if(n.size>0){t=t.filter(d=>{let u=f0(d);return!u||!n.has(u)||d.command!=="put_remote"&&d.command!=="move_remote"});let l=new Map(e.map(d=>[d.identity,d]));for(let d of[...n].sort()){let u=l.get(d);!u||u.entity==="resource"||t.push({key:`${d}:conflict`,depends_on_keys:[],command:"record_conflict",reason:"local_change",identity:d,entity:u.entity,local:u.local,remote:u.remote,conflict_kind:"path_occupied"})}}let a=tp(t);for(let l of t){if(l.command!=="move_remote")continue;let d=l.expected_target_owner;if(d.state!=="exact"||d.object.identity===l.source.identity)continue;let u=a.get(pr(d.object));!u||u===l.key||(l.depends_on_keys.includes(u)||l.depends_on_keys.push(u),l.expected_target_owner={state:"absent"})}return _0(t)}function xM(r){var s;let e=r.filter(o=>o.command==="move_remote"),t=new Map(e.map(o=>[o.key,o])),n=tp(r),i=new Map;for(let o of e){let a=[],c=new Map,l=o;for(;l;){let d=c.get(l.key);if(d!==void 0){let f=a.slice(d);i.set([...f].sort().join("\0"),f);break}c.set(l.key,a.length),a.push(l.key);let u=l.expected_target_owner;l=u.state==="exact"?t.get((s=n.get(pr(u.object)))!=null?s:""):void 0}}return[...i.values()]}function tp(r){let e=new Map;for(let t of r)t.command==="move_remote"?e.set(pr(t.source),t.key):t.command==="delete_remote"&&e.set(pr(t.target),t.key);return e}function f0(r){if(r.command==="move_remote")return r.source.identity;if(r.command==="put_remote"||r.command==="delete_remote")return r.target.identity}function kM(r,e,t){var u;if(!r.some(f=>f.command==="move_local"||f.command==="write_local"))return r;let n=[...r],i=new Set;for(let f of e)f.base.state==="exact"&&i.add(f.base.object.path),f.local.state==="exact"&&i.add(f.local.object.path),f.remote.state==="exact"&&i.add(f.remote.object.path);for(;;){let f=PM(n);if(!f)break;let p=[...f].sort()[0],y=n.findIndex(w=>w.key===p),h=n[y];if(!h||h.command!=="move_local")throw new Error("Planner invariant: local path cycle contains a non-move action.");let m=OM(h.source,h.target_path,i,t);i.add(m);let g={...h.source,path:m},_={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=g,h.expected_source_owner={state:"exact",object:g},h.depends_on_keys=[_.key],n.splice(y,0,_)}let s=rp(n),o=new Map(e.map(f=>[f.identity,f])),a=new Set,c=new Map(n.map(f=>[f.key,f])),l=!0;for(;l;){l=!1;for(let f of n){let p=p0(f),y=Ic(f);if((p==null?void 0:p.state)!=="exact"||p.object.identity===y)continue;let h=c.get((u=s.get(pr(p.object)))!=null?u:""),m=h&&Ic(h);(!h||m&&a.has(m))&&!a.has(y)&&(a.add(y),l=!0)}}if(a.size>0){n=n.filter(f=>!a.has(Ic(f))||f.command!=="move_local"&&f.command!=="write_local");for(let f of[...a].sort()){let p=o.get(f);!p||p.entity==="resource"||n.push({key:`${f}:conflict`,depends_on_keys:[],command:"record_conflict",reason:"remote_change",identity:f,entity:p.entity,local:p.local,remote:p.remote,conflict_kind:"path_occupied"})}}let d=rp(n);for(let f of n){let p=p0(f),y=Ic(f);if((p==null?void 0:p.state)!=="exact"||p.object.identity===y)continue;let h=d.get(pr(p.object));!h||h===f.key||(f.depends_on_keys.includes(h)||f.depends_on_keys.push(h),IM(f,{state:"absent"}))}return _0(n)}function PM(r){var i;let e=r.filter(s=>s.command==="move_local"),t=new Map(e.map(s=>[s.key,s])),n=rp(r);for(let s of e){let o=[],a=new Map,c=s;for(;c;){let l=a.get(c.key);if(l!==void 0)return o.slice(l);a.set(c.key,o.length),o.push(c.key);let d=c.expected_target_owner;c=d.state==="exact"?t.get((i=n.get(pr(d.object)))!=null?i:""):void 0}}}function rp(r){let e=new Map;for(let t of r)t.command==="move_local"?e.set(pr(t.source),t.key):t.command==="delete_local"&&e.set(pr(t.target),t.key);return e}function p0(r){if(r.command==="move_local")return r.expected_target_owner;if(r.command==="write_local")return r.expected_path_owner}function IM(r,e){r.command==="move_local"?r.expected_target_owner=e:r.command==="write_local"&&(r.expected_path_owner=e)}function Ic(r){return r.command==="move_local"?r.source.identity:r.command==="write_local"||r.command==="delete_local"?r.target.identity:""}function pr(r){return`${r.entity}\0${r.identity}\0${r.path}`}function OM(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 d=n(`${r.entity}\0${r.identity}\0${r.path}\0${e}\0${l}`),u=`${s}.mdbase-sync-stage-${d.slice(0,16)}${c}`;if(!t.has(u))return u}}function _0(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 RM(r,e,t){if(e.frozen_conflict){t.push({key:`${e.identity}:conflict`,depends_on_keys:[],command:"record_conflict",reason:"pending",identity:e.identity,entity:e.entity,...e.frozen_conflict});return}let n=!ep(e.local,e.base),i=!ep(e.remote,e.base);if(!(!n&&!i)){if(e.entity==="resource"){if(n)return;Zf(e,t);return}if(r.mode==="read_only"){n||Zf(e,t);return}if(n&&i){if(ep(e.local,e.remote))return;t.push(MM(e));return}n?TM(e,t):Zf(e,t)}}function Zf(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(h0(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(h0(r,t,i?[i]:[]))}function h0(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:Mr(r.local).revision,payload_revision:Mr(r.local).payload_revision,...Mr(r.local).size===void 0?{}:{size:Mr(r.local).size}}}:r.local,expected_path_owner:t.length>0?{state:"exact",object:{...e,revision:Mr(r.local).revision,payload_revision:Mr(r.local).payload_revision,...Mr(r.local).size===void 0?{}:{size:Mr(r.local).size}}}:r.local_target_owner}}function TM(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(m0(r,t,[]));return}let n=r.remote.object,i;if(t.revision!==n.revision){let s=m0(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 m0(r,e,t){return{key:`${r.identity}:put-remote`,depends_on_keys:t,command:"put_remote",reason:"local_change",target:e,payload_revision:Mr(r.local).payload_revision,expected_remote:r.remote,expected_local:r.local,idempotency_key:""}}function MM(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 Mr(r){if(r.state!=="exact")throw new Error("Planner invariant: expected exact object state.");return r.object}function no(r){return r?{state:"exact",object:r}:{state:"absent"}}function CM(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 ep(r,e){return Pc(r)===Pc(e)}function NM(r,e){return`${r.entity}\0${r.identity}`.localeCompare(`${e.entity}\0${e.identity}`)}function LM(r,e){var t,n;return`${(t=r.path)!=null?t:""}\0${r.code}\0${r.message}`.localeCompare(`${(n=e.path)!=null?n:""}\0${e.code}\0${e.message}`)}function jM(r){return r.command==="put_remote"||r.command==="move_remote"||r.command==="delete_remote"}function DM(r){return r.command==="write_local"||r.command==="move_local"||r.command==="delete_local"}var Oc=class{constructor(e,t,n,i,s,o,a,c,l){I(this,"replicaId");I(this,"transport");I(this,"mode");I(this,"fileSystem");I(this,"blobStore");I(this,"selectiveSync");I(this,"runtime");I(this,"readState");I(this,"currentRecordPathPolicy");this.replicaId=e,this.transport=t,this.mode=n,this.fileSystem=i,this.blobStore=s,this.selectiveSync=o,this.runtime=a,this.readState=c,this.currentRecordPathPolicy=l}async inspect(e){let t=e===void 0?await this.readState():e;if(!t)return this.inspectSnapshot("initial",null);if(t.batch)throw new b("mirror_recovery_required","The prepared sync batch must recover before a new inspection can be planned.");return JSON.stringify(t.selective_sync)!==JSON.stringify(this.selectiveSync)?this.inspectSnapshot("rebuild",t):this.inspectIncremental(t)}async inspectSnapshot(e,t){let n=await Ec(this.replicaId,this.transport,this.mode,this.selectiveSync,this.runtime),i=$c(n.resources),s=await this.inspectLocal(t,n.resources,i),o=new Map(n.records.map(({record:c})=>[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){var l,d;let t=new Map;for(let[u,f]of Object.entries(e.records))f.record&&t.set(u,f.record);let n=new Map(Object.entries((l=e.files)!=null?l:{}).map(([u,f])=>[u,f.file])),i=new Map(b0(e).map(u=>[UM(u),u])),s=e.cursor,o=e.cursor;for(;;){let u=s,f=await this.transport.changes(u,200);if(f.scope_epoch!==e.scope_epoch||f.cursorf.head||f.has_more&&f.cursor===u)throw new b("invalid_change_page","Authority returned an invalid change boundary.");if(f.reset_required)return this.inspectSnapshot("rebuild",e);for(let p of f.events){if(p.sequence<=o||p.sequence>f.cursor)throw new b("invalid_change_page","Authority change events are not strictly ordered.");o=p.sequence,this.applyRemoteObservation(i,t,n,p)}if(s=f.cursor,!f.has_more)break}let a=Object.values((d=e.resources)!=null?d:{}).map(u=>({path:u.path,kind:BM(u.path),revision:u.revision,document:""})),c=await this.inspectLocal(e,a,await this.currentRecordPathPolicy(e));return 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"){ww(i);let s=i.record.record_id;On(this.selectiveSync,i.record.path)?(e.set(`record:${s}`,w0(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"){pt(i.file);let s=i.file.file_id;_c(this.selectiveSync,i.file)?(e.set(`file:${s}`,ip(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){var y,h,m,g,_,w,k,v,P,O,$,R,S,V,B;let i=[],s=new Map,o=new Map,a=[],c=new Map(Object.entries((y=e==null?void 0:e.records)!=null?y:{}).map(([T,E])=>[E.path,[T,E]])),l=new Map(Object.entries((h=e==null?void 0:e.planned_conflicts)!=null?h:{}).filter(([,T])=>T.entity==="record"&&T.local.state==="exact").map(([T,E])=>[E.local.state==="exact"?E.local.object.path:"",T])),d=new Map(Object.entries((m=e==null?void 0:e.local_bindings)!=null?m:{}).filter(([,T])=>T.entity==="record").map(([T,E])=>[E.path,T])),u=new Set([...Object.keys((g=e==null?void 0:e.resources)!=null?g:{}),...t.map(T=>T.path)]);for(let T of u){let E=await this.fileSystem.read(T),x=(_=e==null?void 0:e.resources)==null?void 0:_[T];if(E===null)continue;let de=`sha256:${this.runtime.digest(E)}`;i.push({stable_identity:!0,object:Mi("resource",T,T,de)}),s.set(T,E);let Z=t.find(U=>U.path===T);!x&&Z&&Z.revision!==de?a.push({code:"local_collision",message:`${T} differs locally from the exact authority document.`,path:T,blocking:!0}):x&&x.revision!==de&&a.push({code:"mirror_diverged",message:`Authority-owned resource ${T} changed locally.`,path:T,blocking:!0})}let f=new Set(Object.values((w=e==null?void 0:e.records)!=null?w:{}).map(T=>T.path)),p=i0(await this.fileSystem.listMarkdown(u),n).filter(T=>On(this.selectiveSync,T)||f.has(T));for(let T of p){let E=await this.fileSystem.read(T);if(E===null)continue;let x=`sha256:${this.runtime.digest(E)}`,de=l.get(T),Z=d.get(T),U=(k=c.get(T))==null?void 0:k[0],fe=(P=(v=de!=null?de:Z)!=null?v:U)!=null?P:"";i.push({stable_identity:fe!=="",object:Mi("record",fe,T,x)}),s.set(T,E)}if(this.selectiveSync.file_classes.length>0){if(!this.fileSystem.listBinary)throw new b("file_storage_unavailable","Selected files require binary enumeration.");let T=new Set(Object.values((O=e==null?void 0:e.files)!=null?O:{}).map(U=>U.file.path)),E=new Map(Object.entries(($=e==null?void 0:e.files)!=null?$:{}).map(([U,fe])=>[fe.file.path,[U,fe]])),x=new Map(Object.entries((R=e==null?void 0:e.planned_conflicts)!=null?R:{}).filter(([,U])=>U.entity==="file"&&U.local.state==="exact").map(([U,fe])=>[fe.local.state==="exact"?fe.local.object.path:"",U])),de=new Map(Object.entries((S=e==null?void 0:e.local_bindings)!=null?S:{}).filter(([,U])=>U.entity==="file").map(([U,fe])=>[fe.path,U])),Z=(await this.fileSystem.listBinary(u)).filter(U=>Nw(this.selectiveSync,U)||T.has(U));for(let U of Z){let fe=await this.fileSystem.inspectBinary(U);if(!fe)continue;let Ve=x.get(U),Yt=de.get(U),Lr=E.get(U),ln=(B=(V=Ve!=null?Ve:Yt)!=null?V:Lr==null?void 0:Lr[0])!=null?B:"";i.push({stable_identity:ln!=="",object:{entity:"file",identity:ln,path:U,revision:Lr&&Lr[1].file.content_digest===fe.content_digest?Lr[1].file.revision:fe.content_digest,payload_revision:fe.content_digest,size:fe.size}}),o.set(U,fe)}}try{to([...u,...p,...o.keys()])}catch(T){let E=T instanceof Error?T:new Error(String(T));a.push({code:$0(T),message:E.message,blocking:!0})}return{observations:i,documents:s,binary:o,issues:a}}async finish(e){var u,f,p,y,h;let{prior:t,local:n}=e,i=(u=e.remoteRefs)!=null?u:[...e.remoteResources.map(FM),...[...e.remoteRecords.values()].map(w0),...[...e.remoteFiles.values()].map(ip)],s=y0({base:t?b0(t):[],local:n.observations,remote:i},`${this.replicaId}\0${e.scopeEpoch}\0${(f=t==null?void 0:t.generation)!=null?f:0}`,this.runtime.digest);for(let m of s){let g=(p=t==null?void 0:t.planned_conflicts)==null?void 0:p[m.identity];!g||g.entity!==m.entity||(m.frozen_conflict={local:g.local,remote:g.remote,conflict_kind:g.conflict_kind})}let o=[...n.issues];for(let m of s)(e.kind==="initial"||e.kind==="rebuild")&&m.base.state==="absent"&&m.local.state==="exact"&&m.remote.state==="exact"&&!v0(m.local,m.remote)&&o.push({code:"local_collision",message:`${m.remote.object.path} differs locally from the exact authority object.`,path:m.remote.object.path,blocking:!0}),m.remote.state==="exact"&&m.local_target_owner.state==="exact"&&m.remote.object.identity!==m.local_target_owner.object.identity&&o.push({code:"local_collision",message:`${m.remote.object.path} is owned by different local bytes.`,path:m.remote.object.path,blocking:!0});try{to([...i.map(m=>m.path),...n.observations.map(({object:m})=>m.path)])}catch(m){let g=m instanceof Error?m:new Error(String(m));o.push({code:$0(m),message:g.message,blocking:!0})}if(this.mode==="read_only"){for(let m of s)if(m.entity!=="resource"&&!v0(m.local,m.base)){let g=VM(m.local,m.base);if(o.some(_=>_.blocking&&_.path===g))continue;o.push({code:"mirror_diverged",message:`${g} changed in a receive-only mirror.`,path:g,blocking:!0})}}let a=ro(In(this.selectiveSync),this.runtime.digest),c={boundary:{engine_profile:Ac,protocol_profile:"exact_document_v1",planner_policy:xc,projection_policy:kc,replica_id:this.replicaId,scope_epoch:e.scopeEpoch,authority_cursor:e.authorityCursor,checkpoint:{generation:(y=t==null?void 0:t.generation)!=null?y:0,cursor:(h=t==null?void 0:t.cursor)!=null?h:null},selective_sync_fingerprint:a},mode:this.mode,kind:e.kind,selective_sync:In(this.selectiveSync),objects:s,issues:qM(o)},l=g0(c,this.runtime.digest),d=await this.bindPayloads(l,n,e.remoteRecords,e.remoteResources,e.remoteFiles);return{summary:c,plan:l,durable_payloads:d,prior:t,snapshot:e.snapshot,remote_records:e.remoteRecords,remote_files:e.remoteFiles}}async bindPayloads(e,t,n,i,s){let o={documents:{},records:{},resources:{},files:{},local_files:{},mutations:{}},a=new Map(i.map(c=>[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 d=t.binary.get(l);if(!d)throw Mn(c.action_id);await this.stageLocalBinary(l,d),o.local_files[c.action_id]={path:l,...d}}else{let d=t.documents.get(l);if(d===void 0||`sha256:${this.runtime.digest(d)}`!==c.payload_revision)throw Mn(c.action_id);o.documents[c.action_id]=d}c.target.entity==="record"&&(o.mutations[c.action_id]={operation:"put",mutation_id:np(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 Mn(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 Mn(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 Mn(c.action_id);await bc(this.transport,this.blobStore,l),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 Mn(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 Mn(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:np(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:np(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 b("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 b("sync_plan_stale",`${e} disappeared during inspection.`);await this.blobStore.write(t.content_digest,Dw(n,t,e))}};function qM(r){var t;let e=new Map;for(let n of r)e.set(`${n.code}\0${(t=n.path)!=null?t:""}\0${n.message}\0${n.blocking}`,n);return[...e.values()]}function b0(r){var e,t;return[...Object.entries((e=r.resources)!=null?e:{}).map(([n,i])=>Mi("resource",n,i.path,i.revision)),...Object.entries(r.records).map(([n,i])=>Mi("record",n,i.path,i.revision)),...Object.entries((t=r.files)!=null?t:{}).map(([n,i])=>ip({...i.file,file_id:n}))]}function w0(r){return Mi("record",r.record_id,r.path,r.revision)}function FM(r){return Mi("resource",r.path,r.path,r.revision)}function Mi(r,e,t,n){return{entity:r,identity:e,path:t,revision:n,payload_revision:n}}function ip(r){return{entity:"file",identity:r.file_id,path:r.path,revision:r.revision,payload_revision:r.content_digest,size:r.size}}function UM(r){return`${r.entity}:${r.identity}`}function v0(r,e){return JSON.stringify(r)===JSON.stringify(e)}function VM(r,e){return r.state==="exact"?r.object.path:e.state==="exact"?e.object.path:"mirror"}function Mn(r){return new b("sync_payload_incomplete",`Inspected action ${r} has no revision-bound payload.`)}function $0(r){return r&&typeof r=="object"&&"code"in r&&typeof r.code=="string"?r.code:"sync_inspection_failed"}function BM(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 np(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)}`}Ee();Mc();var Nc=class{constructor(e){I(this,"ports");I(this,"materializer");I(this,"ownersByPath",new Map);I(this,"pathsByOwner",new Map);this.ports=e,this.materializer=new Ti(e.fileSystem,e.runtime,e.mode,e.blobStore)}async execute(e,t){var s,o;let n=nt(e);this.indexPathOwners(e);let i=new Set(n.receipts.map(a=>a.action_id));for(await E0(e,this.ports.store);n.next_action!i.has(l));if(c){let l={code:"invalid_mirror_state",message:`Action ${a.action_id} is missing dependency ${c}.`,action_id:a.action_id};return await Rc(e,"blocked",l,this.ports.store),{status:"blocked",completed:n.next_action,failure:l}}try{let l=await this.dispatch(e,a);await A0(e,l,this.ports.store),i.add(l.action_id),(o=(s=this.ports).onProgress)==null||o.call(s,n.next_action,n.plan.actions.length-1)}catch(l){let d=GM(l,a.action_id);return await Rc(e,"blocked",d,this.ports.store),{status:d.code==="sync_plan_stale"?"stale":"blocked",completed:n.next_action,failure:d}}}throw new b("invalid_mirror_state","Prepared plan has no checkpoint action.")}async dispatch(e,t){var n,i;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":return(n=e.planned_conflicts)!=null||(e.planned_conflicts={}),e.planned_conflicts[t.identity]={entity:t.entity,local:t.local,remote:t.remote,conflict_kind:t.conflict_kind},(i=e.local_bindings)!=null||(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"advance_checkpoint":throw new b("invalid_mirror_state","The executor cannot dispatch checkpoint actions.")}}rebaseConflict(e,t){var s;let n=nt(e).payloads;if(t.entity==="record"){if(t.remote.state==="absent"){delete e.records[t.identity];return}let o=n.records[t.action_id];if(!o||o.revision!==t.remote.object.revision)throw hr(t);Cc(o,this.ports.runtime,o.revision),e.records[t.identity]={path:o.path,revision:o.revision,hash:t.local.state==="exact"?t.local.object.payload_revision.replace(/^sha256:/u,""):this.ports.runtime.digest(o.document),...this.ports.mode==="read_write"?{record:o}:{}};return}if((s=e.files)!=null||(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 hr(t);pt(i),e.files[t.identity]={file:i}}async writeLocal(e,t){let n=await this.ports.fileSystem.exists(t.target.path);(!n||!await this.matchesRef(t.target))&&(await this.assertLocal(t.expected_local),await this.assertPathOwner(t.target.path,t.expected_path_owner,n));let i=nt(e).payloads;if(t.target.entity==="record"){let o=i.records[t.action_id];if(!o||o.revision!==t.payload_revision)throw hr(t);return Cc(o,this.ports.runtime,t.payload_revision),await this.materializer.put(e,o,{inspectionPreflighted:!0}),this.installPathOwner(t.target),{action_id:t.action_id,status:"completed"}}if(t.target.entity==="resource"){let o=i.resources[t.action_id];if(!o||o.revision!==t.payload_revision||`sha256:${this.ports.runtime.digest(o.document)}`!==o.revision)throw hr(t);return await this.materializer.putResource(e,o,e),this.installPathOwner(t.target),{action_id:t.action_id,status:"completed"}}let s=i.files[t.action_id];if(!s||s.content_digest!==t.payload_revision)throw hr(t);return await this.materializer.putFile(e,s,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)),KM(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){var i;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 s=(i=e.resources)==null?void 0:i[t.target.identity];s?await this.materializer.removeResource(e,t.target.path,s):await this.ports.fileSystem.remove(t.target.path)}else await this.materializer.removeFile(e,t.target.identity);else WM(e,t.target);return this.removePathOwner(t.target),{action_id:t.action_id,status:"completed"}}async putRemote(e,t){var a,c;let n=nt(e).payloads;if(t.target.entity==="record"){let l=n.mutations[t.action_id],d=n.documents[t.action_id];if(!l||l.operation!=="put"||d===void 0)throw hr(t);if(`sha256:${this.ports.runtime.digest(d)}`!==t.payload_revision)throw new b("sync_plan_stale","Prepared local document payload no longer matches its revision.");let u=await this.ports.transport.mutate(l);return this.acceptRecordReceipt(e,t,u,d),sp(t.action_id,u)}if(t.target.entity==="resource")throw new b("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 hr(t);let s={protocol_version:1,type:"open_file_upload",transfer_id:ap(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(pt(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 op(t);return(a=e.files)!=null||(e.files={}),e.files[o.file.file_id]={file:o.file},(c=e.local_bindings)==null||delete c[t.target.identity],{action_id:t.action_id,status:"completed",file:o.file}}async moveRemote(e,t){var s,o,a;if(t.source.entity==="record"){let c=nt(e).payloads.mutations[t.action_id];if(!c||c.operation!=="move")throw hr(t);let l=await this.ports.transport.mutate(c);return this.acceptRecordReceipt(e,t,l),sp(t.action_id,l)}if(t.source.entity==="resource"||!this.ports.transport.moveFile)throw new b("invalid_sync_plan","This remote move command is unsupported.");let n={protocol_version:1,type:"move_file",mutation_id:ap(t.action_id),file_id:t.source.identity,if_revision:(s=this.dependencyFileRevision(e,t))!=null?s: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(pt(i.file),i.mutation_id!==n.mutation_id||i.file.file_id!==t.source.identity||i.file.path!==t.target_path)throw op(t);return(o=e.files)!=null||(e.files={}),e.files[t.source.identity]={file:i.file},(a=e.local_bindings)==null||delete a[t.source.identity],{action_id:t.action_id,status:"completed",file:i.file}}dependencyFileRevision(e,t){if(!t.revision_from_dependency)return;let n=nt(e).receipts.find(({action_id:i})=>i===t.revision_from_dependency);if(!(n!=null&&n.file)||n.file.file_id!==t.source.identity)throw new b("invalid_mirror_state",`Move ${t.action_id} is missing its dependency file receipt.`);return n.file.revision}async deleteRemote(e,t){var s,o;if(t.target.entity==="record"){let a=nt(e).payloads.mutations[t.action_id];if(!a||a.operation!=="delete")throw hr(t);let c=await this.ports.transport.mutate(a);return this.acceptRecordReceipt(e,t,c),sp(t.action_id,c)}if(t.target.entity==="resource"||!this.ports.transport.deleteFile)throw new b("invalid_sync_plan","This remote delete command is unsupported.");let n={protocol_version:1,type:"delete_file",mutation_id:ap(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 op(t);return(s=e.files)==null||delete s[t.target.identity],(o=e.local_bindings)==null||delete o[t.target.identity],{action_id:t.action_id,status:"completed"}}acceptRecordReceipt(e,t,n,i){var l,d,u,f;let o=("target"in t?t.target:t.source).identity;if(n.status==="applied"||n.status==="previously_applied"){if(n.record){Cc(n.record,this.ports.runtime,n.record.revision);let p=e.records[o];e.records[o]={path:n.record.path,revision:n.record.revision,hash:i===void 0?(l=p==null?void 0:p.hash)!=null?l: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];(d=e.local_bindings)==null||delete d[o];return}let a=n.status==="conflicted"?n.conflict.current:void 0;a&&Cc(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;(u=e.planned_conflicts)!=null||(e.planned_conflicts={}),e.planned_conflicts[o]={entity:"record",local:t.expected_local,remote:c,conflict_kind:n.status==="rejected"?"rejected":"both_changed"},(f=e.local_bindings)!=null||(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 new b("sync_plan_stale",`${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!=null?n:await this.pathExists(e)))throw new b("sync_plan_stale",`${e} is no longer vacant.`);return}if(!i||i.entity!==t.object.entity||i.identity!==t.object.identity)throw new b("sync_plan_stale",`${e} has a different path owner.`)}async matchesRef(e){if(e.entity==="file"){let n=await this.ports.fileSystem.inspectBinary(e.path);return n!==null&&n.content_digest===e.payload_revision&&(e.size===void 0||n.size===e.size)}let t=await this.ports.fileSystem.read(e.path);return t!==null&&`sha256:${this.ports.runtime.digest(t)}`===e.payload_revision}async pathExists(e){return this.ports.fileSystem.exists(e)}indexPathOwners(e){var t,n;this.ownersByPath.clear(),this.pathsByOwner.clear();for(let[i,s]of Object.entries(e.records))this.installPathOwner({entity:"record",identity:i,path:s.path,revision:s.revision,payload_revision:`sha256:${s.hash}`});for(let[i,s]of Object.entries((t=e.resources)!=null?t:{}))this.installPathOwner({entity:"resource",identity:i,path:s.path,revision:s.revision,payload_revision:`sha256:${s.hash}`});for(let[i,s]of Object.entries((n=e.files)!=null?n:{}))this.installPathOwner({entity:"file",identity:i,path:s.file.path,revision:s.file.revision,payload_revision:s.file.content_digest,size:s.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){var i;let t=`${e.entity}:${e.identity}`,n=(i=this.pathsByOwner.get(t))!=null?i:e.path;this.ownersByPath.delete(n),this.pathsByOwner.delete(t)}};function KM(r,e,t){var n,i;if(e.entity==="record"){let s=r.records[e.identity];s&&(s.path=t)}else if(e.entity==="resource"){let s=(n=r.resources)==null?void 0:n[e.identity];s&&(s.path=t)}else{let s=(i=r.files)==null?void 0:i[e.identity];s&&(s.file.path=t)}}function WM(r,e){var t,n;e.entity==="record"?delete r.records[e.identity]:e.entity==="resource"?(t=r.resources)==null||delete t[e.identity]:(n=r.files)==null||delete n[e.identity]}function Cc(r,e,t){let n=dc(r);if(r.revision!==t||`sha256:${e.digest(n)}`!==t)throw new b("invalid_sync_response","Record receipt does not match its exact document revision.")}function sp(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 hr(r){return new b("sync_payload_incomplete",`Prepared action ${r.action_id} has no exact payload capability.`)}function op(r){return new b("invalid_sync_response",`Authority receipt does not match prepared action ${r.action_id}.`)}function GM(r,e){let t=r instanceof Error?r:new Error(String(r));return{code:r&&typeof r=="object"&&"code"in r&&typeof r.code=="string"?r.code:"sync_action_failed",message:t.message,action_id:e}}function ap(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)}`}Ee();var jc=class{constructor(e,t){I(this,"fileSystem");I(this,"runtime");this.fileSystem=e,this.runtime=t}async validate(e,t){var n,i,s;if(((n=t==null?void 0:t.generation)!=null?n:0)!==e.checkpoint_generation||((i=t==null?void 0:t.cursor)!=null?i:null)!==e.base_cursor||((s=t==null?void 0:t.scope_epoch)!=null?s:e.scope_epoch)!==e.scope_epoch)throw Lc("The durable checkpoint changed after inspection.");for(let o of e.actions)o.depends_on.length===0&&await this.validateAction(o)}async validateAction(e){switch(e.command){case"write_local":await this.expected(e.expected_local),await this.expectedAt(e.target.path,e.expected_path_owner);return;case"delete_local":await this.expected(e.expected_local),await this.expectedAt(e.target.path,e.expected_path_owner);return;case"move_local":await this.expectedAt(e.source.path,e.expected_source_owner),await this.expectedAt(e.target_path,e.expected_target_owner);return;case"put_remote":case"move_remote":await this.expected(e.expected_local);return;case"delete_remote":await this.expectedAt(e.target.path,e.expected_local);return;case"record_conflict":await this.expected(e.local);return;case"advance_checkpoint":return}}async expectedAt(e,t){if(t.state==="absent"){if(await this.pathExists(e))throw Lc(`${e} is no longer vacant.`);return}if(t.object.path!==e||!await this.matches(t.object))throw Lc(`${e} no longer has the inspected owner and bytes.`)}async expected(e){if(e.state!=="absent"&&!await this.matches(e.object))throw Lc(`${e.object.path} no longer matches the inspected bytes.`)}async matches(e){if(e.entity==="file"){let n=await this.fileSystem.inspectBinary(e.path);return n!==null&&n.content_digest===e.payload_revision&&(e.size===void 0||n.size===e.size)}let t=await this.fileSystem.read(e.path);return t!==null&&`sha256:${this.runtime.digest(t)}`===e.payload_revision}async pathExists(e){return this.fileSystem.exists(e)}};function Lc(r){return new b("sync_plan_stale",r)}Mc();Ee();Mc();async function P0(r,e,t){var o;let n=nt(r);if(n.phase!=="effects_complete")throw new b("invalid_mirror_state","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 new b("invalid_mirror_state","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 new b("invalid_mirror_state","Prepared checkpoint boundary is inconsistent.");let s=n.plan.fingerprint;return r.generation=i.next.generation,r.cursor=(o=i.next.cursor)!=null?o:0,r.last_completed_plan=s,r.last_synced_at=e.now(),delete r.batch,await t.write(r),s}async function I0(r,e,t,n){var s,o,a;let[i]=e.actions;if(e.actions.length!==1||!i||i.command!=="advance_checkpoint"||i.expected.generation!==((s=r.generation)!=null?s:0)||i.expected.cursor!==r.cursor||i.next.generation!==((o=r.generation)!=null?o:0)+1||i.next.cursor!==e.authority_cursor||r.batch!==void 0)throw new b("invalid_mirror_state","Empty checkpoint plan is inconsistent.");return r.generation=i.next.generation,r.cursor=(a=i.next.cursor)!=null?a:0,r.last_completed_plan=e.fingerprint,r.last_synced_at=t.now(),await n.write(r),e.fingerprint}var Cn=class{constructor(e,t,n,i="read_only"){I(this,"replicaId");I(this,"transport");I(this,"mode");I(this,"stateStore");I(this,"fileSystem");I(this,"blobStore");I(this,"selectiveSync");I(this,"lease");I(this,"runtime");I(this,"materializer");I(this,"onProgress");var s,o;this.replicaId=e,this.transport=t,this.mode=i,this.stateStore=n.stateStore,this.fileSystem=n.fileSystem,this.blobStore=n.blobStore,this.selectiveSync=In(n.selectiveSync),this.lease=(s=n.lease)!=null?s:new Zs,this.runtime=(o=n.runtime)!=null?o:eo,this.materializer=new Ti(this.fileSystem,this.runtime,this.mode,this.blobStore),this.onProgress=n.onProgress}async sync(e={}){return this.lease.runExclusive(async()=>{var i,s;let t=await this.readState();if(((i=t==null?void 0:t.batch)==null?void 0:i.phase)==="blocked"&&((s=t.batch.failure)==null?void 0:s.code)==="sync_plan_stale"&&(await k0(t,this.journalStore()),t=await this.readState()),t!=null&&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()=>{var t,n;let e=await this.readState();return(n=(t=e==null?void 0:e.batch)==null?void 0:t.plan)!=null?n:(await this.inspectDetailed(e)).plan})}async apply(e,t={}){return this.lease.runExclusive(async()=>{let n=await this.readState();if(n!=null&&n.batch){if(n.batch.plan.fingerprint!==e.fingerprint)throw new b("mirror_recovery_required","A different prepared plan must recover before this plan can apply.");return this.executePrepared(n,t.signal)}let i=await this.inspectDetailed(n);return i.plan.fingerprint!==e.fingerprint?cn("stale",e,Tr(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){var s;let n=e.plan;if(n.issues.some(o=>o.blocking))return cn("attention",n,Tr(e.prior,this.mode),0);if(t!=null&&t.aborted)return cn("cancelled",n,Tr(e.prior,this.mode),0,{code:"sync_cancelled",message:"Sync cancelled before preparation."});try{await new jc(this.fileSystem,this.runtime).validate(n,e.prior)}catch(o){let a=o instanceof Error?o:new Error(String(o)),c=o&&typeof o=="object"&&"code"in o&&typeof o.code=="string"?o.code:"sync_revalidation_failed";return cn(c==="sync_plan_stale"?"stale":"failed",n,Tr(e.prior,this.mode),0,{code:c,message:a.message})}if(e.prior&&n.actions.length===1&&((s=n.actions[0])==null?void 0:s.command)==="advance_checkpoint")return await I0(e.prior,n,this.runtime,this.journalStore()),cn("applied",n,Tr(e.prior,this.mode),0);let i=await S0(e.prior,n,e.durable_payloads,this.journalStore());return this.executePrepared(i,t)}async executePrepared(e,t){let n=e.batch,i=await new Nc({transport:this.transport,fileSystem:this.fileSystem,blobStore:this.blobStore,runtime:this.runtime,mode:this.mode,store:this.journalStore(),onProgress:(c,l)=>{var d;return(d=this.onProgress)==null?void 0:d.call(this,{phase:"applying",completed:c,total:l,done:c===l})}}).execute(e,t);if(i.status!=="effects_complete"){let c=Tr(e,this.mode);return cn(i.status==="blocked"?"failed":i.status,n.plan,c,i.completed,i.failure)}let s=n.plan;await P0(e,this.runtime,this.journalStore()),await this.pruneFileBlobs();let o=Tr(e,this.mode),a=o.conflicts.length>0||o.file_conflicts.length>0||o.local_issues.length>0||s.summary.conflicts>0;return cn(a?"attention":"applied",s,o,i.completed)}inspectDetailed(e){return new Oc(this.replicaId,this.transport,this.mode,this.fileSystem,this.blobStore,this.selectiveSync,this.runtime,()=>this.readState(),t=>this.currentRecordPathPolicy(t)).inspect(e)}async status(){let e=await this.checkpointStatus();return e.state==="not_initialized"?e:u0(e,await this.inspect())}async checkpointStatus(){return this.lease.runExclusive(()=>this.checkpointStatusUnlocked())}async checkpointStatusUnlocked(){return Tr(await this.readState(),this.mode)}async authorityPromotionManifest(){return this.lease.runExclusive(async()=>{var i;if(this.mode!=="read_write")throw new b("promotion_requires_writable_mirror","Only a read-write mirror can prove an authority promotion source.");let e=await this.readState();if(!e)throw new b("mirror_not_initialized","Synchronize this mirror first.");if(e.batch||Object.keys((i=e.planned_conflicts)!=null?i:{}).length>0)throw new b("promotion_mirror_not_clean","Finish the prepared batch and resolve conflicts before promotion.");let t=await d0({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(s=>s.command!=="advance_checkpoint"))throw new b("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){await this.lease.runExclusive(()=>this.resolveConflictUnlocked(e,"record",t))}async resolveFileConflict(e,t){await this.lease.runExclusive(()=>this.resolveConflictUnlocked(e,"file",t))}async resolveConflictUnlocked(e,t,n){var o,a,c,l;if(this.mode!=="read_write")throw new b("mirror_read_only","Receive-only mirrors have no writable conflicts.");let i=await this.readState();if(!i||i.batch)throw new b("mirror_recovery_required","Finish sync recovery before resolving conflicts.");if(!((o=i.planned_conflicts)==null?void 0:o[e]))throw new b("mirror_conflict_not_found","Writable mirror conflict was not found.");if(n==="remote"){let d=await Ec(this.replicaId,this.transport,this.mode,this.selectiveSync,this.runtime);if(t==="record"){let u=(a=d.records.find(({record:f})=>f.record_id===e))==null?void 0:a.record;await this.installRemoteRecord(i,e,u)}else{let u=d.files.find(f=>f.file_id===e);await this.installRemoteFile(i,e,u)}}(c=i.planned_conflicts)==null||delete c[e],n==="remote"&&((l=i.local_bindings)==null||delete l[e]),await this.writeState(i)}async installRemoteRecord(e,t,n){var o,a,c,l;if(n){let d=(o=e.planned_conflicts)==null?void 0:o[t],u=await this.fileSystem.read(n.path),f=((a=e.records[t])==null?void 0:a.path)===n.path||(d==null?void 0:d.local.state)==="exact"&&d.local.object.path===n.path;await this.materializer.put(e,n,{inspectionPreflighted:!1,...f&&u!==null?{acceptedHash:this.runtime.digest(u)}:{}});return}let i=(c=e.planned_conflicts)==null?void 0:c[t],s=(i==null?void 0:i.local.state)==="exact"?i.local.object.path:(l=e.records[t])==null?void 0:l.path;s&&await this.fileSystem.read(s)!==null&&await this.fileSystem.remove(s),delete e.records[t]}async installRemoteFile(e,t,n){var o,a,c,l,d,u,f,p;if(n){if(!this.blobStore)throw new b("file_storage_unavailable","File resolution needs a blob store.");await bc(this.transport,this.blobStore,n);let y=(o=e.planned_conflicts)==null?void 0:o[t],h=(y==null?void 0:y.local.state)==="exact"?{content_digest:y.local.object.payload_revision,size:(a=y.local.object.size)!=null?a:0}:void 0,m=(l=(c=e.local_bindings)==null?void 0:c[t])==null?void 0:l.path;await this.materializer.putFile(e,n,e,h),m&&m!==n.path&&await this.fileSystem.remove(m);return}let i=(d=e.planned_conflicts)==null?void 0:d[t],s=(i==null?void 0:i.local.state)==="exact"?i.local.object.path:(f=(u=e.files)==null?void 0:u[t])==null?void 0:f.file.path;s&&await this.fileSystem.inspectBinary(s)!==null&&await this.fileSystem.remove(s),(p=e.files)==null||delete p[t]}async readState(){let e=await this.stateStore.read();if(e===null)return null;try{return Zw(e,this.replicaId,this.mode)}catch(t){throw t instanceof b?t:new b("invalid_mirror_state","Mirror metadata is corrupt or belongs to another replica.")}}writeState(e){return this.stateStore.write(e)}journalStore(){return{write:e=>this.writeState(e),...this.stateStore.appendJournal?{appendJournal:e=>this.stateStore.appendJournal(e)}:{}}}async pruneFileBlobs(){var n,i,s,o,a;if(!this.blobStore)return;let e=await this.readState();if(!e)return;let t=new Set;for(let c of Object.values((n=e.files)!=null?n:{}))t.add(c.file.content_digest);for(let c of Object.values((s=(i=e.batch)==null?void 0:i.payloads.files)!=null?s:{}))t.add(c.content_digest);for(let c of Object.values((a=(o=e.batch)==null?void 0:o.payloads.local_files)!=null?a:{}))t.add(c.content_digest);await this.blobStore.prune(t)}currentRecordPathPolicy(e){return this.materializer.recordPathPolicy(e)}};var so=class extends Cn{constructor(e,t,n){super(e,t,n,"read_write")}};function O0(r){let e=[...r.actions.flatMap(t=>t.command==="advance_checkpoint"?[]:[JM(t)]),...r.issues.map(t=>{var n;return{kind:"document",path:(n=t.path)!=null?n:"Sync engine",direction:"attention",action:"fix",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).map(t=>t.path),local_issues:r.issues.filter(t=>t.code==="invalid_frontmatter"&&t.path!==void 0).map(t=>({code:"invalid_frontmatter",message:t.message,path:t.path}))}}function JM(r){var c;if(r.command==="advance_checkpoint")throw new Error("Checkpoint actions are not preview entries.");if(r.command==="record_conflict"){let l=r.local.state==="exact"?r.local.object:r.remote.state==="exact"?r.remote.object:void 0;return{kind:r.entity==="file"?"file":"document",path:(c=l==null?void 0:l.path)!=null?c:r.identity,direction:"attention",action:"fix",detail:`Local and hosted ${r.entity} changes conflict (${r.conflict_kind.replace(/_/g," ")}).`,...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=r.command.split("_")[0],a=r.command.startsWith("move_")?` from ${t.path}`:"";return{kind:t.entity==="file"?"file":"document",path:n,direction:e?"download":"upload",action:s,detail:`${e?"Hosted":"Local"} ${t.entity} will ${o}${a}.`,...t.entity==="record"?{recordId:t.identity}:{},...t.entity==="file"?{fileId:t.identity}:{}}}var oo=".mdbase/connect-role.json",ao=".mdbase/authority-adoption.json",co=".mdbase/authority-adoption-snapshot.json",YM="mdbase-obsidian-connect-exact-v1",Ci="mirrors",XM="mdbase-connect-access-",QM="mdbase-connect-refresh-",ZM="mdbase-connect-adoption-",eC=300*1e3,lp=[".git/",".obsidian/",".trash/",".mdbase/"],lo=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Ue(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function Dc(r,e){if(e!=null)return e;if(!r.trim())return{};try{return JSON.parse(r)}catch(t){return{}}}function T0(r){var i;let e=(i=r["retry-after"])!=null?i:r["Retry-After"];if(!e)return;let t=Number(e);if(Number.isFinite(t)&&t>=0)return t*1e3;let n=Date.parse(e);if(Number.isFinite(n))return Math.max(0,n-Date.now())}function tC(){return async r=>{var t,n;if((t=r.signal)!=null&&t.aborted)throw new DOMException("Enrollment cancelled.","AbortError");let e=await(0,oe.requestUrl)({url:r.url,method:r.method,headers:r.headers,body:r.body===void 0?void 0:JSON.stringify(r.body),contentType:r.body===void 0?void 0:"application/json",throw:!1});if((n=r.signal)!=null&&n.aborted)throw new DOMException("Enrollment cancelled.","AbortError");return{status:e.status,body:Dc(e.text,e.json),retryAfterMs:T0(e.headers)}}}function rC(){return async r=>{var t,n;if((t=r.signal)!=null&&t.aborted)throw new DOMException("Collection adoption cancelled.","AbortError");let e=await(0,oe.requestUrl)({url:r.url,method:r.method,headers:r.headers,body:r.body===void 0?void 0:JSON.stringify(r.body),contentType:r.body===void 0?void 0:"application/json",throw:!1});if((n=r.signal)!=null&&n.aborted)throw new DOMException("Collection adoption cancelled.","AbortError");return{status:e.status,body:Dc(e.text,e.json),retryAfterMs:T0(e.headers)}}}var dp=class{constructor(e,t){this.accessToken=t;let n;try{n=new URL(e)}catch(i){throw new b("invalid_sync_url","Sync URL must be an absolute authority endpoint.")}if(!(n.protocol==="https:"||n.protocol==="http:"&&["localhost","127.0.0.1","[::1]","::1"].includes(n.hostname))||n.username||n.password||n.search||n.hash||!/^\/v1\/authorities\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\/sync\/?$/i.test(n.pathname))throw new b("invalid_sync_url","Sync URL must identify one authority sync endpoint.");this.syncUrl=n.href.replace(/\/$/,""),this.filesUrl=this.syncUrl.replace(/\/sync$/,"/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){let t=crypto.randomUUID();try{let n=await this.fileRequest("POST","downloads",{protocol_version:1,type:"open_file_download",transfer_id:t,file_id:e.file_id,revision:e.revision}),i=Ue(n.strategy)?n.strategy:{},s=i.part_size;if(n.protocol_version!==1||n.type!=="file_transfer"||n.transfer_id!==t||n.direction!=="download"||n.protection!=="transport_tls"||n.total_size!==e.size||i.kind!=="object_ranges"||!Number.isSafeInteger(s)||s<=0)throw new b("invalid_sync_response","The authority returned an incompatible file download session.");let o=Math.ceil(e.size/s);for(let a=0;a=300){let d=Dc(l.text,l.json),u=Ue(d)&&Ue(d.error)?d.error:{};throw new b(typeof u.code=="string"?u.code:"file_download_failed",typeof u.message=="string"?u.message:`File download failed (${l.status}).`)}if(l.arrayBuffer.byteLength!==c)throw new b("file_integrity_failed","The authority returned a file part with the wrong length.");yield new Uint8Array(l.arrayBuffer)}}finally{await this.fileRequest("DELETE",`transfers/${encodeURIComponent(t)}`).catch(()=>{})}}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)}request(e,t,n){return this.requestAt(this.syncUrl,e,t,n)}fileRequest(e,t,n){return this.requestAt(this.filesUrl,e,t,n)}async requestAt(e,t,n,i){let s=await(0,oe.requestUrl)({url:`${e}/${n}`,method:t,headers:{authorization:`Bearer ${this.accessToken}`},body:i===void 0?void 0:JSON.stringify(i),contentType:i===void 0?void 0:"application/json",throw:!1}),o=Dc(s.text,s.json);if(s.status<200||s.status>=300){let a=Ue(o)&&Ue(o.error)?o.error:{};throw new b(typeof a.code=="string"?a.code:"sync_failed",typeof a.message=="string"?a.message:`Sync request failed (${s.status}).`)}return o}};function Cr(r){let e=Os(r);if(e===".mdbase"||lp.some(t=>e.startsWith(t)))throw new b("unsafe_mirror_path",`The collection authority attempted to write a reserved path: ${e}`);return e}async function Li(r,e){let t=(0,oe.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 oe.TFolder)){if(s)throw new b("mirror_path_collision",`A file blocks the mirror folder ${n}.`);await r.adapter.exists(n)||await r.createFolder(n)}}}var up=class{constructor(e){this.vault=e}async exists(e){let t=Cr(e);return this.vault.getAbstractFileByPath(t)!==null||await this.vault.adapter.exists(t)}async read(e){let t=Cr(e),n=this.vault.getAbstractFileByPath(t);if(n==null)return null;if(!(n instanceof oe.TFile))throw new b("mirror_path_collision",`Expected a file at ${t}.`);return this.vault.cachedRead(n)}async write(e,t){let n=Cr(e),i=n.lastIndexOf("/");i>=0&&await Li(this.vault,n.slice(0,i));let s=this.vault.getAbstractFileByPath(n);if(s instanceof oe.TFolder)throw new b("mirror_path_collision",`A folder blocks the mirror file ${n}.`);s instanceof oe.TFile?await this.vault.modify(s,t):await this.vault.create(n,t)}async move(e,t){let n=Cr(e),i=Cr(t),s=i.lastIndexOf("/");s>=0&&await Li(this.vault,i.slice(0,s));let o=this.vault.getAbstractFileByPath(n);if(!(o instanceof oe.TFile))throw new b("mirror_path_collision",`Expected a file at ${n}.`);if(this.vault.getAbstractFileByPath(i)!==null||await this.vault.adapter.exists(i))throw new b("mirror_path_collision",`A file or folder blocks ${i}.`);await this.vault.rename(o,i)}async remove(e){let t=Cr(e),n=this.vault.getAbstractFileByPath(t);if(n!=null){if(!(n instanceof oe.TFile))throw new b("mirror_path_collision",`Expected a file at ${t}.`);await this.vault.delete(n,!0)}}async listMarkdown(e){return this.vault.getMarkdownFiles().map(t=>(0,oe.normalizePath)(t.path)).filter(t=>!e.has(t)).filter(t=>!lp.some(n=>t.startsWith(n))).sort()}async inspectBinary(e){let t=Cr(e),n=this.vault.getAbstractFileByPath(t);if(n==null)return null;if(!(n instanceof oe.TFile))throw new b("mirror_path_collision",`Expected a file at ${t}.`);let i=await this.vault.readBinary(n),s=await crypto.subtle.digest("SHA-256",i),o=Array.from(new Uint8Array(s),a=>a.toString(16).padStart(2,"0")).join("");return{size:i.byteLength,content_digest:`sha256:${o}`}}async writeBinary(e,t){let n=Cr(e),i=[],s=0;for await(let d of t){if(!(d instanceof Uint8Array)||!Number.isSafeInteger(s+d.byteLength))throw new b("invalid_file_materialization","The binary file stream is invalid or too large.");i.push(d),s+=d.byteLength}let o=new Uint8Array(s),a=0;for(let d of i)o.set(d,a),a+=d.byteLength;let c=n.lastIndexOf("/");c>=0&&await Li(this.vault,n.slice(0,c));let l=this.vault.getAbstractFileByPath(n);if(l instanceof oe.TFolder)throw new b("mirror_path_collision",`A folder blocks the mirror file ${n}.`);l instanceof oe.TFile?await this.vault.modifyBinary(l,o.buffer):await this.vault.createBinary(n,o.buffer)}async listBinary(e){return this.vault.getFiles().map(t=>(0,oe.normalizePath)(t.path)).filter(t=>!t.toLowerCase().endsWith(".md")).filter(t=>!e.has(t)).filter(t=>!lp.some(n=>t.startsWith(n))).sort()}async readBinary(e){let t=Cr(e),n=this.vault.getAbstractFileByPath(t);if(n==null)return null;if(!(n instanceof oe.TFile))throw new b("mirror_path_collision",`Expected a file at ${t}.`);let i=new Uint8Array(await this.vault.readBinary(n));return(async function*(){yield i})()}},fp=class{constructor(e){this.key=e;this.database=null}async read(){let e=await this.open();return new Promise((t,n)=>{let i=e.transaction(Ci,"readonly").objectStore(Ci).get(this.key);i.onsuccess=()=>{var s;return t((s=i.result)!=null?s:null)},i.onerror=()=>n(i.error)})}async write(e){let t=await this.open();await new Promise((n,i)=>{let s=t.transaction(Ci,"readwrite");s.objectStore(Ci).put(e,this.key),s.oncomplete=()=>n(),s.onerror=()=>i(s.error),s.onabort=()=>i(s.error)})}open(){var e;if(typeof indexedDB=="undefined")throw new b("storage_unavailable","IndexedDB is required for persistent mirror state.");return(e=this.database)!=null||(this.database=new Promise((t,n)=>{let i=indexedDB.open(YM,1);i.onupgradeneeded=()=>{i.result.objectStoreNames.contains(Ci)||i.result.createObjectStore(Ci)},i.onerror=()=>n(i.error),i.onsuccess=()=>t(i.result)})),this.database}},Ni=class Ni{constructor(e){this.key=e}async runExclusive(e){if(Ni.active.has(this.key))throw new b("mirror_busy","A mirror operation is already running for this vault.");Ni.active.add(this.key);try{return await e()}finally{Ni.active.delete(this.key)}}};Ni.active=new Set;var pp=Ni,qc=class{constructor(e,t,n={}){this.app=e;this.settingsHost=t;this.options=n;this.progress=null;this.syncAbort=null;this.adoptionMarker=null;var i,s,o;this.fileSystem=(i=n.fileSystem)!=null?i:new up(e.vault),this.enrollmentClient=(s=n.enrollmentClient)!=null?s:new yc({request:tC()}),this.adoptionClient=(o=n.adoptionClient)!=null?o:new vc({request:rC()})}async initialize(){if(this.adoptionMarker=await this.readAdoptionMarker(),this.adoptionMarker&&this.settingsHost.getMirrorProfile())throw new b("authority_adoption_state_conflict","This vault contains both an authority-adoption checkpoint and a mirror profile.")}getProgress(){return this.progress?{...this.progress}:null}cancelSync(){var e;(e=this.syncAbort)==null||e.abort()}getAdoptionMarker(){return this.adoptionMarker?JSON.parse(JSON.stringify(this.adoptionMarker)):null}assertLocalAuthorityWritable(){if(this.adoptionMarker&&["fenced","activating","adopted"].includes(this.adoptionMarker.phase))throw new b("local_authority_fenced",this.adoptionMarker.phase==="adopted"?"Hosted mdbase is now authoritative. Finish reconnecting this vault as its mirror before editing.":"This local authority is frozen while its exact snapshot is adopted by hosted mdbase.")}async adoptLocalCollection(e,t){if(this.settingsHost.getMirrorProfile())throw new b("mirror_already_configured","This vault already mirrors a collection authority.");if(this.adoptionMarker)return this.resumeAdoption(t);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);return await this.storeAdoptionSecret(i),await this.writeAdoptionMarker({version:1,phase:"waiting_for_approval",session:cp(i),manifest_digest:null,source_revision:null,source_head:null}),await t.onVerification(cp(i)),this.runAdoptionWithRecovery(i,t)}async resumeAdoption(e={}){var s,o,a;let t=(s=this.adoptionMarker)!=null?s:await this.readAdoptionMarker();if(!t)throw new b("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 b("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((o=e.onVerification)==null?void 0:o.call(e,cp(i))),this.runAdoptionWithRecovery(i,{...e,onVerification:(a=e.onVerification)!=null?a:(()=>{})})}async cancelAdoption(e){var i;let t=(i=this.adoptionMarker)!=null?i:await this.readAdoptionMarker();if(!t)return;if(["activating","adopted"].includes(t.phase))throw new b("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 b("authority_adoption_credentials_missing","The collection-adoption credential is missing from Obsidian's secret store.");await this.adoptionClient.cancel({...t.session,credential:n},{signal:e}),await this.clearAdoptionCheckpoint(t.session.adoptionId)}async enroll(e,t){let n=await this.assertCanBecomeMirror(e.collectionId),i=await this.enrollmentClient.enroll({...e,...n?{collectionId:n}:{}},t),s=await this.markMirror(i.collectionId);try{await this.persistEnrollment(i)}catch(o){if(s)try{await this.app.vault.adapter.remove(oo)}catch(a){throw new b("enrollment_recovery_required",`Enrollment settings could not be saved and the temporary role marker could not be removed: ${o instanceof Error?o.message:String(o)}`)}throw o}return this.requireProfile()}async preview(){let e=await this.createMirror();return O0(await e.inspect())}async status(){let e=this.settingsHost.getMirrorProfile();return e?(await this.assertMirror(e.collectionId),(await this.createMirror()).status()):null}async sync(e,t){if(this.syncAbort)throw new b("mirror_busy","Synchronization is already running for this vault.");let n=new AbortController;this.syncAbort=n;let i=await this.createMirror(s=>{this.progress=s,t==null||t({...s})});try{return await i.apply(e.plan,{signal:n.signal})}finally{this.progress=null,this.syncAbort=null}}async resolveConflict(e,t){let n=await this.createMirror();return await n.resolveConflict(e,t),n.status()}async runAdoption(e,t){let n=this.requireAdoptionMarker(e.adoptionId),i=null;if(n.phase==="adopted"){let s=await this.adoptionClient.exchange(e,t);if(s.status!=="completed")throw new b("authority_adoption_state_conflict","The local checkpoint says adoption completed, but Connect does not.");i=s}else if(n.phase==="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"&&await this.adoptionClient.uploadSnapshot(e,o,s,t),await this.updateAdoptionPhase("activating",s),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),o=await this.captureAuthoritySnapshot(e.requested.collectionId);await this.updateAdoptionPhase("uploading"),await this.adoptionClient.uploadSnapshot(e,s,o,t);let a=await this.captureAuthoritySnapshot(e.requested.collectionId);await this.writeAdoptionSnapshot(a),await this.updateAdoptionPhase("fenced",a);let c=await this.requirePreparedAdoption(e,t);await this.adoptionClient.uploadSnapshot(e,c,a,t),await this.updateAdoptionPhase("activating",a),i=await this.adoptionClient.complete(e,a,t)}return await this.updateAdoptionPhase("adopted"),this.finishRetainedMirror(e,i,t)}async runAdoptionWithRecovery(e,t){try{return await this.runAdoption(e,t)}catch(n){throw nC(n)?(await this.adoptionClient.cancel(e,{signal:t.signal}).catch(()=>{}),await this.clearAdoptionCheckpoint(e.adoptionId),new b(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 kr("Hosted authority activation has already started. Resume using the saved fenced snapshot."):new b("authority_adoption_already_completed","Hosted authority has already adopted this collection.")}async finishRetainedMirror(e,t,n){var a,c;let i,s=this.adoptionClient.mirrorEnrollmentSession(e,t);if(!s)throw new b("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:l=>{var d;return(d=n.onStatus)==null?void 0:d.call(n,{...l,state:l.state})}})}catch(l){if((a=n.signal)!=null&&a.aborted)throw l;i=await this.enrollmentClient.enroll({controlUrl:e.controlUrl,collectionId:e.requested.collectionId,mirrorName:(c=e.requested.mirrorName)!=null?c:e.requested.sourceName,mode:"read_write"},{signal:n.signal,onVerification:n.onVerification})}let o=await this.markMirror(i.collectionId);try{await this.persistEnrollment(i)}catch(l){throw o&&await this.app.vault.adapter.remove(oo),l}return await this.clearAdoptionCheckpoint(e.adoptionId),this.requireProfile()}async captureAuthoritySnapshot(e){let t=await ui(this.app.vault);if(!t)throw new b("invalid_collection_configuration","A valid mdbase.yaml is required.");let n=await this.app.vault.adapter.read("mdbase.yaml"),i=(0,oe.parseYaml)(n),s=[{path:"mdbase.yaml",kind:"configuration",document:n}],o=`${(0,oe.normalizePath)(t.settings.types_folder)}/`,a=this.app.vault.getMarkdownFiles().filter(d=>(0,oe.normalizePath)(d.path).startsWith(o)).sort((d,u)=>d.path.localeCompare(u.path));for(let d of a)s.push({path:(0,oe.normalizePath)(d.path),kind:"type",document:await this.app.vault.cachedRead(d)});let c=iC(i);if(c.length){let d=c.map(f=>(0,R0.default)(f,{dot:!0})),u=sC(this.app.vault).filter(f=>f.extension==="base").filter(f=>d.some(p=>p((0,oe.normalizePath)(f.path)))).sort((f,p)=>f.path.localeCompare(p.path));for(let f of u)s.push({path:(0,oe.normalizePath)(f.path),kind:"view",document:await this.app.vault.cachedRead(f)})}let l=[];for(let d of this.app.vault.getMarkdownFiles().sort((u,f)=>u.path.localeCompare(f.path))){let u=(0,oe.normalizePath)(d.path);if(Rs(u,t))continue;let f=await this.app.vault.cachedRead(d);l.push({path:u,document:f})}return Hf({collectionId:e,sourceHead:0,specVersion:t.spec_version,resources:s,records:l})}async ensurePortableCollectionIdentity(){if(!await this.app.vault.adapter.exists("mdbase.yaml"))throw new b("collection_not_initialized","Initialize an mdbase collection before hosting it.");let e=await this.app.vault.adapter.read("mdbase.yaml"),t;try{t=(0,oe.parseYaml)(e)}catch(o){throw new b("invalid_collection_configuration","mdbase.yaml must contain valid YAML.")}if(!Ue(t))throw new b("invalid_collection_configuration","mdbase.yaml must contain a YAML mapping.");let n=Ue(t["x-mdbase-connect"])?t["x-mdbase-connect"].collection_id:void 0,i;if(n===void 0){i=crypto.randomUUID();let o=Ue(t["x-mdbase-connect"])?t["x-mdbase-connect"]:{};t["x-mdbase-connect"]={...o,collection_id:i},await this.app.vault.adapter.write("mdbase.yaml",(0,oe.stringifyYaml)(t))}else if(typeof n=="string"&&lo.test(n))i=n;else throw new b("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}}async createMirror(e){var o,a,c,l,d,u,f,p,y;let t=this.requireProfile();await this.assertMirror(t.collectionId);let n=await this.freshAccessToken(t),i=(c=(a=(o=this.options).transportFactory)==null?void 0:a.call(o,t,n))!=null?c:new dp(t.syncUrl,n),s={stateStore:(u=(d=(l=this.options).stateStoreFactory)==null?void 0:d.call(l,t))!=null?u:new fp(`${t.collectionId}:${t.replicaId}`),fileSystem:this.fileSystem,lease:(y=(p=(f=this.options).leaseFactory)==null?void 0:p.call(f,t))!=null?y:new pp(`${t.collectionId}:${t.replicaId}`),onProgress:e};return t.mode==="read_write"?new so(t.replicaId,i,s):new Cn(t.replicaId,i,s)}requireProfile(){let e=this.settingsHost.getMirrorProfile();if(!e)throw new b("mirror_not_configured","This vault is not connected to a collection authority.");return e}accessSecretId(e){return`${XM}${e.toLowerCase()}`}refreshSecretId(e){return`${QM}${e.toLowerCase()}`}adoptionSecretId(e){return`${ZM}${e.toLowerCase()}`}async storeAdoptionSecret(e){this.app.secretStorage.setSecret(this.adoptionSecretId(e.adoptionId),e.credential)}async persistEnrollment(e){this.app.secretStorage.setSecret(this.accessSecretId(e.collectionId),e.accessToken),this.app.secretStorage.setSecret(this.refreshSecretId(e.collectionId),e.refreshCredential),await this.settingsHost.saveMirrorProfile({version:1,syncUrl:e.syncUrl,controlUrl:e.controlUrl,collectionId:e.collectionId,replicaId:e.replicaId,mode:e.mode,name:e.name,enrollmentId:e.enrollmentId,accessTokenExpiresAt:e.accessTokenExpiresAt})}async freshAccessToken(e){let t=this.accessSecretId(e.collectionId),n=this.app.secretStorage.getSecret(t),i=Date.parse(e.accessTokenExpiresAt);if(n&&Number.isFinite(i)&&i-Date.now()>eC)return n;let s=this.app.secretStorage.getSecret(this.refreshSecretId(e.collectionId));if(!s)throw new b("mirror_credentials_missing","The mirror refresh credential is missing. Re-enroll this vault.");let o=await this.enrollmentClient.renew({controlUrl:e.controlUrl,syncUrl:e.syncUrl,collectionId:e.collectionId,replicaId:e.replicaId,mode:e.mode,name:e.name,enrollmentId:e.enrollmentId,accessToken:n!=null?n:"",refreshCredential:s,accessTokenExpiresAt:e.accessTokenExpiresAt});return await this.persistEnrollment(o),o.accessToken}async assertCanBecomeMirror(e){var o;let t=await this.readMarker(),n=await this.readPortableCollectionId();if(n&&!t)throw new b("local_authority_requires_transfer","This vault has a local Connect identity. Transfer authority explicitly before using it as a mirror.");if(n&&(t==null?void 0:t.collection_id)!==n)throw new b("mirror_identity_conflict","The vault identity and mirror role marker identify different collections.");let i=this.settingsHost.getMirrorProfile(),s=(o=i==null?void 0:i.collectionId)!=null?o:e;if(t&&s&&t.collection_id!==s)throw new b("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 b("existing_collection_requires_transfer","This vault already contains an mdbase collection. Connect an empty vault, or transfer collection authority explicitly.");return s!=null?s:t==null?void 0:t.collection_id}async readPortableCollectionId(){if(!await this.app.vault.adapter.exists("mdbase.yaml"))return null;let e;try{e=(0,oe.parseYaml)(await this.app.vault.adapter.read("mdbase.yaml"))}catch(i){throw new b("invalid_collection_configuration","mdbase.yaml must contain valid YAML.")}if(!Ue(e))throw new b("invalid_collection_configuration","mdbase.yaml must contain a YAML mapping.");let t=e["x-mdbase-connect"];if(t===void 0)return null;if(!Ue(t))throw new b("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"||!lo.test(n))throw new b("invalid_collection_configuration","x-mdbase-connect.collection_id must be a UUID string.");return n}async markMirror(e){let t=await this.readMarker();if(t){if(t.collection_id!==e)throw new b("mirror_identity_conflict","This vault already mirrors a different collection authority.");return!1}return await Li(this.app.vault,".mdbase"),await this.app.vault.adapter.write(oo,`${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 b("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(oo))return null;let e;try{e=JSON.parse(await this.app.vault.adapter.read(oo))}catch(t){throw new b("invalid_mirror_marker","The mirror role marker is corrupt.")}if(!Ue(e)||e.version!==1||e.role!=="mirror"||typeof e.collection_id!="string"||!lo.test(e.collection_id))throw new b("invalid_mirror_marker","The mirror role marker is invalid.");return e}requireAdoptionMarker(e){if(!this.adoptionMarker||this.adoptionMarker.session.adoptionId!==e)throw new b("authority_adoption_state_conflict","The collection-adoption checkpoint does not match this approval.");return this.adoptionMarker}async updateAdoptionPhase(e,t){if(!this.adoptionMarker)throw new b("authority_adoption_not_found","Collection-adoption checkpoint is missing.");await this.writeAdoptionMarker({...this.adoptionMarker,phase:e,...t?{manifest_digest:t.manifest_digest,source_revision:t.source_revision,source_head:t.source_head}:{}})}async writeAdoptionMarker(e){await Li(this.app.vault,".mdbase"),await this.app.vault.adapter.write(ao,`${JSON.stringify(e,null,2)} -`),this.adoptionMarker=e}async readAdoptionMarker(){if(!await this.app.vault.adapter.exists(ao))return null;let e;try{e=JSON.parse(await this.app.vault.adapter.read(ao))}catch(t){throw new b("invalid_authority_adoption_checkpoint","The collection-adoption checkpoint is corrupt.")}if(!oC(e))throw new b("invalid_authority_adoption_checkpoint","The collection-adoption checkpoint is invalid.");return e}async writeAdoptionSnapshot(e){await Li(this.app.vault,".mdbase"),await this.app.vault.adapter.write(co,JSON.stringify(e))}async readAdoptionSnapshot(e){if(!await this.app.vault.adapter.exists(co))throw new b("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(co))}catch(n){throw new b("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 b("authority_adoption_snapshot_mismatch","The fenced authority snapshot does not match its durable checkpoint.");return t}async clearAdoptionCheckpoint(e){await this.app.vault.adapter.exists(ao)&&await this.app.vault.adapter.remove(ao),await this.app.vault.adapter.exists(co)&&await this.app.vault.adapter.remove(co),this.app.secretStorage.setSecret(this.adoptionSecretId(e),""),this.adoptionMarker=null}};function cp(r){let{credential:e,...t}=r;return t}function nC(r){return r instanceof J&&["authority_adoption_expired","authority_adoption_cancelled"].includes(r.code)}function iC(r){if(!Ue(r))return[];let e=r["x-obsidian"];return!Ue(e)||!Ue(e.bases)||!Array.isArray(e.bases.include)?[]:e.bases.include.filter(t=>typeof t=="string")}function sC(r){var i;let e=(i=r.getFiles)==null?void 0:i.call(r);if(e)return e;let t=[],n=s=>{for(let o of s.children)o instanceof oe.TFile?t.push(o):o instanceof oe.TFolder&&n(o)};return n(r.getRoot()),t}function oC(r){if(!Ue(r)||r.version!==1||!["waiting_for_approval","uploading","fenced","activating","adopted"].includes(String(r.phase))||!Ue(r.session))return!1;let e=r.session;return typeof e.controlUrl=="string"&&typeof e.adoptionId=="string"&&lo.test(e.adoptionId)&&typeof e.verificationUri=="string"&&typeof e.expiresAt=="string"&&Ue(e.requested)&&typeof e.requested.collectionId=="string"&&lo.test(e.requested.collectionId)&&typeof e.requested.displayName=="string"&&typeof e.requested.sourceName=="string"&&e.requested.retainMirror===!0&&(r.manifest_digest===null||typeof r.manifest_digest=="string")&&(r.source_revision===null||typeof r.source_revision=="string")&&(r.source_head===null||Number.isSafeInteger(r.source_head))}var it=require("obsidian");var ho="0.3.0",aC=new Set(["name","description","display_name_key","strict","path_pattern","filename_pattern","match","fields","extends"]),cC=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 ve(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function Ce(r){return r===void 0?r:JSON.parse(JSON.stringify(r))}function Nr(r){return eo.digest(r)}function Nn(r){return Array.isArray(r)?`[${r.map(Nn).join(",")}]`:ve(r)?`{${Object.keys(r).sort().map(e=>`${JSON.stringify(e)}:${Nn(r[e])}`).join(",")}}`:JSON.stringify(r)}function hp(r){if(Array.isArray(r))return r.map(hp);if(!ve(r))return r;let e={};for(let[t,n]of Object.entries(r)){let i=hp(n);i!=null&&(Array.isArray(i)&&i.length===0||ve(i)&&Object.keys(i).length===0||(e[t]=i))}return e}function ji(r){return[...new Set(r)]}function lC(r){return ve(r.fields)?Object.values(r.fields).some(e=>ve(e)&&(typeof e.tn_role=="string"||Array.isArray(e.tn_completed_values))):!1}function mp(r,e,t){let n=ve(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)?Ce(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=mp(`${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[d,u]of Object.entries(ve(n.fields)?n.fields:{})){let f=mp(`${r}.${d}`,u,t);c[d]=f.schema,Object.assign(i,f.links),Object.assign(s,f.legacy),o.push(...f.unsupported),ve(u)&&u.required===!0&&l.push(d)}t&&r==="blockedBy[]"&&l.push("uid"),a={type:"object",additionalProperties:Object.keys(c).length===0,properties:c,...l.length?{required:ji(l)}:{}};break}default:a={},o.push(`${r}.type`);break}t&&r==="title"&&(a.minLength=1,a.description="Short summary of the task."),typeof n.description=="string"&&(a.description=n.description),typeof n.min=="number"&&(n.type==="string"?a.minLength=n.min:n.type==="list"?a.minItems=n.min:a.minimum=n.min),typeof n.max=="number"&&(n.type==="string"?a.maxLength=n.max:n.type==="list"?a.maxItems=n.max:a.maximum=n.max),typeof n.min_length=="number"&&(a.minLength=n.min_length),typeof n.max_length=="number"&&(a.maxLength=n.max_length),typeof n.pattern=="string"&&(a.pattern=n.pattern),n.deprecated===!0&&(a.deprecated=!0),n.default!==void 0&&(a.default=Ce(n.default)),n.computed!==void 0&&o.push(`${r}.computed`);for(let[c,l]of Object.entries(n)){let d=t&&(c==="tn_role"||c==="tn_completed_values");(!cC.has(c)||(c==="tn_role"||c==="tn_completed_values")&&!d)&&(s[`${r}.${c}`]=Ce(l))}return{schema:a,links:i,legacy:s,unsupported:o}}function uo(r,e,t,n){let i=ve(r[e])?r[e]:{},s=ve(i.set)?i.set:{};s[t]=n,i.set=s,r[e]=i}function dC(r,e,t){if(t==="now")uo(r,"on_create",e,{now:!0});else if(t==="now_on_write")uo(r,"on_update",e,{now:!0});else if(t==="uuid")uo(r,"on_create",e,{uuid:!0});else if(t==="ulid")uo(r,"on_create",e,{ulid:!0});else if(ve(t)&&t.transform==="slugify"&&typeof t.from=="string")uo(r,"on_create",e,{slugify:t.from});else return!1;return!0}function uC(r){var t;let e=r.match(/^(.*\/)?\{title\}\.md$/);return e?{runtime:"tasknotes",template:"{{title}}",folder:((t=e[1])!=null?t:"").replace(/\/$/,""),generated_by:"tasknotes.filename.create"}:{runtime:"tasknotes",template:r,generated_by:"tasknotes.filename.create"}}function fC(r,e,t){var P;if(t.kind==="mdbase.type"||t.schema!==void 0)throw new Error(`${r} already looks like a v0.3 type.`);if(typeof t.name!="string"||!ve(t.fields))throw new Error(`${r} is not a v0.2 type with a name and fields.`);let n=lC(t),i=t.name.trim().toLowerCase(),s={type:{const:i}},o=[],a={},c={},l=[],d={},u={},f=[],p=[],y={},h={},m={};for(let[O,$]of Object.entries(t.fields)){let R=ve($)?$:{},S=mp(O,R,n);s[O]=S.schema,Object.assign(c,S.links),Object.assign(u,S.legacy),f.push(...S.unsupported),R.required===!0&&o.push(O),R.default!==void 0&&(a[O]=Ce(R.default)),R.unique===!0&&l.push({field:O,scope:"collection"}),R.generated!==void 0&&dC(d,O,R.generated)&&p.push(O),typeof R.tn_role=="string"&&(y[R.tn_role]=O),Array.isArray(R.tn_completed_values)&&(h.completed_values=Ce(R.tn_completed_values))}a.status!==void 0&&(h.default=Ce(a.status)),a.priority!==void 0&&(m.default=Ce(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,_={...g?{display:{name_field:g}}:{},read_defaults:a,links:c,unique:l};typeof t.path_pattern=="string"&&(_.path=n?uC(t.path_pattern):{pattern:t.path_pattern});let w={};for(let[O,$]of Object.entries(t))aC.has(O)||(w[O]=Ce($));Object.keys(u).length&&(w.fields=u);let k=hp({kind:"mdbase.type",name:i,version:1,description:typeof t.description=="string"?t.description:void 0,match:ve(t.match)?Ce(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:ji(o)}:{}}},collection:_,lifecycle:d,...n?{"x-tasknotes":{contract:"tasknotes.task",version:1,field_roles:y,status:h,priority:m,archive:{tags_field:(P=y.tags)!=null?P:"tags",archived_tag:"archived"}}}:{},...Object.keys(w).length?{"x-legacy-v0.2":w}:{}}),v=[];t.extends!==void 0&&f.push("extends");for(let O of ji(f).sort())v.push({path:r,code:"migration_lossy",message:`${O} cannot be expressed as canonical v0.3 write behavior and was retained as legacy metadata where possible.`,severity:"lossy"});return n&&v.push({path:r,code:"path_policy_runtime_owned",message:"TaskNotes filename behavior is recorded as TaskNotes runtime metadata.",severity:"warning"}),t.strict!==!0&&v.push({path:r,code:"additional_properties_true",message:"The migrated schema allows additional properties because the source type was not strict.",severity:"warning"}),typeof t.display_name_key=="string"&&!g&&v.push({path:r,code:"display_field_missing",message:`The display field '${t.display_name_key}' is not declared, so collection.display was omitted.`,severity:"warning"}),{target:k,summary:{path:r,name:i,fieldsConverted:Object.keys(t.fields).length,requiredFields:ji(o),defaultsMoved:Object.keys(a),generatedFieldsMoved:ji(p),linksMoved:Object.keys(c),taskNotes:n},diagnostics:v}}function pC(r){let e=Ce(r);e.spec_version=ho;let t=ve(e.settings)?e.settings:{};if(e.settings=t,!Array.isArray(t.record_extensions)){let n=Array.isArray(t.extensions)?t.extensions.map(String).map(i=>i.replace(/^\./,"")):[];t.record_extensions=ji(["md",...n])}return Array.isArray(t.explicit_type_keys)||(t.explicit_type_keys=["type","types"]),typeof t.include_subfolders!="boolean"&&(t.include_subfolders=!0),t.validation===void 0&&typeof t.default_validation=="string"&&(t.validation=t.default_validation),t.validation===void 0&&typeof e.default_validation=="string"&&(t.validation=e.default_validation),delete t.default_validation,delete t.extensions,delete e.default_validation,e}function M0(r,e){let t=ve(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 hC(r,e){var n,i;let t={};for(let[s,o]of Object.entries(ve(e.fields)?e.fields:{}))ve(o)&&(t[s]=Ce(o));return{name:typeof e.name=="string"?e.name:(i=(n=r.split("/").pop())==null?void 0:n.replace(/\.md$/,""))!=null?i:"type",fields:t,match:ve(e.match)?Ce(e.match):void 0,filePath:r,specProfile:"v0.2"}}function mC(r,e){var i,s;let t=ve(e.schema)?e.schema:{},n=ve(t.value)?t.value:{};return{name:typeof e.name=="string"?e.name:(s=(i=r.split("/").pop())==null?void 0:i.replace(/\.md$/,""))!=null?s:"type",fields:Sn(n),match:ve(e.match)?Ce(e.match):void 0,collection:ve(e.collection)?Ce(e.collection):void 0,schema:Ce(n),filePath:r,specProfile:"v0.3"}}function yC(r,e,t){let n=Ce(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]=Ce(a.default))}return n}function gC(r,e,t){var i,s;let n=Ce(r);for(let o of e){let a=t.get(o);if(a)for(let[c,l]of Object.entries((s=(i=a.collection)==null?void 0:i.read_defaults)!=null?s:{}))c in n||(n[c]=Ce(l))}return n}async function _C(r,e){let t=(0,it.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 it.TFolder)){if(s)throw new Error(`A file blocks folder ${n}.`);await r.adapter.exists(n)||await r.createFolder(n)}}}async function Fc(r,e,t){let n=(0,it.normalizePath)(e),i=n.lastIndexOf("/");if(i>=0&&await _C(r,n.slice(0,i)),n.startsWith(".mdbase/")){await r.adapter.write(n,t);return}let s=r.getAbstractFileByPath(n);if(s instanceof it.TFolder)throw new Error(`A folder blocks file ${n}.`);s instanceof it.TFile?await r.modify(s,t):await r.create(n,t)}async function po(r,e){let t=(0,it.normalizePath)(e),n=r.getAbstractFileByPath(t);if(n instanceof it.TFile)return r.cachedRead(n);if(await r.adapter.exists(t))return r.adapter.read(t);throw new Error(`File not found: ${e}`)}async function C0(r){var k;let e=await po(r,"mdbase.yaml"),t=(0,it.parseYaml)(e);if(!ve(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===ho?"This collection is already mdbase v0.3.":`Expected an mdbase v0.2.x collection, found ${JSON.stringify(n)}.`);let i=ve(t.settings)?t.settings:{},s=typeof i.types_folder=="string"?(0,it.normalizePath)(i.types_folder):"_types",o=`${s}/`,a=[],c=[],l=[],d=pC(t),u=`${(0,it.stringifyYaml)(d).trimEnd()} -`;a.push({path:"mdbase.yaml",sourceDigest:Nr(e),targetDigest:Nr(u),source:e,target:u});let f=new Map,p=new Map;for(let v of r.getMarkdownFiles().filter(P=>P.path.startsWith(o)).sort((P,O)=>P.path.localeCompare(O.path))){let P=await r.cachedRead(v),O=It(P);if(!O.hasFrontmatter||O.error)throw new Error(`Cannot migrate ${v.path}: ${(k=O.error)!=null?k:"frontmatter is missing"}.`);let $=fC(v.path,n,O.frontmatter),R=hC(v.path,O.frontmatter),S=mC(v.path,$.target);f.set(R.name,R),p.set(S.name,S);let V=`${yt($.target,O.body)} -`;a.push({path:v.path,sourceDigest:Nr(P),targetDigest:Nr(V),source:P,target:V}),c.push($.summary),l.push(...$.diagnostics)}if(!c.length)throw new Error(`No v0.2 type files were found in ${s}.`);let y=0,h=0,m=M0(t,n),g=M0(d,ho),_=r.getMarkdownFiles().filter(v=>!v.path.startsWith(o)).filter(v=>!v.path.startsWith(".mdbase/")).sort((v,P)=>v.path.localeCompare(P.path));for(let[v,P]of _.entries()){let O=It(await r.cachedRead(P));if(O.error){h+=1;continue}let $=fi(P.path,O.frontmatter,m,f),R=fi(P.path,O.frontmatter,g,p),S=yC(O.frontmatter,$,f),V=gC(O.frontmatter,R,p);(Nn($.slice().sort())!==Nn(R.slice().sort())||Nn(S)!==Nn(V))&&l.push({path:P.path,code:"effective_read_changed",message:"The proposed v0.3 types would change this record's resolved types or effective default values.",severity:"lossy"}),y+=1,v>0&&v%250===0&&await new Promise(B=>setTimeout(B,0))}let w=Nr(Nn({sourceVersion:n,operations:a.map(({path:v,sourceDigest:P,targetDigest:O})=>({path:v,sourceDigest:P,targetDigest:O})),diagnostics:l}));return{planVersion:1,analysisId:w,sourceVersion:n,targetVersion:ho,createdAt:new Date().toISOString(),backupLocation:`.mdbase/migrations/v02-to-v03-${w.slice(0,12)}`,operations:a,typeSummaries:c,diagnostics:l,applicable:!l.some(v=>v.severity==="lossy"),recordFilesRewritten:0,recordsVerified:y,recordsSkipped:h}}async function fo(r,e,t){await Fc(r,e,`${JSON.stringify(t,null,2)} -`)}async function N0(r,e,t={}){if(e.planVersion!==1||e.targetVersion!==ho)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 po(r,s.path);if(Nr(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 Fc(r,`${e.backupLocation}/files/${s.path}`,s.source);await fo(r,n,i),i.status="applying",await fo(r,n,i);try{for(let s of e.operations){let o=await po(r,s.path);if(Nr(o)!==s.sourceDigest)throw new Error(`${s.path} changed during migration.`);i.written.push(s.path),await fo(r,n,i),await Fc(r,s.path,s.target);let a=await po(r,s.path);if(Nr(a)!==s.targetDigest)throw new Error(`${s.path} did not verify after write.`)}return i.status="applied",i.completed_at=new Date().toISOString(),await fo(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 Fc(r,a,c.source),Nr(await po(r,a))!==c.sourceDigest&&o.push(a)}catch(l){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 fo(r,n,i)}catch(a){}return{applied:!1,restored:o.length===0,manifestPath:n,written:[...i.written],error:i.error}}}var Uc=require("obsidian");function Ie(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function mr(r){return JSON.parse(JSON.stringify(r))}var bC=new Set(["file","formula","this"]);function wC(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(bC.has(e.toLowerCase()))throw new Error(`Type name '${e}' is reserved.`);return e}function yp(){return{specProfile:"v0.3",originalFrontmatter:{},name:"",description:"",extendsType:"",displayNameKey:"",strictMode:!1,pathPattern:"",filenamePattern:"",matchPathGlob:"",matchFieldsPresent:"",matchWhere:"",fields:[{name:"title",definition:{type:"string",required:!0}}],body:`# Type +`)&&e.slice(1)===r}function Xf(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)=>Xf(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)&&Xf(s,n[i]))}var Ci=class{constructor(e,t,n,i){I(this,"fileSystem");I(this,"runtime");I(this,"mode");I(this,"blobStore");this.fileSystem=e,this.runtime=t,this.mode=n,this.blobStore=i}async recordPathPolicy(e){var t;return Qw(Object.keys((t=e.resources)!=null?t:{}),()=>this.fileSystem.read("mdbase.yaml"))}async put(e,t,n={}){var p,y,h,m;let{managedState:i=e,acceptedHash:s,materialized:o,inspectionPreflighted:a=!1}=n;a||dn(t.path,await this.recordPathPolicy(e)),o===void 0&&!a&&t0(t.path,t.record_id,Object.keys((p=e.resources)!=null?p:{}),Object.entries(e.records),Object.entries((y=e.files)!=null?y:{}));let c=(h=o==null?void 0:o.document)!=null?h:uc(t),l=await this.fileSystem.read(t.path),d=i==null?void 0:i.records[t.record_id];if(l!==null&&l!==c){let g=this.runtime.digest(l);if(!(d!==void 0&&d.path===t.path&&g===d.hash)&&(s===void 0||g!==s))throw new pt(t.record_id,t.path)}d&&d.path!==t.path&&await this.remove(i,t.record_id,d.path);let u=this.runtime.digest(c);typeof s=="string"&&s===u&&l!==null&&this.runtime.digest(l)===u||await this.fileSystem.write(t.path,c),e.records[t.record_id]={path:t.path,revision:t.revision,hash:(m=o==null?void 0:o.hash)!=null?m:u,...this.mode==="read_write"?{record:t}:{}}}async putFile(e,t,n=e,i){var y,h,m,g;if(ft(t),!this.blobStore)throw new b("file_storage_unavailable","Selected collection files require a content-addressed blob store adapter.");r0(t.path,t.file_id,e),(y=e.files)!=null||(e.files={});let s=(h=n.files)==null?void 0:h[t.file_id],o=await this.fileSystem.inspectBinary(t.path),a=bt(t.path),c=Object.values((m=n.files)!=null?m:{}).find(_=>bt(_.file.path)===a),l=[...Object.values((g=n.resources)!=null?g:{}),...Object.values(n.records)].find(_=>bt(_.path)===a),d=l?await this.fileSystem.read(t.path):null,u=(s==null?void 0:s.file.path)===t.path&&Tr(o,s.file),f=c!==void 0&&Tr(o,c.file),p=l!==void 0&&d!==null&&this.runtime.digest(d)===l.hash;if(o!==null&&!Tr(o,t)&&!u&&!f&&!p&&!(i!==void 0&&(o==null?void 0:o.size)===i.size&&o.content_digest===i.content_digest))throw new pt(t.file_id,t.path);if(s&&s.file.path!==t.path){let _=await this.fileSystem.inspectBinary(s.file.path);if(_!==null&&!Tr(_,s.file))throw new pt(t.file_id,s.file.path)}Tr(o,t)||await this.fileSystem.writeBinary(t.path,_c(this.blobStore.read(t.content_digest),t)),s&&s.file.path!==t.path&&await this.fileSystem.remove(s.file.path),e.files[t.file_id]={file:t}}async removeFile(e,t){var s;let n=(s=e.files)==null?void 0:s[t];if(!n)return;let i=await this.fileSystem.inspectBinary(n.file.path);if(i!==null&&!Tr(i,n.file))throw new pt(t,n.file.path);i!==null&&await this.fileSystem.remove(n.file.path),delete e.files[t]}async remove(e,t,n,i={}){var c;let s=e.records[t],o=(c=s==null?void 0:s.path)!=null?c:n;i.inspectionPreflighted||dn(o,await this.recordPathPolicy(e));let a=await this.fileSystem.read(o);if(a!==null&&s&&this.runtime.digest(a)!==s.hash)throw new pt(t,s.path);a!==null&&await this.fileSystem.remove(o),delete e.records[t]}async putResource(e,t,n){var o,a;let i=await this.fileSystem.read(t.path),s=(o=n==null?void 0:n.resources)==null?void 0:o[t.path];if(i!==null&&i!==t.document&&(!s||this.runtime.digest(i)!==s.hash))throw new pt(`resource:${t.path}`,t.path);await this.fileSystem.write(t.path,t.document),(a=e.resources)!=null||(e.resources={}),e.resources[t.path]={path:t.path,revision:t.revision,hash:this.runtime.digest(t.document)}}async removeResource(e,t,n){let i=await this.fileSystem.read(t);if(i!==null&&this.runtime.digest(i)!==n.hash)throw new pt(`resource:${t}`,t);i!==null&&await this.fileSystem.remove(t),e.resources&&delete e.resources[t]}};async function i0(r,e,t,n){var i,s;for(let o in r.records){if(!Object.hasOwn(r.records,o))continue;let a=r.records[o];dn(a.path,e);let c=await t.read(a.path);if(c===null||n(c)!==a.hash)throw new pt(o,a.path)}for(let[o,a]of Object.entries((i=r.resources)!=null?i:{})){let c=await t.read(a.path);if(c===null||n(c)!==a.hash)throw new pt(`resource:${o}`,a.path)}for(let[o,a]of Object.entries((s=r.files)!=null?s:{})){let c=await t.inspectBinary(a.file.path);if(!Tr(c,a.file))throw new pt(o,a.file.path)}}async function s0(r){var u,f,p,y,h;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 b("promotion_incomplete_file_projection","Moving the source of truth requires every collection file class with no excluded folders.");if(Object.keys((u=e.planned_conflicts)!=null?u:{}).length>0||e.batch!==void 0)throw new b("promotion_not_converged","Upload or resolve every local change before moving the source of truth.");await i0(e,i,n,s);let o=new Set(Object.keys((f=e.resources)!=null?f:{})),a=new Set(Object.values(e.records).map(m=>m.path)),c=(await n.listMarkdown(o)).filter(m=>!a.has(m));if(c.length>0)throw new b("promotion_unmanaged_files",`Synchronize unmanaged Markdown before promotion: ${c.join(", ")}.`);if(!n.listBinary)throw new b("promotion_file_scan_unavailable","Moving the source of truth requires binary file enumeration.");let l=new Set(Object.values((p=e.files)!=null?p:{}).map(m=>m.file.path)),d=(await n.listBinary(new Set([...o,...a]))).filter(m=>!l.has(m));if(d.length>0)throw new b("promotion_unmanaged_files",`Synchronize unmanaged files before moving the source of truth: ${d.join(", ")}.`);return{cursor:e.cursor,digest:pc([...Object.entries((y=e.resources)!=null?y:{}).map(([m,g])=>({kind:"resource",path:m,identity:"",document_hash:Lf(g.hash)})),...Object.entries(e.records).map(([m,g])=>({kind:"record",path:g.path,identity:m,document_hash:Lf(g.hash)})),...Object.values((h=e.files)!=null?h:{}).map(({file:m})=>({kind:"file",path:m.path,identity:m.file_id,document_hash:hc(m)}))])}}function Mr(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+t.file_conflicts.length,issues:e.issues,...i?{failure:i}:{}}}function o0(r,e){return["planned","applying","cancelled","stale","blocked","failed"].includes(r.state)?r:r.conflicts.length>0||r.file_conflicts.length>0||r.local_issues.length>0||e.summary.blocking_issues>0||e.summary.conflicts>0?{...r,state:"attention"}:{...r,state:e.actions.some(t=>t.command!=="advance_checkpoint")?"changes_waiting":"up_to_date"}}function fr(r,e){var a,c,l,d,u,f,p,y,h;if(!r)return{state:"not_initialized",mode:e,pending:0,pending_files:0,conflicts:[],file_conflicts:[],local_issues:[],cursor:null,last_synced_at:null};let t=[],n=[];for(let[m,g]of Object.entries((a=r.planned_conflicts)!=null?a:{})){if(g.entity==="file"){let x=g.local.state==="exact"?g.local.object.path:g.remote.state==="exact"?g.remote.object.path:"",v=n.findIndex(({file_id:P})=>P===m);v!==-1&&n.splice(v,1),n.push({file_id:m,path:x,code:"file_conflict",message:"Local and authority changes need a decision."});continue}let _=t.findIndex(({record_id:x})=>x===m);_!==-1&&t.splice(_,1);let w=g.local.state==="exact"?g.local.object.path:g.remote.state==="exact"?g.remote.object.path:null;t.push({record_id:m,path:w,kind:g.conflict_kind==="rejected"?"rejected":"conflicted",message:g.conflict_kind==="rejected"?"The authority rejected this local change.":"Local and authority changes need a decision."})}let i=[],s=r.batch?r.batch.plan.actions.slice(r.batch.next_action).filter(m=>m.command!=="advance_checkpoint").length:0,o=r.batch?r.batch.phase==="prepared"?"planned":r.batch.phase==="applying"||r.batch.phase==="effects_complete"?"applying":r.batch.phase==="cancelled"?"cancelled":((c=r.batch.failure)==null?void 0:c.code)==="sync_plan_stale"?"stale":"blocked":null;return{state:o!=null?o:t.length||n.length?"attention":"up_to_date",mode:e,pending:s,pending_files:r.batch?r.batch.plan.actions.slice(r.batch.next_action).filter(m=>m.command!=="advance_checkpoint"&&("target"in m&&m.target.entity==="file"||"source"in m&&m.source.entity==="file"||"entity"in m&&m.entity==="file")).length:0,conflicts:t,file_conflicts:n,local_issues:i,cursor:(d=(l=r.batch)==null?void 0:l.checkpoint_before.cursor)!=null?d:r.cursor,last_synced_at:(u=r.last_synced_at)!=null?u:null,generation:(f=r.generation)!=null?f:0,pending_checkpoint:(y=(p=r.batch)==null?void 0:p.checkpoint_after.cursor)!=null?y: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,...(h=r.batch)!=null&&h.failure?{failure:r.batch.failure}:{}}}async function gC(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 b("sync_protocol_incompatible",`Filesystem mirror requires exact-document v1 and its own ${t.replace("_","-")} replica.`);return n}async function Ac(r,e,t,n,i){var f;let s=await gC(r,e,t),o=(f=s.resources.documents)!=null?f:[],a=Sc(o),c=new Ec(a,o,i.digest),l=[];await n0(e,s,async p=>{for(let y of p){let h=c.validate(y);Tn(n,h.record.path)&&l.push(h)}});let d=[],u=new Set;return await Tw(e,s,async p=>{for(let y of p)if(bc(n,y)){if(u.has(y.file_id))throw new b("invalid_snapshot",`Hosted snapshot repeats file identity ${y.file_id}.`);u.add(y.file_id),d.push(y)}}),ro([...o.map(p=>p.path),...l.map(({record:p})=>p.path),...d.map(p=>p.path)]),{session:s,resources:o,records:l,files:d}}var kc="exact_document_plan_only_v1",xc="three_way_exact_document_v1",Pc="portable_mirror_projection_v1";function Ic(r){return JSON.stringify(Qf(r))}function no(r,e){return`sha256:${e(Ic(r))}`}function Qf(r){if(r===null||typeof r=="string"||typeof r=="boolean")return r;if(typeof r=="number"){if(!Number.isSafeInteger(r))throw new b("invalid_sync_plan","Sync plans contain only safe integer numeric values.");return r}if(Array.isArray(r))return r.map(Qf);if(typeof r=="object"){let e={};for(let t of Object.keys(r).sort()){let n=r[t];if(n===void 0)throw new b("invalid_sync_plan",`Sync plan field ${t} is undefined rather than an explicit state.`);e[t]=Qf(n)}return e}throw new b("invalid_sync_plan","Sync plans contain only canonical I-JSON values.")}function u0(r,e,t){let n=new Map(r.base.map(d=>[d.identity,d])),i=new Map(r.remote.map(d=>[d.identity,d])),s=new Map,o=new Map(r.local.map(d=>[d.object.path,d]));for(let d of r.local)!d.stable_identity||d.object.identity===""||(s.set(d.object.identity,d.object),o.delete(d.object.path));for(let[d,u]of n){let f=o.get(u.path);f&&(s.set(d,{...f.object,identity:d}),o.delete(u.path))}for(let[d,u]of i){if(s.has(d))continue;let f=o.get(u.path);f&&f.object.entity===u.entity&&(s.set(d,{...f.object,identity:d}),o.delete(u.path))}for(let[d,u]of n){if(s.has(d))continue;let f=[...o.values()].filter(y=>y.object.entity===u.entity&&y.object.payload_revision===u.payload_revision);if(f.length!==1)continue;let p=f[0];s.set(d,{...p.object,identity:d,revision:p.object.payload_revision===u.payload_revision?u.revision:p.object.revision}),o.delete(p.object.path)}for(let d of o.values()){let u=d.stable_identity?d.object.identity:xC(e,d.object,t);s.set(u,{...d.object,identity:u})}let a=new Set([...n.keys(),...s.keys(),...i.keys()]),c=new Map([...s.values()].map(d=>[d.path,d])),l=new Map([...i.values()].map(d=>[d.path,d]));return[...a].sort().map(d=>{var m,g,_,w,x;let u=n.get(d),f=s.get(d),p=i.get(d),y=(g=(m=p==null?void 0:p.path)!=null?m:f==null?void 0:f.path)!=null?g:u.path,h=(w=(_=f==null?void 0:f.path)!=null?_:p==null?void 0:p.path)!=null?w:u.path;return{entity:((x=f!=null?f:p)!=null?x:u).entity,identity:d,base:io(u),local:io(f),remote:io(p),local_target_owner:io(c.get(y)),remote_target_owner:io(l.get(h))}})}function f0(r,e){let t=[];for(let l of[...r.objects].sort(PC))EC(r,l,t);if(t=wC(t,r.objects,e),t=_C(t,r.objects),t.length>0||r.kind!=="incremental"||r.boundary.checkpoint.cursor!==r.boundary.authority_cursor){let l=t.map(d=>d.key);t.push({key:"checkpoint",depends_on_keys:l,command:"advance_checkpoint",reason:r.kind==="incremental"?"remote_change":r.kind,expected:r.boundary.checkpoint,next:{generation:r.boundary.checkpoint.generation+1,cursor:r.boundary.authority_cursor}})}let i=new Map;for(let l of t){let{key:d,depends_on_keys:u,...f}=l;i.set(d,no({action_scope:{replica_id:r.boundary.replica_id,scope_epoch:r.boundary.scope_epoch,generation:r.boundary.checkpoint.generation},key:d,...f},e))}let s=t.map(l=>{let{key:d,depends_on_keys:u,...f}=l,p={...f,action_id:i.get(d),depends_on:u.map(y=>i.get(y))};if((p.command==="put_remote"||p.command==="move_remote"||p.command==="delete_remote")&&(p.idempotency_key=p.action_id),p.command==="move_remote"){let y=u.find(h=>h===`${p.source.identity}:put-remote`);y&&(p.revision_from_dependency=i.get(y))}return p}),o=[...r.issues].sort(IC),a={uploads:s.filter(OC).length,downloads:s.filter(RC).length,conflicts:s.filter(l=>l.command==="record_conflict").length,blocking_issues:o.filter(l=>l.blocking).length},c={plan_version:1,engine_profile:kc,protocol_profile:"exact_document_v1",planner_policy:xc,projection_policy:Pc,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:s,issues:o,summary:a};return{...c,fingerprint:no(c,e)}}function _C(r,e){var c;if(!r.some(l=>l.command==="move_remote"))return r;let t=[...r],n=new Set;for(let l of bC(t))for(let d of l){let u=t.find(f=>f.key===d);(u==null?void 0:u.command)==="move_remote"&&n.add(u.source.identity)}let i=tp(t),s=new Map(t.map(l=>[l.key,l])),o=!0;for(;o;){o=!1;for(let l of t){if(l.command!=="move_remote")continue;let d=l.expected_target_owner;if(d.state!=="exact"||d.object.identity===l.source.identity)continue;let u=s.get((c=i.get(pr(d.object)))!=null?c:""),f=u&&a0(u);(!u||f&&n.has(f))&&!n.has(l.source.identity)&&(n.add(l.source.identity),o=!0)}}if(n.size>0){t=t.filter(d=>{let u=a0(d);return!u||!n.has(u)||d.command!=="put_remote"&&d.command!=="move_remote"});let l=new Map(e.map(d=>[d.identity,d]));for(let d of[...n].sort()){let u=l.get(d);!u||u.entity==="resource"||t.push({key:`${d}:conflict`,depends_on_keys:[],command:"record_conflict",reason:"local_change",identity:d,entity:u.entity,local:u.local,remote:u.remote,conflict_kind:"path_occupied"})}}let a=tp(t);for(let l of t){if(l.command!=="move_remote")continue;let d=l.expected_target_owner;if(d.state!=="exact"||d.object.identity===l.source.identity)continue;let u=a.get(pr(d.object));!u||u===l.key||(l.depends_on_keys.includes(u)||l.depends_on_keys.push(u),l.expected_target_owner={state:"absent"})}return p0(t)}function bC(r){var s;let e=r.filter(o=>o.command==="move_remote"),t=new Map(e.map(o=>[o.key,o])),n=tp(r),i=new Map;for(let o of e){let a=[],c=new Map,l=o;for(;l;){let d=c.get(l.key);if(d!==void 0){let f=a.slice(d);i.set([...f].sort().join("\0"),f);break}c.set(l.key,a.length),a.push(l.key);let u=l.expected_target_owner;l=u.state==="exact"?t.get((s=n.get(pr(u.object)))!=null?s:""):void 0}}return[...i.values()]}function tp(r){let e=new Map;for(let t of r)t.command==="move_remote"?e.set(pr(t.source),t.key):t.command==="delete_remote"&&e.set(pr(t.target),t.key);return e}function a0(r){if(r.command==="move_remote")return r.source.identity;if(r.command==="put_remote"||r.command==="delete_remote")return r.target.identity}function wC(r,e,t){var u;if(!r.some(f=>f.command==="move_local"||f.command==="write_local"))return r;let n=[...r],i=new Set;for(let f of e)f.base.state==="exact"&&i.add(f.base.object.path),f.local.state==="exact"&&i.add(f.local.object.path),f.remote.state==="exact"&&i.add(f.remote.object.path);for(;;){let f=vC(n);if(!f)break;let p=[...f].sort()[0],y=n.findIndex(w=>w.key===p),h=n[y];if(!h||h.command!=="move_local")throw new Error("Planner invariant: local path cycle contains a non-move action.");let m=SC(h.source,h.target_path,i,t);i.add(m);let g={...h.source,path:m},_={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=g,h.expected_source_owner={state:"exact",object:g},h.depends_on_keys=[_.key],n.splice(y,0,_)}let s=rp(n),o=new Map(e.map(f=>[f.identity,f])),a=new Set,c=new Map(n.map(f=>[f.key,f])),l=!0;for(;l;){l=!1;for(let f of n){let p=c0(f),y=Oc(f);if((p==null?void 0:p.state)!=="exact"||p.object.identity===y)continue;let h=c.get((u=s.get(pr(p.object)))!=null?u:""),m=h&&Oc(h);(!h||m&&a.has(m))&&!a.has(y)&&(a.add(y),l=!0)}}if(a.size>0){n=n.filter(f=>!a.has(Oc(f))||f.command!=="move_local"&&f.command!=="write_local");for(let f of[...a].sort()){let p=o.get(f);!p||p.entity==="resource"||n.push({key:`${f}:conflict`,depends_on_keys:[],command:"record_conflict",reason:"remote_change",identity:f,entity:p.entity,local:p.local,remote:p.remote,conflict_kind:"path_occupied"})}}let d=rp(n);for(let f of n){let p=c0(f),y=Oc(f);if((p==null?void 0:p.state)!=="exact"||p.object.identity===y)continue;let h=d.get(pr(p.object));!h||h===f.key||(f.depends_on_keys.includes(h)||f.depends_on_keys.push(h),$C(f,{state:"absent"}))}return p0(n)}function vC(r){var i;let e=r.filter(s=>s.command==="move_local"),t=new Map(e.map(s=>[s.key,s])),n=rp(r);for(let s of e){let o=[],a=new Map,c=s;for(;c;){let l=a.get(c.key);if(l!==void 0)return o.slice(l);a.set(c.key,o.length),o.push(c.key);let d=c.expected_target_owner;c=d.state==="exact"?t.get((i=n.get(pr(d.object)))!=null?i:""):void 0}}}function rp(r){let e=new Map;for(let t of r)t.command==="move_local"?e.set(pr(t.source),t.key):t.command==="delete_local"&&e.set(pr(t.target),t.key);return e}function c0(r){if(r.command==="move_local")return r.expected_target_owner;if(r.command==="write_local")return r.expected_path_owner}function $C(r,e){r.command==="move_local"?r.expected_target_owner=e:r.command==="write_local"&&(r.expected_path_owner=e)}function Oc(r){return r.command==="move_local"?r.source.identity:r.command==="write_local"||r.command==="delete_local"?r.target.identity:""}function pr(r){return`${r.entity}\0${r.identity}\0${r.path}`}function SC(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 d=n(`${r.entity}\0${r.identity}\0${r.path}\0${e}\0${l}`),u=`${s}.mdbase-sync-stage-${d.slice(0,16)}${c}`;if(!t.has(u))return u}}function p0(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 EC(r,e,t){if(e.frozen_conflict){t.push({key:`${e.identity}:conflict`,depends_on_keys:[],command:"record_conflict",reason:"pending",identity:e.identity,entity:e.entity,...e.frozen_conflict});return}let n=!ep(e.local,e.base),i=!ep(e.remote,e.base);if(!(!n&&!i)){if(e.entity==="resource"){if(n)return;Zf(e,t);return}if(r.mode==="read_only"){n||Zf(e,t);return}if(n&&i){if(ep(e.local,e.remote))return;t.push(kC(e));return}n?AC(e,t):Zf(e,t)}}function Zf(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(l0(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(l0(r,t,i?[i]:[]))}function l0(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:Nr(r.local).revision,payload_revision:Nr(r.local).payload_revision,...Nr(r.local).size===void 0?{}:{size:Nr(r.local).size}}}:r.local,expected_path_owner:t.length>0?{state:"exact",object:{...e,revision:Nr(r.local).revision,payload_revision:Nr(r.local).payload_revision,...Nr(r.local).size===void 0?{}:{size:Nr(r.local).size}}}:r.local_target_owner}}function AC(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(d0(r,t,[]));return}let n=r.remote.object,i;if(t.revision!==n.revision){let s=d0(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 d0(r,e,t){return{key:`${r.identity}:put-remote`,depends_on_keys:t,command:"put_remote",reason:"local_change",target:e,payload_revision:Nr(r.local).payload_revision,expected_remote:r.remote,expected_local:r.local,idempotency_key:""}}function kC(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 Nr(r){if(r.state!=="exact")throw new Error("Planner invariant: expected exact object state.");return r.object}function io(r){return r?{state:"exact",object:r}:{state:"absent"}}function xC(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 ep(r,e){return Ic(r)===Ic(e)}function PC(r,e){return`${r.entity}\0${r.identity}`.localeCompare(`${e.entity}\0${e.identity}`)}function IC(r,e){var t,n;return`${(t=r.path)!=null?t:""}\0${r.code}\0${r.message}`.localeCompare(`${(n=e.path)!=null?n:""}\0${e.code}\0${e.message}`)}function OC(r){return r.command==="put_remote"||r.command==="move_remote"||r.command==="delete_remote"}function RC(r){return r.command==="write_local"||r.command==="move_local"||r.command==="delete_local"}var Rc=class{constructor(e,t,n,i,s,o,a,c,l){I(this,"replicaId");I(this,"transport");I(this,"mode");I(this,"fileSystem");I(this,"blobStore");I(this,"selectiveSync");I(this,"runtime");I(this,"readState");I(this,"currentRecordPathPolicy");this.replicaId=e,this.transport=t,this.mode=n,this.fileSystem=i,this.blobStore=s,this.selectiveSync=o,this.runtime=a,this.readState=c,this.currentRecordPathPolicy=l}async inspect(e){let t=e===void 0?await this.readState():e;if(!t)return this.inspectSnapshot("initial",null);if(t.batch)throw new b("mirror_recovery_required","The prepared sync batch must recover before a new inspection can be planned.");return JSON.stringify(t.selective_sync)!==JSON.stringify(this.selectiveSync)?this.inspectSnapshot("rebuild",t):this.inspectIncremental(t)}async inspectSnapshot(e,t){let n=await Ac(this.replicaId,this.transport,this.mode,this.selectiveSync,this.runtime),i=Sc(n.resources),s=await this.inspectLocal(t,n.resources,i),o=new Map(n.records.map(({record:c})=>[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){var l,d;let t=new Map;for(let[u,f]of Object.entries(e.records))f.record&&t.set(u,f.record);let n=new Map(Object.entries((l=e.files)!=null?l:{}).map(([u,f])=>[u,f.file])),i=new Map(h0(e).map(u=>[MC(u),u])),s=e.cursor,o=e.cursor;for(;;){let u=s,f=await this.transport.changes(u,200);if(f.scope_epoch!==e.scope_epoch||f.cursorf.head||f.has_more&&f.cursor===u)throw new b("invalid_change_page","Authority returned an invalid change boundary.");if(f.reset_required)return this.inspectSnapshot("rebuild",e);for(let p of f.events){if(p.sequence<=o||p.sequence>f.cursor)throw new b("invalid_change_page","Authority change events are not strictly ordered.");o=p.sequence,this.applyRemoteObservation(i,t,n,p)}if(s=f.cursor,!f.has_more)break}let a=Object.values((d=e.resources)!=null?d:{}).map(u=>({path:u.path,kind:LC(u.path),revision:u.revision,document:""})),c=await this.inspectLocal(e,a,await this.currentRecordPathPolicy(e));return 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"){mw(i);let s=i.record.record_id;Tn(this.selectiveSync,i.record.path)?(e.set(`record:${s}`,m0(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"){ft(i.file);let s=i.file.file_id;bc(this.selectiveSync,i.file)?(e.set(`file:${s}`,ip(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){var y,h,m,g,_,w,x,v,P,O,$,R,S,U,B;let i=[],s=new Map,o=new Map,a=[],c=new Map(Object.entries((y=e==null?void 0:e.records)!=null?y:{}).map(([T,E])=>[E.path,[T,E]])),l=new Map(Object.entries((h=e==null?void 0:e.planned_conflicts)!=null?h:{}).filter(([,T])=>T.entity==="record"&&T.local.state==="exact").map(([T,E])=>[E.local.state==="exact"?E.local.object.path:"",T])),d=new Map(Object.entries((m=e==null?void 0:e.local_bindings)!=null?m:{}).filter(([,T])=>T.entity==="record").map(([T,E])=>[E.path,T])),u=new Set([...Object.keys((g=e==null?void 0:e.resources)!=null?g:{}),...t.map(T=>T.path)]);for(let T of u){let E=await this.fileSystem.read(T),k=(_=e==null?void 0:e.resources)==null?void 0:_[T];if(E===null)continue;let de=`sha256:${this.runtime.digest(E)}`;i.push({stable_identity:!0,object:Mi("resource",T,T,de)}),s.set(T,E);let Z=t.find(V=>V.path===T);!k&&Z&&Z.revision!==de?a.push({code:"local_collision",message:`${T} differs locally from the exact authority document.`,path:T,blocking:!0}):k&&k.revision!==de&&a.push({code:"mirror_diverged",message:`Authority-owned resource ${T} changed locally.`,path:T,blocking:!0})}let f=new Set(Object.values((w=e==null?void 0:e.records)!=null?w:{}).map(T=>T.path)),p=Zw(await this.fileSystem.listMarkdown(u),n).filter(T=>Tn(this.selectiveSync,T)||f.has(T));for(let T of p){let E=await this.fileSystem.read(T);if(E===null)continue;let k=`sha256:${this.runtime.digest(E)}`,de=l.get(T),Z=d.get(T),V=(x=c.get(T))==null?void 0:x[0],fe=(P=(v=de!=null?de:Z)!=null?v:V)!=null?P:"";i.push({stable_identity:fe!=="",object:Mi("record",fe,T,k)}),s.set(T,E)}if(this.selectiveSync.file_classes.length>0){if(!this.fileSystem.listBinary)throw new b("file_storage_unavailable","Selected files require binary enumeration.");let T=new Set(Object.values((O=e==null?void 0:e.files)!=null?O:{}).map(V=>V.file.path)),E=new Map(Object.entries(($=e==null?void 0:e.files)!=null?$:{}).map(([V,fe])=>[fe.file.path,[V,fe]])),k=new Map(Object.entries((R=e==null?void 0:e.planned_conflicts)!=null?R:{}).filter(([,V])=>V.entity==="file"&&V.local.state==="exact").map(([V,fe])=>[fe.local.state==="exact"?fe.local.object.path:"",V])),de=new Map(Object.entries((S=e==null?void 0:e.local_bindings)!=null?S:{}).filter(([,V])=>V.entity==="file").map(([V,fe])=>[fe.path,V])),Z=(await this.fileSystem.listBinary(u)).filter(V=>Ow(this.selectiveSync,V)||T.has(V));for(let V of Z){let fe=await this.fileSystem.inspectBinary(V);if(!fe)continue;let Ve=k.get(V),Jt=de.get(V),Dr=E.get(V),un=(B=(U=Ve!=null?Ve:Jt)!=null?U:Dr==null?void 0:Dr[0])!=null?B:"";i.push({stable_identity:un!=="",object:{entity:"file",identity:un,path:V,revision:Dr&&Dr[1].file.content_digest===fe.content_digest?Dr[1].file.revision:fe.content_digest,payload_revision:fe.content_digest,size:fe.size}}),o.set(V,fe)}}try{ro([...u,...p,...o.keys()])}catch(T){let E=T instanceof Error?T:new Error(String(T));a.push({code:g0(T),message:E.message,blocking:!0})}return{observations:i,documents:s,binary:o,issues:a}}async finish(e){var u,f,p,y,h;let{prior:t,local:n}=e,i=(u=e.remoteRefs)!=null?u:[...e.remoteResources.map(CC),...[...e.remoteRecords.values()].map(m0),...[...e.remoteFiles.values()].map(ip)],s=u0({base:t?h0(t):[],local:n.observations,remote:i},`${this.replicaId}\0${e.scopeEpoch}\0${(f=t==null?void 0:t.generation)!=null?f:0}`,this.runtime.digest);for(let m of s){let g=(p=t==null?void 0:t.planned_conflicts)==null?void 0:p[m.identity];!g||g.entity!==m.entity||(m.frozen_conflict={local:g.local,remote:g.remote,conflict_kind:g.conflict_kind})}let o=[...n.issues];for(let m of s)(e.kind==="initial"||e.kind==="rebuild")&&m.base.state==="absent"&&m.local.state==="exact"&&m.remote.state==="exact"&&!y0(m.local,m.remote)&&o.push({code:"local_collision",message:`${m.remote.object.path} differs locally from the exact authority object.`,path:m.remote.object.path,blocking:!0}),m.remote.state==="exact"&&m.local_target_owner.state==="exact"&&m.remote.object.identity!==m.local_target_owner.object.identity&&o.push({code:"local_collision",message:`${m.remote.object.path} is owned by different local bytes.`,path:m.remote.object.path,blocking:!0});try{ro([...i.map(m=>m.path),...n.observations.map(({object:m})=>m.path)])}catch(m){let g=m instanceof Error?m:new Error(String(m));o.push({code:g0(m),message:g.message,blocking:!0})}if(this.mode==="read_only"){for(let m of s)if(m.entity!=="resource"&&!y0(m.local,m.base)){let g=NC(m.local,m.base);if(o.some(_=>_.blocking&&_.path===g))continue;o.push({code:"mirror_diverged",message:`${g} changed in a receive-only mirror.`,path:g,blocking:!0})}}let a=no(Rn(this.selectiveSync),this.runtime.digest),c={boundary:{engine_profile:kc,protocol_profile:"exact_document_v1",planner_policy:xc,projection_policy:Pc,replica_id:this.replicaId,scope_epoch:e.scopeEpoch,authority_cursor:e.authorityCursor,checkpoint:{generation:(y=t==null?void 0:t.generation)!=null?y:0,cursor:(h=t==null?void 0:t.cursor)!=null?h:null},selective_sync_fingerprint:a},mode:this.mode,kind:e.kind,selective_sync:Rn(this.selectiveSync),objects:s,issues:TC(o)},l=f0(c,this.runtime.digest),d=await this.bindPayloads(l,n,e.remoteRecords,e.remoteResources,e.remoteFiles);return{summary:c,plan:l,durable_payloads:d,prior:t,snapshot:e.snapshot,remote_records:e.remoteRecords,remote_files:e.remoteFiles}}async bindPayloads(e,t,n,i,s){let o={documents:{},records:{},resources:{},files:{},local_files:{},mutations:{}},a=new Map(i.map(c=>[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 d=t.binary.get(l);if(!d)throw Nn(c.action_id);await this.stageLocalBinary(l,d),o.local_files[c.action_id]={path:l,...d}}else{let d=t.documents.get(l);if(d===void 0||`sha256:${this.runtime.digest(d)}`!==c.payload_revision)throw Nn(c.action_id);o.documents[c.action_id]=d}c.target.entity==="record"&&(o.mutations[c.action_id]={operation:"put",mutation_id:np(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 Nn(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 Nn(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 Nn(c.action_id);await wc(this.transport,this.blobStore,l),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 Nn(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 Nn(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:np(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:np(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 b("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 b("sync_plan_stale",`${e} disappeared during inspection.`);await this.blobStore.write(t.content_digest,Cw(n,t,e))}};function TC(r){var t;let e=new Map;for(let n of r)e.set(`${n.code}\0${(t=n.path)!=null?t:""}\0${n.message}\0${n.blocking}`,n);return[...e.values()]}function h0(r){var e,t;return[...Object.entries((e=r.resources)!=null?e:{}).map(([n,i])=>Mi("resource",n,i.path,i.revision)),...Object.entries(r.records).map(([n,i])=>Mi("record",n,i.path,i.revision)),...Object.entries((t=r.files)!=null?t:{}).map(([n,i])=>ip({...i.file,file_id:n}))]}function m0(r){return Mi("record",r.record_id,r.path,r.revision)}function CC(r){return Mi("resource",r.path,r.path,r.revision)}function Mi(r,e,t,n){return{entity:r,identity:e,path:t,revision:n,payload_revision:n}}function ip(r){return{entity:"file",identity:r.file_id,path:r.path,revision:r.revision,payload_revision:r.content_digest,size:r.size}}function MC(r){return`${r.entity}:${r.identity}`}function y0(r,e){return JSON.stringify(r)===JSON.stringify(e)}function NC(r,e){return r.state==="exact"?r.object.path:e.state==="exact"?e.object.path:"mirror"}function Nn(r){return new b("sync_payload_incomplete",`Inspected action ${r} has no revision-bound payload.`)}function g0(r){return r&&typeof r=="object"&&"code"in r&&typeof r.code=="string"?r.code:"sync_inspection_failed"}function LC(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 np(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 _0(r,e,t,n){if(r!=null&&r.batch){if(r.batch.plan.fingerprint!==e.fingerprint)throw new b("mirror_recovery_required","A different prepared sync batch must recover before this plan can apply.");return r}let i=r?structuredClone(r):DC(e.replica_id,e.scope_epoch,e.mode,e.selective_sync);return i.scope_epoch=e.scope_epoch,i.selective_sync=e.selective_sync,i.batch={phase:"prepared",plan:e,next_action:0,receipts:[],payloads:t,checkpoint_before:{generation:e.checkpoint_generation,cursor:e.base_cursor},checkpoint_after:{generation:e.checkpoint_generation+1,cursor:e.authority_cursor}},await n.write(i),i}async function b0(r,e){let t=rt(r);t.phase!=="effects_complete"&&(t.phase="applying",delete t.failure,await Cc(r,{type:"phase",plan_fingerprint:t.plan.fingerprint,phase:"applying"},e))}async function w0(r,e,t){let n=rt(r),i=n.plan.actions[n.next_action];if(!i||i.action_id!==e.action_id)throw new b("invalid_mirror_state","The durable sync receipt does not match the next prepared action.");let s={type:"receipt",plan_fingerprint:n.plan.fingerprint,receipt:structuredClone(e),delta:jC(r,i)};n.receipts.push(structuredClone(e)),n.next_action+=1,await Cc(r,s,t)}async function v0(r,e){let t=rt(r),n=t.plan.actions[t.next_action];if(!n||n.command!=="advance_checkpoint")throw new b("invalid_mirror_state","Sync effects cannot complete before the checkpoint action is next.");t.phase="effects_complete",await Cc(r,{type:"effects_complete",plan_fingerprint:t.plan.fingerprint},e)}async function Tc(r,e,t,n){let i=rt(r);i.phase=e,i.failure=t,await Cc(r,{type:"phase",plan_fingerprint:i.plan.fingerprint,phase:e,failure:t},n)}async function Cc(r,e,t){t.appendJournal?await t.appendJournal(e):await t.write(r)}function jC(r,e){var s,o,a,c;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]:so((s=r.planned_conflicts)==null?void 0:s[t])},local_bindings:{[t]:so((o=r.local_bindings)==null?void 0:o[t])}};return n==="record"?i.records={[t]:so(r.records[t])}:n==="resource"?i.resources={[t]:so((a=r.resources)==null?void 0:a[t])}:i.files={[t]:so((c=r.files)==null?void 0:c[t])},i}function so(r){return r===void 0?null:structuredClone(r)}function rt(r){if(!r.batch)throw new b("invalid_mirror_state","The mirror has no prepared sync batch.");return r.batch}async function $0(r,e){var n;let t=rt(r);if(t.phase!=="blocked"||((n=t.failure)==null?void 0:n.code)!=="sync_plan_stale")throw new b("mirror_recovery_required","Only a stale batch at a durable action boundary can be abandoned.");delete r.batch,await e.write(r)}function DC(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 Nc=class{constructor(e){I(this,"ports");I(this,"materializer");I(this,"ownersByPath",new Map);I(this,"pathsByOwner",new Map);this.ports=e,this.materializer=new Ci(e.fileSystem,e.runtime,e.mode,e.blobStore)}async execute(e,t){var s,o;let n=rt(e);this.indexPathOwners(e);let i=new Set(n.receipts.map(a=>a.action_id));for(await b0(e,this.ports.store);n.next_action!i.has(l));if(c){let l={code:"invalid_mirror_state",message:`Action ${a.action_id} is missing dependency ${c}.`,action_id:a.action_id};return await Tc(e,"blocked",l,this.ports.store),{status:"blocked",completed:n.next_action,failure:l}}try{let l=await this.dispatch(e,a);await w0(e,l,this.ports.store),i.add(l.action_id),(o=(s=this.ports).onProgress)==null||o.call(s,n.next_action,n.plan.actions.length-1)}catch(l){let d=VC(l,a.action_id);return await Tc(e,"blocked",d,this.ports.store),{status:d.code==="sync_plan_stale"?"stale":"blocked",completed:n.next_action,failure:d}}}throw new b("invalid_mirror_state","Prepared plan has no checkpoint action.")}async dispatch(e,t){var n,i;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":return(n=e.planned_conflicts)!=null||(e.planned_conflicts={}),e.planned_conflicts[t.identity]={entity:t.entity,local:t.local,remote:t.remote,conflict_kind:t.conflict_kind},(i=e.local_bindings)!=null||(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"advance_checkpoint":throw new b("invalid_mirror_state","The executor cannot dispatch checkpoint actions.")}}rebaseConflict(e,t){var s;let n=rt(e).payloads;if(t.entity==="record"){if(t.remote.state==="absent"){delete e.records[t.identity];return}let o=n.records[t.action_id];if(!o||o.revision!==t.remote.object.revision)throw hr(t);Mc(o,this.ports.runtime,o.revision),e.records[t.identity]={path:o.path,revision:o.revision,hash:t.local.state==="exact"?t.local.object.payload_revision.replace(/^sha256:/u,""):this.ports.runtime.digest(o.document),...this.ports.mode==="read_write"?{record:o}:{}};return}if((s=e.files)!=null||(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 hr(t);ft(i),e.files[t.identity]={file:i}}async writeLocal(e,t){let n=await this.ports.fileSystem.exists(t.target.path);(!n||!await this.matchesRef(t.target))&&(await this.assertLocal(t.expected_local),await this.assertPathOwner(t.target.path,t.expected_path_owner,n));let i=rt(e).payloads;if(t.target.entity==="record"){let o=i.records[t.action_id];if(!o||o.revision!==t.payload_revision)throw hr(t);return Mc(o,this.ports.runtime,t.payload_revision),await this.materializer.put(e,o,{inspectionPreflighted:!0}),this.installPathOwner(t.target),{action_id:t.action_id,status:"completed"}}if(t.target.entity==="resource"){let o=i.resources[t.action_id];if(!o||o.revision!==t.payload_revision||`sha256:${this.ports.runtime.digest(o.document)}`!==o.revision)throw hr(t);return await this.materializer.putResource(e,o,e),this.installPathOwner(t.target),{action_id:t.action_id,status:"completed"}}let s=i.files[t.action_id];if(!s||s.content_digest!==t.payload_revision)throw hr(t);return await this.materializer.putFile(e,s,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)),qC(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){var i;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 s=(i=e.resources)==null?void 0:i[t.target.identity];s?await this.materializer.removeResource(e,t.target.path,s):await this.ports.fileSystem.remove(t.target.path)}else await this.materializer.removeFile(e,t.target.identity);else FC(e,t.target);return this.removePathOwner(t.target),{action_id:t.action_id,status:"completed"}}async putRemote(e,t){var a,c;let n=rt(e).payloads;if(t.target.entity==="record"){let l=n.mutations[t.action_id],d=n.documents[t.action_id];if(!l||l.operation!=="put"||d===void 0)throw hr(t);if(`sha256:${this.ports.runtime.digest(d)}`!==t.payload_revision)throw new b("sync_plan_stale","Prepared local document payload no longer matches its revision.");let u=await this.ports.transport.mutate(l);return this.acceptRecordReceipt(e,t,u,d),sp(t.action_id,u)}if(t.target.entity==="resource")throw new b("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 hr(t);let s={protocol_version:1,type:"open_file_upload",transfer_id:ap(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(ft(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 op(t);return(a=e.files)!=null||(e.files={}),e.files[o.file.file_id]={file:o.file},(c=e.local_bindings)==null||delete c[t.target.identity],{action_id:t.action_id,status:"completed",file:o.file}}async moveRemote(e,t){var s,o,a;if(t.source.entity==="record"){let c=rt(e).payloads.mutations[t.action_id];if(!c||c.operation!=="move")throw hr(t);let l=await this.ports.transport.mutate(c);return this.acceptRecordReceipt(e,t,l),sp(t.action_id,l)}if(t.source.entity==="resource"||!this.ports.transport.moveFile)throw new b("invalid_sync_plan","This remote move command is unsupported.");let n={protocol_version:1,type:"move_file",mutation_id:ap(t.action_id),file_id:t.source.identity,if_revision:(s=this.dependencyFileRevision(e,t))!=null?s: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(ft(i.file),i.mutation_id!==n.mutation_id||i.file.file_id!==t.source.identity||i.file.path!==t.target_path)throw op(t);return(o=e.files)!=null||(e.files={}),e.files[t.source.identity]={file:i.file},(a=e.local_bindings)==null||delete a[t.source.identity],{action_id:t.action_id,status:"completed",file:i.file}}dependencyFileRevision(e,t){if(!t.revision_from_dependency)return;let n=rt(e).receipts.find(({action_id:i})=>i===t.revision_from_dependency);if(!(n!=null&&n.file)||n.file.file_id!==t.source.identity)throw new b("invalid_mirror_state",`Move ${t.action_id} is missing its dependency file receipt.`);return n.file.revision}async deleteRemote(e,t){var s,o;if(t.target.entity==="record"){let a=rt(e).payloads.mutations[t.action_id];if(!a||a.operation!=="delete")throw hr(t);let c=await this.ports.transport.mutate(a);return this.acceptRecordReceipt(e,t,c),sp(t.action_id,c)}if(t.target.entity==="resource"||!this.ports.transport.deleteFile)throw new b("invalid_sync_plan","This remote delete command is unsupported.");let n={protocol_version:1,type:"delete_file",mutation_id:ap(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 op(t);return(s=e.files)==null||delete s[t.target.identity],(o=e.local_bindings)==null||delete o[t.target.identity],{action_id:t.action_id,status:"completed"}}acceptRecordReceipt(e,t,n,i){var l,d,u,f;let o=("target"in t?t.target:t.source).identity;if(n.status==="applied"||n.status==="previously_applied"){if(n.record){Mc(n.record,this.ports.runtime,n.record.revision);let p=e.records[o];e.records[o]={path:n.record.path,revision:n.record.revision,hash:i===void 0?(l=p==null?void 0:p.hash)!=null?l: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];(d=e.local_bindings)==null||delete d[o];return}let a=n.status==="conflicted"?n.conflict.current:void 0;a&&Mc(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;(u=e.planned_conflicts)!=null||(e.planned_conflicts={}),e.planned_conflicts[o]={entity:"record",local:t.expected_local,remote:c,conflict_kind:n.status==="rejected"?"rejected":"both_changed"},(f=e.local_bindings)!=null||(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 new b("sync_plan_stale",`${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!=null?n:await this.pathExists(e)))throw new b("sync_plan_stale",`${e} is no longer vacant.`);return}if(!i||i.entity!==t.object.entity||i.identity!==t.object.identity)throw new b("sync_plan_stale",`${e} has a different path owner.`)}async matchesRef(e){if(e.entity==="file"){let n=await this.ports.fileSystem.inspectBinary(e.path);return n!==null&&n.content_digest===e.payload_revision&&(e.size===void 0||n.size===e.size)}let t=await this.ports.fileSystem.read(e.path);return t!==null&&`sha256:${this.ports.runtime.digest(t)}`===e.payload_revision}async pathExists(e){return this.ports.fileSystem.exists(e)}indexPathOwners(e){var t,n;this.ownersByPath.clear(),this.pathsByOwner.clear();for(let[i,s]of Object.entries(e.records))this.installPathOwner({entity:"record",identity:i,path:s.path,revision:s.revision,payload_revision:`sha256:${s.hash}`});for(let[i,s]of Object.entries((t=e.resources)!=null?t:{}))this.installPathOwner({entity:"resource",identity:i,path:s.path,revision:s.revision,payload_revision:`sha256:${s.hash}`});for(let[i,s]of Object.entries((n=e.files)!=null?n:{}))this.installPathOwner({entity:"file",identity:i,path:s.file.path,revision:s.file.revision,payload_revision:s.file.content_digest,size:s.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){var i;let t=`${e.entity}:${e.identity}`,n=(i=this.pathsByOwner.get(t))!=null?i:e.path;this.ownersByPath.delete(n),this.pathsByOwner.delete(t)}};function qC(r,e,t){var n,i;if(e.entity==="record"){let s=r.records[e.identity];s&&(s.path=t)}else if(e.entity==="resource"){let s=(n=r.resources)==null?void 0:n[e.identity];s&&(s.path=t)}else{let s=(i=r.files)==null?void 0:i[e.identity];s&&(s.file.path=t)}}function FC(r,e){var t,n;e.entity==="record"?delete r.records[e.identity]:e.entity==="resource"?(t=r.resources)==null||delete t[e.identity]:(n=r.files)==null||delete n[e.identity]}function Mc(r,e,t){let n=uc(r);if(r.revision!==t||`sha256:${e.digest(n)}`!==t)throw new b("invalid_sync_response","Record receipt does not match its exact document revision.")}function sp(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 hr(r){return new b("sync_payload_incomplete",`Prepared action ${r.action_id} has no exact payload capability.`)}function op(r){return new b("invalid_sync_response",`Authority receipt does not match prepared action ${r.action_id}.`)}function VC(r,e){let t=r instanceof Error?r:new Error(String(r));return{code:r&&typeof r=="object"&&"code"in r&&typeof r.code=="string"?r.code:"sync_action_failed",message:t.message,action_id:e}}function ap(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 jc=class{constructor(e,t){I(this,"fileSystem");I(this,"runtime");this.fileSystem=e,this.runtime=t}async validate(e,t){var n,i,s;if(((n=t==null?void 0:t.generation)!=null?n:0)!==e.checkpoint_generation||((i=t==null?void 0:t.cursor)!=null?i:null)!==e.base_cursor||((s=t==null?void 0:t.scope_epoch)!=null?s:e.scope_epoch)!==e.scope_epoch)throw Lc("The durable checkpoint changed after inspection.");for(let o of e.actions)o.depends_on.length===0&&await this.validateAction(o)}async validateAction(e){switch(e.command){case"write_local":await this.expected(e.expected_local),await this.expectedAt(e.target.path,e.expected_path_owner);return;case"delete_local":await this.expected(e.expected_local),await this.expectedAt(e.target.path,e.expected_path_owner);return;case"move_local":await this.expectedAt(e.source.path,e.expected_source_owner),await this.expectedAt(e.target_path,e.expected_target_owner);return;case"put_remote":case"move_remote":await this.expected(e.expected_local);return;case"delete_remote":await this.expectedAt(e.target.path,e.expected_local);return;case"record_conflict":await this.expected(e.local);return;case"advance_checkpoint":return}}async expectedAt(e,t){if(t.state==="absent"){if(await this.pathExists(e))throw Lc(`${e} is no longer vacant.`);return}if(t.object.path!==e||!await this.matches(t.object))throw Lc(`${e} no longer has the inspected owner and bytes.`)}async expected(e){if(e.state!=="absent"&&!await this.matches(e.object))throw Lc(`${e.object.path} no longer matches the inspected bytes.`)}async matches(e){if(e.entity==="file"){let n=await this.fileSystem.inspectBinary(e.path);return n!==null&&n.content_digest===e.payload_revision&&(e.size===void 0||n.size===e.size)}let t=await this.fileSystem.read(e.path);return t!==null&&`sha256:${this.runtime.digest(t)}`===e.payload_revision}async pathExists(e){return this.fileSystem.exists(e)}};function Lc(r){return new b("sync_plan_stale",r)}async function S0(r,e,t){var o;let n=rt(r);if(n.phase!=="effects_complete")throw new b("invalid_mirror_state","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 new b("invalid_mirror_state","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 new b("invalid_mirror_state","Prepared checkpoint boundary is inconsistent.");let s=n.plan.fingerprint;return r.generation=i.next.generation,r.cursor=(o=i.next.cursor)!=null?o:0,r.last_completed_plan=s,r.last_synced_at=e.now(),delete r.batch,await t.write(r),s}async function E0(r,e,t,n){var s,o,a;let[i]=e.actions;if(e.actions.length!==1||!i||i.command!=="advance_checkpoint"||i.expected.generation!==((s=r.generation)!=null?s:0)||i.expected.cursor!==r.cursor||i.next.generation!==((o=r.generation)!=null?o:0)+1||i.next.cursor!==e.authority_cursor||r.batch!==void 0)throw new b("invalid_mirror_state","Empty checkpoint plan is inconsistent.");return r.generation=i.next.generation,r.cursor=(a=i.next.cursor)!=null?a:0,r.last_completed_plan=e.fingerprint,r.last_synced_at=t.now(),await n.write(r),e.fingerprint}var Ln=class{constructor(e,t,n,i="read_only"){I(this,"replicaId");I(this,"transport");I(this,"mode");I(this,"stateStore");I(this,"fileSystem");I(this,"blobStore");I(this,"selectiveSync");I(this,"lease");I(this,"runtime");I(this,"materializer");I(this,"onProgress");var s,o;this.replicaId=e,this.transport=t,this.mode=i,this.stateStore=n.stateStore,this.fileSystem=n.fileSystem,this.blobStore=n.blobStore,this.selectiveSync=Rn(n.selectiveSync),this.lease=(s=n.lease)!=null?s:new eo,this.runtime=(o=n.runtime)!=null?o:to,this.materializer=new Ci(this.fileSystem,this.runtime,this.mode,this.blobStore),this.onProgress=n.onProgress}async sync(e={}){return this.lease.runExclusive(async()=>{var i,s;let t=await this.readState();if(((i=t==null?void 0:t.batch)==null?void 0:i.phase)==="blocked"&&((s=t.batch.failure)==null?void 0:s.code)==="sync_plan_stale"&&(await $0(t,this.journalStore()),t=await this.readState()),t!=null&&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()=>{var t,n;let e=await this.readState();return(n=(t=e==null?void 0:e.batch)==null?void 0:t.plan)!=null?n:(await this.inspectDetailed(e)).plan})}async apply(e,t={}){return this.lease.runExclusive(async()=>{let n=await this.readState();if(n!=null&&n.batch){if(n.batch.plan.fingerprint!==e.fingerprint)throw new b("mirror_recovery_required","A different prepared plan must recover before this plan can apply.");return this.executePrepared(n,t.signal)}let i=await this.inspectDetailed(n);return i.plan.fingerprint!==e.fingerprint?Mr("stale",e,fr(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){var s;let n=e.plan;if(n.issues.some(o=>o.blocking))return Mr("attention",n,fr(e.prior,this.mode),0);if(t!=null&&t.aborted)return Mr("cancelled",n,fr(e.prior,this.mode),0,{code:"sync_cancelled",message:"Sync cancelled before preparation."});try{await new jc(this.fileSystem,this.runtime).validate(n,e.prior)}catch(o){let a=o instanceof Error?o:new Error(String(o)),c=o&&typeof o=="object"&&"code"in o&&typeof o.code=="string"?o.code:"sync_revalidation_failed";return Mr(c==="sync_plan_stale"?"stale":"failed",n,fr(e.prior,this.mode),0,{code:c,message:a.message})}if(n.actions.length===0)return Mr("applied",n,fr(e.prior,this.mode),0);if(e.prior&&n.actions.length===1&&((s=n.actions[0])==null?void 0:s.command)==="advance_checkpoint")return await E0(e.prior,n,this.runtime,this.journalStore()),Mr("applied",n,fr(e.prior,this.mode),0);let i=await _0(e.prior,n,e.durable_payloads,this.journalStore());return this.executePrepared(i,t)}async executePrepared(e,t){let n=e.batch,i=await new Nc({transport:this.transport,fileSystem:this.fileSystem,blobStore:this.blobStore,runtime:this.runtime,mode:this.mode,store:this.journalStore(),onProgress:(c,l)=>{var d;return(d=this.onProgress)==null?void 0:d.call(this,{phase:"applying",completed:c,total:l,done:c===l})}}).execute(e,t);if(i.status!=="effects_complete"){let c=fr(e,this.mode);return Mr(i.status==="blocked"?"failed":i.status,n.plan,c,i.completed,i.failure)}let s=n.plan;await S0(e,this.runtime,this.journalStore()),await this.pruneFileBlobs();let o=fr(e,this.mode),a=o.conflicts.length>0||o.file_conflicts.length>0||o.local_issues.length>0||s.summary.conflicts>0;return Mr(a?"attention":"applied",s,o,i.completed)}inspectDetailed(e){return new Rc(this.replicaId,this.transport,this.mode,this.fileSystem,this.blobStore,this.selectiveSync,this.runtime,()=>this.readState(),t=>this.currentRecordPathPolicy(t)).inspect(e)}async status(){let e=await this.checkpointStatus();return e.state==="not_initialized"?e:o0(e,await this.inspect())}async checkpointStatus(){return this.lease.runExclusive(()=>this.checkpointStatusUnlocked())}async checkpointStatusUnlocked(){return fr(await this.readState(),this.mode)}async authorityPromotionManifest(){return this.lease.runExclusive(async()=>{var i;if(this.mode!=="read_write")throw new b("promotion_requires_writable_mirror","Only a read-write mirror can prove an authority promotion source.");let e=await this.readState();if(!e)throw new b("mirror_not_initialized","Synchronize this mirror first.");if(e.batch||Object.keys((i=e.planned_conflicts)!=null?i:{}).length>0)throw new b("promotion_mirror_not_clean","Finish the prepared batch and resolve conflicts before promotion.");let t=await s0({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(s=>s.command!=="advance_checkpoint"))throw new b("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){await this.lease.runExclusive(()=>this.resolveConflictUnlocked(e,"record",t))}async resolveFileConflict(e,t){await this.lease.runExclusive(()=>this.resolveConflictUnlocked(e,"file",t))}async resolveConflictUnlocked(e,t,n){var o,a,c,l;if(this.mode!=="read_write")throw new b("mirror_read_only","Receive-only mirrors have no writable conflicts.");let i=await this.readState();if(!i||i.batch)throw new b("mirror_recovery_required","Finish sync recovery before resolving conflicts.");if(!((o=i.planned_conflicts)==null?void 0:o[e]))throw new b("mirror_conflict_not_found","Writable mirror conflict was not found.");if(n==="remote"){let d=await Ac(this.replicaId,this.transport,this.mode,this.selectiveSync,this.runtime);if(t==="record"){let u=(a=d.records.find(({record:f})=>f.record_id===e))==null?void 0:a.record;await this.installRemoteRecord(i,e,u)}else{let u=d.files.find(f=>f.file_id===e);await this.installRemoteFile(i,e,u)}}(c=i.planned_conflicts)==null||delete c[e],n==="remote"&&((l=i.local_bindings)==null||delete l[e]),await this.writeState(i)}async installRemoteRecord(e,t,n){var o,a,c,l;if(n){let d=(o=e.planned_conflicts)==null?void 0:o[t],u=await this.fileSystem.read(n.path),f=((a=e.records[t])==null?void 0:a.path)===n.path||(d==null?void 0:d.local.state)==="exact"&&d.local.object.path===n.path;await this.materializer.put(e,n,{inspectionPreflighted:!1,...f&&u!==null?{acceptedHash:this.runtime.digest(u)}:{}});return}let i=(c=e.planned_conflicts)==null?void 0:c[t],s=(i==null?void 0:i.local.state)==="exact"?i.local.object.path:(l=e.records[t])==null?void 0:l.path;s&&await this.fileSystem.read(s)!==null&&await this.fileSystem.remove(s),delete e.records[t]}async installRemoteFile(e,t,n){var o,a,c,l,d,u,f,p;if(n){if(!this.blobStore)throw new b("file_storage_unavailable","File resolution needs a blob store.");await wc(this.transport,this.blobStore,n);let y=(o=e.planned_conflicts)==null?void 0:o[t],h=(y==null?void 0:y.local.state)==="exact"?{content_digest:y.local.object.payload_revision,size:(a=y.local.object.size)!=null?a:0}:void 0,m=(l=(c=e.local_bindings)==null?void 0:c[t])==null?void 0:l.path;await this.materializer.putFile(e,n,e,h),m&&m!==n.path&&await this.fileSystem.remove(m);return}let i=(d=e.planned_conflicts)==null?void 0:d[t],s=(i==null?void 0:i.local.state)==="exact"?i.local.object.path:(f=(u=e.files)==null?void 0:u[t])==null?void 0:f.file.path;s&&await this.fileSystem.inspectBinary(s)!==null&&await this.fileSystem.remove(s),(p=e.files)==null||delete p[t]}async readState(){let e=await this.stateStore.read();if(e===null)return null;try{return Gw(e,this.replicaId,this.mode)}catch(t){throw t instanceof b?t:new b("invalid_mirror_state","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(){var n,i,s,o,a;if(!this.blobStore)return;let e=await this.readState();if(!e)return;let t=new Set;for(let c of Object.values((n=e.files)!=null?n:{}))t.add(c.file.content_digest);for(let c of Object.values((s=(i=e.batch)==null?void 0:i.payloads.files)!=null?s:{}))t.add(c.content_digest);for(let c of Object.values((a=(o=e.batch)==null?void 0:o.payloads.local_files)!=null?a:{}))t.add(c.content_digest);await this.blobStore.prune(t)}currentRecordPathPolicy(e){return this.materializer.recordPathPolicy(e)}};var oo=class extends Ln{constructor(e,t,n){super(e,t,n,"read_write")}};function A0(r){let e=[...r.actions.flatMap(t=>t.command==="advance_checkpoint"?[]:[UC(t)]),...r.issues.map(t=>{var n;return{kind:"document",path:(n=t.path)!=null?n:"Sync engine",direction:"attention",action:"fix",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).map(t=>t.path),local_issues:r.issues.filter(t=>t.code==="invalid_frontmatter"&&t.path!==void 0).map(t=>({code:"invalid_frontmatter",message:t.message,path:t.path}))}}function UC(r){var c;if(r.command==="advance_checkpoint")throw new Error("Checkpoint actions are not preview entries.");if(r.command==="record_conflict"){let l=r.local.state==="exact"?r.local.object:r.remote.state==="exact"?r.remote.object:void 0;return{kind:r.entity==="file"?"file":"document",path:(c=l==null?void 0:l.path)!=null?c:r.identity,direction:"attention",action:"fix",detail:`Local and hosted ${r.entity} changes conflict (${r.conflict_kind.replace(/_/g," ")}).`,...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=r.command.split("_")[0],a=r.command.startsWith("move_")?` from ${t.path}`:"";return{kind:t.entity==="file"?"file":"document",path:n,direction:e?"download":"upload",action:s,detail:`${e?"Hosted":"Local"} ${t.entity} will ${o}${a}.`,...t.entity==="record"?{recordId:t.identity}:{},...t.entity==="file"?{fileId:t.identity}:{}}}var ao=".mdbase/connect-role.json",co=".mdbase/authority-adoption.json",lo=".mdbase/authority-adoption-snapshot.json",BC="mdbase-obsidian-connect-exact-v1",Ni="mirrors",zC="mdbase-connect-access-",HC="mdbase-connect-refresh-",KC="mdbase-connect-adoption-",WC=300*1e3,lp=[".git/",".obsidian/",".trash/",".mdbase/"],uo=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Fe(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function Dc(r,e){if(e!=null)return e;if(!r.trim())return{};try{return JSON.parse(r)}catch(t){return{}}}function x0(r){var i;let e=(i=r["retry-after"])!=null?i:r["Retry-After"];if(!e)return;let t=Number(e);if(Number.isFinite(t)&&t>=0)return t*1e3;let n=Date.parse(e);if(Number.isFinite(n))return Math.max(0,n-Date.now())}function GC(){return async r=>{var t,n;if((t=r.signal)!=null&&t.aborted)throw new DOMException("Enrollment cancelled.","AbortError");let e=await(0,oe.requestUrl)({url:r.url,method:r.method,headers:r.headers,body:r.body===void 0?void 0:JSON.stringify(r.body),contentType:r.body===void 0?void 0:"application/json",throw:!1});if((n=r.signal)!=null&&n.aborted)throw new DOMException("Enrollment cancelled.","AbortError");return{status:e.status,body:Dc(e.text,e.json),retryAfterMs:x0(e.headers)}}}function JC(){return async r=>{var t,n;if((t=r.signal)!=null&&t.aborted)throw new DOMException("Collection adoption cancelled.","AbortError");let e=await(0,oe.requestUrl)({url:r.url,method:r.method,headers:r.headers,body:r.body===void 0?void 0:JSON.stringify(r.body),contentType:r.body===void 0?void 0:"application/json",throw:!1});if((n=r.signal)!=null&&n.aborted)throw new DOMException("Collection adoption cancelled.","AbortError");return{status:e.status,body:Dc(e.text,e.json),retryAfterMs:x0(e.headers)}}}var dp=class{constructor(e,t){this.accessToken=t;let n;try{n=new URL(e)}catch(i){throw new b("invalid_sync_url","Sync URL must be an absolute authority endpoint.")}if(!(n.protocol==="https:"||n.protocol==="http:"&&["localhost","127.0.0.1","[::1]","::1"].includes(n.hostname))||n.username||n.password||n.search||n.hash||!/^\/v1\/authorities\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\/sync\/?$/i.test(n.pathname))throw new b("invalid_sync_url","Sync URL must identify one authority sync endpoint.");this.syncUrl=n.href.replace(/\/$/,""),this.filesUrl=this.syncUrl.replace(/\/sync$/,"/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){let t=crypto.randomUUID();try{let n=await this.fileRequest("POST","downloads",{protocol_version:1,type:"open_file_download",transfer_id:t,file_id:e.file_id,revision:e.revision}),i=Fe(n.strategy)?n.strategy:{},s=i.part_size;if(n.protocol_version!==1||n.type!=="file_transfer"||n.transfer_id!==t||n.direction!=="download"||n.protection!=="transport_tls"||n.total_size!==e.size||i.kind!=="object_ranges"||!Number.isSafeInteger(s)||s<=0)throw new b("invalid_sync_response","The authority returned an incompatible file download session.");let o=Math.ceil(e.size/s);for(let a=0;a=300){let d=Dc(l.text,l.json),u=Fe(d)&&Fe(d.error)?d.error:{};throw new b(typeof u.code=="string"?u.code:"file_download_failed",typeof u.message=="string"?u.message:`File download failed (${l.status}).`)}if(l.arrayBuffer.byteLength!==c)throw new b("file_integrity_failed","The authority returned a file part with the wrong length.");yield new Uint8Array(l.arrayBuffer)}}finally{await this.fileRequest("DELETE",`transfers/${encodeURIComponent(t)}`).catch(()=>{})}}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)}request(e,t,n){return this.requestAt(this.syncUrl,e,t,n)}fileRequest(e,t,n){return this.requestAt(this.filesUrl,e,t,n)}async requestAt(e,t,n,i){let s=await(0,oe.requestUrl)({url:`${e}/${n}`,method:t,headers:{authorization:`Bearer ${this.accessToken}`},body:i===void 0?void 0:JSON.stringify(i),contentType:i===void 0?void 0:"application/json",throw:!1}),o=Dc(s.text,s.json);if(s.status<200||s.status>=300){let a=Fe(o)&&Fe(o.error)?o.error:{};throw new b(typeof a.code=="string"?a.code:"sync_failed",typeof a.message=="string"?a.message:`Sync request failed (${s.status}).`)}return o}};function Lr(r){let e=Rs(r);if(e===".mdbase"||lp.some(t=>e.startsWith(t)))throw new b("unsafe_mirror_path",`The collection authority attempted to write a reserved path: ${e}`);return e}async function ji(r,e){let t=(0,oe.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 oe.TFolder)){if(s)throw new b("mirror_path_collision",`A file blocks the mirror folder ${n}.`);await r.adapter.exists(n)||await r.createFolder(n)}}}var up=class{constructor(e){this.vault=e}async exists(e){let t=Lr(e);return this.vault.getAbstractFileByPath(t)!==null||await this.vault.adapter.exists(t)}async read(e){let t=Lr(e),n=this.vault.getAbstractFileByPath(t);if(n==null)return null;if(!(n instanceof oe.TFile))throw new b("mirror_path_collision",`Expected a file at ${t}.`);return this.vault.cachedRead(n)}async write(e,t){let n=Lr(e),i=n.lastIndexOf("/");i>=0&&await ji(this.vault,n.slice(0,i));let s=this.vault.getAbstractFileByPath(n);if(s instanceof oe.TFolder)throw new b("mirror_path_collision",`A folder blocks the mirror file ${n}.`);s instanceof oe.TFile?await this.vault.modify(s,t):await this.vault.create(n,t)}async move(e,t){let n=Lr(e),i=Lr(t),s=i.lastIndexOf("/");s>=0&&await ji(this.vault,i.slice(0,s));let o=this.vault.getAbstractFileByPath(n);if(!(o instanceof oe.TFile))throw new b("mirror_path_collision",`Expected a file at ${n}.`);if(this.vault.getAbstractFileByPath(i)!==null||await this.vault.adapter.exists(i))throw new b("mirror_path_collision",`A file or folder blocks ${i}.`);await this.vault.rename(o,i)}async remove(e){let t=Lr(e),n=this.vault.getAbstractFileByPath(t);if(n!=null){if(!(n instanceof oe.TFile))throw new b("mirror_path_collision",`Expected a file at ${t}.`);await this.vault.delete(n,!0)}}async listMarkdown(e){return this.vault.getMarkdownFiles().map(t=>(0,oe.normalizePath)(t.path)).filter(t=>!e.has(t)).filter(t=>!lp.some(n=>t.startsWith(n))).sort()}async inspectBinary(e){let t=Lr(e),n=this.vault.getAbstractFileByPath(t);if(n==null)return null;if(!(n instanceof oe.TFile))throw new b("mirror_path_collision",`Expected a file at ${t}.`);let i=await this.vault.readBinary(n),s=await crypto.subtle.digest("SHA-256",i),o=Array.from(new Uint8Array(s),a=>a.toString(16).padStart(2,"0")).join("");return{size:i.byteLength,content_digest:`sha256:${o}`}}async writeBinary(e,t){let n=Lr(e),i=[],s=0;for await(let d of t){if(!(d instanceof Uint8Array)||!Number.isSafeInteger(s+d.byteLength))throw new b("invalid_file_materialization","The binary file stream is invalid or too large.");i.push(d),s+=d.byteLength}let o=new Uint8Array(s),a=0;for(let d of i)o.set(d,a),a+=d.byteLength;let c=n.lastIndexOf("/");c>=0&&await ji(this.vault,n.slice(0,c));let l=this.vault.getAbstractFileByPath(n);if(l instanceof oe.TFolder)throw new b("mirror_path_collision",`A folder blocks the mirror file ${n}.`);l instanceof oe.TFile?await this.vault.modifyBinary(l,o.buffer):await this.vault.createBinary(n,o.buffer)}async listBinary(e){return this.vault.getFiles().map(t=>(0,oe.normalizePath)(t.path)).filter(t=>!t.toLowerCase().endsWith(".md")).filter(t=>!e.has(t)).filter(t=>!lp.some(n=>t.startsWith(n))).sort()}async readBinary(e){let t=Lr(e),n=this.vault.getAbstractFileByPath(t);if(n==null)return null;if(!(n instanceof oe.TFile))throw new b("mirror_path_collision",`Expected a file at ${t}.`);let i=new Uint8Array(await this.vault.readBinary(n));return(async function*(){yield i})()}},fp=class{constructor(e){this.key=e;this.database=null}async read(){let e=await this.open();return new Promise((t,n)=>{let i=e.transaction(Ni,"readonly").objectStore(Ni).get(this.key);i.onsuccess=()=>{var s;return t((s=i.result)!=null?s:null)},i.onerror=()=>n(i.error)})}async write(e){let t=await this.open();await new Promise((n,i)=>{let s=t.transaction(Ni,"readwrite");s.objectStore(Ni).put(e,this.key),s.oncomplete=()=>n(),s.onerror=()=>i(s.error),s.onabort=()=>i(s.error)})}open(){var e;if(typeof indexedDB=="undefined")throw new b("storage_unavailable","IndexedDB is required for persistent mirror state.");return(e=this.database)!=null||(this.database=new Promise((t,n)=>{let i=indexedDB.open(BC,1);i.onupgradeneeded=()=>{i.result.objectStoreNames.contains(Ni)||i.result.createObjectStore(Ni)},i.onerror=()=>n(i.error),i.onsuccess=()=>t(i.result)})),this.database}},Li=class Li{constructor(e){this.key=e}async runExclusive(e){if(Li.active.has(this.key))throw new b("mirror_busy","A mirror operation is already running for this vault.");Li.active.add(this.key);try{return await e()}finally{Li.active.delete(this.key)}}};Li.active=new Set;var pp=Li,qc=class{constructor(e,t,n={}){this.app=e;this.settingsHost=t;this.options=n;this.progress=null;this.syncAbort=null;this.adoptionMarker=null;var i,s,o;this.fileSystem=(i=n.fileSystem)!=null?i:new up(e.vault),this.enrollmentClient=(s=n.enrollmentClient)!=null?s:new gc({request:GC()}),this.adoptionClient=(o=n.adoptionClient)!=null?o:new $c({request:JC()})}async initialize(){if(this.adoptionMarker=await this.readAdoptionMarker(),this.adoptionMarker&&this.settingsHost.getMirrorProfile())throw new b("authority_adoption_state_conflict","This vault contains both an authority-adoption checkpoint and a mirror profile.")}getProgress(){return this.progress?{...this.progress}:null}cancelSync(){var e;(e=this.syncAbort)==null||e.abort()}getAdoptionMarker(){return this.adoptionMarker?JSON.parse(JSON.stringify(this.adoptionMarker)):null}assertLocalAuthorityWritable(){if(this.adoptionMarker&&["fenced","activating","adopted"].includes(this.adoptionMarker.phase))throw new b("local_authority_fenced",this.adoptionMarker.phase==="adopted"?"Hosted mdbase is now authoritative. Finish reconnecting this vault as its mirror before editing.":"This local authority is frozen while its exact snapshot is adopted by hosted mdbase.")}async adoptLocalCollection(e,t){if(this.settingsHost.getMirrorProfile())throw new b("mirror_already_configured","This vault already mirrors a collection authority.");if(this.adoptionMarker)return this.resumeAdoption(t);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);return await this.storeAdoptionSecret(i),await this.writeAdoptionMarker({version:1,phase:"waiting_for_approval",session:cp(i),manifest_digest:null,source_revision:null,source_head:null}),await t.onVerification(cp(i)),this.runAdoptionWithRecovery(i,t)}async resumeAdoption(e={}){var s,o,a;let t=(s=this.adoptionMarker)!=null?s:await this.readAdoptionMarker();if(!t)throw new b("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 b("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((o=e.onVerification)==null?void 0:o.call(e,cp(i))),this.runAdoptionWithRecovery(i,{...e,onVerification:(a=e.onVerification)!=null?a:(()=>{})})}async cancelAdoption(e){var i;let t=(i=this.adoptionMarker)!=null?i:await this.readAdoptionMarker();if(!t)return;if(["activating","adopted"].includes(t.phase))throw new b("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 b("authority_adoption_credentials_missing","The collection-adoption credential is missing from Obsidian's secret store.");await this.adoptionClient.cancel({...t.session,credential:n},{signal:e}),await this.clearAdoptionCheckpoint(t.session.adoptionId)}async enroll(e,t){let n=await this.assertCanBecomeMirror(e.collectionId),i=await this.enrollmentClient.enroll({...e,...n?{collectionId:n}:{}},t),s=await this.markMirror(i.collectionId);try{await this.persistEnrollment(i)}catch(o){if(s)try{await this.app.vault.adapter.remove(ao)}catch(a){throw new b("enrollment_recovery_required",`Enrollment settings could not be saved and the temporary role marker could not be removed: ${o instanceof Error?o.message:String(o)}`)}throw o}return this.requireProfile()}async preview(){let e=await this.createMirror();return A0(await e.inspect())}async status(){let e=this.settingsHost.getMirrorProfile();return e?(await this.assertMirror(e.collectionId),(await this.createMirror()).status()):null}async sync(e,t){if(this.syncAbort)throw new b("mirror_busy","Synchronization is already running for this vault.");let n=new AbortController;this.syncAbort=n;let i=await this.createMirror(s=>{this.progress=s,t==null||t({...s})});try{return await i.apply(e.plan,{signal:n.signal})}finally{this.progress=null,this.syncAbort=null}}async resolveConflict(e,t){let n=await this.createMirror();return await n.resolveConflict(e,t),n.status()}async runAdoption(e,t){let n=this.requireAdoptionMarker(e.adoptionId),i=null;if(n.phase==="adopted"){let s=await this.adoptionClient.exchange(e,t);if(s.status!=="completed")throw new b("authority_adoption_state_conflict","The local checkpoint says adoption completed, but Connect does not.");i=s}else if(n.phase==="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"&&await this.adoptionClient.uploadSnapshot(e,o,s,t),await this.updateAdoptionPhase("activating",s),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),o=await this.captureAuthoritySnapshot(e.requested.collectionId);await this.updateAdoptionPhase("uploading"),await this.adoptionClient.uploadSnapshot(e,s,o,t);let a=await this.captureAuthoritySnapshot(e.requested.collectionId);await this.writeAdoptionSnapshot(a),await this.updateAdoptionPhase("fenced",a);let c=await this.requirePreparedAdoption(e,t);await this.adoptionClient.uploadSnapshot(e,c,a,t),await this.updateAdoptionPhase("activating",a),i=await this.adoptionClient.complete(e,a,t)}return await this.updateAdoptionPhase("adopted"),this.finishRetainedMirror(e,i,t)}async runAdoptionWithRecovery(e,t){try{return await this.runAdoption(e,t)}catch(n){throw YC(n)?(await this.adoptionClient.cancel(e,{signal:t.signal}).catch(()=>{}),await this.clearAdoptionCheckpoint(e.adoptionId),new b(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 Ir("Hosted authority activation has already started. Resume using the saved fenced snapshot."):new b("authority_adoption_already_completed","Hosted authority has already adopted this collection.")}async finishRetainedMirror(e,t,n){var a,c;let i,s=this.adoptionClient.mirrorEnrollmentSession(e,t);if(!s)throw new b("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:l=>{var d;return(d=n.onStatus)==null?void 0:d.call(n,{...l,state:l.state})}})}catch(l){if((a=n.signal)!=null&&a.aborted)throw l;i=await this.enrollmentClient.enroll({controlUrl:e.controlUrl,collectionId:e.requested.collectionId,mirrorName:(c=e.requested.mirrorName)!=null?c:e.requested.sourceName,mode:"read_write"},{signal:n.signal,onVerification:n.onVerification})}let o=await this.markMirror(i.collectionId);try{await this.persistEnrollment(i)}catch(l){throw o&&await this.app.vault.adapter.remove(ao),l}return await this.clearAdoptionCheckpoint(e.adoptionId),this.requireProfile()}async captureAuthoritySnapshot(e){let t=await pi(this.app.vault);if(!t)throw new b("invalid_collection_configuration","A valid mdbase.yaml is required.");let n=await this.app.vault.adapter.read("mdbase.yaml"),i=(0,oe.parseYaml)(n),s=[{path:"mdbase.yaml",kind:"configuration",document:n}],o=`${(0,oe.normalizePath)(t.settings.types_folder)}/`,a=this.app.vault.getMarkdownFiles().filter(d=>(0,oe.normalizePath)(d.path).startsWith(o)).sort((d,u)=>d.path.localeCompare(u.path));for(let d of a)s.push({path:(0,oe.normalizePath)(d.path),kind:"type",document:await this.app.vault.cachedRead(d)});let c=XC(i);if(c.length){let d=c.map(f=>(0,k0.default)(f,{dot:!0})),u=QC(this.app.vault).filter(f=>f.extension==="base").filter(f=>d.some(p=>p((0,oe.normalizePath)(f.path)))).sort((f,p)=>f.path.localeCompare(p.path));for(let f of u)s.push({path:(0,oe.normalizePath)(f.path),kind:"view",document:await this.app.vault.cachedRead(f)})}let l=[];for(let d of this.app.vault.getMarkdownFiles().sort((u,f)=>u.path.localeCompare(f.path))){let u=(0,oe.normalizePath)(d.path);if(Ts(u,t))continue;let f=await this.app.vault.cachedRead(d);l.push({path:u,document:f})}return Hf({collectionId:e,sourceHead:0,specVersion:t.spec_version,resources:s,records:l})}async ensurePortableCollectionIdentity(){if(!await this.app.vault.adapter.exists("mdbase.yaml"))throw new b("collection_not_initialized","Initialize an mdbase collection before hosting it.");let e=await this.app.vault.adapter.read("mdbase.yaml"),t;try{t=(0,oe.parseYaml)(e)}catch(o){throw new b("invalid_collection_configuration","mdbase.yaml must contain valid YAML.")}if(!Fe(t))throw new b("invalid_collection_configuration","mdbase.yaml must contain a YAML mapping.");let n=Fe(t["x-mdbase-connect"])?t["x-mdbase-connect"].collection_id:void 0,i;if(n===void 0){i=crypto.randomUUID();let o=Fe(t["x-mdbase-connect"])?t["x-mdbase-connect"]:{};t["x-mdbase-connect"]={...o,collection_id:i},await this.app.vault.adapter.write("mdbase.yaml",(0,oe.stringifyYaml)(t))}else if(typeof n=="string"&&uo.test(n))i=n;else throw new b("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}}async createMirror(e){var o,a,c,l,d,u,f,p,y;let t=this.requireProfile();await this.assertMirror(t.collectionId);let n=await this.freshAccessToken(t),i=(c=(a=(o=this.options).transportFactory)==null?void 0:a.call(o,t,n))!=null?c:new dp(t.syncUrl,n),s={stateStore:(u=(d=(l=this.options).stateStoreFactory)==null?void 0:d.call(l,t))!=null?u:new fp(`${t.collectionId}:${t.replicaId}`),fileSystem:this.fileSystem,lease:(y=(p=(f=this.options).leaseFactory)==null?void 0:p.call(f,t))!=null?y:new pp(`${t.collectionId}:${t.replicaId}`),onProgress:e};return t.mode==="read_write"?new oo(t.replicaId,i,s):new Ln(t.replicaId,i,s)}requireProfile(){let e=this.settingsHost.getMirrorProfile();if(!e)throw new b("mirror_not_configured","This vault is not connected to a collection authority.");return e}accessSecretId(e){return`${zC}${e.toLowerCase()}`}refreshSecretId(e){return`${HC}${e.toLowerCase()}`}adoptionSecretId(e){return`${KC}${e.toLowerCase()}`}async storeAdoptionSecret(e){this.app.secretStorage.setSecret(this.adoptionSecretId(e.adoptionId),e.credential)}async persistEnrollment(e){this.app.secretStorage.setSecret(this.accessSecretId(e.collectionId),e.accessToken),this.app.secretStorage.setSecret(this.refreshSecretId(e.collectionId),e.refreshCredential),await this.settingsHost.saveMirrorProfile({version:1,syncUrl:e.syncUrl,controlUrl:e.controlUrl,collectionId:e.collectionId,replicaId:e.replicaId,mode:e.mode,name:e.name,enrollmentId:e.enrollmentId,accessTokenExpiresAt:e.accessTokenExpiresAt})}async freshAccessToken(e){let t=this.accessSecretId(e.collectionId),n=this.app.secretStorage.getSecret(t),i=Date.parse(e.accessTokenExpiresAt);if(n&&Number.isFinite(i)&&i-Date.now()>WC)return n;let s=this.app.secretStorage.getSecret(this.refreshSecretId(e.collectionId));if(!s)throw new b("mirror_credentials_missing","The mirror refresh credential is missing. Re-enroll this vault.");let o=await this.enrollmentClient.renew({controlUrl:e.controlUrl,syncUrl:e.syncUrl,collectionId:e.collectionId,replicaId:e.replicaId,mode:e.mode,name:e.name,enrollmentId:e.enrollmentId,accessToken:n!=null?n:"",refreshCredential:s,accessTokenExpiresAt:e.accessTokenExpiresAt});return await this.persistEnrollment(o),o.accessToken}async assertCanBecomeMirror(e){var o;let t=await this.readMarker(),n=await this.readPortableCollectionId();if(n&&!t)throw new b("local_authority_requires_transfer","This vault has a local Connect identity. Transfer authority explicitly before using it as a mirror.");if(n&&(t==null?void 0:t.collection_id)!==n)throw new b("mirror_identity_conflict","The vault identity and mirror role marker identify different collections.");let i=this.settingsHost.getMirrorProfile(),s=(o=i==null?void 0:i.collectionId)!=null?o:e;if(t&&s&&t.collection_id!==s)throw new b("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 b("existing_collection_requires_transfer","This vault already contains an mdbase collection. Connect an empty vault, or transfer collection authority explicitly.");return s!=null?s:t==null?void 0:t.collection_id}async readPortableCollectionId(){if(!await this.app.vault.adapter.exists("mdbase.yaml"))return null;let e;try{e=(0,oe.parseYaml)(await this.app.vault.adapter.read("mdbase.yaml"))}catch(i){throw new b("invalid_collection_configuration","mdbase.yaml must contain valid YAML.")}if(!Fe(e))throw new b("invalid_collection_configuration","mdbase.yaml must contain a YAML mapping.");let t=e["x-mdbase-connect"];if(t===void 0)return null;if(!Fe(t))throw new b("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"||!uo.test(n))throw new b("invalid_collection_configuration","x-mdbase-connect.collection_id must be a UUID string.");return n}async markMirror(e){let t=await this.readMarker();if(t){if(t.collection_id!==e)throw new b("mirror_identity_conflict","This vault already mirrors a different collection authority.");return!1}return await ji(this.app.vault,".mdbase"),await this.app.vault.adapter.write(ao,`${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 b("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(ao))return null;let e;try{e=JSON.parse(await this.app.vault.adapter.read(ao))}catch(t){throw new b("invalid_mirror_marker","The mirror role marker is corrupt.")}if(!Fe(e)||e.version!==1||e.role!=="mirror"||typeof e.collection_id!="string"||!uo.test(e.collection_id))throw new b("invalid_mirror_marker","The mirror role marker is invalid.");return e}requireAdoptionMarker(e){if(!this.adoptionMarker||this.adoptionMarker.session.adoptionId!==e)throw new b("authority_adoption_state_conflict","The collection-adoption checkpoint does not match this approval.");return this.adoptionMarker}async updateAdoptionPhase(e,t){if(!this.adoptionMarker)throw new b("authority_adoption_not_found","Collection-adoption checkpoint is missing.");await this.writeAdoptionMarker({...this.adoptionMarker,phase:e,...t?{manifest_digest:t.manifest_digest,source_revision:t.source_revision,source_head:t.source_head}:{}})}async writeAdoptionMarker(e){await ji(this.app.vault,".mdbase"),await this.app.vault.adapter.write(co,`${JSON.stringify(e,null,2)} +`),this.adoptionMarker=e}async readAdoptionMarker(){if(!await this.app.vault.adapter.exists(co))return null;let e;try{e=JSON.parse(await this.app.vault.adapter.read(co))}catch(t){throw new b("invalid_authority_adoption_checkpoint","The collection-adoption checkpoint is corrupt.")}if(!ZC(e))throw new b("invalid_authority_adoption_checkpoint","The collection-adoption checkpoint is invalid.");return e}async writeAdoptionSnapshot(e){await ji(this.app.vault,".mdbase"),await this.app.vault.adapter.write(lo,JSON.stringify(e))}async readAdoptionSnapshot(e){if(!await this.app.vault.adapter.exists(lo))throw new b("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(lo))}catch(n){throw new b("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 b("authority_adoption_snapshot_mismatch","The fenced authority snapshot does not match its durable checkpoint.");return t}async clearAdoptionCheckpoint(e){await this.app.vault.adapter.exists(co)&&await this.app.vault.adapter.remove(co),await this.app.vault.adapter.exists(lo)&&await this.app.vault.adapter.remove(lo),this.app.secretStorage.setSecret(this.adoptionSecretId(e),""),this.adoptionMarker=null}};function cp(r){let{credential:e,...t}=r;return t}function YC(r){return r instanceof J&&["authority_adoption_expired","authority_adoption_cancelled"].includes(r.code)}function XC(r){if(!Fe(r))return[];let e=r["x-obsidian"];return!Fe(e)||!Fe(e.bases)||!Array.isArray(e.bases.include)?[]:e.bases.include.filter(t=>typeof t=="string")}function QC(r){var i;let e=(i=r.getFiles)==null?void 0:i.call(r);if(e)return e;let t=[],n=s=>{for(let o of s.children)o instanceof oe.TFile?t.push(o):o instanceof oe.TFolder&&n(o)};return n(r.getRoot()),t}function ZC(r){if(!Fe(r)||r.version!==1||!["waiting_for_approval","uploading","fenced","activating","adopted"].includes(String(r.phase))||!Fe(r.session))return!1;let e=r.session;return typeof e.controlUrl=="string"&&typeof e.adoptionId=="string"&&uo.test(e.adoptionId)&&typeof e.verificationUri=="string"&&typeof e.expiresAt=="string"&&Fe(e.requested)&&typeof e.requested.collectionId=="string"&&uo.test(e.requested.collectionId)&&typeof e.requested.displayName=="string"&&typeof e.requested.sourceName=="string"&&e.requested.retainMirror===!0&&(r.manifest_digest===null||typeof r.manifest_digest=="string")&&(r.source_revision===null||typeof r.source_revision=="string")&&(r.source_head===null||Number.isSafeInteger(r.source_head))}var nt=require("obsidian");var mo="0.3.0",eM=new Set(["name","description","display_name_key","strict","path_pattern","filename_pattern","match","fields","extends"]),tM=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 ve(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function Ce(r){return r===void 0?r:JSON.parse(JSON.stringify(r))}function jr(r){return to.digest(r)}function jn(r){return Array.isArray(r)?`[${r.map(jn).join(",")}]`:ve(r)?`{${Object.keys(r).sort().map(e=>`${JSON.stringify(e)}:${jn(r[e])}`).join(",")}}`:JSON.stringify(r)}function hp(r){if(Array.isArray(r))return r.map(hp);if(!ve(r))return r;let e={};for(let[t,n]of Object.entries(r)){let i=hp(n);i!=null&&(Array.isArray(i)&&i.length===0||ve(i)&&Object.keys(i).length===0||(e[t]=i))}return e}function Di(r){return[...new Set(r)]}function rM(r){return ve(r.fields)?Object.values(r.fields).some(e=>ve(e)&&(typeof e.tn_role=="string"||Array.isArray(e.tn_completed_values))):!1}function mp(r,e,t){let n=ve(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)?Ce(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=mp(`${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[d,u]of Object.entries(ve(n.fields)?n.fields:{})){let f=mp(`${r}.${d}`,u,t);c[d]=f.schema,Object.assign(i,f.links),Object.assign(s,f.legacy),o.push(...f.unsupported),ve(u)&&u.required===!0&&l.push(d)}t&&r==="blockedBy[]"&&l.push("uid"),a={type:"object",additionalProperties:Object.keys(c).length===0,properties:c,...l.length?{required:Di(l)}:{}};break}default:a={},o.push(`${r}.type`);break}t&&r==="title"&&(a.minLength=1,a.description="Short summary of the task."),typeof n.description=="string"&&(a.description=n.description),typeof n.min=="number"&&(n.type==="string"?a.minLength=n.min:n.type==="list"?a.minItems=n.min:a.minimum=n.min),typeof n.max=="number"&&(n.type==="string"?a.maxLength=n.max:n.type==="list"?a.maxItems=n.max:a.maximum=n.max),typeof n.min_length=="number"&&(a.minLength=n.min_length),typeof n.max_length=="number"&&(a.maxLength=n.max_length),typeof n.pattern=="string"&&(a.pattern=n.pattern),n.deprecated===!0&&(a.deprecated=!0),n.default!==void 0&&(a.default=Ce(n.default)),n.computed!==void 0&&o.push(`${r}.computed`);for(let[c,l]of Object.entries(n)){let d=t&&(c==="tn_role"||c==="tn_completed_values");(!tM.has(c)||(c==="tn_role"||c==="tn_completed_values")&&!d)&&(s[`${r}.${c}`]=Ce(l))}return{schema:a,links:i,legacy:s,unsupported:o}}function fo(r,e,t,n){let i=ve(r[e])?r[e]:{},s=ve(i.set)?i.set:{};s[t]=n,i.set=s,r[e]=i}function nM(r,e,t){if(t==="now")fo(r,"on_create",e,{now:!0});else if(t==="now_on_write")fo(r,"on_update",e,{now:!0});else if(t==="uuid")fo(r,"on_create",e,{uuid:!0});else if(t==="ulid")fo(r,"on_create",e,{ulid:!0});else if(ve(t)&&t.transform==="slugify"&&typeof t.from=="string")fo(r,"on_create",e,{slugify:t.from});else return!1;return!0}function iM(r){var t;let e=r.match(/^(.*\/)?\{title\}\.md$/);return e?{runtime:"tasknotes",template:"{{title}}",folder:((t=e[1])!=null?t:"").replace(/\/$/,""),generated_by:"tasknotes.filename.create"}:{runtime:"tasknotes",template:r,generated_by:"tasknotes.filename.create"}}function sM(r,e,t){var P;if(t.kind==="mdbase.type"||t.schema!==void 0)throw new Error(`${r} already looks like a v0.3 type.`);if(typeof t.name!="string"||!ve(t.fields))throw new Error(`${r} is not a v0.2 type with a name and fields.`);let n=rM(t),i=t.name.trim().toLowerCase(),s={type:{const:i}},o=[],a={},c={},l=[],d={},u={},f=[],p=[],y={},h={},m={};for(let[O,$]of Object.entries(t.fields)){let R=ve($)?$:{},S=mp(O,R,n);s[O]=S.schema,Object.assign(c,S.links),Object.assign(u,S.legacy),f.push(...S.unsupported),R.required===!0&&o.push(O),R.default!==void 0&&(a[O]=Ce(R.default)),R.unique===!0&&l.push({field:O,scope:"collection"}),R.generated!==void 0&&nM(d,O,R.generated)&&p.push(O),typeof R.tn_role=="string"&&(y[R.tn_role]=O),Array.isArray(R.tn_completed_values)&&(h.completed_values=Ce(R.tn_completed_values))}a.status!==void 0&&(h.default=Ce(a.status)),a.priority!==void 0&&(m.default=Ce(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,_={...g?{display:{name_field:g}}:{},read_defaults:a,links:c,unique:l};typeof t.path_pattern=="string"&&(_.path=n?iM(t.path_pattern):{pattern:t.path_pattern});let w={};for(let[O,$]of Object.entries(t))eM.has(O)||(w[O]=Ce($));Object.keys(u).length&&(w.fields=u);let x=hp({kind:"mdbase.type",name:i,version:1,description:typeof t.description=="string"?t.description:void 0,match:ve(t.match)?Ce(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:Di(o)}:{}}},collection:_,lifecycle:d,...n?{"x-tasknotes":{contract:"tasknotes.task",version:1,field_roles:y,status:h,priority:m,archive:{tags_field:(P=y.tags)!=null?P:"tags",archived_tag:"archived"}}}:{},...Object.keys(w).length?{"x-legacy-v0.2":w}:{}}),v=[];t.extends!==void 0&&f.push("extends");for(let O of Di(f).sort())v.push({path:r,code:"migration_lossy",message:`${O} cannot be expressed as canonical v0.3 write behavior and was retained as legacy metadata where possible.`,severity:"lossy"});return n&&v.push({path:r,code:"path_policy_runtime_owned",message:"TaskNotes filename behavior is recorded as TaskNotes runtime metadata.",severity:"warning"}),t.strict!==!0&&v.push({path:r,code:"additional_properties_true",message:"The migrated schema allows additional properties because the source type was not strict.",severity:"warning"}),typeof t.display_name_key=="string"&&!g&&v.push({path:r,code:"display_field_missing",message:`The display field '${t.display_name_key}' is not declared, so collection.display was omitted.`,severity:"warning"}),{target:x,summary:{path:r,name:i,fieldsConverted:Object.keys(t.fields).length,requiredFields:Di(o),defaultsMoved:Object.keys(a),generatedFieldsMoved:Di(p),linksMoved:Object.keys(c),taskNotes:n},diagnostics:v}}function oM(r){let e=Ce(r);e.spec_version=mo;let t=ve(e.settings)?e.settings:{};if(e.settings=t,!Array.isArray(t.record_extensions)){let n=Array.isArray(t.extensions)?t.extensions.map(String).map(i=>i.replace(/^\./,"")):[];t.record_extensions=Di(["md",...n])}return Array.isArray(t.explicit_type_keys)||(t.explicit_type_keys=["type","types"]),typeof t.include_subfolders!="boolean"&&(t.include_subfolders=!0),t.validation===void 0&&typeof t.default_validation=="string"&&(t.validation=t.default_validation),t.validation===void 0&&typeof e.default_validation=="string"&&(t.validation=e.default_validation),delete t.default_validation,delete t.extensions,delete e.default_validation,e}function P0(r,e){let t=ve(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 aM(r,e){var n,i;let t={};for(let[s,o]of Object.entries(ve(e.fields)?e.fields:{}))ve(o)&&(t[s]=Ce(o));return{name:typeof e.name=="string"?e.name:(i=(n=r.split("/").pop())==null?void 0:n.replace(/\.md$/,""))!=null?i:"type",fields:t,match:ve(e.match)?Ce(e.match):void 0,filePath:r,specProfile:"v0.2"}}function cM(r,e){var i,s;let t=ve(e.schema)?e.schema:{},n=ve(t.value)?t.value:{};return{name:typeof e.name=="string"?e.name:(s=(i=r.split("/").pop())==null?void 0:i.replace(/\.md$/,""))!=null?s:"type",fields:An(n),match:ve(e.match)?Ce(e.match):void 0,collection:ve(e.collection)?Ce(e.collection):void 0,schema:Ce(n),filePath:r,specProfile:"v0.3"}}function lM(r,e,t){let n=Ce(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]=Ce(a.default))}return n}function dM(r,e,t){var i,s;let n=Ce(r);for(let o of e){let a=t.get(o);if(a)for(let[c,l]of Object.entries((s=(i=a.collection)==null?void 0:i.read_defaults)!=null?s:{}))c in n||(n[c]=Ce(l))}return n}async function uM(r,e){let t=(0,nt.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 nt.TFolder)){if(s)throw new Error(`A file blocks folder ${n}.`);await r.adapter.exists(n)||await r.createFolder(n)}}}async function Fc(r,e,t){let n=(0,nt.normalizePath)(e),i=n.lastIndexOf("/");if(i>=0&&await uM(r,n.slice(0,i)),n.startsWith(".mdbase/")){await r.adapter.write(n,t);return}let s=r.getAbstractFileByPath(n);if(s instanceof nt.TFolder)throw new Error(`A folder blocks file ${n}.`);s instanceof nt.TFile?await r.modify(s,t):await r.create(n,t)}async function ho(r,e){let t=(0,nt.normalizePath)(e),n=r.getAbstractFileByPath(t);if(n instanceof nt.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 I0(r){var x;let e=await ho(r,"mdbase.yaml"),t=(0,nt.parseYaml)(e);if(!ve(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===mo?"This collection is already mdbase v0.3.":`Expected an mdbase v0.2.x collection, found ${JSON.stringify(n)}.`);let i=ve(t.settings)?t.settings:{},s=typeof i.types_folder=="string"?(0,nt.normalizePath)(i.types_folder):"_types",o=`${s}/`,a=[],c=[],l=[],d=oM(t),u=`${(0,nt.stringifyYaml)(d).trimEnd()} +`;a.push({path:"mdbase.yaml",sourceDigest:jr(e),targetDigest:jr(u),source:e,target:u});let f=new Map,p=new Map;for(let v of r.getMarkdownFiles().filter(P=>P.path.startsWith(o)).sort((P,O)=>P.path.localeCompare(O.path))){let P=await r.cachedRead(v),O=Pt(P);if(!O.hasFrontmatter||O.error)throw new Error(`Cannot migrate ${v.path}: ${(x=O.error)!=null?x:"frontmatter is missing"}.`);let $=sM(v.path,n,O.frontmatter),R=aM(v.path,O.frontmatter),S=cM(v.path,$.target);f.set(R.name,R),p.set(S.name,S);let U=`${mt($.target,O.body)} +`;a.push({path:v.path,sourceDigest:jr(P),targetDigest:jr(U),source:P,target:U}),c.push($.summary),l.push(...$.diagnostics)}if(!c.length)throw new Error(`No v0.2 type files were found in ${s}.`);let y=0,h=0,m=P0(t,n),g=P0(d,mo),_=r.getMarkdownFiles().filter(v=>!v.path.startsWith(o)).filter(v=>!v.path.startsWith(".mdbase/")).sort((v,P)=>v.path.localeCompare(P.path));for(let[v,P]of _.entries()){let O=Pt(await r.cachedRead(P));if(O.error){h+=1;continue}let $=hi(P.path,O.frontmatter,m,f),R=hi(P.path,O.frontmatter,g,p),S=lM(O.frontmatter,$,f),U=dM(O.frontmatter,R,p);(jn($.slice().sort())!==jn(R.slice().sort())||jn(S)!==jn(U))&&l.push({path:P.path,code:"effective_read_changed",message:"The proposed v0.3 types would change this record's resolved types or effective default values.",severity:"lossy"}),y+=1,v>0&&v%250===0&&await new Promise(B=>setTimeout(B,0))}let w=jr(jn({sourceVersion:n,operations:a.map(({path:v,sourceDigest:P,targetDigest:O})=>({path:v,sourceDigest:P,targetDigest:O})),diagnostics:l}));return{planVersion:1,analysisId:w,sourceVersion:n,targetVersion:mo,createdAt:new Date().toISOString(),backupLocation:`.mdbase/migrations/v02-to-v03-${w.slice(0,12)}`,operations:a,typeSummaries:c,diagnostics:l,applicable:!l.some(v=>v.severity==="lossy"),recordFilesRewritten:0,recordsVerified:y,recordsSkipped:h}}async function po(r,e,t){await Fc(r,e,`${JSON.stringify(t,null,2)} +`)}async function O0(r,e,t={}){if(e.planVersion!==1||e.targetVersion!==mo)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 ho(r,s.path);if(jr(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 Fc(r,`${e.backupLocation}/files/${s.path}`,s.source);await po(r,n,i),i.status="applying",await po(r,n,i);try{for(let s of e.operations){let o=await ho(r,s.path);if(jr(o)!==s.sourceDigest)throw new Error(`${s.path} changed during migration.`);i.written.push(s.path),await po(r,n,i),await Fc(r,s.path,s.target);let a=await ho(r,s.path);if(jr(a)!==s.targetDigest)throw new Error(`${s.path} did not verify after write.`)}return i.status="applied",i.completed_at=new Date().toISOString(),await po(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 Fc(r,a,c.source),jr(await ho(r,a))!==c.sourceDigest&&o.push(a)}catch(l){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 po(r,n,i)}catch(a){}return{applied:!1,restored:o.length===0,manifestPath:n,written:[...i.written],error:i.error}}}var Vc=require("obsidian");function Pe(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function mr(r){return JSON.parse(JSON.stringify(r))}var fM=new Set(["file","formula","this"]);function pM(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(fM.has(e.toLowerCase()))throw new Error(`Type name '${e}' is reserved.`);return e}function yp(){return{specProfile:"v0.3",originalFrontmatter:{},name:"",description:"",extendsType:"",displayNameKey:"",strictMode:!1,pathPattern:"",filenamePattern:"",matchPathGlob:"",matchFieldsPresent:"",matchWhere:"",fields:[{name:"title",definition:{type:"string",required:!0}}],body:`# Type -Describe the type and intended usage.`,extraFrontmatter:{}}}function vC(r){return Ie(r)?Object.entries(r).filter(e=>Ie(e[1])).map(([e,t])=>({name:e,definition:mr(t)})):[]}function $C(r){return Object.fromEntries(r.map(e=>[e.name,e.definition]))}function SC(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 Vc(r,e,t){let n=r.kind==="mdbase.type",i=n&&Ie(r.schema)?r.schema:{},s=Ie(i.value)?i.value:{},o=typeof i.ref=="string"?i.ref:"",a=n&&Ie(r.collection)?r.collection:{},c=Ie(a.display)?a.display:{},l=Ie(a.path)?a.path:{},d=vC(n?Sn(s):r.fields);n&&EC(d,a.links);let u=Ie(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"]),y={};for(let[m,g]of Object.entries(r))p.has(m)||(y[m]=mr(g));let h="";if(u.where!==void 0)try{h=(0,Uc.stringifyYaml)(u.where).trim()}catch(m){h=""}return{specProfile:n?"v0.3":"v0.2",originalFrontmatter:mr(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 u.path_glob=="string"?u.path_glob:"",matchFieldsPresent:Array.isArray(u.fields_present)?u.fields_present.map(String).join(", "):"",matchWhere:h,fields:d.length||o?d:yp().fields,body:e.trim()||`# ${t} +Describe the type and intended usage.`,extraFrontmatter:{}}}function hM(r){return Pe(r)?Object.entries(r).filter(e=>Pe(e[1])).map(([e,t])=>({name:e,definition:mr(t)})):[]}function mM(r){return Object.fromEntries(r.map(e=>[e.name,e.definition]))}function yM(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 Uc(r,e,t){let n=r.kind==="mdbase.type",i=n&&Pe(r.schema)?r.schema:{},s=Pe(i.value)?i.value:{},o=typeof i.ref=="string"?i.ref:"",a=n&&Pe(r.collection)?r.collection:{},c=Pe(a.display)?a.display:{},l=Pe(a.path)?a.path:{},d=hM(n?An(s):r.fields);n&&gM(d,a.links);let u=Pe(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"]),y={};for(let[m,g]of Object.entries(r))p.has(m)||(y[m]=mr(g));let h="";if(u.where!==void 0)try{h=(0,Vc.stringifyYaml)(u.where).trim()}catch(m){h=""}return{specProfile:n?"v0.3":"v0.2",originalFrontmatter:mr(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 u.path_glob=="string"?u.path_glob:"",matchFieldsPresent:Array.isArray(u.fields_present)?u.fields_present.map(String).join(", "):"",matchWhere:h,fields:d.length||o?d:yp().fields,body:e.trim()||`# ${t} -Type definition for ${t}.`,extraFrontmatter:y,...o?{readOnlyReason:`This type uses schema.ref (${o}). Edit the referenced JSON Schema file directly.`}:{}}}function mo(r){if(r.specProfile!=="v0.3")throw new Error("mdbase v0.2 type definitions are read-only. Migrate the collection before editing.");if(r.readOnlyReason)throw new Error(r.readOnlyReason);let e=r.originalFrontmatter?mr(r.originalFrontmatter):{},t=Ie(e.schema)?e.schema:{},n=Ie(t.value)?t.value:{},i=Object.create(null);for(let h of r.fields){let m=h.name.trim();if(!m)throw new Error("Every field needs a name.");if(Object.prototype.hasOwnProperty.call(i,m))throw new Error(`Duplicate field name: ${m}`);i[m]=mr(h.definition)}let s=wC(r.name),o={...e,kind:"mdbase.type",name:s,version:typeof e.version=="number"?e.version:1,schema:{...t,dialect:"json-schema-2020-12",value:Qu(i,n,r.strictMode===!0)}};delete o.schema.ref,r.description.trim()?o.description=r.description.trim():delete o.description;let a=Ie(o.match)?mr(o.match):{};r.matchPathGlob.trim()?a.path_glob=r.matchPathGlob.trim():delete a.path_glob;let c=r.matchFieldsPresent.split(",").map(h=>h.trim()).filter(Boolean);if(c.length?a.fields_present=c:delete a.fields_present,r.matchWhere.trim()){let h=(0,Uc.parseYaml)(r.matchWhere);if(!Ie(h))throw new Error("Match where must be a YAML mapping.");a.where=h}else delete a.where;Object.keys(a).length?o.match=a:delete o.match;let l=Ie(o.collection)?mr(o.collection):{},d=Ie(l.display)?mr(l.display):{};if(r.displayNameKey.trim()?d.name_field=r.displayNameKey.trim():delete d.name_field,Object.keys(d).length?l.display=d:delete l.display,r.pathPattern.trim()){let h=Ie(l.path)?l.path:{};l.path={...h,pattern:r.pathPattern.trim()}}else if(Ie(l.path)&&typeof l.path.pattern=="string"){let h={...l.path};delete h.pattern,Object.keys(h).length?l.path=h:delete l.path}let u=Ie(l.links)?mr(l.links):{},f=mr(u),p=L0(i),y=L0(Sn(n));for(let h of new Set([...y.selectors,...p.selectors]))delete f[h];for(let[h,m]of p.links)f[h]={...Ie(u[h])?u[h]:{},target_type:m.target_type,validate_exists:m.validate_exists};Object.keys(f).length?l.links=f:delete l.links,Object.keys(l).length?o.collection=l:delete o.collection;for(let h of["fields","strict","extends","display_name_key","path_pattern","filename_pattern"])delete o[h];return o}var Ae=require("obsidian");var Di="mdbase-frontmatter",j0=` +Type definition for ${t}.`,extraFrontmatter:y,...o?{readOnlyReason:`This type uses schema.ref (${o}). Edit the referenced JSON Schema file directly.`}:{}}}function yo(r){if(r.specProfile!=="v0.3")throw new Error("mdbase v0.2 type definitions are read-only. Migrate the collection before editing.");if(r.readOnlyReason)throw new Error(r.readOnlyReason);let e=r.originalFrontmatter?mr(r.originalFrontmatter):{},t=Pe(e.schema)?e.schema:{},n=Pe(t.value)?t.value:{},i=Object.create(null);for(let h of r.fields){let m=h.name.trim();if(!m)throw new Error("Every field needs a name.");if(Object.prototype.hasOwnProperty.call(i,m))throw new Error(`Duplicate field name: ${m}`);i[m]=mr(h.definition)}let s=pM(r.name),o={...e,kind:"mdbase.type",name:s,version:typeof e.version=="number"?e.version:1,schema:{...t,dialect:"json-schema-2020-12",value:Qu(i,n,r.strictMode===!0)}};delete o.schema.ref,r.description.trim()?o.description=r.description.trim():delete o.description;let a=Pe(o.match)?mr(o.match):{};r.matchPathGlob.trim()?a.path_glob=r.matchPathGlob.trim():delete a.path_glob;let c=r.matchFieldsPresent.split(",").map(h=>h.trim()).filter(Boolean);if(c.length?a.fields_present=c:delete a.fields_present,r.matchWhere.trim()){let h=(0,Vc.parseYaml)(r.matchWhere);if(!Pe(h))throw new Error("Match where must be a YAML mapping.");a.where=h}else delete a.where;Object.keys(a).length?o.match=a:delete o.match;let l=Pe(o.collection)?mr(o.collection):{},d=Pe(l.display)?mr(l.display):{};if(r.displayNameKey.trim()?d.name_field=r.displayNameKey.trim():delete d.name_field,Object.keys(d).length?l.display=d:delete l.display,r.pathPattern.trim()){let h=Pe(l.path)?l.path:{};l.path={...h,pattern:r.pathPattern.trim()}}else if(Pe(l.path)&&typeof l.path.pattern=="string"){let h={...l.path};delete h.pattern,Object.keys(h).length?l.path=h:delete l.path}let u=Pe(l.links)?mr(l.links):{},f=mr(u),p=R0(i),y=R0(An(n));for(let h of new Set([...y.selectors,...p.selectors]))delete f[h];for(let[h,m]of p.links)f[h]={...Pe(u[h])?u[h]:{},target_type:m.target_type,validate_exists:m.validate_exists};Object.keys(f).length?l.links=f:delete l.links,Object.keys(l).length?o.collection=l:delete o.collection;for(let h of["fields","strict","extends","display_name_key","path_pattern","filename_pattern"])delete o[h];return o}var Ee=require("obsidian");var qi="mdbase-frontmatter",T0=` @@ -185,13 +185,13 @@ Type definition for ${t}.`,extraFrontmatter:y,...o?{readOnlyReason:`This type us -`;var jn="mdbase-workspace-view",AC=["string","integer","number","boolean","date","datetime","time","enum","link","list","object","any"];function Ln(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function gp(r){return JSON.parse(JSON.stringify(r))}function D0(r){return typeof r.type=="string"?r.type:"any"}function xC(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 q0(r,e,t){Object.defineProperty(r,e,{configurable:!0,enumerable:!0,writable:!0,value:t})}function kC(r,e){if(!r)return["A new type definition will be created."];let t=[];r.name!==e.name&&t.push(`Rename type from ${r.name} to ${e.name}.`),(r.matchPathGlob!==e.matchPathGlob||r.matchFieldsPresent!==e.matchFieldsPresent||r.matchWhere!==e.matchWhere)&&t.push("Membership rules changed; different records may match this type.");let n=new Map(r.fields.map(c=>[c.name,c])),i=new Map(e.fields.map(c=>[c.name,c])),s=[...n.keys()].filter(c=>!i.has(c)),o=[...i.keys()].filter(c=>!n.has(c));o.length&&t.push(`Add ${o.length} field${o.length===1?"":"s"}: ${o.join(", ")}.`),s.length&&t.push(`Remove ${s.length} field${s.length===1?"":"s"}: ${s.join(", ")}.`);let a=[...i.entries()].filter(([c,l])=>{var d;return l.definition.required===!0&&((d=n.get(c))==null?void 0:d.definition.required)!==!0}).map(([c])=>c);return a.length&&t.push(`New required fields may invalidate records: ${a.join(", ")}.`),t.length||t.push("Metadata, schema details, or documentation changed."),t}function Rt(r,e,t,n,i={}){var l;let s=r.createDiv({cls:"mdbase-form-row"}),o=s.createEl("label",{text:e}),a=`mdbase-${Math.random().toString(36).slice(2)}`;o.htmlFor=a,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.value=t,c.placeholder=(l=i.placeholder)!=null?l:"",c.addEventListener("input",()=>n(c.value)),c}function Ne(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 PC(r){if(r<1e3)return String(r);let e=r<1e4?1:0;return`${(r/1e3).toFixed(e)}k`}var Bc=class extends Ae.ItemView{constructor(t,n){super(t);this.host=n;this.destination="types";this.editorMode="design";this.schema=null;this.query="";this.selectedPath=null;this.model=null;this.originalModel=null;this.yamlDraft="";this.dirty=!1;this.busy=!1;this.migrationPlan=null;this.allowLossy=!1;this.mirrorStatus=null;this.mirrorPreview=null;this.mirrorProgress=null;this.transientMessage="";this.issueQuery="";this.issueSeverity="all";this.issueLimit=250;this.enrollmentVerification="";this.enrollmentAbort=null}getViewType(){return jn}getDisplayText(){return"mdbase"}getIcon(){return Di}async onOpen(){this.containerEl.addClass("mdbase-workspace"),await this.refresh(!0)}async onClose(){var t;(t=this.enrollmentAbort)==null||t.abort(),this.enrollmentAbort=null}async refresh(t=!1){try{this.schema=await this.host.loadWorkspaceSchema(t),this.selectedPath&&!this.typeEntries().some(n=>n.filePath===this.selectedPath)&&(this.selectedPath=null,this.model=null,this.originalModel=null),!this.selectedPath&&this.typeEntries().length&&!Ae.Platform.isMobile&&(this.selectedPath=this.typeEntries()[0].filePath),this.selectedPath&&(!this.model||t)&&await this.selectType(this.selectedPath,!1),this.destination==="sync"&&await this.refreshMirrorStatus(),this.render()}catch(n){this.transientMessage=n instanceof Error?n.message:String(n),this.render()}}showDestination(t){this.destination=t,t==="sync"?this.refreshMirrorStatus().then(()=>this.render()):this.render()}typeEntries(){return this.schema?[...this.schema.types.values()].sort((t,n)=>t.name.localeCompare(n.name)):[]}render(){let t=this.containerEl;t.empty(),t.addClass("mdbase-workspace");let n=t.createDiv({cls:"mdbase-shell"});this.renderTopbar(n),this.transientMessage&&n.createDiv({cls:"mdbase-inline-message",text:this.transientMessage}).setAttr("role","status");let i=n.createDiv({cls:"mdbase-workspace-content"});this.destination==="types"?this.renderTypes(i):this.destination==="sync"?this.renderSync(i):this.renderIssues(i)}renderTopbar(t){let n=t.createDiv({cls:"mdbase-topbar"}),i=n.createDiv({cls:"mdbase-identity"}),s=i.createSpan({cls:"mdbase-mark"});s.setAttr("aria-hidden","true"),(0,Ae.setIcon)(s,Di),i.createSpan({cls:"mdbase-title",text:"mdbase"});let o=n.createDiv({cls:"mdbase-nav"});o.setAttr("role","tablist");for(let[a,c]of[["types","Types"],["sync","Sync"],["issues","Issues"]]){let l=o.createEl("button",{text:c});if(l.addClass("mdbase-nav-button"),l.setAttr("role","tab"),l.setAttr("aria-selected",String(this.destination===a)),this.destination===a&&l.addClass("is-active"),a==="issues"&&this.host.getIssues().length){let d=this.host.getIssues().length;l.createSpan({cls:"mdbase-count",text:PC(d)}).setAttr("title",`${d} issues`)}l.onclick=()=>this.showDestination(a)}}renderTypes(t){if(!this.schema){let i=t.createDiv({cls:"mdbase-empty-state"});i.createEl("h2",{text:"Start an mdbase collection"}),i.createEl("p",{text:"Initialize this vault as a local v0.3 collection, or use Sync to connect an empty vault to a collection authority."});let s=i.createDiv({cls:"mdbase-actions"}),o=s.createEl("button",{text:"Initialize local collection"});o.addClass("mod-cta"),o.disabled=this.busy||this.host.getMirrorProfile()!==null,o.onclick=()=>void this.perform(async()=>{await this.host.initializeCollection(),await this.refresh(!0)});let a=s.createEl("button",{text:"Connect collection authority"});a.onclick=()=>this.showDestination("sync");return}this.schema.config.spec_version.startsWith("0.2.")&&this.renderLegacyBanner(t);let n=t.createDiv({cls:"mdbase-types-layout"});this.model&&n.addClass("has-selection"),this.renderTypeList(n),this.renderTypeEditor(n)}renderLegacyBanner(t){var o;let n=t.createDiv({cls:"mdbase-legacy-banner"}),i=n.createDiv();i.createEl("strong",{text:`mdbase ${(o=this.schema)==null?void 0:o.config.spec_version} compatibility mode`}),i.createEl("p",{text:"Types are readable and validation remains available, but authoring is disabled until a reviewed v0.3 migration."});let s=n.createEl("button",{text:this.migrationPlan?"Review migration":"Analyze migration"});s.disabled=this.busy||this.host.getMirrorProfile()!==null,s.onclick=()=>void this.perform(async()=>{this.migrationPlan=await this.host.analyzeMigration(),this.render()}),this.host.getMirrorProfile()&&n.createDiv({cls:"mdbase-form-description",text:"Hosted resources must be migrated at the collection authority."}),this.migrationPlan&&this.renderMigrationReview(t,this.migrationPlan)}renderMigrationReview(t,n){let i=t.createDiv({cls:"mdbase-migration-review"}),s=i.createDiv({cls:"mdbase-section-header"});s.createEl("h3",{text:"Migration review"}),s.createSpan({cls:"mdbase-spec-badge",text:`${n.sourceVersion} \u2192 ${n.targetVersion}`});let o=i.createDiv({cls:"mdbase-status-list"});Ne(o,"Files replaced",String(n.operations.length)),Ne(o,"Type definitions",String(n.typeSummaries.length)),Ne(o,"Record reads verified",String(n.recordsVerified)),n.recordsSkipped&&Ne(o,"Records skipped",String(n.recordsSkipped)),Ne(o,"Record files rewritten","0"),Ne(o,"Recovery backup",n.backupLocation);let a=i.createDiv({cls:"mdbase-review-list"});n.diagnostics.length||a.createDiv({cls:"mdbase-review-ok",text:"No migration diagnostics."});for(let u of n.diagnostics.slice(0,250)){let f=a.createDiv({cls:"mdbase-review-item"});f.setAttr("data-severity",u.severity),f.createDiv({cls:"mdbase-review-code",text:`${u.severity} \xB7 ${u.path}`}),f.createDiv({text:u.message})}if(n.diagnostics.length>250&&a.createDiv({cls:"mdbase-form-description",text:`Showing 250 of ${n.diagnostics.length} diagnostics.`}),!n.applicable){let u=i.createEl("label",{cls:"mdbase-consent"}),f=u.createEl("input",{type:"checkbox"});f.checked=this.allowLossy,f.onchange=()=>{this.allowLossy=f.checked,this.render()},u.createSpan({text:"I reviewed the lossy diagnostics and want to apply this migration."})}let c=i.createDiv({cls:"mdbase-actions"}),l=c.createEl("button",{text:"Apply migration"});l.addClass("mod-warning"),l.disabled=this.busy||!n.applicable&&!this.allowLossy,l.onclick=()=>void this.perform(async()=>{await this.host.applyMigration(n,this.allowLossy),this.migrationPlan=null,this.allowLossy=!1,this.model=null,this.originalModel=null,await this.refresh(!0)});let d=c.createEl("button",{text:"Close review"});d.onclick=()=>{this.migrationPlan=null,this.render()}}renderTypeList(t){var d,u,f,p;let n=t.createDiv({cls:"mdbase-type-list-pane"}),i=n.createDiv({cls:"mdbase-pane-header"});i.createEl("h2",{text:"Types"});let s=i.createEl("button");s.setAttr("aria-label","Create type"),(0,Ae.setIcon)(s,"plus"),s.disabled=((u=(d=this.schema)==null?void 0:d.config.spec_version.startsWith("0.2."))!=null?u:!0)||((f=this.host.getMirrorProfile())==null?void 0:f.mode)==="read_only",s.onclick=()=>this.createType();let o=n.createEl("input",{type:"search"});o.addClass("mdbase-type-search"),o.placeholder="Search types",o.setAttr("aria-label","Search types"),o.value=this.query,o.oninput=()=>{this.query=o.value,this.render();let y=this.containerEl.querySelector(".mdbase-type-search");y==null||y.focus(),y==null||y.setSelectionRange(y.value.length,y.value.length)};let a=n.createDiv({cls:"mdbase-type-list"}),c=this.query.trim().toLowerCase(),l=this.typeEntries().filter(y=>{var h;return`${y.name} ${(h=y.description)!=null?h:""} ${y.filePath}`.toLowerCase().includes(c)});if(!l.length){a.createDiv({cls:"mdbase-empty-list",text:c?"No matching types.":"No type definitions."});return}for(let y of l){let h=a.createEl("button",{cls:"mdbase-type-row"});y.filePath===this.selectedPath&&h.addClass("is-active"),h.setAttr("aria-current",y.filePath===this.selectedPath?"true":"false"),h.createSpan({cls:"mdbase-type-name",text:y.name}),h.createSpan({cls:"mdbase-type-meta",text:`${Object.keys(y.fields).length} fields \xB7 ${(p=y.specProfile)!=null?p:"v0.2"}`}),h.onclick=()=>void this.selectType(y.filePath)}}renderTypeEditor(t){var h,m,g,_;let n=t.createDiv({cls:"mdbase-type-editor-pane"});if(!this.model){let w=n.createDiv({cls:"mdbase-empty-state"});w.createEl("h2",{text:"Choose a type"}),w.createEl("p",{text:"Select a type definition from the list to inspect or edit it."});return}let i=((h=this.host.getMirrorProfile())==null?void 0:h.mode)==="read_only",s=this.model.specProfile==="v0.2"||i||!!this.model.readOnlyReason,o=(m=this.model.readOnlyReason)!=null?m:i?"This mirror has read-only access. Re-enroll it with write access before editing types.":"This v0.2 type is read-only. Review and apply a collection migration before editing.",a=n.createDiv({cls:"mdbase-editor-header"}),c=a.createEl("button",{cls:"mdbase-mobile-back"});c.setAttr("aria-label","Back to type list"),(0,Ae.setIcon)(c,"arrow-left"),c.onclick=()=>{if(this.dirty){new Ae.Notice("Save or discard the current type changes before going back.");return}this.selectedPath=null,this.model=null,this.originalModel=null,this.render()};let l=a.createDiv(),d=l.createDiv({cls:"mdbase-editor-title-line"});d.createEl("h2",{text:this.model.name||"Untitled type"}),d.createSpan({cls:"mdbase-spec-badge",text:(g=this.model.specProfile)!=null?g:"v0.2"}),this.dirty&&d.createSpan({cls:"mdbase-dirty",text:"Unsaved"}),l.createDiv({cls:"mdbase-editor-path",text:(_=this.selectedPath)!=null?_:"New type"});let u=a.createDiv({cls:"mdbase-editor-actions"});if(this.selectedPath){let w=u.createEl("button",{text:"Open source"});w.onclick=()=>void this.host.openFileByPath(this.selectedPath)}let f=u.createEl("button",{text:"Save"});f.addClass("mod-cta"),f.disabled=s||!this.dirty||this.busy,f.onclick=()=>void this.saveCurrentType(),s&&n.createDiv({cls:"mdbase-readonly-note",text:o});let p=n.createDiv({cls:"mdbase-mode-switch"});p.setAttr("role","tablist");for(let[w,k]of[["design","Design"],["yaml","YAML"]]){let v=p.createEl("button",{text:k});v.setAttr("role","tab"),v.setAttr("aria-selected",String(this.editorMode===w)),this.editorMode===w&&v.addClass("is-active"),v.onclick=()=>this.switchEditorMode(w)}let y=n.createDiv({cls:"mdbase-editor-document"});this.editorMode==="design"?this.renderDesignEditor(y,this.model,s):this.renderYamlEditor(y,s)}renderDesignEditor(t,n,i){let s=t.createEl("section",{cls:"mdbase-editor-section"});s.createEl("h3",{text:"Identity"});let o=Rt(s,"Name",n.name,P=>{n.name=P,this.markDirty()},{description:"Stable type name used by collection records."});o.disabled=i;let a=Rt(s,"Description",n.description,P=>{n.description=P,this.markDirty()},{multiline:!0});a.disabled=i;let c=Rt(s,"Display field",n.displayNameKey,P=>{n.displayNameKey=P,this.markDirty()},{placeholder:"title"});c.disabled=i;let l=s.createEl("label",{cls:"mdbase-checkbox-row"}),d=l.createEl("input",{type:"checkbox"});d.checked=n.strictMode===!0,d.disabled=i,d.onchange=()=>{n.strictMode=d.checked,this.markDirty()},l.createSpan({text:"Reject undeclared fields"});let u=t.createEl("section",{cls:"mdbase-editor-section"});u.createEl("h3",{text:"Membership"});let f=Rt(u,"Path glob",n.matchPathGlob,P=>{n.matchPathGlob=P,this.markDirty()},{placeholder:"Projects/**/*.md"});f.disabled=i;let p=Rt(u,"Fields present",n.matchFieldsPresent,P=>{n.matchFieldsPresent=P,this.markDirty()},{description:"Comma-separated frontmatter keys."});p.disabled=i;let y=Rt(u,"Where",n.matchWhere,P=>{n.matchWhere=P,this.markDirty()},{multiline:!0,description:"YAML predicate, including contains and nested equality conditions.",placeholder:`tags: - contains: task`});y.disabled=i;let h=t.createEl("section",{cls:"mdbase-editor-section"}),m=h.createDiv({cls:"mdbase-section-header"});m.createEl("h3",{text:"Fields"});let g=m.createEl("button",{text:"Add field"});g.disabled=i,g.onclick=()=>{n.fields.push({name:"",definition:{type:"string"}}),this.markDirty(!0)};let _=h.createDiv({cls:"mdbase-fields"});for(let[P,O]of n.fields.entries())this.renderFieldRow(_,O,P,i);n.fields.length||_.createDiv({cls:"mdbase-empty-list",text:"No fields declared."});let w=t.createEl("section",{cls:"mdbase-editor-section"});w.createEl("h3",{text:"Placement"});let k=Rt(w,"Path pattern",n.pathPattern,P=>{n.pathPattern=P,this.markDirty()},{placeholder:"Notes/{title}.md"});k.disabled=i;let v=t.createEl("section",{cls:"mdbase-editor-section mdbase-change-review"});if(v.createEl("h3",{text:"Change review"}),!this.dirty)v.createEl("p",{text:"No pending changes."});else{let P=v.createEl("ul");for(let O of kC(this.originalModel,n))P.createEl("li",{text:O})}}renderFieldRow(t,n,i,s){this.renderFieldDefinition(t,n.definition,{name:n.name,nameLabel:`Field ${i+1} name`,onNameInput:o=>{n.name=o,this.markDirty()},required:n.definition.required===!0,onRequiredChange:o=>{n.definition.required=o,this.markDirty()},onRemove:()=>{var o;(o=this.model)==null||o.fields.splice(i,1),this.markDirty(!0)},readOnly:s,depth:0})}renderFieldDefinition(t,n,i){var d;let s=t.createDiv({cls:"mdbase-field-node"});s.setAttr("data-depth",String(i.depth));let o=s.createDiv({cls:"mdbase-field-row"});if(i.staticLabel)o.createDiv({cls:"mdbase-field-role",text:i.staticLabel});else{let u=o.createEl("input",{type:"text",cls:"mdbase-field-name-control"});u.setAttr("aria-label",i.nameLabel),u.placeholder="fieldName",u.value=(d=i.name)!=null?d:"",u.disabled=i.readOnly,i.onNameInput&&(u.oninput=()=>{var f;return(f=i.onNameInput)==null?void 0:f.call(i,u.value)}),i.onNameCommit&&(u.onchange=()=>{var f;return(f=i.onNameCommit)==null?void 0:f.call(i,u.value,u)})}let a=o.createEl("select",{cls:"mdbase-field-type-control"});a.setAttr("aria-label",`${i.name||i.staticLabel||"Field"} type`);for(let u of AC){let f=u==="any"?"Any value":u[0].toUpperCase()+u.slice(1);a.createEl("option",{value:u,text:f})}a.value=D0(n),a.disabled=i.readOnly,a.onchange=()=>{n.type=a.value,a.value==="list"&&!Ln(n.items)&&(n.items={type:"string"}),a.value==="object"&&!Ln(n.fields)&&(n.fields={}),a.value==="enum"&&!Array.isArray(n.values)&&(n.values=[]),this.markDirty(!0)};let c=o.createEl("input",{type:"text",cls:"mdbase-field-description-control"});if(c.setAttr("aria-label",`${i.name||i.staticLabel||"Field"} description`),c.placeholder="Description",c.value=typeof n.description=="string"?n.description:"",c.disabled=i.readOnly,c.oninput=()=>{c.value?n.description=c.value:delete n.description,this.markDirty()},i.onRequiredChange){let u=o.createEl("label",{cls:"mdbase-field-required"}),f=u.createEl("input",{type:"checkbox"});f.checked=i.required===!0,f.disabled=i.readOnly,f.onchange=()=>{var p;return(p=i.onRequiredChange)==null?void 0:p.call(i,f.checked)},u.createSpan({text:"Required"})}if(i.onRemove){let u=o.createEl("button",{cls:"mdbase-field-remove"});u.setAttr("aria-label",`Remove ${i.name||i.staticLabel||"field"}`),(0,Ae.setIcon)(u,"trash-2"),u.disabled=i.readOnly,u.onclick=i.onRemove}let l=D0(n);l==="enum"&&this.renderEnumFieldDetails(s,n,i),l==="link"&&this.renderLinkFieldDetails(s,n,i),l==="list"&&this.renderListFieldDetails(s,n,i),l==="object"&&this.renderObjectFieldDetails(s,n,i)}renderEnumFieldDetails(t,n,i){let s=t.createDiv({cls:"mdbase-field-details mdbase-field-options"}),o=s.createEl("label",{text:"Allowed values"}),a=s.createEl("input",{type:"text"});a.setAttr("aria-label",`${i.name||i.staticLabel||"Enum"} allowed values`),a.placeholder="draft, published, archived",a.value=Array.isArray(n.values)?n.values.map(String).join(", "):"",a.disabled=i.readOnly,a.oninput=()=>{n.values=a.value.split(",").map(c=>c.trim()).filter(Boolean),this.markDirty()},o.htmlFor=a.id=`mdbase-${Math.random().toString(36).slice(2)}`}renderLinkFieldDetails(t,n,i){let s=t.createDiv({cls:"mdbase-field-details mdbase-field-options"}),o=s.createEl("label",{text:"Target type"}),a=s.createEl("input",{type:"text"});a.setAttr("aria-label",`${i.name||i.staticLabel||"Link"} target type`),a.placeholder="Any type",a.value=typeof n.target=="string"?n.target:"",a.disabled=i.readOnly,a.oninput=()=>{a.value.trim()?n.target=a.value.trim():delete n.target,this.markDirty()},o.htmlFor=a.id=`mdbase-${Math.random().toString(36).slice(2)}`;let c=s.createEl("label",{cls:"mdbase-field-required"}),l=c.createEl("input",{type:"checkbox"});l.checked=n.validate_exists===!0,l.disabled=i.readOnly,l.onchange=()=>{n.validate_exists=l.checked,this.markDirty()},c.createSpan({text:"Validate target exists"})}renderListFieldDetails(t,n,i){let s=t.createDiv({cls:"mdbase-field-children"});s.createDiv({cls:"mdbase-field-children-label",text:"List items"});let o=Ln(n.items)?n.items:{type:"any"};!Ln(n.items)&&!i.readOnly&&(n.items=o),this.renderFieldDefinition(s,o,{staticLabel:"Item",nameLabel:"List item",readOnly:i.readOnly,depth:i.depth+1})}renderObjectFieldDetails(t,n,i){let s=t.createDiv({cls:"mdbase-field-children"}),o=s.createDiv({cls:"mdbase-field-children-header"});o.createDiv({cls:"mdbase-field-children-label",text:"Object fields"});let a=o.createEl("button",{text:"Add nested field"});a.disabled=i.readOnly;let c=Ln(n.fields)?n.fields:{};!Ln(n.fields)&&!i.readOnly&&(n.fields=c),a.onclick=()=>{let u=xC(c);q0(c,u,{type:"string"}),this.markDirty(!0)};let l=s.createDiv({cls:"mdbase-nested-fields"}),d=Object.entries(c).filter(u=>Ln(u[1]));if(!d.length){l.createDiv({cls:"mdbase-empty-list",text:"No nested fields."});return}for(let[u,f]of d){let p=u;this.renderFieldDefinition(l,f,{name:p,nameLabel:`${p} nested field name`,onNameCommit:(y,h)=>{let m=y.trim();if(!m){new Ae.Notice("Nested field name is required."),h.value=p;return}if(m!==p&&Object.prototype.hasOwnProperty.call(c,m)){new Ae.Notice(`Nested field already exists: ${m}`),h.value=p;return}m!==p&&(delete c[p],q0(c,m,f),p=m,this.markDirty())},required:f.required===!0,onRequiredChange:y=>{f.required=y,this.markDirty()},onRemove:()=>{delete c[p],this.markDirty(!0)},readOnly:i.readOnly,depth:i.depth+1})}}renderYamlEditor(t,n){let i=t.createEl("section",{cls:"mdbase-editor-section mdbase-yaml-section"});i.createEl("h3",{text:"Canonical type document"}),i.createEl("p",{cls:"mdbase-form-description",text:"Unknown v0.3 extensions are preserved. Invalid YAML is never normalized or saved."});let s=i.createEl("textarea",{cls:"mdbase-yaml-editor"});s.setAttr("aria-label","Type definition YAML"),s.value=this.yamlDraft,s.disabled=n,s.spellcheck=!1,s.oninput=()=>{this.yamlDraft=s.value,this.markDirty(!1)}}renderSync(t){var y,h,m,g,_,w,k,v,P,O;let n=t.createDiv({cls:"mdbase-sync-document"}),i=n.createDiv({cls:"mdbase-document-header"});i.createEl("h2",{text:"Sync"}),i.createEl("p",{text:"Connect this vault to a collection authority and keep ordinary Markdown mirrored locally."});let s=this.host.getMirrorProfile();if(!s){this.renderEnrollment(n);return}let o=n.createEl("section",{cls:"mdbase-editor-section"});o.createEl("h3",{text:"Collection authority"});let a=o.createDiv({cls:"mdbase-status-list"});if(Ne(a,"Name",s.name),Ne(a,"Collection",s.collectionId),Ne(a,"Access",s.mode==="read_write"?"Read and write":"Read only"),Ne(a,"Provider",s.syncUrl),Ne(a,"State",(h=(y=this.mirrorStatus)==null?void 0:y.state.replace(/_/g," "))!=null?h:"Checking"),Ne(a,"Last synced",(g=(m=this.mirrorStatus)==null?void 0:m.last_synced_at)!=null?g:"Never"),this.mirrorProgress){let $=this.mirrorProgress.total,R=o.createEl("progress");R.max=$!=null?$:1,R.value=$==null?0:this.mirrorProgress.completed,$==null&&R.removeAttribute("value"),o.createDiv({cls:"mdbase-progress-label",text:`${this.mirrorProgress.phase}: ${this.mirrorProgress.completed}${$==null?"":` of ${$}`}`});let S=o.createEl("button",{text:"Stop safely"});S.onclick=()=>{this.host.connectSync.cancelSync(),this.transientMessage="Stopping after the current action boundary\u2026",this.render()}}let c=o.createDiv({cls:"mdbase-actions"}),l=c.createEl("button",{text:"Preview"});l.disabled=this.busy,l.onclick=()=>void this.perform(async()=>{this.mirrorPreview=await this.host.connectSync.preview(),this.transientMessage=this.mirrorPreview.entries.length?"Review the engine plan below, then sync when ready.":"No content effects are needed; confirm the sync checkpoint when ready.",this.render()});let d=(w=(_=this.mirrorPreview)==null?void 0:_.plan.actions.filter($=>$.command!=="advance_checkpoint").length)!=null?w:0,u=((v=(k=this.mirrorPreview)==null?void 0:k.plan.summary.blocking_issues)!=null?v:0)>0,f=c.createEl("button",{text:this.mirrorPreview?d?`Sync ${d} ${d===1?"outcome":"outcomes"}`:"Confirm sync checkpoint":"Review before syncing"});f.addClass("mod-cta"),f.disabled=this.busy||!this.mirrorPreview||u,f.onclick=()=>void this.perform(async()=>{var R,S;let $=await this.host.connectSync.sync(this.mirrorPreview,V=>{this.mirrorProgress=V,this.render()});this.mirrorStatus=await this.host.connectSync.status(),this.mirrorPreview=await this.host.connectSync.preview(),this.mirrorProgress=null,this.transientMessage=$.status==="applied"?"Sync completed and the local checkpoint was verified.":$.status==="attention"?"Sync checkpointed completed actions and recorded the items that need attention.":$.status==="cancelled"?`Sync stopped safely after ${$.applied} actions; ${$.pending} remain pending.`:$.status==="stale"?"The reviewed plan became stale. Review the new engine plan before syncing again.":`Sync stopped at a durable action boundary: ${(S=(R=$.failure)==null?void 0:R.message)!=null?S:$.status}.`,await this.refresh(!0)}),this.mirrorPreview&&this.renderMirrorPreview(n,this.mirrorPreview),(P=this.mirrorStatus)!=null&&P.conflicts.length&&this.renderConflicts(n,this.mirrorStatus),(O=this.mirrorStatus)!=null&&O.local_issues.length&&this.renderLocalMirrorIssues(n,this.mirrorStatus);let p=n.createEl("section",{cls:"mdbase-editor-section"});p.createEl("h3",{text:"Mirror ownership"}),p.createEl("p",{text:"Use this plugin as the only sync owner for this vault. Obsidian protects concurrent operations inside the app; a separate desktop mirror process cannot share that mobile-safe lease."})}renderEnrollment(t){if(this.schema||this.host.connectSync.getAdoptionMarker()){this.renderLocalAdoption(t);return}let n=t.createEl("section",{cls:"mdbase-editor-section mdbase-enrollment"});if(n.createEl("h3",{text:"Connect collection authority"}),n.createEl("p",{text:"Connect will open an approval page. Credentials are stored in Obsidian's secret store and never written into this vault."}),this.enrollmentVerification){let u=n.createDiv({cls:"mdbase-approval-link"});u.createSpan({text:"Approval page: "});let f=u.createEl("a",{text:"Open Connect",href:this.enrollmentVerification});f.setAttr("target","_blank"),f.setAttr("rel","noopener noreferrer")}let i="https://connect.mdbase.dev",s="Obsidian",o="",a="read_write";Rt(n,"Connect URL",i,u=>{i=u},{placeholder:"https://connect.mdbase.dev"}),Rt(n,"Mirror name",s,u=>{s=u}),Rt(n,"Collection ID",o,u=>{o=u},{description:"Optional. Leave blank to choose during approval."});let c=n.createDiv({cls:"mdbase-form-row"});c.createEl("label",{text:"Access"});let l=c.createEl("select");l.createEl("option",{value:"read_write",text:"Read and write"}),l.createEl("option",{value:"read_only",text:"Read only"}),l.value=a,l.onchange=()=>{a=l.value==="read_only"?"read_only":"read_write"};let d=n.createEl("button",{text:"Open Connect approval"});d.addClass("mod-cta"),d.disabled=this.busy,d.onclick=()=>void this.perform(async()=>{var f;(f=this.enrollmentAbort)==null||f.abort();let u=new AbortController;this.enrollmentAbort=u;try{await this.host.connectSync.enroll({controlUrl:i,mirrorName:s,mode:a,...o.trim()?{collectionId:o.trim()}:{}},{signal:u.signal,onVerification:p=>{this.enrollmentVerification=p.verificationUri,this.transientMessage="Approve the mirror in the Connect page. This view will keep waiting securely.",window.open(p.verificationUri,"_blank","noopener,noreferrer"),this.render()},onStatus:p=>{this.transientMessage=p.state==="waiting_for_approval"?"Waiting for approval in Connect\u2026":`Connect is retrying enrollment (attempt ${p.attempt}).`,this.render()}}),this.enrollmentVerification="",this.transientMessage="Mirror enrolled. Preview before the first sync.",await this.refreshMirrorStatus(),this.render()}finally{this.enrollmentAbort===u&&(this.enrollmentAbort=null)}})}renderLocalAdoption(t){var d,u;let n=this.host.connectSync.getAdoptionMarker(),i=t.createEl("section",{cls:"mdbase-editor-section mdbase-enrollment"});i.createEl("h3",{text:"Host this local collection"}),i.createEl("p",{text:n?"This vault has a durable adoption checkpoint. Resume it without creating another hosted collection.":"Hosted mdbase will adopt an exact snapshot and become the collection authority. This vault will then continue as a read-write mirror."});let s=this.enrollmentVerification||(n==null?void 0:n.session.verificationUri);if(s){let f=i.createDiv({cls:"mdbase-approval-link"});f.createSpan({text:"Approval page: "});let p=f.createEl("a",{text:"Open Connect",href:s});p.setAttr("target","_blank"),p.setAttr("rel","noopener noreferrer")}let o=(d=n==null?void 0:n.session.controlUrl)!=null?d:"https://connect.mdbase.dev",a=(u=n==null?void 0:n.session.requested.mirrorName)!=null?u:"Obsidian";if(!n)Rt(i,"Connect URL",o,f=>{o=f},{placeholder:"https://connect.mdbase.dev"}),Rt(i,"Mirror name",a,f=>{a=f});else{let f=i.createDiv({cls:"mdbase-status-list"});Ne(f,"Collection",n.session.requested.collectionId),Ne(f,"Phase",n.phase.replace(/_/g," ")),Ne(f,"Connect",n.session.controlUrl)}let c=i.createDiv({cls:"mdbase-inline-message"});c.createEl("strong",{text:"Authority cut-over: "}),c.appendText("once final staging begins, plugin-managed local edits pause until hosted activation is confirmed. The checkpoint survives app restarts and uncertain network responses.");let l=i.createEl("button",{text:n?"Resume adoption":"Approve and host collection"});if(l.addClass("mod-cta"),l.disabled=this.busy,l.onclick=()=>void this.perform(async()=>{var h;(h=this.enrollmentAbort)==null||h.abort();let f=new AbortController;this.enrollmentAbort=f;let p=m=>{this.enrollmentVerification=m.verificationUri,this.transientMessage="Approve the authority move in Connect, then return here. This checkpoint is safe to resume.",this.render()},y=m=>{this.transientMessage=m.state==="waiting_for_approval"?"Waiting for authority-move approval in Connect\u2026":`Connect is retrying (attempt ${m.attempt}).`,this.render()};try{n?await this.host.connectSync.resumeAdoption({signal:f.signal,onVerification:p,onStatus:y}):await this.host.connectSync.adoptLocalCollection({controlUrl:o,mirrorName:a},{signal:f.signal,onVerification:p,onStatus:y}),this.enrollmentVerification="",this.transientMessage="Hosted mdbase is authoritative and this vault is now its read-write mirror.",await this.refresh(!0)}finally{this.enrollmentAbort===f&&(this.enrollmentAbort=null)}}),n&&!["activating","adopted"].includes(n.phase)){let f=i.createEl("button",{text:"Cancel adoption"});f.disabled=this.busy,f.onclick=()=>void this.perform(async()=>{await this.host.connectSync.cancelAdoption(),this.enrollmentVerification="",this.transientMessage="Collection adoption cancelled. This vault remains the local authority.",await this.refresh(!0)})}}renderMirrorPreview(t,n){let i=t.createEl("section",{cls:"mdbase-editor-section"});i.createEl("h3",{text:"Sync preview"});let s=i.createDiv({cls:"mdbase-status-list"});if(Ne(s,"Download documents",String(n.download_documents)),Ne(s,"Upload documents",String(n.upload_documents)),Ne(s,"Unchanged documents",String(n.unchanged_documents)),Ne(s,"Plan",n.plan.fingerprint),n.entries.length){let o=i.createEl("ul");for(let a of n.entries.slice(0,200))o.createEl("li",{text:`${a.direction==="attention"?"Attention":a.direction}: ${a.path} \u2014 ${a.detail}`})}if(n.collisions.length){i.createDiv({cls:"mdbase-inline-error",text:`${n.collisions.length} path collision${n.collisions.length===1?"":"s"} must be resolved before sync.`});let o=i.createEl("ul");for(let a of n.collisions.slice(0,100))o.createEl("li",{text:a})}if(n.local_issues.length){i.createDiv({cls:"mdbase-inline-error",text:`${n.local_issues.length} local file${n.local_issues.length===1?"":"s"} cannot be uploaded until its frontmatter is fixed.`});let o=i.createEl("ul");for(let a of n.local_issues.slice(0,100))o.createEl("li",{text:`${a.path}: ${a.message}`})}}renderConflicts(t,n){var s;let i=t.createEl("section",{cls:"mdbase-editor-section"});i.createEl("h3",{text:"Conflicts"});for(let o of n.conflicts){let a=i.createDiv({cls:"mdbase-conflict-row"}),c=a.createDiv();c.createEl("strong",{text:(s=o.path)!=null?s:o.record_id}),c.createDiv({text:o.message});let l=a.createDiv({cls:"mdbase-actions"});for(let d of["local","remote"]){let u=l.createEl("button",{text:d==="local"?"Keep local":"Use remote"});u.disabled=this.busy,u.onclick=()=>void this.perform(async()=>{this.mirrorStatus=await this.host.connectSync.resolveConflict(o.record_id,d),this.render()})}}}renderLocalMirrorIssues(t,n){let i=t.createEl("section",{cls:"mdbase-editor-section"});i.createEl("h3",{text:"Local files needing attention"}),i.createEl("p",{text:"These files remain untouched and unsynced. Other valid Markdown continues to synchronize."});for(let s of n.local_issues){let o=i.createDiv({cls:"mdbase-conflict-row"}),a=o.createDiv();a.createEl("strong",{text:s.path}),a.createDiv({text:s.message});let l=o.createDiv({cls:"mdbase-actions"}).createEl("button",{text:"Open file"});l.disabled=this.busy,l.onclick=()=>void this.host.openFileByPath(s.path)}}renderIssues(t){var g;let n=t.createDiv({cls:"mdbase-issues-document"}),i=this.host.getIssues(),s=new Set(i.map(_=>_.path)).size,o=n.createDiv({cls:"mdbase-document-header"}),a=o.createDiv();a.createEl("h2",{text:"Issues"}),a.createEl("p",{text:i.length?`${i.length.toLocaleString()} validation issues in ${s.toLocaleString()} files.`:"The collection has no current validation issues."});let c=o.createEl("button",{text:"Validate collection"});c.disabled=this.busy,c.onclick=()=>void this.perform(async()=>{await this.host.validateCollection(),this.render()});let l=n.createDiv({cls:"mdbase-issue-controls"}),d=l.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.render()};let u=l.createEl("input",{type:"search"});u.setAttr("aria-label","Filter issues"),u.placeholder="Filter by path, code, field, or message",u.value=this.issueQuery,u.oninput=()=>{this.issueQuery=u.value,this.issueLimit=250,this.render();let _=this.containerEl.querySelector(".mdbase-issue-controls input[type='search']");_==null||_.focus(),_==null||_.setSelectionRange(_.value.length,_.value.length)};let f=this.issueQuery.trim().toLowerCase(),p=i.filter(_=>{var w;return this.issueSeverity!=="all"&&_.severity!==this.issueSeverity?!1:f?`${_.path} ${_.code} ${(w=_.field)!=null?w:""} ${_.message}`.toLowerCase().includes(f):!0}),y=new Set(p.map(_=>_.path)).size;if(n.createDiv({cls:"mdbase-issues-summary",text:p.length===i.length?`Showing ${Math.min(p.length,this.issueLimit).toLocaleString()} of ${p.length.toLocaleString()} issues`:`${p.length.toLocaleString()} matching issues in ${y.toLocaleString()} files`}),!p.length){n.createDiv({cls:"mdbase-empty-state",text:"No validation issues."});return}let h=p.slice(0,this.issueLimit),m=new Map;for(let _ of h)m.set(_.path,[...(g=m.get(_.path))!=null?g:[],_]);for(let[_,w]of m){let k=n.createEl("section",{cls:"mdbase-issue-group"}),v=k.createDiv({cls:"mdbase-issue-group-header"}),P=v.createEl("button",{cls:"mdbase-issue-file-button"});(0,Ae.setIcon)(P.createSpan({cls:"mdbase-issue-file-icon"}),"file-text"),P.createSpan({cls:"mdbase-issue-file-path",text:_}),P.onclick=()=>void this.host.openFileByPath(_),v.createSpan({cls:"mdbase-issue-file-count",text:`${w.length} ${w.length===1?"issue":"issues"}`});for(let O of w){let $=k.createEl("button",{cls:"mdbase-issue-row"});$.setAttr("data-severity",O.severity),$.setAttr("aria-label",`${O.severity==="warn"?"Warning":"Error"}: ${O.message}`),$.createSpan({cls:"mdbase-issue-indicator"}).setAttr("aria-hidden","true");let R=$.createDiv({cls:"mdbase-issue-metadata"});R.createEl("code",{text:O.code}),R.createDiv({cls:"mdbase-issue-context",text:`${O.severity==="warn"?"Warning":"Error"}${O.field?` \xB7 ${O.field}`:""}`}),$.createDiv({cls:"mdbase-issue-row-message",text:O.message}),$.onclick=()=>void this.host.openFileByPath(O.path,O.field)}}if(p.length>h.length){let _=n.createEl("button",{cls:"mdbase-load-more",text:`Load ${Math.min(250,p.length-h.length)} more`});_.onclick=()=>{this.issueLimit+=250,this.render()}}}async selectType(t,n=!0){if(n&&this.dirty&&t!==this.selectedPath){new Ae.Notice("Save or discard the current type changes before switching.");return}let i=await this.host.loadTypeModel(t);this.selectedPath=t,this.model=i,this.originalModel=gp(i),this.yamlDraft=`${yt(F0(i),i.body)} -`,this.dirty=!1,this.editorMode="design",this.render()}createType(){if(this.dirty){new Ae.Notice("Save or discard the current type changes before creating another type.");return}let t=yp();this.selectedPath=null,this.model=t,this.originalModel=null,this.yamlDraft=`${yt(mo(t),t.body)} -`,this.dirty=!0,this.editorMode="design",this.render()}switchEditorMode(t){if(!(!this.model||t===this.editorMode)){if(t==="yaml")try{this.yamlDraft=`${yt(F0(this.model),this.model.body)} -`}catch(n){new Ae.Notice(n instanceof Error?n.message:String(n));return}else if(!this.readYamlDraftIntoModel())return;this.editorMode=t,this.render()}}readYamlDraftIntoModel(){var n,i;let t=It(this.yamlDraft);if(!t.hasFrontmatter||t.error)return new Ae.Notice(`Invalid type YAML: ${(n=t.error)!=null?n:"frontmatter is missing"}`),!1;if(t.frontmatter.kind!=="mdbase.type")return new Ae.Notice("Canonical v0.3 type YAML requires kind: mdbase.type."),!1;try{return this.model=Vc(t.frontmatter,t.body,((i=this.model)==null?void 0:i.name)||"type"),!0}catch(s){return new Ae.Notice(s instanceof Error?s.message:String(s)),!1}}async saveCurrentType(){if(!(!this.model||this.model.specProfile!=="v0.3"||this.model.readOnlyReason)&&!(this.editorMode==="yaml"&&!this.readYamlDraftIntoModel())){if(!this.model.name.trim()){new Ae.Notice("Type name is required.");return}await this.perform(async()=>{let t=await this.host.saveTypeModel(this.model,this.selectedPath);this.selectedPath=t.path,this.originalModel=gp(this.model),this.dirty=!1,this.transientMessage=`Saved ${t.path}.`,await this.refresh(!0)})}}markDirty(t=!1){var o,a;if(this.dirty=!0,t){this.render();return}let n=this.containerEl.querySelector(".mdbase-editor-title-line");n&&!n.querySelector(".mdbase-dirty")&&n.createSpan({cls:"mdbase-dirty",text:"Unsaved"});let i=this.containerEl.querySelector(".mdbase-editor-actions .mod-cta");i&&((o=this.model)==null?void 0:o.specProfile)==="v0.3"&&!this.model.readOnlyReason&&((a=this.host.getMirrorProfile())==null?void 0:a.mode)!=="read_only"&&(i.disabled=!1);let s=this.containerEl.querySelector(".mdbase-change-review");if(s){let c=s.querySelector("p");c&&c.setText("Pending changes. Review details after leaving the current field.")}}async refreshMirrorStatus(){try{this.mirrorStatus=await this.host.connectSync.status()}catch(t){this.mirrorStatus=null,this.transientMessage=t instanceof Error?t.message:String(t)}}async perform(t){if(!this.busy){this.busy=!0,this.transientMessage="",this.render();try{await t()}catch(n){let i=n instanceof Error?n.message:String(n);this.transientMessage=i,new Ae.Notice(i)}finally{this.busy=!1,this.render()}}}};function F0(r){var e;return r.specProfile==="v0.3"&&!r.readOnlyReason?mo(r):gp((e=r.originalFrontmatter)!=null?e:{name:r.name,fields:Object.fromEntries(r.fields.map(t=>[t.name,t.definition]))})}var qi="mdbase-issues-view",IC={validateOnSave:!0,validateOnOpen:!0,showNoticeOnSave:!1,interopEnabled:!1,mirrorProfile:null};function OC(r){if(!r||typeof r!="object"||Array.isArray(r))return!1;let e=r;return e.version===1&&typeof e.syncUrl=="string"&&typeof e.controlUrl=="string"&&typeof e.collectionId=="string"&&typeof e.replicaId=="string"&&(e.mode==="read_only"||e.mode==="read_write")&&typeof e.name=="string"&&typeof e.enrollmentId=="string"&&typeof e.accessTokenExpiresAt=="string"}function RC(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var yo=class extends L.Modal{constructor(t,n,i="",s=""){super(t);this.resolvePromise=null;this.settled=!1;this.title=n,this.placeholder=i,this.defaultValue=s}openAndGetValue(){return new Promise(t=>{this.settled=!1,this.resolvePromise=t,this.open()})}onOpen(){let{contentEl:t}=this;t.empty(),t.createEl("h3",{text:this.title});let n=t.createEl("input",{type:"text"});n.placeholder=this.placeholder,n.value=this.defaultValue,n.addClass("prompt-input");let i=t.createDiv({cls:"modal-button-container"}),s=i.createEl("button",{text:"Cancel"}),o=i.createEl("button",{text:"OK"});o.addClass("mod-cta"),s.onclick=()=>{this.finish(null),this.close()},o.onclick=()=>{this.finish(n.value.trim()),this.close()},n.addEventListener("keydown",a=>{a.key==="Enter"&&(a.preventDefault(),this.finish(n.value.trim()),this.close()),a.key==="Escape"&&(a.preventDefault(),this.finish(null),this.close())}),window.setTimeout(()=>n.focus(),0)}onClose(){this.settled||this.finish(null),this.contentEl.empty()}finish(t){var n;this.settled||(this.settled=!0,(n=this.resolvePromise)==null||n.call(this,t),this.resolvePromise=null)}},_p=class extends L.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=>{var a,c,l;let s=(c=(a=i.match)==null?void 0:a.path_glob)!=null?c:"";return`${i.name} ${(l=i.display_name_key)!=null?l:""} ${i.filePath} ${s}`.toLowerCase().includes(n)}).slice(0,100):this.typeDefs.slice(0,100)}renderSuggestion(t,n){var o,a;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((o=t.fields)!=null?o:{}).length} fields`}),(a=t.match)!=null&&a.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 TC(r,e){return new Promise(t=>{new _p(r,e,i=>{if(i.type==="selected"){t(i.typeDef);return}t(null)}).open()})}var bp=class extends L.ItemView{constructor(t,n){super(t);this.severityFilter="all";this.query="";this.plugin=n}getViewType(){return qi}getDisplayText(){return"mdbase issues"}getIcon(){return"shield-alert"}async onOpen(){this.containerEl.empty(),this.containerEl.addClass("mdbase-issues-view"),this.render()}render(){var y;let t=this.containerEl;t.empty(),t.addClass("mdbase-issues-view");let n=t.createDiv({cls:"mdbase-issues-header"});n.createEl("h3",{text:"mdbase Issues"});let s=n.createDiv({cls:"mdbase-issues-header-actions"}).createEl("button",{text:"Refresh"});s.addClass("mod-cta"),s.onclick=()=>{this.plugin.runCollectionValidation(!1)};let o=t.createDiv({cls:"mdbase-issues-controls"}),a=o.createEl("select");a.addClass("mdbase-issues-severity"),a.createEl("option",{value:"all",text:"All severities"}),a.createEl("option",{value:"error",text:"Errors only"}),a.createEl("option",{value:"warn",text:"Warnings only"}),a.value=this.severityFilter,a.onchange=()=>{let h=a.value;(h==="error"||h==="warn"||h==="all")&&(this.severityFilter=h),this.render()};let c=o.createEl("input",{type:"search"});c.addClass("mdbase-issues-query"),c.placeholder="Filter by path, code, message, field",c.value=this.query,c.oninput=()=>{this.query=c.value,this.render()};let l=this.plugin.getIssues(),d=this.query.trim().toLowerCase(),u=l.filter(h=>{var g;return this.severityFilter!=="all"&&h.severity!==this.severityFilter?!1:d?`${h.path} ${h.code} ${h.message} ${(g=h.field)!=null?g:""}`.toLowerCase().includes(d):!0}),f=u.slice(0,500);if(t.createDiv({cls:"mdbase-issues-count",text:u.length>f.length?`Showing ${f.length} of ${u.length} matching issues`:u.length===l.length?`${u.length} issue${u.length===1?"":"s"}`:`${u.length} of ${l.length} issue${l.length===1?"":"s"}`}),u.length===0){t.createDiv({cls:"mdbase-empty",text:l.length===0?"No validation issues.":"No issues match current filters."});return}let p=new Map;for(let h of f){let m=(y=p.get(h.path))!=null?y:[];m.push(h),p.set(h.path,m)}for(let[h,m]of p.entries()){t.createDiv({cls:"mdbase-issue-file",text:h});for(let g of m){let _=t.createDiv({cls:"mdbase-issue-item"});_.setAttr("data-severity",g.severity),_.createDiv({cls:"mdbase-issue-code",text:`${g.severity.toUpperCase()} \xB7 ${g.code}${g.field?` \xB7 ${g.field}`:""}`}),_.createDiv({cls:"mdbase-issue-message",text:g.message});let w=_.createDiv({cls:"mdbase-issue-actions"}),k=w.createEl("button",{text:g.field?"Open field":"Open file"});k.onclick=P=>{P.stopPropagation(),this.plugin.openIssue(g)};let v=this.plugin.getQuickFixLabel(g);if(v){let P=w.createEl("button",{text:v});P.onclick=O=>{O.stopPropagation(),this.plugin.applyQuickFix(g)}}_.onclick=()=>{this.plugin.openIssue(g)}}}}},wp=class extends L.PluginSettingTab{constructor(e,t){super(e,t),this.plugin=t}display(){let{containerEl:e}=this;e.empty(),e.createEl("h2",{text:"mdbase settings"}),new L.Setting(e).setName("Validate on save").setDesc("Run mdbase validation when a markdown file is modified.").addToggle(t=>t.setValue(this.plugin.settings.validateOnSave).onChange(async n=>{this.plugin.settings.validateOnSave=n,await this.plugin.saveSettings()})),new L.Setting(e).setName("Validate on file open").setDesc("Validate the active note when opened.").addToggle(t=>t.setValue(this.plugin.settings.validateOnOpen).onChange(async n=>{this.plugin.settings.validateOnOpen=n,await this.plugin.saveSettings()})),new L.Setting(e).setName("Show notices on save").setDesc("Display a notice when save-time validation finds issues.").addToggle(t=>t.setValue(this.plugin.settings.showNoticeOnSave).onChange(async n=>{this.plugin.settings.showNoticeOnSave=n,await this.plugin.saveSettings()})),new L.Setting(e).setName("Allow local application interoperability").setDesc("Allow installed Obsidian plugins to exchange validated mdbase events and actions in this vault. Contracts establish compatibility; this switch is the separate user grant.").addToggle(t=>t.setValue(this.plugin.settings.interopEnabled).onChange(async n=>{this.plugin.settings.interopEnabled=n,await this.plugin.saveSettings()}))}},zc=class extends L.Plugin{constructor(t,n){super(t,n);this.issueMap=new Map;this.sortedIssuesCache=null;this.schemaCache=null;this.schemaLoadPromise=null;this.pendingSaveValidations=new Map;this.saveValidationDebounceMs=250;this.connectSync=new qc(t,{getMirrorProfile:()=>this.getMirrorProfile(),saveMirrorProfile:async i=>{this.settings.mirrorProfile=i,await this.saveSettings()}}),this.interopBridge=new ya(t,()=>{var i;return((i=this.settings)==null?void 0:i.interopEnabled)===!0}),this.api={apiVersion:1,interop:this.interopBridge,getInteropStatus:()=>{var i;return{enabled:((i=this.settings)==null?void 0:i.interopEnabled)===!0,profileVersion:"0.1"}}}}async onload(){await this.loadSettings(),await this.connectSync.initialize(),(0,L.addIcon)(Di,j0),this.statusBarEl=this.addStatusBarItem(),this.updateStatusBar(),this.registerView(jn,n=>new Bc(n,this)),this.registerView(qi,n=>new bp(n,this)),this.addSettingTab(new wp(this.app,this)),this.addRibbonIcon(Di,"Open mdbase",()=>void this.openWorkspace()),this.addCommand({id:"mdbase-open",name:"mdbase: Open workspace",callback:()=>void this.openWorkspace()}),this.addCommand({id:"mdbase-initialize-collection",name:"mdbase: Initialize collection",callback:()=>void this.initializeCollectionCommand()}),this.addCommand({id:"mdbase-create-type",name:"mdbase: Create type definition",callback:()=>void this.openWorkspace("types")}),this.addCommand({id:"mdbase-edit-type",name:"mdbase: Edit type definition",callback:()=>void this.openWorkspace("types")}),this.addCommand({id:"mdbase-edit-current-type",name:"mdbase: Edit current type definition",callback:()=>void this.openWorkspace("types")}),this.addCommand({id:"mdbase-create-note-from-type",name:"mdbase: Create note from type",callback:()=>void this.createNoteFromTypeCommand()}),this.addCommand({id:"mdbase-validate-current-note",name:"mdbase: Validate current note",callback:()=>void this.validateCurrentNoteCommand()}),this.addCommand({id:"mdbase-validate-collection",name:"mdbase: Validate collection",callback:()=>void this.runCollectionValidation(!0)}),this.addCommand({id:"mdbase-open-issues-view",name:"mdbase: Open issues view",callback:()=>void this.openWorkspace("issues")}),this.addCommand({id:"mdbase-sync",name:"mdbase: Sync collection authority",callback:()=>void this.syncHostedCollectionCommand()}),this.addCommand({id:"mdbase-open-sync",name:"mdbase: Open sync",callback:()=>void this.openWorkspace("sync")}),this.registerEvent(this.app.vault.on("modify",n=>{n instanceof L.TFile&&this.onVaultModify(n)})),this.registerEvent(this.app.vault.on("rename",(n,i)=>{n instanceof L.TFile&&this.onVaultRename(n,i)})),this.registerEvent(this.app.vault.on("delete",n=>{n instanceof L.TFile&&this.onVaultDelete(n)})),this.registerEvent(this.app.vault.on("create",n=>{n instanceof L.TFile&&this.onVaultCreate(n)})),this.registerEvent(this.app.workspace.on("file-open",n=>{this.settings.validateOnOpen&&(!(n instanceof L.TFile)||n.extension!=="md"||this.validateFileAndStore(n,"open"))}));let t=this.app.workspace.getActiveFile();t&&this.settings.validateOnOpen&&this.validateFileAndStore(t,"open")}async onunload(){await this.interopBridge.dispose(),this.app.workspace.getLeavesOfType(jn).forEach(t=>t.detach()),this.app.workspace.getLeavesOfType(qi).forEach(t=>t.detach()),this.clearAllPendingSaveValidations()}async loadSettings(){this.settings=Object.assign({},IC,await this.loadData()),OC(this.settings.mirrorProfile)||(this.settings.mirrorProfile=null)}async saveSettings(){await this.saveData(this.settings)}getIssues(){var t;return(t=this.sortedIssuesCache)!=null||(this.sortedIssuesCache=Array.from(this.issueMap.values()).flat().sort((n,i)=>n.path.localeCompare(i.path)||n.severity.localeCompare(i.severity)||n.code.localeCompare(i.code))),this.sortedIssuesCache}getMirrorProfile(){return this.settings.mirrorProfile?{...this.settings.mirrorProfile}:null}async loadWorkspaceSchema(t=!1){return this.getConfigAndTypes(t)}async loadTypeModel(t){var s;let n=this.app.vault.getAbstractFileByPath((0,L.normalizePath)(t));if(!(n instanceof L.TFile))throw new Error(`Type file not found: ${t}`);let i=It(await this.app.vault.cachedRead(n));if(!i.hasFrontmatter||i.error)throw new Error(`Invalid type frontmatter: ${(s=i.error)!=null?s:"frontmatter is missing"}`);return Vc(i.frontmatter,i.body,n.basename)}async saveTypeModel(t,n){var a;if(this.connectSync.assertLocalAuthorityWritable(),((a=this.getMirrorProfile())==null?void 0:a.mode)==="read_only")throw new Error("This mirror has read-only access. Re-enroll it with write access before editing types.");let i=await ui(this.app.vault);if(!i)throw new Error("No mdbase.yaml found.");if(!i.spec_version.startsWith("0.3."))throw new Error("mdbase v0.2 type definitions are read-only. Migrate the collection first.");let s=n?this.app.vault.getAbstractFileByPath((0,L.normalizePath)(n)):null;if(s!=null&&!(s instanceof L.TFile))throw new Error(`Type file not found: ${n}`);let o=await this.writeTypeDefinition(i,t,s);return this.refreshWorkspaceViews(!0),o}async initializeCollection(){this.connectSync.assertLocalAuthorityWritable(),await this.initializeCollectionCommand(),this.refreshWorkspaceViews(!0)}async validateCollection(){await this.runCollectionValidation(!1)}analyzeMigration(){if(this.getMirrorProfile())throw new Error("Collection authority resources must be migrated at the collection authority.");return C0(this.app.vault)}async applyMigration(t,n){var s,o;if(this.connectSync.assertLocalAuthorityWritable(),this.getMirrorProfile())throw new Error("Collection authority resources must be migrated at the collection authority.");let i=await N0(this.app.vault,t,{allowLossy:n});if(!i.applied)throw new Error(i.restored?`Migration failed and all writes were rolled back. ${(s=i.error)!=null?s:""}`.trim():`Migration needs manual recovery. See ${i.manifestPath}. ${(o=i.error)!=null?o:""}`.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["unknown_field","schema_additional_properties"].includes(t.code)&&t.field?"Remove field":["missing_required","schema_required"].includes(t.code)&&t.field?"Add placeholder":null}async applyQuickFix(t){this.connectSync.assertLocalAuthorityWritable();let n=this.app.vault.getAbstractFileByPath(t.path);if(!(n instanceof L.TFile)){new L.Notice(`File not found: ${t.path}`);return}let i=await this.app.vault.cachedRead(n),s=It(i);if(s.error){new L.Notice(`Cannot apply quick fix: invalid frontmatter (${s.error})`);return}if(["unknown_field","schema_additional_properties"].includes(t.code)&&t.field){let o=va(t.field);if(!(o in s.frontmatter)){new L.Notice(`Field '${o}' not found in frontmatter.`);return}delete s.frontmatter[o],await this.app.vault.modify(n,`${yt(s.frontmatter,s.body)} -`),new L.Notice(`Removed '${o}' from ${n.basename}`),await this.validateFileAndStore(n,"manual");return}if(["missing_required","schema_required"].includes(t.code)&&t.field){let o=va(t.field);s.frontmatter[o]===void 0&&(s.frontmatter[o]="TODO");let a=s.hasFrontmatter?s.body:i;await this.app.vault.modify(n,`${yt(s.frontmatter,a)} -`),new L.Notice(`Added placeholder '${o}' to ${n.basename}`),await this.validateFileAndStore(n,"manual");return}new L.Notice("No quick fix available for this issue.")}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=va(n),l=new RegExp(`^\\s*${RC(c)}\\s*:`);if(o.getLine(0).trim()==="---")for(let d=1;ds.severity==="error").length,i=t.length-n;if(t.length===0){this.statusBarEl.setText("mdbase: no issues");return}this.statusBarEl.setText(`mdbase: ${n} error${n===1?"":"s"}, ${i} warning${i===1?"":"s"}`)}async openIssuesView(){var i;let t=this.app.workspace.getLeavesOfType(qi)[0];if(t){this.app.workspace.revealLeaf(t),t.view.render();return}let n=(i=this.app.workspace.getRightLeaf(!1))!=null?i:this.app.workspace.getLeaf(!0);await n.setViewState({type:qi,active:!0}),this.app.workspace.revealLeaf(n)}async openWorkspace(t="types"){let n=this.app.workspace.getLeavesOfType(jn)[0];if(n){this.app.workspace.revealLeaf(n);let o=n.view;o.showDestination(t),await o.refresh();return}let i=this.app.workspace.getLeaf(!0);await i.setViewState({type:jn,active:!0}),this.app.workspace.revealLeaf(i),i.view.showDestination(t)}refreshWorkspaceViews(t=!1){for(let n of this.app.workspace.getLeavesOfType(jn))n.view.refresh(t)}refreshIssueViews(){this.updateStatusBar();for(let t of this.app.workspace.getLeavesOfType(qi))t.view.render();this.refreshWorkspaceViews()}setFileIssues(t,n){n.length===0?this.issueMap.delete(t):this.issueMap.set(t,n),this.sortedIssuesCache=null,this.refreshIssueViews()}clearFileIssues(t){this.issueMap.has(t)&&(this.issueMap.delete(t),this.sortedIssuesCache=null,this.refreshIssueViews())}moveFileIssues(t,n){let 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())}clearAllPendingSaveValidations(){for(let t of this.pendingSaveValidations.values())window.clearTimeout(t);this.pendingSaveValidations.clear()}clearPendingSaveValidation(t){let n=this.pendingSaveValidations.get(t);n!=null&&(window.clearTimeout(n),this.pendingSaveValidations.delete(t))}scheduleSaveValidation(t){this.clearPendingSaveValidation(t.path);let n=window.setTimeout(()=>{this.pendingSaveValidations.delete(t.path),this.validateFileAndStore(t,"save")},this.saveValidationDebounceMs);this.pendingSaveValidations.set(t.path,n)}isSchemaRelevantPath(t){let n=(0,L.normalizePath)(t);if(n==="mdbase.yaml")return!0;let i=new Set(["_types"]);this.schemaCache&&i.add((0,L.normalizePath)(this.schemaCache.config.settings.types_folder));for(let s of i)if(n===s||n.startsWith(`${s}/`))return!0;return!1}invalidateSchemaCache(){this.schemaCache=null,this.schemaLoadPromise=null}async getConfigAndTypes(t=!1){if(t&&this.invalidateSchemaCache(),this.schemaCache)return this.schemaCache;if(this.schemaLoadPromise)return this.schemaLoadPromise;this.schemaLoadPromise=(async()=>{let n=await ui(this.app.vault);if(!n)return null;let i=await pb(this.app.vault,n);return{config:n,types:i}})();try{let n=await this.schemaLoadPromise;return n&&(this.schemaCache=n),n}finally{this.schemaLoadPromise=null}}async requireConfigAndTypes(t={}){var s,o;let n=(s=t.background)!=null?s:!1,i=await this.getConfigAndTypes((o=t.forceReload)!=null?o:!1);return i?(i.types.size===0&&!n&&new L.Notice(`No types found in ${i.config.settings.types_folder}`),i):(n||new L.Notice("No mdbase.yaml found. Run 'mdbase: Initialize collection' first."),null)}onVaultModify(t){this.isSchemaRelevantPath(t.path)&&(this.invalidateSchemaCache(),this.refreshWorkspaceViews()),this.settings.validateOnSave&&t.extension==="md"&&this.scheduleSaveValidation(t)}onVaultRename(t,n){(this.isSchemaRelevantPath(n)||this.isSchemaRelevantPath(t.path))&&(this.invalidateSchemaCache(),this.refreshWorkspaceViews()),t.extension==="md"&&(this.clearPendingSaveValidation(n),this.moveFileIssues(n,t.path),this.settings.validateOnSave&&this.scheduleSaveValidation(t))}onVaultDelete(t){this.isSchemaRelevantPath(t.path)&&(this.invalidateSchemaCache(),this.refreshWorkspaceViews()),t.extension==="md"&&(this.clearPendingSaveValidation(t.path),this.clearFileIssues(t.path))}onVaultCreate(t){this.isSchemaRelevantPath(t.path)&&(this.invalidateSchemaCache(),this.refreshWorkspaceViews())}async validateFileAndStore(t,n){let i=await this.requireConfigAndTypes({background:n!=="manual"});if(!i)return n!=="manual"&&this.clearFileIssues(t.path),[];let s=await ef(this.app.vault,t,i.config,i.types);return this.setFileIssues(t.path,s),n==="save"&&this.settings.showNoticeOnSave&&s.length>0&&new L.Notice(`mdbase: ${s.length} issue${s.length===1?"":"s"} in ${t.basename}`),s}async initializeCollectionCommand(){if(this.connectSync.assertLocalAuthorityWritable(),this.getMirrorProfile()){new L.Notice("This vault is configured as a mirror. Sync it instead of initializing a local collection.");return}let{created:t}=await db(this.app.vault);if(this.invalidateSchemaCache(),t.length===0){new L.Notice("mdbase collection already initialized.");return}new L.Notice(`Initialized mdbase collection: ${t.join(", ")}`)}async syncHostedCollectionCommand(){var t,n,i,s;if(!this.getMirrorProfile()){await this.openWorkspace("sync");return}try{let o=await this.connectSync.preview(),a=await this.connectSync.sync(o),c=await this.connectSync.status();this.invalidateSchemaCache(),this.refreshWorkspaceViews(!0);let l=((t=c==null?void 0:c.conflicts.length)!=null?t:0)+((n=c==null?void 0:c.local_issues.length)!=null?n:0);new L.Notice(a.status==="stale"?"The sync plan changed before it could apply. Review the new plan in the mdbase workspace.":a.status==="failed"||a.status==="blocked"?`mdbase sync stopped safely: ${(s=(i=a.failure)==null?void 0:i.message)!=null?s:a.status}.`:l?`Sync completed with ${l} item${l===1?"":"s"} needing attention.`:"mdbase sync completed.")}catch(o){new L.Notice(`mdbase sync failed: ${o instanceof Error?o.message:String(o)}`),await this.openWorkspace("sync")}}async createNoteFromTypeCommand(){var d,u;this.connectSync.assertLocalAuthorityWritable();let t=await this.requireConfigAndTypes();if(!t)return;if(t.types.size===0){new L.Notice("No type definitions found.");return}let n=await TC(this.app,Array.from(t.types.values()));if(!n)return;let i=yb(n,t.config),s=gb(n,i);for(let[f,p]of s){let y=`Required field: ${f}`,h=await new yo(this.app,y,(d=p.type)!=null?d:"string").openAndGetValue();if(h==null)return;if(h.trim().length===0){new L.Notice(`Field '${f}' is required.`);return}try{i[f]=tf(h,p)}catch(m){new L.Notice(`Invalid value for ${f}: ${m instanceof Error?m.message:String(m)}`);return}}let o=(u=n.display_name_key)!=null?u:"title";if(i[o]==null){let f=await new yo(this.app,`Optional ${o} (used for filename)`,"").openAndGetValue();f&&f.trim().length>0&&(i[o]=f.trim())}let a=await bb(this.app.vault,n,i),c=await new yo(this.app,"Note path","Relative path in vault",a).openAndGetValue();if(c==null)return;let l=(0,L.normalizePath)(c.trim().length>0?c.trim():a);l.endsWith(".md")||(l=`${l}.md`);try{let f=await wb(this.app.vault,l,i);await this.app.workspace.getLeaf(!0).openFile(f),new L.Notice(`Created note: ${f.path}`),await this.validateFileAndStore(f,"manual")}catch(f){new L.Notice(f instanceof Error?f.message:String(f))}}async validateCurrentNoteCommand(){let t=this.app.workspace.getActiveFile();if(!(t instanceof L.TFile)||t.extension!=="md"){new L.Notice("Open a markdown note first.");return}let n=await this.validateFileAndStore(t,"manual");n.length===0?new L.Notice("No issues in current note."):(new L.Notice(`Found ${n.length} issue${n.length===1?"":"s"} in current note.`),await this.openIssuesView())}async runCollectionValidation(t){var o;let n=await this.requireConfigAndTypes({background:!1});if(!n)return;let i=await mb(this.app.vault,n.config,n.types),s=new Map;for(let a of i){let c=(o=s.get(a.path))!=null?o:[];c.push(a),s.set(a.path,c)}if(this.issueMap=s,this.sortedIssuesCache=null,this.refreshIssueViews(),t)if(i.length===0)new L.Notice("Collection validation passed with no issues.");else{let a=i.filter(l=>l.severity==="error").length,c=i.length-a;new L.Notice(`Collection validation: ${a} error(s), ${c} warning(s)`),await this.openIssuesView()}}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){let s=n.name.trim();if(!s)throw new Error("Type name is required.");if(!t.spec_version.startsWith("0.3.")||n.specProfile!=="v0.3")throw new Error("mdbase v0.2 type definitions are read-only. Migrate the collection first.");let o=mo(n),a=n.body.trim()||`# ${s} +`;var qn="mdbase-workspace-view",_M=["string","integer","number","boolean","date","datetime","time","enum","link","list","object","any"];function Dn(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function gp(r){return JSON.parse(JSON.stringify(r))}function C0(r){return typeof r.type=="string"?r.type:"any"}function bM(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 M0(r,e,t){Object.defineProperty(r,e,{configurable:!0,enumerable:!0,writable:!0,value:t})}function wM(r,e){if(!r)return["A new type definition will be created."];let t=[];r.name!==e.name&&t.push(`Rename type from ${r.name} to ${e.name}.`),(r.matchPathGlob!==e.matchPathGlob||r.matchFieldsPresent!==e.matchFieldsPresent||r.matchWhere!==e.matchWhere)&&t.push("Membership rules changed; different records may match this type.");let n=new Map(r.fields.map(c=>[c.name,c])),i=new Map(e.fields.map(c=>[c.name,c])),s=[...n.keys()].filter(c=>!i.has(c)),o=[...i.keys()].filter(c=>!n.has(c));o.length&&t.push(`Add ${o.length} field${o.length===1?"":"s"}: ${o.join(", ")}.`),s.length&&t.push(`Remove ${s.length} field${s.length===1?"":"s"}: ${s.join(", ")}.`);let a=[...i.entries()].filter(([c,l])=>{var d;return l.definition.required===!0&&((d=n.get(c))==null?void 0:d.definition.required)!==!0}).map(([c])=>c);return a.length&&t.push(`New required fields may invalidate records: ${a.join(", ")}.`),t.length||t.push("Metadata, schema details, or documentation changed."),t}function Ot(r,e,t,n,i={}){var l;let s=r.createDiv({cls:"mdbase-form-row"}),o=s.createEl("label",{text:e}),a=`mdbase-${Math.random().toString(36).slice(2)}`;o.htmlFor=a,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.value=t,c.placeholder=(l=i.placeholder)!=null?l:"",c.addEventListener("input",()=>n(c.value)),c}function Me(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 vM(r){if(r<1e3)return String(r);let e=r<1e4?1:0;return`${(r/1e3).toFixed(e)}k`}var Bc=class extends Ee.ItemView{constructor(t,n){super(t);this.host=n;this.destination="types";this.editorMode="design";this.schema=null;this.query="";this.selectedPath=null;this.model=null;this.originalModel=null;this.yamlDraft="";this.dirty=!1;this.busy=!1;this.migrationPlan=null;this.allowLossy=!1;this.mirrorStatus=null;this.mirrorPreview=null;this.mirrorProgress=null;this.transientMessage="";this.issueQuery="";this.issueSeverity="all";this.issueLimit=250;this.enrollmentVerification="";this.enrollmentAbort=null}getViewType(){return qn}getDisplayText(){return"mdbase"}getIcon(){return qi}async onOpen(){this.containerEl.addClass("mdbase-workspace"),await this.refresh(!0)}async onClose(){var t;(t=this.enrollmentAbort)==null||t.abort(),this.enrollmentAbort=null}async refresh(t=!1){try{this.schema=await this.host.loadWorkspaceSchema(t),this.selectedPath&&!this.typeEntries().some(n=>n.filePath===this.selectedPath)&&(this.selectedPath=null,this.model=null,this.originalModel=null),!this.selectedPath&&this.typeEntries().length&&!Ee.Platform.isMobile&&(this.selectedPath=this.typeEntries()[0].filePath),this.selectedPath&&(!this.model||t)&&await this.selectType(this.selectedPath,!1),this.destination==="sync"&&await this.refreshMirrorStatus(),this.render()}catch(n){this.transientMessage=n instanceof Error?n.message:String(n),this.render()}}showDestination(t){this.destination=t,t==="sync"?this.refreshMirrorStatus().then(()=>this.render()):this.render()}typeEntries(){return this.schema?[...this.schema.types.values()].sort((t,n)=>t.name.localeCompare(n.name)):[]}render(){let t=this.containerEl;t.empty(),t.addClass("mdbase-workspace");let n=t.createDiv({cls:"mdbase-shell"});this.renderTopbar(n),this.transientMessage&&n.createDiv({cls:"mdbase-inline-message",text:this.transientMessage}).setAttr("role","status");let i=n.createDiv({cls:"mdbase-workspace-content"});this.destination==="types"?this.renderTypes(i):this.destination==="sync"?this.renderSync(i):this.renderIssues(i)}renderTopbar(t){let n=t.createDiv({cls:"mdbase-topbar"}),i=n.createDiv({cls:"mdbase-identity"}),s=i.createSpan({cls:"mdbase-mark"});s.setAttr("aria-hidden","true"),(0,Ee.setIcon)(s,qi),i.createSpan({cls:"mdbase-title",text:"mdbase"});let o=n.createDiv({cls:"mdbase-nav"});o.setAttr("role","tablist");for(let[a,c]of[["types","Types"],["sync","Sync"],["issues","Issues"]]){let l=o.createEl("button",{text:c});if(l.addClass("mdbase-nav-button"),l.setAttr("role","tab"),l.setAttr("aria-selected",String(this.destination===a)),this.destination===a&&l.addClass("is-active"),a==="issues"&&this.host.getIssues().length){let d=this.host.getIssues().length;l.createSpan({cls:"mdbase-count",text:vM(d)}).setAttr("title",`${d} issues`)}l.onclick=()=>this.showDestination(a)}}renderTypes(t){if(!this.schema){let i=t.createDiv({cls:"mdbase-empty-state"});i.createEl("h2",{text:"Start an mdbase collection"}),i.createEl("p",{text:"Initialize this vault as a local v0.3 collection, or use Sync to connect an empty vault to a collection authority."});let s=i.createDiv({cls:"mdbase-actions"}),o=s.createEl("button",{text:"Initialize local collection"});o.addClass("mod-cta"),o.disabled=this.busy||this.host.getMirrorProfile()!==null,o.onclick=()=>void this.perform(async()=>{await this.host.initializeCollection(),await this.refresh(!0)});let a=s.createEl("button",{text:"Connect collection authority"});a.onclick=()=>this.showDestination("sync");return}this.schema.config.spec_version.startsWith("0.2.")&&this.renderLegacyBanner(t);let n=t.createDiv({cls:"mdbase-types-layout"});this.model&&n.addClass("has-selection"),this.renderTypeList(n),this.renderTypeEditor(n)}renderLegacyBanner(t){var o;let n=t.createDiv({cls:"mdbase-legacy-banner"}),i=n.createDiv();i.createEl("strong",{text:`mdbase ${(o=this.schema)==null?void 0:o.config.spec_version} compatibility mode`}),i.createEl("p",{text:"Types are readable and validation remains available, but authoring is disabled until a reviewed v0.3 migration."});let s=n.createEl("button",{text:this.migrationPlan?"Review migration":"Analyze migration"});s.disabled=this.busy||this.host.getMirrorProfile()!==null,s.onclick=()=>void this.perform(async()=>{this.migrationPlan=await this.host.analyzeMigration(),this.render()}),this.host.getMirrorProfile()&&n.createDiv({cls:"mdbase-form-description",text:"Hosted resources must be migrated at the collection authority."}),this.migrationPlan&&this.renderMigrationReview(t,this.migrationPlan)}renderMigrationReview(t,n){let i=t.createDiv({cls:"mdbase-migration-review"}),s=i.createDiv({cls:"mdbase-section-header"});s.createEl("h3",{text:"Migration review"}),s.createSpan({cls:"mdbase-spec-badge",text:`${n.sourceVersion} \u2192 ${n.targetVersion}`});let o=i.createDiv({cls:"mdbase-status-list"});Me(o,"Files replaced",String(n.operations.length)),Me(o,"Type definitions",String(n.typeSummaries.length)),Me(o,"Record reads verified",String(n.recordsVerified)),n.recordsSkipped&&Me(o,"Records skipped",String(n.recordsSkipped)),Me(o,"Record files rewritten","0"),Me(o,"Recovery backup",n.backupLocation);let a=i.createDiv({cls:"mdbase-review-list"});n.diagnostics.length||a.createDiv({cls:"mdbase-review-ok",text:"No migration diagnostics."});for(let u of n.diagnostics.slice(0,250)){let f=a.createDiv({cls:"mdbase-review-item"});f.setAttr("data-severity",u.severity),f.createDiv({cls:"mdbase-review-code",text:`${u.severity} \xB7 ${u.path}`}),f.createDiv({text:u.message})}if(n.diagnostics.length>250&&a.createDiv({cls:"mdbase-form-description",text:`Showing 250 of ${n.diagnostics.length} diagnostics.`}),!n.applicable){let u=i.createEl("label",{cls:"mdbase-consent"}),f=u.createEl("input",{type:"checkbox"});f.checked=this.allowLossy,f.onchange=()=>{this.allowLossy=f.checked,this.render()},u.createSpan({text:"I reviewed the lossy diagnostics and want to apply this migration."})}let c=i.createDiv({cls:"mdbase-actions"}),l=c.createEl("button",{text:"Apply migration"});l.addClass("mod-warning"),l.disabled=this.busy||!n.applicable&&!this.allowLossy,l.onclick=()=>void this.perform(async()=>{await this.host.applyMigration(n,this.allowLossy),this.migrationPlan=null,this.allowLossy=!1,this.model=null,this.originalModel=null,await this.refresh(!0)});let d=c.createEl("button",{text:"Close review"});d.onclick=()=>{this.migrationPlan=null,this.render()}}renderTypeList(t){var d,u,f,p;let n=t.createDiv({cls:"mdbase-type-list-pane"}),i=n.createDiv({cls:"mdbase-pane-header"});i.createEl("h2",{text:"Types"});let s=i.createEl("button");s.setAttr("aria-label","Create type"),(0,Ee.setIcon)(s,"plus"),s.disabled=((u=(d=this.schema)==null?void 0:d.config.spec_version.startsWith("0.2."))!=null?u:!0)||((f=this.host.getMirrorProfile())==null?void 0:f.mode)==="read_only",s.onclick=()=>this.createType();let o=n.createEl("input",{type:"search"});o.addClass("mdbase-type-search"),o.placeholder="Search types",o.setAttr("aria-label","Search types"),o.value=this.query,o.oninput=()=>{this.query=o.value,this.render();let y=this.containerEl.querySelector(".mdbase-type-search");y==null||y.focus(),y==null||y.setSelectionRange(y.value.length,y.value.length)};let a=n.createDiv({cls:"mdbase-type-list"}),c=this.query.trim().toLowerCase(),l=this.typeEntries().filter(y=>{var h;return`${y.name} ${(h=y.description)!=null?h:""} ${y.filePath}`.toLowerCase().includes(c)});if(!l.length){a.createDiv({cls:"mdbase-empty-list",text:c?"No matching types.":"No type definitions."});return}for(let y of l){let h=a.createEl("button",{cls:"mdbase-type-row"});y.filePath===this.selectedPath&&h.addClass("is-active"),h.setAttr("aria-current",y.filePath===this.selectedPath?"true":"false"),h.createSpan({cls:"mdbase-type-name",text:y.name}),h.createSpan({cls:"mdbase-type-meta",text:`${Object.keys(y.fields).length} fields \xB7 ${(p=y.specProfile)!=null?p:"v0.2"}`}),h.onclick=()=>void this.selectType(y.filePath)}}renderTypeEditor(t){var h,m,g,_;let n=t.createDiv({cls:"mdbase-type-editor-pane"});if(!this.model){let w=n.createDiv({cls:"mdbase-empty-state"});w.createEl("h2",{text:"Choose a type"}),w.createEl("p",{text:"Select a type definition from the list to inspect or edit it."});return}let i=((h=this.host.getMirrorProfile())==null?void 0:h.mode)==="read_only",s=this.model.specProfile==="v0.2"||i||!!this.model.readOnlyReason,o=(m=this.model.readOnlyReason)!=null?m:i?"This mirror has read-only access. Re-enroll it with write access before editing types.":"This v0.2 type is read-only. Review and apply a collection migration before editing.",a=n.createDiv({cls:"mdbase-editor-header"}),c=a.createEl("button",{cls:"mdbase-mobile-back"});c.setAttr("aria-label","Back to type list"),(0,Ee.setIcon)(c,"arrow-left"),c.onclick=()=>{if(this.dirty){new Ee.Notice("Save or discard the current type changes before going back.");return}this.selectedPath=null,this.model=null,this.originalModel=null,this.render()};let l=a.createDiv(),d=l.createDiv({cls:"mdbase-editor-title-line"});d.createEl("h2",{text:this.model.name||"Untitled type"}),d.createSpan({cls:"mdbase-spec-badge",text:(g=this.model.specProfile)!=null?g:"v0.2"}),this.dirty&&d.createSpan({cls:"mdbase-dirty",text:"Unsaved"}),l.createDiv({cls:"mdbase-editor-path",text:(_=this.selectedPath)!=null?_:"New type"});let u=a.createDiv({cls:"mdbase-editor-actions"});if(this.selectedPath){let w=u.createEl("button",{text:"Open source"});w.onclick=()=>void this.host.openFileByPath(this.selectedPath)}let f=u.createEl("button",{text:"Save"});f.addClass("mod-cta"),f.disabled=s||!this.dirty||this.busy,f.onclick=()=>void this.saveCurrentType(),s&&n.createDiv({cls:"mdbase-readonly-note",text:o});let p=n.createDiv({cls:"mdbase-mode-switch"});p.setAttr("role","tablist");for(let[w,x]of[["design","Design"],["yaml","YAML"]]){let v=p.createEl("button",{text:x});v.setAttr("role","tab"),v.setAttr("aria-selected",String(this.editorMode===w)),this.editorMode===w&&v.addClass("is-active"),v.onclick=()=>this.switchEditorMode(w)}let y=n.createDiv({cls:"mdbase-editor-document"});this.editorMode==="design"?this.renderDesignEditor(y,this.model,s):this.renderYamlEditor(y,s)}renderDesignEditor(t,n,i){let s=t.createEl("section",{cls:"mdbase-editor-section"});s.createEl("h3",{text:"Identity"});let o=Ot(s,"Name",n.name,P=>{n.name=P,this.markDirty()},{description:"Stable type name used by collection records."});o.disabled=i;let a=Ot(s,"Description",n.description,P=>{n.description=P,this.markDirty()},{multiline:!0});a.disabled=i;let c=Ot(s,"Display field",n.displayNameKey,P=>{n.displayNameKey=P,this.markDirty()},{placeholder:"title"});c.disabled=i;let l=s.createEl("label",{cls:"mdbase-checkbox-row"}),d=l.createEl("input",{type:"checkbox"});d.checked=n.strictMode===!0,d.disabled=i,d.onchange=()=>{n.strictMode=d.checked,this.markDirty()},l.createSpan({text:"Reject undeclared fields"});let u=t.createEl("section",{cls:"mdbase-editor-section"});u.createEl("h3",{text:"Membership"});let f=Ot(u,"Path glob",n.matchPathGlob,P=>{n.matchPathGlob=P,this.markDirty()},{placeholder:"Projects/**/*.md"});f.disabled=i;let p=Ot(u,"Fields present",n.matchFieldsPresent,P=>{n.matchFieldsPresent=P,this.markDirty()},{description:"Comma-separated frontmatter keys."});p.disabled=i;let y=Ot(u,"Where",n.matchWhere,P=>{n.matchWhere=P,this.markDirty()},{multiline:!0,description:"YAML predicate, including contains and nested equality conditions.",placeholder:`tags: + contains: task`});y.disabled=i;let h=t.createEl("section",{cls:"mdbase-editor-section"}),m=h.createDiv({cls:"mdbase-section-header"});m.createEl("h3",{text:"Fields"});let g=m.createEl("button",{text:"Add field"});g.disabled=i,g.onclick=()=>{n.fields.push({name:"",definition:{type:"string"}}),this.markDirty(!0)};let _=h.createDiv({cls:"mdbase-fields"});for(let[P,O]of n.fields.entries())this.renderFieldRow(_,O,P,i);n.fields.length||_.createDiv({cls:"mdbase-empty-list",text:"No fields declared."});let w=t.createEl("section",{cls:"mdbase-editor-section"});w.createEl("h3",{text:"Placement"});let x=Ot(w,"Path pattern",n.pathPattern,P=>{n.pathPattern=P,this.markDirty()},{placeholder:"Notes/{title}.md"});x.disabled=i;let v=t.createEl("section",{cls:"mdbase-editor-section mdbase-change-review"});if(v.createEl("h3",{text:"Change review"}),!this.dirty)v.createEl("p",{text:"No pending changes."});else{let P=v.createEl("ul");for(let O of wM(this.originalModel,n))P.createEl("li",{text:O})}}renderFieldRow(t,n,i,s){this.renderFieldDefinition(t,n.definition,{name:n.name,nameLabel:`Field ${i+1} name`,onNameInput:o=>{n.name=o,this.markDirty()},required:n.definition.required===!0,onRequiredChange:o=>{n.definition.required=o,this.markDirty()},onRemove:()=>{var o;(o=this.model)==null||o.fields.splice(i,1),this.markDirty(!0)},readOnly:s,depth:0})}renderFieldDefinition(t,n,i){var d;let s=t.createDiv({cls:"mdbase-field-node"});s.setAttr("data-depth",String(i.depth));let o=s.createDiv({cls:"mdbase-field-row"});if(i.staticLabel)o.createDiv({cls:"mdbase-field-role",text:i.staticLabel});else{let u=o.createEl("input",{type:"text",cls:"mdbase-field-name-control"});u.setAttr("aria-label",i.nameLabel),u.placeholder="fieldName",u.value=(d=i.name)!=null?d:"",u.disabled=i.readOnly,i.onNameInput&&(u.oninput=()=>{var f;return(f=i.onNameInput)==null?void 0:f.call(i,u.value)}),i.onNameCommit&&(u.onchange=()=>{var f;return(f=i.onNameCommit)==null?void 0:f.call(i,u.value,u)})}let a=o.createEl("select",{cls:"mdbase-field-type-control"});a.setAttr("aria-label",`${i.name||i.staticLabel||"Field"} type`);for(let u of _M){let f=u==="any"?"Any value":u[0].toUpperCase()+u.slice(1);a.createEl("option",{value:u,text:f})}a.value=C0(n),a.disabled=i.readOnly,a.onchange=()=>{n.type=a.value,a.value==="list"&&!Dn(n.items)&&(n.items={type:"string"}),a.value==="object"&&!Dn(n.fields)&&(n.fields={}),a.value==="enum"&&!Array.isArray(n.values)&&(n.values=[]),this.markDirty(!0)};let c=o.createEl("input",{type:"text",cls:"mdbase-field-description-control"});if(c.setAttr("aria-label",`${i.name||i.staticLabel||"Field"} description`),c.placeholder="Description",c.value=typeof n.description=="string"?n.description:"",c.disabled=i.readOnly,c.oninput=()=>{c.value?n.description=c.value:delete n.description,this.markDirty()},i.onRequiredChange){let u=o.createEl("label",{cls:"mdbase-field-required"}),f=u.createEl("input",{type:"checkbox"});f.checked=i.required===!0,f.disabled=i.readOnly,f.onchange=()=>{var p;return(p=i.onRequiredChange)==null?void 0:p.call(i,f.checked)},u.createSpan({text:"Required"})}if(i.onRemove){let u=o.createEl("button",{cls:"mdbase-field-remove"});u.setAttr("aria-label",`Remove ${i.name||i.staticLabel||"field"}`),(0,Ee.setIcon)(u,"trash-2"),u.disabled=i.readOnly,u.onclick=i.onRemove}let l=C0(n);l==="enum"&&this.renderEnumFieldDetails(s,n,i),l==="link"&&this.renderLinkFieldDetails(s,n,i),l==="list"&&this.renderListFieldDetails(s,n,i),l==="object"&&this.renderObjectFieldDetails(s,n,i)}renderEnumFieldDetails(t,n,i){let s=t.createDiv({cls:"mdbase-field-details mdbase-field-options"}),o=s.createEl("label",{text:"Allowed values"}),a=s.createEl("input",{type:"text"});a.setAttr("aria-label",`${i.name||i.staticLabel||"Enum"} allowed values`),a.placeholder="draft, published, archived",a.value=Array.isArray(n.values)?n.values.map(String).join(", "):"",a.disabled=i.readOnly,a.oninput=()=>{n.values=a.value.split(",").map(c=>c.trim()).filter(Boolean),this.markDirty()},o.htmlFor=a.id=`mdbase-${Math.random().toString(36).slice(2)}`}renderLinkFieldDetails(t,n,i){let s=t.createDiv({cls:"mdbase-field-details mdbase-field-options"}),o=s.createEl("label",{text:"Target type"}),a=s.createEl("input",{type:"text"});a.setAttr("aria-label",`${i.name||i.staticLabel||"Link"} target type`),a.placeholder="Any type",a.value=typeof n.target=="string"?n.target:"",a.disabled=i.readOnly,a.oninput=()=>{a.value.trim()?n.target=a.value.trim():delete n.target,this.markDirty()},o.htmlFor=a.id=`mdbase-${Math.random().toString(36).slice(2)}`;let c=s.createEl("label",{cls:"mdbase-field-required"}),l=c.createEl("input",{type:"checkbox"});l.checked=n.validate_exists===!0,l.disabled=i.readOnly,l.onchange=()=>{n.validate_exists=l.checked,this.markDirty()},c.createSpan({text:"Validate target exists"})}renderListFieldDetails(t,n,i){let s=t.createDiv({cls:"mdbase-field-children"});s.createDiv({cls:"mdbase-field-children-label",text:"List items"});let o=Dn(n.items)?n.items:{type:"any"};!Dn(n.items)&&!i.readOnly&&(n.items=o),this.renderFieldDefinition(s,o,{staticLabel:"Item",nameLabel:"List item",readOnly:i.readOnly,depth:i.depth+1})}renderObjectFieldDetails(t,n,i){let s=t.createDiv({cls:"mdbase-field-children"}),o=s.createDiv({cls:"mdbase-field-children-header"});o.createDiv({cls:"mdbase-field-children-label",text:"Object fields"});let a=o.createEl("button",{text:"Add nested field"});a.disabled=i.readOnly;let c=Dn(n.fields)?n.fields:{};!Dn(n.fields)&&!i.readOnly&&(n.fields=c),a.onclick=()=>{let u=bM(c);M0(c,u,{type:"string"}),this.markDirty(!0)};let l=s.createDiv({cls:"mdbase-nested-fields"}),d=Object.entries(c).filter(u=>Dn(u[1]));if(!d.length){l.createDiv({cls:"mdbase-empty-list",text:"No nested fields."});return}for(let[u,f]of d){let p=u;this.renderFieldDefinition(l,f,{name:p,nameLabel:`${p} nested field name`,onNameCommit:(y,h)=>{let m=y.trim();if(!m){new Ee.Notice("Nested field name is required."),h.value=p;return}if(m!==p&&Object.prototype.hasOwnProperty.call(c,m)){new Ee.Notice(`Nested field already exists: ${m}`),h.value=p;return}m!==p&&(delete c[p],M0(c,m,f),p=m,this.markDirty())},required:f.required===!0,onRequiredChange:y=>{f.required=y,this.markDirty()},onRemove:()=>{delete c[p],this.markDirty(!0)},readOnly:i.readOnly,depth:i.depth+1})}}renderYamlEditor(t,n){let i=t.createEl("section",{cls:"mdbase-editor-section mdbase-yaml-section"});i.createEl("h3",{text:"Canonical type document"}),i.createEl("p",{cls:"mdbase-form-description",text:"Unknown v0.3 extensions are preserved. Invalid YAML is never normalized or saved."});let s=i.createEl("textarea",{cls:"mdbase-yaml-editor"});s.setAttr("aria-label","Type definition YAML"),s.value=this.yamlDraft,s.disabled=n,s.spellcheck=!1,s.oninput=()=>{this.yamlDraft=s.value,this.markDirty(!1)}}renderSync(t){var y,h,m,g,_,w,x,v,P,O;let n=t.createDiv({cls:"mdbase-sync-document"}),i=n.createDiv({cls:"mdbase-document-header"});i.createEl("h2",{text:"Sync"}),i.createEl("p",{text:"Connect this vault to a collection authority and keep ordinary Markdown mirrored locally."});let s=this.host.getMirrorProfile();if(!s){this.renderEnrollment(n);return}let o=n.createEl("section",{cls:"mdbase-editor-section"});o.createEl("h3",{text:"Collection authority"});let a=o.createDiv({cls:"mdbase-status-list"});if(Me(a,"Name",s.name),Me(a,"Collection",s.collectionId),Me(a,"Access",s.mode==="read_write"?"Read and write":"Read only"),Me(a,"Provider",s.syncUrl),Me(a,"State",(h=(y=this.mirrorStatus)==null?void 0:y.state.replace(/_/g," "))!=null?h:"Checking"),Me(a,"Last synced",(g=(m=this.mirrorStatus)==null?void 0:m.last_synced_at)!=null?g:"Never"),this.mirrorProgress){let $=this.mirrorProgress.total,R=o.createEl("progress");R.max=$!=null?$:1,R.value=$==null?0:this.mirrorProgress.completed,$==null&&R.removeAttribute("value"),o.createDiv({cls:"mdbase-progress-label",text:`${this.mirrorProgress.phase}: ${this.mirrorProgress.completed}${$==null?"":` of ${$}`}`});let S=o.createEl("button",{text:"Stop safely"});S.onclick=()=>{this.host.connectSync.cancelSync(),this.transientMessage="Stopping after the current action boundary\u2026",this.render()}}let c=o.createDiv({cls:"mdbase-actions"}),l=c.createEl("button",{text:"Preview"});l.disabled=this.busy,l.onclick=()=>void this.perform(async()=>{this.mirrorPreview=await this.host.connectSync.preview(),this.transientMessage=this.mirrorPreview.entries.length?"Review the engine plan below, then sync when ready.":"No content effects are needed; confirm the sync checkpoint when ready.",this.render()});let d=(w=(_=this.mirrorPreview)==null?void 0:_.plan.actions.filter($=>$.command!=="advance_checkpoint").length)!=null?w:0,u=((v=(x=this.mirrorPreview)==null?void 0:x.plan.summary.blocking_issues)!=null?v:0)>0,f=c.createEl("button",{text:this.mirrorPreview?d?`Sync ${d} ${d===1?"outcome":"outcomes"}`:"Confirm sync checkpoint":"Review before syncing"});f.addClass("mod-cta"),f.disabled=this.busy||!this.mirrorPreview||u,f.onclick=()=>void this.perform(async()=>{var R,S;let $=await this.host.connectSync.sync(this.mirrorPreview,U=>{this.mirrorProgress=U,this.render()});this.mirrorStatus=await this.host.connectSync.status(),this.mirrorPreview=await this.host.connectSync.preview(),this.mirrorProgress=null,this.transientMessage=$.status==="applied"?"Sync completed and the local checkpoint was verified.":$.status==="attention"?"Sync checkpointed completed actions and recorded the items that need attention.":$.status==="cancelled"?`Sync stopped safely after ${$.applied} actions; ${$.pending} remain pending.`:$.status==="stale"?"The reviewed plan became stale. Review the new engine plan before syncing again.":`Sync stopped at a durable action boundary: ${(S=(R=$.failure)==null?void 0:R.message)!=null?S:$.status}.`,await this.refresh(!0)}),this.mirrorPreview&&this.renderMirrorPreview(n,this.mirrorPreview),(P=this.mirrorStatus)!=null&&P.conflicts.length&&this.renderConflicts(n,this.mirrorStatus),(O=this.mirrorStatus)!=null&&O.local_issues.length&&this.renderLocalMirrorIssues(n,this.mirrorStatus);let p=n.createEl("section",{cls:"mdbase-editor-section"});p.createEl("h3",{text:"Mirror ownership"}),p.createEl("p",{text:"Use this plugin as the only sync owner for this vault. Obsidian protects concurrent operations inside the app; a separate desktop mirror process cannot share that mobile-safe lease."})}renderEnrollment(t){if(this.schema||this.host.connectSync.getAdoptionMarker()){this.renderLocalAdoption(t);return}let n=t.createEl("section",{cls:"mdbase-editor-section mdbase-enrollment"});if(n.createEl("h3",{text:"Connect collection authority"}),n.createEl("p",{text:"Connect will open an approval page. Credentials are stored in Obsidian's secret store and never written into this vault."}),this.enrollmentVerification){let u=n.createDiv({cls:"mdbase-approval-link"});u.createSpan({text:"Approval page: "});let f=u.createEl("a",{text:"Open Connect",href:this.enrollmentVerification});f.setAttr("target","_blank"),f.setAttr("rel","noopener noreferrer")}let i="https://connect.mdbase.dev",s="Obsidian",o="",a="read_write";Ot(n,"Connect URL",i,u=>{i=u},{placeholder:"https://connect.mdbase.dev"}),Ot(n,"Mirror name",s,u=>{s=u}),Ot(n,"Collection ID",o,u=>{o=u},{description:"Optional. Leave blank to choose during approval."});let c=n.createDiv({cls:"mdbase-form-row"});c.createEl("label",{text:"Access"});let l=c.createEl("select");l.createEl("option",{value:"read_write",text:"Read and write"}),l.createEl("option",{value:"read_only",text:"Read only"}),l.value=a,l.onchange=()=>{a=l.value==="read_only"?"read_only":"read_write"};let d=n.createEl("button",{text:"Open Connect approval"});d.addClass("mod-cta"),d.disabled=this.busy,d.onclick=()=>void this.perform(async()=>{var f;(f=this.enrollmentAbort)==null||f.abort();let u=new AbortController;this.enrollmentAbort=u;try{await this.host.connectSync.enroll({controlUrl:i,mirrorName:s,mode:a,...o.trim()?{collectionId:o.trim()}:{}},{signal:u.signal,onVerification:p=>{this.enrollmentVerification=p.verificationUri,this.transientMessage="Approve the mirror in the Connect page. This view will keep waiting securely.",window.open(p.verificationUri,"_blank","noopener,noreferrer"),this.render()},onStatus:p=>{this.transientMessage=p.state==="waiting_for_approval"?"Waiting for approval in Connect\u2026":`Connect is retrying enrollment (attempt ${p.attempt}).`,this.render()}}),this.enrollmentVerification="",this.transientMessage="Mirror enrolled. Preview before the first sync.",await this.refreshMirrorStatus(),this.render()}finally{this.enrollmentAbort===u&&(this.enrollmentAbort=null)}})}renderLocalAdoption(t){var d,u;let n=this.host.connectSync.getAdoptionMarker(),i=t.createEl("section",{cls:"mdbase-editor-section mdbase-enrollment"});i.createEl("h3",{text:"Host this local collection"}),i.createEl("p",{text:n?"This vault has a durable adoption checkpoint. Resume it without creating another hosted collection.":"Hosted mdbase will adopt an exact snapshot and become the collection authority. This vault will then continue as a read-write mirror."});let s=this.enrollmentVerification||(n==null?void 0:n.session.verificationUri);if(s){let f=i.createDiv({cls:"mdbase-approval-link"});f.createSpan({text:"Approval page: "});let p=f.createEl("a",{text:"Open Connect",href:s});p.setAttr("target","_blank"),p.setAttr("rel","noopener noreferrer")}let o=(d=n==null?void 0:n.session.controlUrl)!=null?d:"https://connect.mdbase.dev",a=(u=n==null?void 0:n.session.requested.mirrorName)!=null?u:"Obsidian";if(!n)Ot(i,"Connect URL",o,f=>{o=f},{placeholder:"https://connect.mdbase.dev"}),Ot(i,"Mirror name",a,f=>{a=f});else{let f=i.createDiv({cls:"mdbase-status-list"});Me(f,"Collection",n.session.requested.collectionId),Me(f,"Phase",n.phase.replace(/_/g," ")),Me(f,"Connect",n.session.controlUrl)}let c=i.createDiv({cls:"mdbase-inline-message"});c.createEl("strong",{text:"Authority cut-over: "}),c.appendText("once final staging begins, plugin-managed local edits pause until hosted activation is confirmed. The checkpoint survives app restarts and uncertain network responses.");let l=i.createEl("button",{text:n?"Resume adoption":"Approve and host collection"});if(l.addClass("mod-cta"),l.disabled=this.busy,l.onclick=()=>void this.perform(async()=>{var h;(h=this.enrollmentAbort)==null||h.abort();let f=new AbortController;this.enrollmentAbort=f;let p=m=>{this.enrollmentVerification=m.verificationUri,this.transientMessage="Approve the authority move in Connect, then return here. This checkpoint is safe to resume.",this.render()},y=m=>{this.transientMessage=m.state==="waiting_for_approval"?"Waiting for authority-move approval in Connect\u2026":`Connect is retrying (attempt ${m.attempt}).`,this.render()};try{n?await this.host.connectSync.resumeAdoption({signal:f.signal,onVerification:p,onStatus:y}):await this.host.connectSync.adoptLocalCollection({controlUrl:o,mirrorName:a},{signal:f.signal,onVerification:p,onStatus:y}),this.enrollmentVerification="",this.transientMessage="Hosted mdbase is authoritative and this vault is now its read-write mirror.",await this.refresh(!0)}finally{this.enrollmentAbort===f&&(this.enrollmentAbort=null)}}),n&&!["activating","adopted"].includes(n.phase)){let f=i.createEl("button",{text:"Cancel adoption"});f.disabled=this.busy,f.onclick=()=>void this.perform(async()=>{await this.host.connectSync.cancelAdoption(),this.enrollmentVerification="",this.transientMessage="Collection adoption cancelled. This vault remains the local authority.",await this.refresh(!0)})}}renderMirrorPreview(t,n){let i=t.createEl("section",{cls:"mdbase-editor-section"});i.createEl("h3",{text:"Sync preview"});let s=i.createDiv({cls:"mdbase-status-list"});if(Me(s,"Download documents",String(n.download_documents)),Me(s,"Upload documents",String(n.upload_documents)),Me(s,"Unchanged documents",String(n.unchanged_documents)),Me(s,"Plan",n.plan.fingerprint),n.entries.length){let o=i.createEl("ul");for(let a of n.entries.slice(0,200))o.createEl("li",{text:`${a.direction==="attention"?"Attention":a.direction}: ${a.path} \u2014 ${a.detail}`})}if(n.collisions.length){i.createDiv({cls:"mdbase-inline-error",text:`${n.collisions.length} path collision${n.collisions.length===1?"":"s"} must be resolved before sync.`});let o=i.createEl("ul");for(let a of n.collisions.slice(0,100))o.createEl("li",{text:a})}if(n.local_issues.length){i.createDiv({cls:"mdbase-inline-error",text:`${n.local_issues.length} local file${n.local_issues.length===1?"":"s"} cannot be uploaded until its frontmatter is fixed.`});let o=i.createEl("ul");for(let a of n.local_issues.slice(0,100))o.createEl("li",{text:`${a.path}: ${a.message}`})}}renderConflicts(t,n){var s;let i=t.createEl("section",{cls:"mdbase-editor-section"});i.createEl("h3",{text:"Conflicts"});for(let o of n.conflicts){let a=i.createDiv({cls:"mdbase-conflict-row"}),c=a.createDiv();c.createEl("strong",{text:(s=o.path)!=null?s:o.record_id}),c.createDiv({text:o.message});let l=a.createDiv({cls:"mdbase-actions"});for(let d of["local","remote"]){let u=l.createEl("button",{text:d==="local"?"Keep local":"Use remote"});u.disabled=this.busy,u.onclick=()=>void this.perform(async()=>{this.mirrorStatus=await this.host.connectSync.resolveConflict(o.record_id,d),this.render()})}}}renderLocalMirrorIssues(t,n){let i=t.createEl("section",{cls:"mdbase-editor-section"});i.createEl("h3",{text:"Local files needing attention"}),i.createEl("p",{text:"These files remain untouched and unsynced. Other valid Markdown continues to synchronize."});for(let s of n.local_issues){let o=i.createDiv({cls:"mdbase-conflict-row"}),a=o.createDiv();a.createEl("strong",{text:s.path}),a.createDiv({text:s.message});let l=o.createDiv({cls:"mdbase-actions"}).createEl("button",{text:"Open file"});l.disabled=this.busy,l.onclick=()=>void this.host.openFileByPath(s.path)}}renderIssues(t){var g;let n=t.createDiv({cls:"mdbase-issues-document"}),i=this.host.getIssues(),s=new Set(i.map(_=>_.path)).size,o=n.createDiv({cls:"mdbase-document-header"}),a=o.createDiv();a.createEl("h2",{text:"Issues"}),a.createEl("p",{text:i.length?`${i.length.toLocaleString()} validation issues in ${s.toLocaleString()} files.`:"The collection has no current validation issues."});let c=o.createEl("button",{text:"Validate collection"});c.disabled=this.busy,c.onclick=()=>void this.perform(async()=>{await this.host.validateCollection(),this.render()});let l=n.createDiv({cls:"mdbase-issue-controls"}),d=l.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.render()};let u=l.createEl("input",{type:"search"});u.setAttr("aria-label","Filter issues"),u.placeholder="Filter by path, code, field, or message",u.value=this.issueQuery,u.oninput=()=>{this.issueQuery=u.value,this.issueLimit=250,this.render();let _=this.containerEl.querySelector(".mdbase-issue-controls input[type='search']");_==null||_.focus(),_==null||_.setSelectionRange(_.value.length,_.value.length)};let f=this.issueQuery.trim().toLowerCase(),p=i.filter(_=>{var w;return this.issueSeverity!=="all"&&_.severity!==this.issueSeverity?!1:f?`${_.path} ${_.code} ${(w=_.field)!=null?w:""} ${_.message}`.toLowerCase().includes(f):!0}),y=new Set(p.map(_=>_.path)).size;if(n.createDiv({cls:"mdbase-issues-summary",text:p.length===i.length?`Showing ${Math.min(p.length,this.issueLimit).toLocaleString()} of ${p.length.toLocaleString()} issues`:`${p.length.toLocaleString()} matching issues in ${y.toLocaleString()} files`}),!p.length){n.createDiv({cls:"mdbase-empty-state",text:"No validation issues."});return}let h=p.slice(0,this.issueLimit),m=new Map;for(let _ of h)m.set(_.path,[...(g=m.get(_.path))!=null?g:[],_]);for(let[_,w]of m){let x=n.createEl("section",{cls:"mdbase-issue-group"}),v=x.createDiv({cls:"mdbase-issue-group-header"}),P=v.createEl("button",{cls:"mdbase-issue-file-button"});(0,Ee.setIcon)(P.createSpan({cls:"mdbase-issue-file-icon"}),"file-text"),P.createSpan({cls:"mdbase-issue-file-path",text:_}),P.onclick=()=>void this.host.openFileByPath(_),v.createSpan({cls:"mdbase-issue-file-count",text:`${w.length} ${w.length===1?"issue":"issues"}`});for(let O of w){let $=x.createEl("button",{cls:"mdbase-issue-row"});$.setAttr("data-severity",O.severity),$.setAttr("aria-label",`${O.severity==="warn"?"Warning":"Error"}: ${O.message}`),$.createSpan({cls:"mdbase-issue-indicator"}).setAttr("aria-hidden","true");let R=$.createDiv({cls:"mdbase-issue-metadata"});R.createEl("code",{text:O.code}),R.createDiv({cls:"mdbase-issue-context",text:`${O.severity==="warn"?"Warning":"Error"}${O.field?` \xB7 ${O.field}`:""}`}),$.createDiv({cls:"mdbase-issue-row-message",text:O.message}),$.onclick=()=>void this.host.openFileByPath(O.path,O.field)}}if(p.length>h.length){let _=n.createEl("button",{cls:"mdbase-load-more",text:`Load ${Math.min(250,p.length-h.length)} more`});_.onclick=()=>{this.issueLimit+=250,this.render()}}}async selectType(t,n=!0){if(n&&this.dirty&&t!==this.selectedPath){new Ee.Notice("Save or discard the current type changes before switching.");return}let i=await this.host.loadTypeModel(t);this.selectedPath=t,this.model=i,this.originalModel=gp(i),this.yamlDraft=`${mt(N0(i),i.body)} +`,this.dirty=!1,this.editorMode="design",this.render()}createType(){if(this.dirty){new Ee.Notice("Save or discard the current type changes before creating another type.");return}let t=yp();this.selectedPath=null,this.model=t,this.originalModel=null,this.yamlDraft=`${mt(yo(t),t.body)} +`,this.dirty=!0,this.editorMode="design",this.render()}switchEditorMode(t){if(!(!this.model||t===this.editorMode)){if(t==="yaml")try{this.yamlDraft=`${mt(N0(this.model),this.model.body)} +`}catch(n){new Ee.Notice(n instanceof Error?n.message:String(n));return}else if(!this.readYamlDraftIntoModel())return;this.editorMode=t,this.render()}}readYamlDraftIntoModel(){var n,i;let t=Pt(this.yamlDraft);if(!t.hasFrontmatter||t.error)return new Ee.Notice(`Invalid type YAML: ${(n=t.error)!=null?n:"frontmatter is missing"}`),!1;if(t.frontmatter.kind!=="mdbase.type")return new Ee.Notice("Canonical v0.3 type YAML requires kind: mdbase.type."),!1;try{return this.model=Uc(t.frontmatter,t.body,((i=this.model)==null?void 0:i.name)||"type"),!0}catch(s){return new Ee.Notice(s instanceof Error?s.message:String(s)),!1}}async saveCurrentType(){if(!(!this.model||this.model.specProfile!=="v0.3"||this.model.readOnlyReason)&&!(this.editorMode==="yaml"&&!this.readYamlDraftIntoModel())){if(!this.model.name.trim()){new Ee.Notice("Type name is required.");return}await this.perform(async()=>{let t=await this.host.saveTypeModel(this.model,this.selectedPath);this.selectedPath=t.path,this.originalModel=gp(this.model),this.dirty=!1,this.transientMessage=`Saved ${t.path}.`,await this.refresh(!0)})}}markDirty(t=!1){var o,a;if(this.dirty=!0,t){this.render();return}let n=this.containerEl.querySelector(".mdbase-editor-title-line");n&&!n.querySelector(".mdbase-dirty")&&n.createSpan({cls:"mdbase-dirty",text:"Unsaved"});let i=this.containerEl.querySelector(".mdbase-editor-actions .mod-cta");i&&((o=this.model)==null?void 0:o.specProfile)==="v0.3"&&!this.model.readOnlyReason&&((a=this.host.getMirrorProfile())==null?void 0:a.mode)!=="read_only"&&(i.disabled=!1);let s=this.containerEl.querySelector(".mdbase-change-review");if(s){let c=s.querySelector("p");c&&c.setText("Pending changes. Review details after leaving the current field.")}}async refreshMirrorStatus(){try{this.mirrorStatus=await this.host.connectSync.status()}catch(t){this.mirrorStatus=null,this.transientMessage=t instanceof Error?t.message:String(t)}}async perform(t){if(!this.busy){this.busy=!0,this.transientMessage="",this.render();try{await t()}catch(n){let i=n instanceof Error?n.message:String(n);this.transientMessage=i,new Ee.Notice(i)}finally{this.busy=!1,this.render()}}}};function N0(r){var e;return r.specProfile==="v0.3"&&!r.readOnlyReason?yo(r):gp((e=r.originalFrontmatter)!=null?e:{name:r.name,fields:Object.fromEntries(r.fields.map(t=>[t.name,t.definition]))})}var Fi="mdbase-issues-view",$M={validateOnSave:!0,validateOnOpen:!0,showNoticeOnSave:!1,interopEnabled:!1,mirrorProfile:null};function SM(r){if(!r||typeof r!="object"||Array.isArray(r))return!1;let e=r;return e.version===1&&typeof e.syncUrl=="string"&&typeof e.controlUrl=="string"&&typeof e.collectionId=="string"&&typeof e.replicaId=="string"&&(e.mode==="read_only"||e.mode==="read_write")&&typeof e.name=="string"&&typeof e.enrollmentId=="string"&&typeof e.accessTokenExpiresAt=="string"}function EM(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var go=class extends L.Modal{constructor(t,n,i="",s=""){super(t);this.resolvePromise=null;this.settled=!1;this.title=n,this.placeholder=i,this.defaultValue=s}openAndGetValue(){return new Promise(t=>{this.settled=!1,this.resolvePromise=t,this.open()})}onOpen(){let{contentEl:t}=this;t.empty(),t.createEl("h3",{text:this.title});let n=t.createEl("input",{type:"text"});n.placeholder=this.placeholder,n.value=this.defaultValue,n.addClass("prompt-input");let i=t.createDiv({cls:"modal-button-container"}),s=i.createEl("button",{text:"Cancel"}),o=i.createEl("button",{text:"OK"});o.addClass("mod-cta"),s.onclick=()=>{this.finish(null),this.close()},o.onclick=()=>{this.finish(n.value.trim()),this.close()},n.addEventListener("keydown",a=>{a.key==="Enter"&&(a.preventDefault(),this.finish(n.value.trim()),this.close()),a.key==="Escape"&&(a.preventDefault(),this.finish(null),this.close())}),window.setTimeout(()=>n.focus(),0)}onClose(){this.settled||this.finish(null),this.contentEl.empty()}finish(t){var n;this.settled||(this.settled=!0,(n=this.resolvePromise)==null||n.call(this,t),this.resolvePromise=null)}},_p=class extends L.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=>{var a,c,l;let s=(c=(a=i.match)==null?void 0:a.path_glob)!=null?c:"";return`${i.name} ${(l=i.display_name_key)!=null?l:""} ${i.filePath} ${s}`.toLowerCase().includes(n)}).slice(0,100):this.typeDefs.slice(0,100)}renderSuggestion(t,n){var o,a;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((o=t.fields)!=null?o:{}).length} fields`}),(a=t.match)!=null&&a.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 AM(r,e){return new Promise(t=>{new _p(r,e,i=>{if(i.type==="selected"){t(i.typeDef);return}t(null)}).open()})}var bp=class extends L.ItemView{constructor(t,n){super(t);this.severityFilter="all";this.query="";this.plugin=n}getViewType(){return Fi}getDisplayText(){return"mdbase issues"}getIcon(){return"shield-alert"}async onOpen(){this.containerEl.empty(),this.containerEl.addClass("mdbase-issues-view"),this.render()}render(){var y;let t=this.containerEl;t.empty(),t.addClass("mdbase-issues-view");let n=t.createDiv({cls:"mdbase-issues-header"});n.createEl("h3",{text:"mdbase Issues"});let s=n.createDiv({cls:"mdbase-issues-header-actions"}).createEl("button",{text:"Refresh"});s.addClass("mod-cta"),s.onclick=()=>{this.plugin.runCollectionValidation(!1)};let o=t.createDiv({cls:"mdbase-issues-controls"}),a=o.createEl("select");a.addClass("mdbase-issues-severity"),a.createEl("option",{value:"all",text:"All severities"}),a.createEl("option",{value:"error",text:"Errors only"}),a.createEl("option",{value:"warn",text:"Warnings only"}),a.value=this.severityFilter,a.onchange=()=>{let h=a.value;(h==="error"||h==="warn"||h==="all")&&(this.severityFilter=h),this.render()};let c=o.createEl("input",{type:"search"});c.addClass("mdbase-issues-query"),c.placeholder="Filter by path, code, message, field",c.value=this.query,c.oninput=()=>{this.query=c.value,this.render()};let l=this.plugin.getIssues(),d=this.query.trim().toLowerCase(),u=l.filter(h=>{var g;return this.severityFilter!=="all"&&h.severity!==this.severityFilter?!1:d?`${h.path} ${h.code} ${h.message} ${(g=h.field)!=null?g:""}`.toLowerCase().includes(d):!0}),f=u.slice(0,500);if(t.createDiv({cls:"mdbase-issues-count",text:u.length>f.length?`Showing ${f.length} of ${u.length} matching issues`:u.length===l.length?`${u.length} issue${u.length===1?"":"s"}`:`${u.length} of ${l.length} issue${l.length===1?"":"s"}`}),u.length===0){t.createDiv({cls:"mdbase-empty",text:l.length===0?"No validation issues.":"No issues match current filters."});return}let p=new Map;for(let h of f){let m=(y=p.get(h.path))!=null?y:[];m.push(h),p.set(h.path,m)}for(let[h,m]of p.entries()){t.createDiv({cls:"mdbase-issue-file",text:h});for(let g of m){let _=t.createDiv({cls:"mdbase-issue-item"});_.setAttr("data-severity",g.severity),_.createDiv({cls:"mdbase-issue-code",text:`${g.severity.toUpperCase()} \xB7 ${g.code}${g.field?` \xB7 ${g.field}`:""}`}),_.createDiv({cls:"mdbase-issue-message",text:g.message});let w=_.createDiv({cls:"mdbase-issue-actions"}),x=w.createEl("button",{text:g.field?"Open field":"Open file"});x.onclick=P=>{P.stopPropagation(),this.plugin.openIssue(g)};let v=this.plugin.getQuickFixLabel(g);if(v){let P=w.createEl("button",{text:v});P.onclick=O=>{O.stopPropagation(),this.plugin.applyQuickFix(g)}}_.onclick=()=>{this.plugin.openIssue(g)}}}}},wp=class extends L.PluginSettingTab{constructor(e,t){super(e,t),this.plugin=t}display(){let{containerEl:e}=this;e.empty(),e.createEl("h2",{text:"mdbase settings"}),new L.Setting(e).setName("Validate on save").setDesc("Run mdbase validation when a markdown file is modified.").addToggle(t=>t.setValue(this.plugin.settings.validateOnSave).onChange(async n=>{this.plugin.settings.validateOnSave=n,await this.plugin.saveSettings()})),new L.Setting(e).setName("Validate on file open").setDesc("Validate the active note when opened.").addToggle(t=>t.setValue(this.plugin.settings.validateOnOpen).onChange(async n=>{this.plugin.settings.validateOnOpen=n,await this.plugin.saveSettings()})),new L.Setting(e).setName("Show notices on save").setDesc("Display a notice when save-time validation finds issues.").addToggle(t=>t.setValue(this.plugin.settings.showNoticeOnSave).onChange(async n=>{this.plugin.settings.showNoticeOnSave=n,await this.plugin.saveSettings()})),new L.Setting(e).setName("Allow local application interoperability").setDesc("Allow installed Obsidian plugins to exchange validated mdbase events and actions in this vault. Contracts establish compatibility; this switch is the separate user grant.").addToggle(t=>t.setValue(this.plugin.settings.interopEnabled).onChange(async n=>{this.plugin.settings.interopEnabled=n,await this.plugin.saveSettings()}))}},zc=class extends L.Plugin{constructor(t,n){super(t,n);this.issueMap=new Map;this.sortedIssuesCache=null;this.schemaCache=null;this.schemaLoadPromise=null;this.pendingSaveValidations=new Map;this.saveValidationDebounceMs=250;this.connectSync=new qc(t,{getMirrorProfile:()=>this.getMirrorProfile(),saveMirrorProfile:async i=>{this.settings.mirrorProfile=i,await this.saveSettings()}}),this.interopBridge=new ga(t,()=>{var i;return((i=this.settings)==null?void 0:i.interopEnabled)===!0}),this.api={apiVersion:1,interop:this.interopBridge,getInteropStatus:()=>{var i;return{enabled:((i=this.settings)==null?void 0:i.interopEnabled)===!0,profileVersion:"0.1"}}}}async onload(){await this.loadSettings(),await this.connectSync.initialize(),(0,L.addIcon)(qi,T0),this.statusBarEl=this.addStatusBarItem(),this.updateStatusBar(),this.registerView(qn,n=>new Bc(n,this)),this.registerView(Fi,n=>new bp(n,this)),this.addSettingTab(new wp(this.app,this)),this.addRibbonIcon(qi,"Open mdbase",()=>void this.openWorkspace()),this.addCommand({id:"mdbase-open",name:"mdbase: Open workspace",callback:()=>void this.openWorkspace()}),this.addCommand({id:"mdbase-initialize-collection",name:"mdbase: Initialize collection",callback:()=>void this.initializeCollectionCommand()}),this.addCommand({id:"mdbase-create-type",name:"mdbase: Create type definition",callback:()=>void this.openWorkspace("types")}),this.addCommand({id:"mdbase-edit-type",name:"mdbase: Edit type definition",callback:()=>void this.openWorkspace("types")}),this.addCommand({id:"mdbase-edit-current-type",name:"mdbase: Edit current type definition",callback:()=>void this.openWorkspace("types")}),this.addCommand({id:"mdbase-create-note-from-type",name:"mdbase: Create note from type",callback:()=>void this.createNoteFromTypeCommand()}),this.addCommand({id:"mdbase-validate-current-note",name:"mdbase: Validate current note",callback:()=>void this.validateCurrentNoteCommand()}),this.addCommand({id:"mdbase-validate-collection",name:"mdbase: Validate collection",callback:()=>void this.runCollectionValidation(!0)}),this.addCommand({id:"mdbase-open-issues-view",name:"mdbase: Open issues view",callback:()=>void this.openWorkspace("issues")}),this.addCommand({id:"mdbase-sync",name:"mdbase: Sync collection authority",callback:()=>void this.syncHostedCollectionCommand()}),this.addCommand({id:"mdbase-open-sync",name:"mdbase: Open sync",callback:()=>void this.openWorkspace("sync")}),this.registerEvent(this.app.vault.on("modify",n=>{n instanceof L.TFile&&this.onVaultModify(n)})),this.registerEvent(this.app.vault.on("rename",(n,i)=>{n instanceof L.TFile&&this.onVaultRename(n,i)})),this.registerEvent(this.app.vault.on("delete",n=>{n instanceof L.TFile&&this.onVaultDelete(n)})),this.registerEvent(this.app.vault.on("create",n=>{n instanceof L.TFile&&this.onVaultCreate(n)})),this.registerEvent(this.app.workspace.on("file-open",n=>{this.settings.validateOnOpen&&(!(n instanceof L.TFile)||n.extension!=="md"||this.validateFileAndStore(n,"open"))}));let t=this.app.workspace.getActiveFile();t&&this.settings.validateOnOpen&&this.validateFileAndStore(t,"open")}async onunload(){await this.interopBridge.dispose(),this.app.workspace.getLeavesOfType(qn).forEach(t=>t.detach()),this.app.workspace.getLeavesOfType(Fi).forEach(t=>t.detach()),this.clearAllPendingSaveValidations()}async loadSettings(){this.settings=Object.assign({},$M,await this.loadData()),SM(this.settings.mirrorProfile)||(this.settings.mirrorProfile=null)}async saveSettings(){await this.saveData(this.settings)}getIssues(){var t;return(t=this.sortedIssuesCache)!=null||(this.sortedIssuesCache=Array.from(this.issueMap.values()).flat().sort((n,i)=>n.path.localeCompare(i.path)||n.severity.localeCompare(i.severity)||n.code.localeCompare(i.code))),this.sortedIssuesCache}getMirrorProfile(){return this.settings.mirrorProfile?{...this.settings.mirrorProfile}:null}async loadWorkspaceSchema(t=!1){return this.getConfigAndTypes(t)}async loadTypeModel(t){var s;let n=this.app.vault.getAbstractFileByPath((0,L.normalizePath)(t));if(!(n instanceof L.TFile))throw new Error(`Type file not found: ${t}`);let i=Pt(await this.app.vault.cachedRead(n));if(!i.hasFrontmatter||i.error)throw new Error(`Invalid type frontmatter: ${(s=i.error)!=null?s:"frontmatter is missing"}`);return Uc(i.frontmatter,i.body,n.basename)}async saveTypeModel(t,n){var a;if(this.connectSync.assertLocalAuthorityWritable(),((a=this.getMirrorProfile())==null?void 0:a.mode)==="read_only")throw new Error("This mirror has read-only access. Re-enroll it with write access before editing types.");let i=await pi(this.app.vault);if(!i)throw new Error("No mdbase.yaml found.");if(!i.spec_version.startsWith("0.3."))throw new Error("mdbase v0.2 type definitions are read-only. Migrate the collection first.");let s=n?this.app.vault.getAbstractFileByPath((0,L.normalizePath)(n)):null;if(s!=null&&!(s instanceof L.TFile))throw new Error(`Type file not found: ${n}`);let o=await this.writeTypeDefinition(i,t,s);return this.refreshWorkspaceViews(!0),o}async initializeCollection(){this.connectSync.assertLocalAuthorityWritable(),await this.initializeCollectionCommand(),this.refreshWorkspaceViews(!0)}async validateCollection(){await this.runCollectionValidation(!1)}analyzeMigration(){if(this.getMirrorProfile())throw new Error("Collection authority resources must be migrated at the collection authority.");return I0(this.app.vault)}async applyMigration(t,n){var s,o;if(this.connectSync.assertLocalAuthorityWritable(),this.getMirrorProfile())throw new Error("Collection authority resources must be migrated at the collection authority.");let i=await O0(this.app.vault,t,{allowLossy:n});if(!i.applied)throw new Error(i.restored?`Migration failed and all writes were rolled back. ${(s=i.error)!=null?s:""}`.trim():`Migration needs manual recovery. See ${i.manifestPath}. ${(o=i.error)!=null?o:""}`.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["unknown_field","schema_additional_properties"].includes(t.code)&&t.field?"Remove field":["missing_required","schema_required"].includes(t.code)&&t.field?"Add placeholder":null}async applyQuickFix(t){this.connectSync.assertLocalAuthorityWritable();let n=this.app.vault.getAbstractFileByPath(t.path);if(!(n instanceof L.TFile)){new L.Notice(`File not found: ${t.path}`);return}let i=await this.app.vault.cachedRead(n),s=Pt(i);if(s.error){new L.Notice(`Cannot apply quick fix: invalid frontmatter (${s.error})`);return}if(["unknown_field","schema_additional_properties"].includes(t.code)&&t.field){let o=$a(t.field);if(!(o in s.frontmatter)){new L.Notice(`Field '${o}' not found in frontmatter.`);return}delete s.frontmatter[o],await this.app.vault.modify(n,`${mt(s.frontmatter,s.body)} +`),new L.Notice(`Removed '${o}' from ${n.basename}`),await this.validateFileAndStore(n,"manual");return}if(["missing_required","schema_required"].includes(t.code)&&t.field){let o=$a(t.field);s.frontmatter[o]===void 0&&(s.frontmatter[o]="TODO");let a=s.hasFrontmatter?s.body:i;await this.app.vault.modify(n,`${mt(s.frontmatter,a)} +`),new L.Notice(`Added placeholder '${o}' to ${n.basename}`),await this.validateFileAndStore(n,"manual");return}new L.Notice("No quick fix available for this issue.")}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=$a(n),l=new RegExp(`^\\s*${EM(c)}\\s*:`);if(o.getLine(0).trim()==="---")for(let d=1;ds.severity==="error").length,i=t.length-n;if(t.length===0){this.statusBarEl.setText("mdbase: no issues");return}this.statusBarEl.setText(`mdbase: ${n} error${n===1?"":"s"}, ${i} warning${i===1?"":"s"}`)}async openIssuesView(){var i;let t=this.app.workspace.getLeavesOfType(Fi)[0];if(t){this.app.workspace.revealLeaf(t),t.view.render();return}let n=(i=this.app.workspace.getRightLeaf(!1))!=null?i:this.app.workspace.getLeaf(!0);await n.setViewState({type:Fi,active:!0}),this.app.workspace.revealLeaf(n)}async openWorkspace(t="types"){let n=this.app.workspace.getLeavesOfType(qn)[0];if(n){this.app.workspace.revealLeaf(n);let o=n.view;o.showDestination(t),await o.refresh();return}let i=this.app.workspace.getLeaf(!0);await i.setViewState({type:qn,active:!0}),this.app.workspace.revealLeaf(i),i.view.showDestination(t)}refreshWorkspaceViews(t=!1){for(let n of this.app.workspace.getLeavesOfType(qn))n.view.refresh(t)}refreshIssueViews(){this.updateStatusBar();for(let t of this.app.workspace.getLeavesOfType(Fi))t.view.render();this.refreshWorkspaceViews()}setFileIssues(t,n){n.length===0?this.issueMap.delete(t):this.issueMap.set(t,n),this.sortedIssuesCache=null,this.refreshIssueViews()}clearFileIssues(t){this.issueMap.has(t)&&(this.issueMap.delete(t),this.sortedIssuesCache=null,this.refreshIssueViews())}moveFileIssues(t,n){let 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())}clearAllPendingSaveValidations(){for(let t of this.pendingSaveValidations.values())window.clearTimeout(t);this.pendingSaveValidations.clear()}clearPendingSaveValidation(t){let n=this.pendingSaveValidations.get(t);n!=null&&(window.clearTimeout(n),this.pendingSaveValidations.delete(t))}scheduleSaveValidation(t){this.clearPendingSaveValidation(t.path);let n=window.setTimeout(()=>{this.pendingSaveValidations.delete(t.path),this.validateFileAndStore(t,"save")},this.saveValidationDebounceMs);this.pendingSaveValidations.set(t.path,n)}isSchemaRelevantPath(t){let n=(0,L.normalizePath)(t);if(n==="mdbase.yaml")return!0;let i=new Set(["_types"]);this.schemaCache&&i.add((0,L.normalizePath)(this.schemaCache.config.settings.types_folder));for(let s of i)if(n===s||n.startsWith(`${s}/`))return!0;return!1}invalidateSchemaCache(){this.schemaCache=null,this.schemaLoadPromise=null}async getConfigAndTypes(t=!1){if(t&&this.invalidateSchemaCache(),this.schemaCache)return this.schemaCache;if(this.schemaLoadPromise)return this.schemaLoadPromise;this.schemaLoadPromise=(async()=>{let n=await pi(this.app.vault);if(!n)return null;let i=await fb(this.app.vault,n);return{config:n,types:i}})();try{let n=await this.schemaLoadPromise;return n&&(this.schemaCache=n),n}finally{this.schemaLoadPromise=null}}async requireConfigAndTypes(t={}){var s,o;let n=(s=t.background)!=null?s:!1,i=await this.getConfigAndTypes((o=t.forceReload)!=null?o:!1);return i?(i.types.size===0&&!n&&new L.Notice(`No types found in ${i.config.settings.types_folder}`),i):(n||new L.Notice("No mdbase.yaml found. Run 'mdbase: Initialize collection' first."),null)}onVaultModify(t){this.isSchemaRelevantPath(t.path)&&(this.invalidateSchemaCache(),this.refreshWorkspaceViews()),this.settings.validateOnSave&&t.extension==="md"&&this.scheduleSaveValidation(t)}onVaultRename(t,n){(this.isSchemaRelevantPath(n)||this.isSchemaRelevantPath(t.path))&&(this.invalidateSchemaCache(),this.refreshWorkspaceViews()),t.extension==="md"&&(this.clearPendingSaveValidation(n),this.moveFileIssues(n,t.path),this.settings.validateOnSave&&this.scheduleSaveValidation(t))}onVaultDelete(t){this.isSchemaRelevantPath(t.path)&&(this.invalidateSchemaCache(),this.refreshWorkspaceViews()),t.extension==="md"&&(this.clearPendingSaveValidation(t.path),this.clearFileIssues(t.path))}onVaultCreate(t){this.isSchemaRelevantPath(t.path)&&(this.invalidateSchemaCache(),this.refreshWorkspaceViews())}async validateFileAndStore(t,n){let i=await this.requireConfigAndTypes({background:n!=="manual"});if(!i)return n!=="manual"&&this.clearFileIssues(t.path),[];let s=await ef(this.app.vault,t,i.config,i.types);return this.setFileIssues(t.path,s),n==="save"&&this.settings.showNoticeOnSave&&s.length>0&&new L.Notice(`mdbase: ${s.length} issue${s.length===1?"":"s"} in ${t.basename}`),s}async initializeCollectionCommand(){if(this.connectSync.assertLocalAuthorityWritable(),this.getMirrorProfile()){new L.Notice("This vault is configured as a mirror. Sync it instead of initializing a local collection.");return}let{created:t}=await lb(this.app.vault);if(this.invalidateSchemaCache(),t.length===0){new L.Notice("mdbase collection already initialized.");return}new L.Notice(`Initialized mdbase collection: ${t.join(", ")}`)}async syncHostedCollectionCommand(){var t,n,i,s;if(!this.getMirrorProfile()){await this.openWorkspace("sync");return}try{let o=await this.connectSync.preview(),a=await this.connectSync.sync(o),c=await this.connectSync.status();this.invalidateSchemaCache(),this.refreshWorkspaceViews(!0);let l=((t=c==null?void 0:c.conflicts.length)!=null?t:0)+((n=c==null?void 0:c.local_issues.length)!=null?n:0);new L.Notice(a.status==="stale"?"The sync plan changed before it could apply. Review the new plan in the mdbase workspace.":a.status==="failed"||a.status==="blocked"?`mdbase sync stopped safely: ${(s=(i=a.failure)==null?void 0:i.message)!=null?s:a.status}.`:l?`Sync completed with ${l} item${l===1?"":"s"} needing attention.`:"mdbase sync completed.")}catch(o){new L.Notice(`mdbase sync failed: ${o instanceof Error?o.message:String(o)}`),await this.openWorkspace("sync")}}async createNoteFromTypeCommand(){var d,u;this.connectSync.assertLocalAuthorityWritable();let t=await this.requireConfigAndTypes();if(!t)return;if(t.types.size===0){new L.Notice("No type definitions found.");return}let n=await AM(this.app,Array.from(t.types.values()));if(!n)return;let i=mb(n,t.config),s=yb(n,i);for(let[f,p]of s){let y=`Required field: ${f}`,h=await new go(this.app,y,(d=p.type)!=null?d:"string").openAndGetValue();if(h==null)return;if(h.trim().length===0){new L.Notice(`Field '${f}' is required.`);return}try{i[f]=tf(h,p)}catch(m){new L.Notice(`Invalid value for ${f}: ${m instanceof Error?m.message:String(m)}`);return}}let o=(u=n.display_name_key)!=null?u:"title";if(i[o]==null){let f=await new go(this.app,`Optional ${o} (used for filename)`,"").openAndGetValue();f&&f.trim().length>0&&(i[o]=f.trim())}let a=await _b(this.app.vault,n,i),c=await new go(this.app,"Note path","Relative path in vault",a).openAndGetValue();if(c==null)return;let l=(0,L.normalizePath)(c.trim().length>0?c.trim():a);l.endsWith(".md")||(l=`${l}.md`);try{let f=await bb(this.app.vault,l,i);await this.app.workspace.getLeaf(!0).openFile(f),new L.Notice(`Created note: ${f.path}`),await this.validateFileAndStore(f,"manual")}catch(f){new L.Notice(f instanceof Error?f.message:String(f))}}async validateCurrentNoteCommand(){let t=this.app.workspace.getActiveFile();if(!(t instanceof L.TFile)||t.extension!=="md"){new L.Notice("Open a markdown note first.");return}let n=await this.validateFileAndStore(t,"manual");n.length===0?new L.Notice("No issues in current note."):(new L.Notice(`Found ${n.length} issue${n.length===1?"":"s"} in current note.`),await this.openIssuesView())}async runCollectionValidation(t){var o;let n=await this.requireConfigAndTypes({background:!1});if(!n)return;let i=await hb(this.app.vault,n.config,n.types),s=new Map;for(let a of i){let c=(o=s.get(a.path))!=null?o:[];c.push(a),s.set(a.path,c)}if(this.issueMap=s,this.sortedIssuesCache=null,this.refreshIssueViews(),t)if(i.length===0)new L.Notice("Collection validation passed with no issues.");else{let a=i.filter(l=>l.severity==="error").length,c=i.length-a;new L.Notice(`Collection validation: ${a} error(s), ${c} warning(s)`),await this.openIssuesView()}}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){let s=n.name.trim();if(!s)throw new Error("Type name is required.");if(!t.spec_version.startsWith("0.3.")||n.specProfile!=="v0.3")throw new Error("mdbase v0.2 type definitions are read-only. Migrate the collection first.");let o=yo(n),a=n.body.trim()||`# ${s} -Type definition for ${s}.`,c=`${yt(o,a)} +Type definition for ${s}.`,c=`${mt(o,a)} `,l=(0,L.normalizePath)(t.settings.types_folder),d=(0,L.normalizePath)(`${l}/${s}.md`);if(!i){if(await this.ensureFolderExists(l),await this.app.vault.adapter.exists(d))throw new Error(`Type already exists: ${d}`);let m=await this.app.vault.create(d,c);return this.invalidateSchemaCache(),m}let u=i.path.lastIndexOf("/"),f=u>=0?i.path.slice(0,u):"",y=(0,L.normalizePath)(`${f?`${f}/`:""}${s}.md`)||d;if(y!==i.path&&await this.app.vault.adapter.exists(y))throw new Error(`Cannot rename type file to ${y}; file already exists.`);y!==i.path&&await this.app.fileManager.renameFile(i,y);let h=this.app.vault.getAbstractFileByPath(y);if(!(h instanceof L.TFile))throw new Error(`Unable to access updated type file: ${y}`);return await this.app.vault.modify(h,c),this.invalidateSchemaCache(),h}}; diff --git a/package-lock.json b/package-lock.json index 2b29dfb..0d9afc3 100644 --- a/package-lock.json +++ b/package-lock.json @@ -10,8 +10,8 @@ "license": "MIT", "dependencies": { "@callumalpass/mdbase-interop": "0.1.0-rc.2", - "@mdbase-dev/connect-protocol": "0.1.0-beta.23", - "@mdbase-dev/connect-sync": "0.1.0-beta.23", + "@mdbase-dev/connect-protocol": "0.1.0-beta.40", + "@mdbase-dev/connect-sync": "0.1.0-beta.40", "ajv": "^8.20.0", "ajv-formats": "^3.0.1", "picomatch": "^4.0.5" @@ -513,18 +513,22 @@ "peer": true }, "node_modules/@mdbase-dev/connect-protocol": { - "version": "0.1.0-beta.23", - "resolved": "https://registry.npmjs.org/@mdbase-dev/connect-protocol/-/connect-protocol-0.1.0-beta.23.tgz", - "integrity": "sha512-IHbuwIBSh1d+Xys7KVnKctqz2c4SuE7g78A1K7ZGgUjWpqo+li99k4cNYcpgjPNOTlGr9hs19HPLqLFhVxZ9UA==", - "license": "MIT" + "version": "0.1.0-beta.40", + "resolved": "https://registry.npmjs.org/@mdbase-dev/connect-protocol/-/connect-protocol-0.1.0-beta.40.tgz", + "integrity": "sha512-LTGyCtfLWsy4U4oxnmMcJm/kMF7BI/EGLMisxGjzOP+q8K4hsrYQxVygaXBk6Ta8q0RAz9XfS37Tkynz2BVR5w==", + "license": "MIT", + "dependencies": { + "ajv": "^8.20.0", + "ajv-formats": "^3.0.1" + } }, "node_modules/@mdbase-dev/connect-sync": { - "version": "0.1.0-beta.23", - "resolved": "https://registry.npmjs.org/@mdbase-dev/connect-sync/-/connect-sync-0.1.0-beta.23.tgz", - "integrity": "sha512-hEfXJwJkaSNRLljNayF13pOLDDQTnHx1uf3elCJuARP/8kjHFBgQAzB7uDjM0j/W8YFrTca8yF9XJAHw4vk+CQ==", + "version": "0.1.0-beta.40", + "resolved": "https://registry.npmjs.org/@mdbase-dev/connect-sync/-/connect-sync-0.1.0-beta.40.tgz", + "integrity": "sha512-0QdeBQXeg4eSV2zOWkijNAJCyjl1w/V39FCoOP+yURtycrnbDL1f4vMAfZ8amtSv9k6OsJGhR+oiBo8ohA4ASA==", "license": "MIT", "dependencies": { - "@mdbase-dev/connect-protocol": "0.1.0-beta.23", + "@mdbase-dev/connect-protocol": "0.1.0-beta.40", "@noble/hashes": "^2.2.0", "yaml": "^2.9.0" }, diff --git a/package.json b/package.json index db76f28..2f5d972 100644 --- a/package.json +++ b/package.json @@ -33,8 +33,8 @@ }, "dependencies": { "@callumalpass/mdbase-interop": "0.1.0-rc.2", - "@mdbase-dev/connect-protocol": "0.1.0-beta.23", - "@mdbase-dev/connect-sync": "0.1.0-beta.23", + "@mdbase-dev/connect-protocol": "0.1.0-beta.40", + "@mdbase-dev/connect-sync": "0.1.0-beta.40", "ajv": "^8.20.0", "ajv-formats": "^3.0.1", "picomatch": "^4.0.5" From 692ff5d3b58ed17493a012d7b03285d3f3f150c2 Mon Sep 17 00:00:00 2001 From: callumalpass Date: Fri, 7 Aug 2026 09:46:37 +1000 Subject: [PATCH 3/3] fix(sync): present idle plans as up to date --- main.js | 70 ++++++++++++++++++++-------------------- src/workspaceView.ts | 13 ++++++-- test/syncPreview.test.ts | 12 +++++++ 3 files changed, 57 insertions(+), 38 deletions(-) diff --git a/main.js b/main.js index 981b412..b152750 100644 --- a/main.js +++ b/main.js @@ -3,14 +3,14 @@ THIS IS A GENERATED/BUNDLED FILE BY ESBUILD if you want to view the source, please visit the github repository of this plugin */ -var j0=Object.create;var Vi=Object.defineProperty;var D0=Object.getOwnPropertyDescriptor;var q0=Object.getOwnPropertyNames;var F0=Object.getPrototypeOf,V0=Object.prototype.hasOwnProperty;var U0=(r,e,t)=>e in r?Vi(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var A=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),B0=(r,e)=>{for(var t in e)Vi(r,t,{get:e[t],enumerable:!0})},vp=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of q0(e))!V0.call(r,i)&&i!==t&&Vi(r,i,{get:()=>e[i],enumerable:!(n=D0(e,i))||n.enumerable});return r};var fn=(r,e,t)=>(t=r!=null?j0(F0(r)):{},vp(e||!r||!r.__esModule?Vi(t,"default",{value:r,enumerable:!0}):t,r)),z0=r=>vp(Vi({},"__esModule",{value:!0}),r);var I=(r,e,t)=>U0(r,typeof e!="symbol"?e+"":e,t);var Hi=A(ce=>{"use strict";Object.defineProperty(ce,"__esModule",{value:!0});ce.regexpCode=ce.getEsmExportName=ce.getProperty=ce.safeStringify=ce.stringify=ce.strConcat=ce.addCodeArg=ce.str=ce._=ce.nil=ce._Code=ce.Name=ce.IDENTIFIER=ce._CodeOrName=void 0;var Bi=class{};ce._CodeOrName=Bi;ce.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var pn=class extends Bi{constructor(e){if(super(),!ce.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}}};ce.Name=pn;var wt=class extends Bi{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 pn&&(t[n.str]=(t[n.str]||0)+1),t),{})}};ce._Code=wt;ce.nil=new wt("");function $p(r,...e){let t=[r[0]],n=0;for(;n{"use strict";Object.defineProperty(st,"__esModule",{value:!0});st.ValueScope=st.ValueScopeName=st.Scope=st.varKinds=st.UsedValueState=void 0;var it=Hi(),Wc=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},bo;(function(r){r[r.Started=0]="Started",r[r.Completed=1]="Completed"})(bo||(st.UsedValueState=bo={}));st.varKinds={const:new it.Name("const"),let:new it.Name("let"),var:new it.Name("var")};var wo=class{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t}toName(e){return e instanceof it.Name?e:this.name(e)}name(e){return new it.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}}};st.Scope=wo;var vo=class extends it.Name{constructor(e,t){super(t),this.prefix=e}setValue(e,{property:t,itemIndex:n}){this.value=e,this.scopePath=(0,it._)`.${new it.Name(t)}[${n}]`}};st.ValueScopeName=vo;var Z0=(0,it._)`\n`,Gc=class extends wo{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?Z0:it.nil}}get(){return this._scope}name(e){return new vo(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 d=a.get(o);if(d)return d}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,it._)`${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=it.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,bo.Started);let d=t(l);if(d){let u=this.opts.es5?st.varKinds.var:st.varKinds.const;s=(0,it._)`${s}${u} ${l} = ${d};${this.opts._n}`}else if(d=i==null?void 0:i(l))s=(0,it._)`${s}${d}${this.opts._n}`;else throw new Wc(l);c.set(l,bo.Completed)})}return s}};st.ValueScope=Gc});var H=A(Y=>{"use strict";Object.defineProperty(Y,"__esModule",{value:!0});Y.or=Y.and=Y.not=Y.CodeGen=Y.operators=Y.varKinds=Y.ValueScopeName=Y.ValueScope=Y.Scope=Y.Name=Y.regexpCode=Y.stringify=Y.getProperty=Y.nil=Y.strConcat=Y.str=Y._=void 0;var ie=Hi(),Rt=Jc(),Fr=Hi();Object.defineProperty(Y,"_",{enumerable:!0,get:function(){return Fr._}});Object.defineProperty(Y,"str",{enumerable:!0,get:function(){return Fr.str}});Object.defineProperty(Y,"strConcat",{enumerable:!0,get:function(){return Fr.strConcat}});Object.defineProperty(Y,"nil",{enumerable:!0,get:function(){return Fr.nil}});Object.defineProperty(Y,"getProperty",{enumerable:!0,get:function(){return Fr.getProperty}});Object.defineProperty(Y,"stringify",{enumerable:!0,get:function(){return Fr.stringify}});Object.defineProperty(Y,"regexpCode",{enumerable:!0,get:function(){return Fr.regexpCode}});Object.defineProperty(Y,"Name",{enumerable:!0,get:function(){return Fr.Name}});var Ao=Jc();Object.defineProperty(Y,"Scope",{enumerable:!0,get:function(){return Ao.Scope}});Object.defineProperty(Y,"ValueScope",{enumerable:!0,get:function(){return Ao.ValueScope}});Object.defineProperty(Y,"ValueScopeName",{enumerable:!0,get:function(){return Ao.ValueScopeName}});Object.defineProperty(Y,"varKinds",{enumerable:!0,get:function(){return Ao.varKinds}});Y.operators={GT:new ie._Code(">"),GTE:new ie._Code(">="),LT:new ie._Code("<"),LTE:new ie._Code("<="),EQ:new ie._Code("==="),NEQ:new ie._Code("!=="),NOT:new ie._Code("!"),OR:new ie._Code("||"),AND:new ie._Code("&&"),ADD:new ie._Code("+")};var yr=class{optimizeNodes(){return this}optimizeNames(e,t){return this}},Yc=class extends yr{constructor(e,t,n){super(),this.varKind=e,this.name=t,this.rhs=n}render({es5:e,_n:t}){let n=e?Rt.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=Vn(this.rhs,e,t)),this}get names(){return this.rhs instanceof ie._CodeOrName?this.rhs.names:{}}},$o=class extends yr{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 ie.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Vn(this.rhs,e,t),this}get names(){let e=this.lhs instanceof ie.Name?{}:{...this.lhs.names};return Eo(e,this.rhs)}},Xc=class extends $o{constructor(e,t,n,i){super(e,n,i),this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Qc=class extends yr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Zc=class extends yr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},el=class extends yr{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},tl=class extends yr{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=Vn(this.code,e,t),this}get names(){return this.code instanceof ie._CodeOrName?this.code.names:{}}},Ki=class extends yr{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)||(ev(e,s.names),n.splice(i,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>yn(e,t.names),{})}},gr=class extends Ki{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},rl=class extends Ki{},Fn=class extends gr{};Fn.kind="else";var hn=class r extends gr{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 Fn(n):n}if(t)return e===!1?t instanceof r?t:t.nodes:this.nodes.length?this:new r(Ep(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=Vn(this.condition,e,t),this}get names(){let e=super.names;return Eo(e,this.condition),this.else&&yn(e,this.else.names),e}};hn.kind="if";var mn=class extends gr{};mn.kind="for";var nl=class extends mn{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=Vn(this.iteration,e,t),this}get names(){return yn(super.names,this.iteration.names)}},il=class extends mn{constructor(e,t,n,i){super(),this.varKind=e,this.name=t,this.from=n,this.to=i}render(e){let t=e.es5?Rt.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=Eo(super.names,this.from);return Eo(e,this.to)}},So=class extends mn{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=Vn(this.iterable,e,t),this}get names(){return yn(super.names,this.iterable.names)}},Wi=class extends gr{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)}};Wi.kind="func";var Gi=class extends Ki{render(e){return"return "+super.render(e)}};Gi.kind="return";var sl=class extends gr{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&&yn(e,this.catch.names),this.finally&&yn(e,this.finally.names),e}},Ji=class extends gr{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};Ji.kind="catch";var Yi=class extends gr{render(e){return"finally"+super.render(e)}};Yi.kind="finally";var ol=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?` -`:""},this._extScope=e,this._scope=new Rt.Scope({parent:e}),this._nodes=[new rl]}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 Yc(e,s,n)),s}const(e,t,n){return this._def(Rt.varKinds.const,e,t,n)}let(e,t,n){return this._def(Rt.varKinds.let,e,t,n)}var(e,t,n){return this._def(Rt.varKinds.var,e,t,n)}assign(e,t,n){return this._leafNode(new $o(e,t,n))}add(e,t){return this._leafNode(new Xc(e,Y.operators.ADD,t))}code(e){return typeof e=="function"?e():e!==ie.nil&&this._leafNode(new tl(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,ie.addCodeArg)(t,i));return t.push("}"),new ie._Code(t)}if(e,t,n){if(this._blockNode(new hn(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 hn(e))}else(){return this._elseNode(new Fn)}endIf(){return this._endBlockNode(hn,Fn)}_for(e,t){return this._blockNode(e),t&&this.code(t).endFor(),this}for(e,t){return this._for(new nl(e),t)}forRange(e,t,n,i,s=this.opts.es5?Rt.varKinds.var:Rt.varKinds.let){let o=this._scope.toName(e);return this._for(new il(s,o,t,n),()=>i(o))}forOf(e,t,n,i=Rt.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let o=t instanceof ie.Name?t:this.var("_arr",t);return this.forRange("_i",0,(0,ie._)`${o}.length`,a=>{this.var(s,(0,ie._)`${o}[${a}]`),n(s)})}return this._for(new So("of",i,s,t),()=>n(s))}forIn(e,t,n,i=this.opts.es5?Rt.varKinds.var:Rt.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,ie._)`Object.keys(${t})`,n);let s=this._scope.toName(e);return this._for(new So("in",i,s,t),()=>n(s))}endFor(){return this._endBlockNode(mn)}label(e){return this._leafNode(new Qc(e))}break(e){return this._leafNode(new Zc(e))}return(e){let t=new Gi;if(this._blockNode(t),this.code(e),t.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Gi)}try(e,t,n){if(!t&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let i=new sl;if(this._blockNode(i),this.code(e),t){let s=this.name("e");this._currNode=i.catch=new Ji(s),t(s)}return n&&(this._currNode=i.finally=new Yi,this.code(n)),this._endBlockNode(Ji,Yi)}throw(e){return this._leafNode(new el(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=ie.nil,n,i){return this._blockNode(new Wi(e,t,n)),i&&this.code(i).endFunc(),this}endFunc(){return this._endBlockNode(Wi)}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 hn))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=ol;function yn(r,e){for(let t in e)r[t]=(r[t]||0)+(e[t]||0);return r}function Eo(r,e){return e instanceof ie._CodeOrName?yn(r,e.names):r}function Vn(r,e,t){if(r instanceof ie.Name)return n(r);if(!i(r))return r;return new ie._Code(r._items.reduce((s,o)=>(o instanceof ie.Name&&(o=n(o)),o instanceof ie._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 ie._Code&&s._items.some(o=>o instanceof ie.Name&&e[o.str]===1&&t[o.str]!==void 0)}}function ev(r,e){for(let t in e)r[t]=(r[t]||0)-(e[t]||0)}function Ep(r){return typeof r=="boolean"||typeof r=="number"||r===null?!r:(0,ie._)`!${al(r)}`}Y.not=Ep;var tv=Ap(Y.operators.AND);function rv(...r){return r.reduce(tv)}Y.and=rv;var nv=Ap(Y.operators.OR);function iv(...r){return r.reduce(nv)}Y.or=iv;function Ap(r){return(e,t)=>e===ie.nil?t:t===ie.nil?e:(0,ie._)`${al(e)} ${r} ${al(t)}`}function al(r){return r instanceof ie.Name?r:(0,ie._)`(${r})`}});var Q=A(X=>{"use strict";Object.defineProperty(X,"__esModule",{value:!0});X.checkStrictMode=X.getErrorPath=X.Type=X.useFunc=X.setEvaluated=X.evaluatedPropsToName=X.mergeEvaluated=X.eachItem=X.unescapeJsonPointer=X.escapeJsonPointer=X.escapeFragment=X.unescapeFragment=X.schemaRefOrVal=X.schemaHasRulesButRef=X.schemaHasRules=X.checkUnknownRules=X.alwaysValidSchema=X.toHash=void 0;var pe=H(),sv=Hi();function ov(r){let e={};for(let t of r)e[t]=!0;return e}X.toHash=ov;function av(r,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(Pp(r,e),!Ip(e,r.self.RULES.all))}X.alwaysValidSchema=av;function Pp(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]||Tp(r,`unknown keyword: "${s}"`)}X.checkUnknownRules=Pp;function Ip(r,e){if(typeof r=="boolean")return!r;for(let t in r)if(e[t])return!0;return!1}X.schemaHasRules=Ip;function cv(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=cv;function lv({topSchemaRef:r,schemaPath:e},t,n,i){if(!i){if(typeof t=="number"||typeof t=="boolean")return t;if(typeof t=="string")return(0,pe._)`${t}`}return(0,pe._)`${r}${e}${(0,pe.getProperty)(n)}`}X.schemaRefOrVal=lv;function dv(r){return Op(decodeURIComponent(r))}X.unescapeFragment=dv;function uv(r){return encodeURIComponent(ll(r))}X.escapeFragment=uv;function ll(r){return typeof r=="number"?`${r}`:r.replace(/~/g,"~0").replace(/\//g,"~1")}X.escapeJsonPointer=ll;function Op(r){return r.replace(/~1/g,"/").replace(/~0/g,"~")}X.unescapeJsonPointer=Op;function fv(r,e){if(Array.isArray(r))for(let t of r)e(t);else e(r)}X.eachItem=fv;function kp({mergeNames:r,mergeToName:e,mergeValues:t,resultToName:n}){return(i,s,o,a)=>{let c=o===void 0?s:o instanceof pe.Name?(s instanceof pe.Name?r(i,s,o):e(i,s,o),o):s instanceof pe.Name?(e(i,o,s),s):t(s,o);return a===pe.Name&&!(c instanceof pe.Name)?n(i,c):c}}X.mergeEvaluated={props:kp({mergeNames:(r,e,t)=>r.if((0,pe._)`${t} !== true && ${e} !== undefined`,()=>{r.if((0,pe._)`${e} === true`,()=>r.assign(t,!0),()=>r.assign(t,(0,pe._)`${t} || {}`).code((0,pe._)`Object.assign(${t}, ${e})`))}),mergeToName:(r,e,t)=>r.if((0,pe._)`${t} !== true`,()=>{e===!0?r.assign(t,!0):(r.assign(t,(0,pe._)`${t} || {}`),dl(r,t,e))}),mergeValues:(r,e)=>r===!0?!0:{...r,...e},resultToName:Rp}),items:kp({mergeNames:(r,e,t)=>r.if((0,pe._)`${t} !== true && ${e} !== undefined`,()=>r.assign(t,(0,pe._)`${e} === true ? true : ${t} > ${e} ? ${t} : ${e}`)),mergeToName:(r,e,t)=>r.if((0,pe._)`${t} !== true`,()=>r.assign(t,e===!0?!0:(0,pe._)`${t} > ${e} ? ${t} : ${e}`)),mergeValues:(r,e)=>r===!0?!0:Math.max(r,e),resultToName:(r,e)=>r.var("items",e)})};function Rp(r,e){if(e===!0)return r.var("props",!0);let t=r.var("props",(0,pe._)`{}`);return e!==void 0&&dl(r,t,e),t}X.evaluatedPropsToName=Rp;function dl(r,e,t){Object.keys(t).forEach(n=>r.assign((0,pe._)`${e}${(0,pe.getProperty)(n)}`,!0))}X.setEvaluated=dl;var xp={};function pv(r,e){return r.scopeValue("func",{ref:e,code:xp[e.code]||(xp[e.code]=new sv._Code(e.code))})}X.useFunc=pv;var cl;(function(r){r[r.Num=0]="Num",r[r.Str=1]="Str"})(cl||(X.Type=cl={}));function hv(r,e,t){if(r instanceof pe.Name){let n=e===cl.Num;return t?n?(0,pe._)`"[" + ${r} + "]"`:(0,pe._)`"['" + ${r} + "']"`:n?(0,pe._)`"/" + ${r}`:(0,pe._)`"/" + ${r}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return t?(0,pe.getProperty)(r).toString():"/"+ll(r)}X.getErrorPath=hv;function Tp(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=Tp});var vt=A(ul=>{"use strict";Object.defineProperty(ul,"__esModule",{value:!0});var Ue=H(),mv={data:new Ue.Name("data"),valCxt:new Ue.Name("valCxt"),instancePath:new Ue.Name("instancePath"),parentData:new Ue.Name("parentData"),parentDataProperty:new Ue.Name("parentDataProperty"),rootData:new Ue.Name("rootData"),dynamicAnchors:new Ue.Name("dynamicAnchors"),vErrors:new Ue.Name("vErrors"),errors:new Ue.Name("errors"),this:new Ue.Name("this"),self:new Ue.Name("self"),scope:new Ue.Name("scope"),json:new Ue.Name("json"),jsonPos:new Ue.Name("jsonPos"),jsonLen:new Ue.Name("jsonLen"),jsonPart:new Ue.Name("jsonPart")};ul.default=mv});var Xi=A(Be=>{"use strict";Object.defineProperty(Be,"__esModule",{value:!0});Be.extendErrors=Be.resetErrorsCount=Be.reportExtraError=Be.reportError=Be.keyword$DataError=Be.keywordError=void 0;var ae=H(),ko=Q(),Je=vt();Be.keywordError={message:({keyword:r})=>(0,ae.str)`must pass "${r}" keyword validation`};Be.keyword$DataError={message:({keyword:r,schemaType:e})=>e?(0,ae.str)`"${r}" keyword must be ${e} ($data)`:(0,ae.str)`"${r}" keyword is invalid ($data)`};function yv(r,e=Be.keywordError,t,n){let{it:i}=r,{gen:s,compositeRule:o,allErrors:a}=i,c=Np(r,e,t);(n!=null?n:o||a)?Cp(s,c):Mp(i,(0,ae._)`[${c}]`)}Be.reportError=yv;function gv(r,e=Be.keywordError,t){let{it:n}=r,{gen:i,compositeRule:s,allErrors:o}=n,a=Np(r,e,t);Cp(i,a),s||o||Mp(n,Je.default.vErrors)}Be.reportExtraError=gv;function _v(r,e){r.assign(Je.default.errors,e),r.if((0,ae._)`${Je.default.vErrors} !== null`,()=>r.if(e,()=>r.assign((0,ae._)`${Je.default.vErrors}.length`,e),()=>r.assign(Je.default.vErrors,null)))}Be.resetErrorsCount=_v;function bv({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,Je.default.errors,a=>{r.const(o,(0,ae._)`${Je.default.vErrors}[${a}]`),r.if((0,ae._)`${o}.instancePath === undefined`,()=>r.assign((0,ae._)`${o}.instancePath`,(0,ae.strConcat)(Je.default.instancePath,s.errorPath))),r.assign((0,ae._)`${o}.schemaPath`,(0,ae.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(r.assign((0,ae._)`${o}.schema`,t),r.assign((0,ae._)`${o}.data`,n))})}Be.extendErrors=bv;function Cp(r,e){let t=r.const("err",e);r.if((0,ae._)`${Je.default.vErrors} === null`,()=>r.assign(Je.default.vErrors,(0,ae._)`[${t}]`),(0,ae._)`${Je.default.vErrors}.push(${t})`),r.code((0,ae._)`${Je.default.errors}++`)}function Mp(r,e){let{gen:t,validateName:n,schemaEnv:i}=r;i.$async?t.throw((0,ae._)`new ${r.ValidationError}(${e})`):(t.assign((0,ae._)`${n}.errors`,e),t.return(!1))}var gn={keyword:new ae.Name("keyword"),schemaPath:new ae.Name("schemaPath"),params:new ae.Name("params"),propertyName:new ae.Name("propertyName"),message:new ae.Name("message"),schema:new ae.Name("schema"),parentSchema:new ae.Name("parentSchema")};function Np(r,e,t){let{createErrors:n}=r.it;return n===!1?(0,ae._)`{}`:wv(r,e,t)}function wv(r,e,t={}){let{gen:n,it:i}=r,s=[vv(i,t),$v(r,t)];return Sv(r,e,s),n.object(...s)}function vv({errorPath:r},{instancePath:e}){let t=e?(0,ae.str)`${r}${(0,ko.getErrorPath)(e,ko.Type.Str)}`:r;return[Je.default.instancePath,(0,ae.strConcat)(Je.default.instancePath,t)]}function $v({keyword:r,it:{errSchemaPath:e}},{schemaPath:t,parentSchema:n}){let i=n?e:(0,ae.str)`${e}/${r}`;return t&&(i=(0,ae.str)`${i}${(0,ko.getErrorPath)(t,ko.Type.Str)}`),[gn.schemaPath,i]}function Sv(r,{params:e,message:t},n){let{keyword:i,data:s,schemaValue:o,it:a}=r,{opts:c,propertyName:l,topSchemaRef:d,schemaPath:u}=a;n.push([gn.keyword,i],[gn.params,typeof e=="function"?e(r):e||(0,ae._)`{}`]),c.messages&&n.push([gn.message,typeof t=="function"?t(r):t]),c.verbose&&n.push([gn.schema,o],[gn.parentSchema,(0,ae._)`${d}${u}`],[Je.default.data,s]),l&&n.push([gn.propertyName,l])}});var jp=A(Un=>{"use strict";Object.defineProperty(Un,"__esModule",{value:!0});Un.boolOrEmptySchema=Un.topBoolOrEmptySchema=void 0;var Ev=Xi(),Av=H(),kv=vt(),xv={message:"boolean schema is false"};function Pv(r){let{gen:e,schema:t,validateName:n}=r;t===!1?Lp(r,!1):typeof t=="object"&&t.$async===!0?e.return(kv.default.data):(e.assign((0,Av._)`${n}.errors`,null),e.return(!0))}Un.topBoolOrEmptySchema=Pv;function Iv(r,e){let{gen:t,schema:n}=r;n===!1?(t.var(e,!1),Lp(r)):t.var(e,!0)}Un.boolOrEmptySchema=Iv;function Lp(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,Ev.reportError)(i,xv,void 0,e)}});var fl=A(Bn=>{"use strict";Object.defineProperty(Bn,"__esModule",{value:!0});Bn.getRules=Bn.isJSONType=void 0;var Ov=["string","number","integer","boolean","null","object","array"],Rv=new Set(Ov);function Tv(r){return typeof r=="string"&&Rv.has(r)}Bn.isJSONType=Tv;function Cv(){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:{}}}Bn.getRules=Cv});var pl=A(Vr=>{"use strict";Object.defineProperty(Vr,"__esModule",{value:!0});Vr.shouldUseRule=Vr.shouldUseGroup=Vr.schemaHasRulesForType=void 0;function Mv({schema:r,self:e},t){let n=e.RULES.types[t];return n&&n!==!0&&Dp(r,n)}Vr.schemaHasRulesForType=Mv;function Dp(r,e){return e.rules.some(t=>qp(r,t))}Vr.shouldUseGroup=Dp;function qp(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))}Vr.shouldUseRule=qp});var Qi=A(ze=>{"use strict";Object.defineProperty(ze,"__esModule",{value:!0});ze.reportTypeError=ze.checkDataTypes=ze.checkDataType=ze.coerceAndCheckDataType=ze.getJSONTypes=ze.getSchemaTypes=ze.DataType=void 0;var Nv=fl(),Lv=pl(),jv=Xi(),W=H(),Fp=Q(),zn;(function(r){r[r.Correct=0]="Correct",r[r.Wrong=1]="Wrong"})(zn||(ze.DataType=zn={}));function Dv(r){let e=Vp(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}ze.getSchemaTypes=Dv;function Vp(r){let e=Array.isArray(r)?r:r?[r]:[];if(e.every(Nv.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}ze.getJSONTypes=Vp;function qv(r,e){let{gen:t,data:n,opts:i}=r,s=Fv(e,i.coerceTypes),o=e.length>0&&!(s.length===0&&e.length===1&&(0,Lv.schemaHasRulesForType)(r,e[0]));if(o){let a=ml(e,n,i.strictNumbers,zn.Wrong);t.if(a,()=>{s.length?Vv(r,e,s):yl(r)})}return o}ze.coerceAndCheckDataType=qv;var Up=new Set(["string","number","integer","boolean","null"]);function Fv(r,e){return e?r.filter(t=>Up.has(t)||e==="array"&&t==="array"):[]}function Vv(r,e,t){let{gen:n,data:i,opts:s}=r,o=n.let("dataType",(0,W._)`typeof ${i}`),a=n.let("coerced",(0,W._)`undefined`);s.coerceTypes==="array"&&n.if((0,W._)`${o} == 'object' && Array.isArray(${i}) && ${i}.length == 1`,()=>n.assign(i,(0,W._)`${i}[0]`).assign(o,(0,W._)`typeof ${i}`).if(ml(e,i,s.strictNumbers),()=>n.assign(a,i))),n.if((0,W._)`${a} !== undefined`);for(let l of t)(Up.has(l)||l==="array"&&s.coerceTypes==="array")&&c(l);n.else(),yl(r),n.endIf(),n.if((0,W._)`${a} !== undefined`,()=>{n.assign(i,a),Uv(r,a)});function c(l){switch(l){case"string":n.elseIf((0,W._)`${o} == "number" || ${o} == "boolean"`).assign(a,(0,W._)`"" + ${i}`).elseIf((0,W._)`${i} === null`).assign(a,(0,W._)`""`);return;case"number":n.elseIf((0,W._)`${o} == "boolean" || ${i} === null +var j0=Object.create;var Vi=Object.defineProperty;var D0=Object.getOwnPropertyDescriptor;var q0=Object.getOwnPropertyNames;var F0=Object.getPrototypeOf,V0=Object.prototype.hasOwnProperty;var U0=(r,e,t)=>e in r?Vi(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var E=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),B0=(r,e)=>{for(var t in e)Vi(r,t,{get:e[t],enumerable:!0})},vp=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of q0(e))!V0.call(r,i)&&i!==t&&Vi(r,i,{get:()=>e[i],enumerable:!(n=D0(e,i))||n.enumerable});return r};var fn=(r,e,t)=>(t=r!=null?j0(F0(r)):{},vp(e||!r||!r.__esModule?Vi(t,"default",{value:r,enumerable:!0}):t,r)),z0=r=>vp(Vi({},"__esModule",{value:!0}),r);var I=(r,e,t)=>U0(r,typeof e!="symbol"?e+"":e,t);var Hi=E(ce=>{"use strict";Object.defineProperty(ce,"__esModule",{value:!0});ce.regexpCode=ce.getEsmExportName=ce.getProperty=ce.safeStringify=ce.stringify=ce.strConcat=ce.addCodeArg=ce.str=ce._=ce.nil=ce._Code=ce.Name=ce.IDENTIFIER=ce._CodeOrName=void 0;var Bi=class{};ce._CodeOrName=Bi;ce.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var pn=class extends Bi{constructor(e){if(super(),!ce.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}}};ce.Name=pn;var wt=class extends Bi{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 pn&&(t[n.str]=(t[n.str]||0)+1),t),{})}};ce._Code=wt;ce.nil=new wt("");function $p(r,...e){let t=[r[0]],n=0;for(;n{"use strict";Object.defineProperty(st,"__esModule",{value:!0});st.ValueScope=st.ValueScopeName=st.Scope=st.varKinds=st.UsedValueState=void 0;var it=Hi(),Wc=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},bo;(function(r){r[r.Started=0]="Started",r[r.Completed=1]="Completed"})(bo||(st.UsedValueState=bo={}));st.varKinds={const:new it.Name("const"),let:new it.Name("let"),var:new it.Name("var")};var wo=class{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t}toName(e){return e instanceof it.Name?e:this.name(e)}name(e){return new it.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}}};st.Scope=wo;var vo=class extends it.Name{constructor(e,t){super(t),this.prefix=e}setValue(e,{property:t,itemIndex:n}){this.value=e,this.scopePath=(0,it._)`.${new it.Name(t)}[${n}]`}};st.ValueScopeName=vo;var Z0=(0,it._)`\n`,Gc=class extends wo{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?Z0:it.nil}}get(){return this._scope}name(e){return new vo(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 d=a.get(o);if(d)return d}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,it._)`${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=it.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,bo.Started);let d=t(l);if(d){let u=this.opts.es5?st.varKinds.var:st.varKinds.const;s=(0,it._)`${s}${u} ${l} = ${d};${this.opts._n}`}else if(d=i==null?void 0:i(l))s=(0,it._)`${s}${d}${this.opts._n}`;else throw new Wc(l);c.set(l,bo.Completed)})}return s}};st.ValueScope=Gc});var H=E(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 ie=Hi(),Rt=Jc(),Fr=Hi();Object.defineProperty(Y,"_",{enumerable:!0,get:function(){return Fr._}});Object.defineProperty(Y,"str",{enumerable:!0,get:function(){return Fr.str}});Object.defineProperty(Y,"strConcat",{enumerable:!0,get:function(){return Fr.strConcat}});Object.defineProperty(Y,"nil",{enumerable:!0,get:function(){return Fr.nil}});Object.defineProperty(Y,"getProperty",{enumerable:!0,get:function(){return Fr.getProperty}});Object.defineProperty(Y,"stringify",{enumerable:!0,get:function(){return Fr.stringify}});Object.defineProperty(Y,"regexpCode",{enumerable:!0,get:function(){return Fr.regexpCode}});Object.defineProperty(Y,"Name",{enumerable:!0,get:function(){return Fr.Name}});var Ao=Jc();Object.defineProperty(Y,"Scope",{enumerable:!0,get:function(){return Ao.Scope}});Object.defineProperty(Y,"ValueScope",{enumerable:!0,get:function(){return Ao.ValueScope}});Object.defineProperty(Y,"ValueScopeName",{enumerable:!0,get:function(){return Ao.ValueScopeName}});Object.defineProperty(Y,"varKinds",{enumerable:!0,get:function(){return Ao.varKinds}});Y.operators={GT:new ie._Code(">"),GTE:new ie._Code(">="),LT:new ie._Code("<"),LTE:new ie._Code("<="),EQ:new ie._Code("==="),NEQ:new ie._Code("!=="),NOT:new ie._Code("!"),OR:new ie._Code("||"),AND:new ie._Code("&&"),ADD:new ie._Code("+")};var yr=class{optimizeNodes(){return this}optimizeNames(e,t){return this}},Yc=class extends yr{constructor(e,t,n){super(),this.varKind=e,this.name=t,this.rhs=n}render({es5:e,_n:t}){let n=e?Rt.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=Vn(this.rhs,e,t)),this}get names(){return this.rhs instanceof ie._CodeOrName?this.rhs.names:{}}},$o=class extends yr{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 ie.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Vn(this.rhs,e,t),this}get names(){let e=this.lhs instanceof ie.Name?{}:{...this.lhs.names};return Eo(e,this.rhs)}},Xc=class extends $o{constructor(e,t,n,i){super(e,n,i),this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Qc=class extends yr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Zc=class extends yr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},el=class extends yr{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},tl=class extends yr{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=Vn(this.code,e,t),this}get names(){return this.code instanceof ie._CodeOrName?this.code.names:{}}},Ki=class extends yr{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)||(ev(e,s.names),n.splice(i,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>yn(e,t.names),{})}},gr=class extends Ki{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},rl=class extends Ki{},Fn=class extends gr{};Fn.kind="else";var hn=class r extends gr{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 Fn(n):n}if(t)return e===!1?t instanceof r?t:t.nodes:this.nodes.length?this:new r(Ep(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=Vn(this.condition,e,t),this}get names(){let e=super.names;return Eo(e,this.condition),this.else&&yn(e,this.else.names),e}};hn.kind="if";var mn=class extends gr{};mn.kind="for";var nl=class extends mn{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=Vn(this.iteration,e,t),this}get names(){return yn(super.names,this.iteration.names)}},il=class extends mn{constructor(e,t,n,i){super(),this.varKind=e,this.name=t,this.from=n,this.to=i}render(e){let t=e.es5?Rt.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=Eo(super.names,this.from);return Eo(e,this.to)}},So=class extends mn{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=Vn(this.iterable,e,t),this}get names(){return yn(super.names,this.iterable.names)}},Wi=class extends gr{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)}};Wi.kind="func";var Gi=class extends Ki{render(e){return"return "+super.render(e)}};Gi.kind="return";var sl=class extends gr{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&&yn(e,this.catch.names),this.finally&&yn(e,this.finally.names),e}},Ji=class extends gr{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};Ji.kind="catch";var Yi=class extends gr{render(e){return"finally"+super.render(e)}};Yi.kind="finally";var ol=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?` +`:""},this._extScope=e,this._scope=new Rt.Scope({parent:e}),this._nodes=[new rl]}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 Yc(e,s,n)),s}const(e,t,n){return this._def(Rt.varKinds.const,e,t,n)}let(e,t,n){return this._def(Rt.varKinds.let,e,t,n)}var(e,t,n){return this._def(Rt.varKinds.var,e,t,n)}assign(e,t,n){return this._leafNode(new $o(e,t,n))}add(e,t){return this._leafNode(new Xc(e,Y.operators.ADD,t))}code(e){return typeof e=="function"?e():e!==ie.nil&&this._leafNode(new tl(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,ie.addCodeArg)(t,i));return t.push("}"),new ie._Code(t)}if(e,t,n){if(this._blockNode(new hn(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 hn(e))}else(){return this._elseNode(new Fn)}endIf(){return this._endBlockNode(hn,Fn)}_for(e,t){return this._blockNode(e),t&&this.code(t).endFor(),this}for(e,t){return this._for(new nl(e),t)}forRange(e,t,n,i,s=this.opts.es5?Rt.varKinds.var:Rt.varKinds.let){let o=this._scope.toName(e);return this._for(new il(s,o,t,n),()=>i(o))}forOf(e,t,n,i=Rt.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let o=t instanceof ie.Name?t:this.var("_arr",t);return this.forRange("_i",0,(0,ie._)`${o}.length`,a=>{this.var(s,(0,ie._)`${o}[${a}]`),n(s)})}return this._for(new So("of",i,s,t),()=>n(s))}forIn(e,t,n,i=this.opts.es5?Rt.varKinds.var:Rt.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,ie._)`Object.keys(${t})`,n);let s=this._scope.toName(e);return this._for(new So("in",i,s,t),()=>n(s))}endFor(){return this._endBlockNode(mn)}label(e){return this._leafNode(new Qc(e))}break(e){return this._leafNode(new Zc(e))}return(e){let t=new Gi;if(this._blockNode(t),this.code(e),t.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Gi)}try(e,t,n){if(!t&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let i=new sl;if(this._blockNode(i),this.code(e),t){let s=this.name("e");this._currNode=i.catch=new Ji(s),t(s)}return n&&(this._currNode=i.finally=new Yi,this.code(n)),this._endBlockNode(Ji,Yi)}throw(e){return this._leafNode(new el(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=ie.nil,n,i){return this._blockNode(new Wi(e,t,n)),i&&this.code(i).endFunc(),this}endFunc(){return this._endBlockNode(Wi)}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 hn))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=ol;function yn(r,e){for(let t in e)r[t]=(r[t]||0)+(e[t]||0);return r}function Eo(r,e){return e instanceof ie._CodeOrName?yn(r,e.names):r}function Vn(r,e,t){if(r instanceof ie.Name)return n(r);if(!i(r))return r;return new ie._Code(r._items.reduce((s,o)=>(o instanceof ie.Name&&(o=n(o)),o instanceof ie._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 ie._Code&&s._items.some(o=>o instanceof ie.Name&&e[o.str]===1&&t[o.str]!==void 0)}}function ev(r,e){for(let t in e)r[t]=(r[t]||0)-(e[t]||0)}function Ep(r){return typeof r=="boolean"||typeof r=="number"||r===null?!r:(0,ie._)`!${al(r)}`}Y.not=Ep;var tv=Ap(Y.operators.AND);function rv(...r){return r.reduce(tv)}Y.and=rv;var nv=Ap(Y.operators.OR);function iv(...r){return r.reduce(nv)}Y.or=iv;function Ap(r){return(e,t)=>e===ie.nil?t:t===ie.nil?e:(0,ie._)`${al(e)} ${r} ${al(t)}`}function al(r){return r instanceof ie.Name?r:(0,ie._)`(${r})`}});var Q=E(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 pe=H(),sv=Hi();function ov(r){let e={};for(let t of r)e[t]=!0;return e}X.toHash=ov;function av(r,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(Pp(r,e),!Ip(e,r.self.RULES.all))}X.alwaysValidSchema=av;function Pp(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]||Tp(r,`unknown keyword: "${s}"`)}X.checkUnknownRules=Pp;function Ip(r,e){if(typeof r=="boolean")return!r;for(let t in r)if(e[t])return!0;return!1}X.schemaHasRules=Ip;function cv(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=cv;function lv({topSchemaRef:r,schemaPath:e},t,n,i){if(!i){if(typeof t=="number"||typeof t=="boolean")return t;if(typeof t=="string")return(0,pe._)`${t}`}return(0,pe._)`${r}${e}${(0,pe.getProperty)(n)}`}X.schemaRefOrVal=lv;function dv(r){return Op(decodeURIComponent(r))}X.unescapeFragment=dv;function uv(r){return encodeURIComponent(ll(r))}X.escapeFragment=uv;function ll(r){return typeof r=="number"?`${r}`:r.replace(/~/g,"~0").replace(/\//g,"~1")}X.escapeJsonPointer=ll;function Op(r){return r.replace(/~1/g,"/").replace(/~0/g,"~")}X.unescapeJsonPointer=Op;function fv(r,e){if(Array.isArray(r))for(let t of r)e(t);else e(r)}X.eachItem=fv;function kp({mergeNames:r,mergeToName:e,mergeValues:t,resultToName:n}){return(i,s,o,a)=>{let c=o===void 0?s:o instanceof pe.Name?(s instanceof pe.Name?r(i,s,o):e(i,s,o),o):s instanceof pe.Name?(e(i,o,s),s):t(s,o);return a===pe.Name&&!(c instanceof pe.Name)?n(i,c):c}}X.mergeEvaluated={props:kp({mergeNames:(r,e,t)=>r.if((0,pe._)`${t} !== true && ${e} !== undefined`,()=>{r.if((0,pe._)`${e} === true`,()=>r.assign(t,!0),()=>r.assign(t,(0,pe._)`${t} || {}`).code((0,pe._)`Object.assign(${t}, ${e})`))}),mergeToName:(r,e,t)=>r.if((0,pe._)`${t} !== true`,()=>{e===!0?r.assign(t,!0):(r.assign(t,(0,pe._)`${t} || {}`),dl(r,t,e))}),mergeValues:(r,e)=>r===!0?!0:{...r,...e},resultToName:Rp}),items:kp({mergeNames:(r,e,t)=>r.if((0,pe._)`${t} !== true && ${e} !== undefined`,()=>r.assign(t,(0,pe._)`${e} === true ? true : ${t} > ${e} ? ${t} : ${e}`)),mergeToName:(r,e,t)=>r.if((0,pe._)`${t} !== true`,()=>r.assign(t,e===!0?!0:(0,pe._)`${t} > ${e} ? ${t} : ${e}`)),mergeValues:(r,e)=>r===!0?!0:Math.max(r,e),resultToName:(r,e)=>r.var("items",e)})};function Rp(r,e){if(e===!0)return r.var("props",!0);let t=r.var("props",(0,pe._)`{}`);return e!==void 0&&dl(r,t,e),t}X.evaluatedPropsToName=Rp;function dl(r,e,t){Object.keys(t).forEach(n=>r.assign((0,pe._)`${e}${(0,pe.getProperty)(n)}`,!0))}X.setEvaluated=dl;var xp={};function pv(r,e){return r.scopeValue("func",{ref:e,code:xp[e.code]||(xp[e.code]=new sv._Code(e.code))})}X.useFunc=pv;var cl;(function(r){r[r.Num=0]="Num",r[r.Str=1]="Str"})(cl||(X.Type=cl={}));function hv(r,e,t){if(r instanceof pe.Name){let n=e===cl.Num;return t?n?(0,pe._)`"[" + ${r} + "]"`:(0,pe._)`"['" + ${r} + "']"`:n?(0,pe._)`"/" + ${r}`:(0,pe._)`"/" + ${r}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return t?(0,pe.getProperty)(r).toString():"/"+ll(r)}X.getErrorPath=hv;function Tp(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=Tp});var vt=E(ul=>{"use strict";Object.defineProperty(ul,"__esModule",{value:!0});var Ue=H(),mv={data:new Ue.Name("data"),valCxt:new Ue.Name("valCxt"),instancePath:new Ue.Name("instancePath"),parentData:new Ue.Name("parentData"),parentDataProperty:new Ue.Name("parentDataProperty"),rootData:new Ue.Name("rootData"),dynamicAnchors:new Ue.Name("dynamicAnchors"),vErrors:new Ue.Name("vErrors"),errors:new Ue.Name("errors"),this:new Ue.Name("this"),self:new Ue.Name("self"),scope:new Ue.Name("scope"),json:new Ue.Name("json"),jsonPos:new Ue.Name("jsonPos"),jsonLen:new Ue.Name("jsonLen"),jsonPart:new Ue.Name("jsonPart")};ul.default=mv});var Xi=E(Be=>{"use strict";Object.defineProperty(Be,"__esModule",{value:!0});Be.extendErrors=Be.resetErrorsCount=Be.reportExtraError=Be.reportError=Be.keyword$DataError=Be.keywordError=void 0;var ae=H(),ko=Q(),Je=vt();Be.keywordError={message:({keyword:r})=>(0,ae.str)`must pass "${r}" keyword validation`};Be.keyword$DataError={message:({keyword:r,schemaType:e})=>e?(0,ae.str)`"${r}" keyword must be ${e} ($data)`:(0,ae.str)`"${r}" keyword is invalid ($data)`};function yv(r,e=Be.keywordError,t,n){let{it:i}=r,{gen:s,compositeRule:o,allErrors:a}=i,c=Np(r,e,t);(n!=null?n:o||a)?Cp(s,c):Mp(i,(0,ae._)`[${c}]`)}Be.reportError=yv;function gv(r,e=Be.keywordError,t){let{it:n}=r,{gen:i,compositeRule:s,allErrors:o}=n,a=Np(r,e,t);Cp(i,a),s||o||Mp(n,Je.default.vErrors)}Be.reportExtraError=gv;function _v(r,e){r.assign(Je.default.errors,e),r.if((0,ae._)`${Je.default.vErrors} !== null`,()=>r.if(e,()=>r.assign((0,ae._)`${Je.default.vErrors}.length`,e),()=>r.assign(Je.default.vErrors,null)))}Be.resetErrorsCount=_v;function bv({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,Je.default.errors,a=>{r.const(o,(0,ae._)`${Je.default.vErrors}[${a}]`),r.if((0,ae._)`${o}.instancePath === undefined`,()=>r.assign((0,ae._)`${o}.instancePath`,(0,ae.strConcat)(Je.default.instancePath,s.errorPath))),r.assign((0,ae._)`${o}.schemaPath`,(0,ae.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(r.assign((0,ae._)`${o}.schema`,t),r.assign((0,ae._)`${o}.data`,n))})}Be.extendErrors=bv;function Cp(r,e){let t=r.const("err",e);r.if((0,ae._)`${Je.default.vErrors} === null`,()=>r.assign(Je.default.vErrors,(0,ae._)`[${t}]`),(0,ae._)`${Je.default.vErrors}.push(${t})`),r.code((0,ae._)`${Je.default.errors}++`)}function Mp(r,e){let{gen:t,validateName:n,schemaEnv:i}=r;i.$async?t.throw((0,ae._)`new ${r.ValidationError}(${e})`):(t.assign((0,ae._)`${n}.errors`,e),t.return(!1))}var gn={keyword:new ae.Name("keyword"),schemaPath:new ae.Name("schemaPath"),params:new ae.Name("params"),propertyName:new ae.Name("propertyName"),message:new ae.Name("message"),schema:new ae.Name("schema"),parentSchema:new ae.Name("parentSchema")};function Np(r,e,t){let{createErrors:n}=r.it;return n===!1?(0,ae._)`{}`:wv(r,e,t)}function wv(r,e,t={}){let{gen:n,it:i}=r,s=[vv(i,t),$v(r,t)];return Sv(r,e,s),n.object(...s)}function vv({errorPath:r},{instancePath:e}){let t=e?(0,ae.str)`${r}${(0,ko.getErrorPath)(e,ko.Type.Str)}`:r;return[Je.default.instancePath,(0,ae.strConcat)(Je.default.instancePath,t)]}function $v({keyword:r,it:{errSchemaPath:e}},{schemaPath:t,parentSchema:n}){let i=n?e:(0,ae.str)`${e}/${r}`;return t&&(i=(0,ae.str)`${i}${(0,ko.getErrorPath)(t,ko.Type.Str)}`),[gn.schemaPath,i]}function Sv(r,{params:e,message:t},n){let{keyword:i,data:s,schemaValue:o,it:a}=r,{opts:c,propertyName:l,topSchemaRef:d,schemaPath:u}=a;n.push([gn.keyword,i],[gn.params,typeof e=="function"?e(r):e||(0,ae._)`{}`]),c.messages&&n.push([gn.message,typeof t=="function"?t(r):t]),c.verbose&&n.push([gn.schema,o],[gn.parentSchema,(0,ae._)`${d}${u}`],[Je.default.data,s]),l&&n.push([gn.propertyName,l])}});var jp=E(Un=>{"use strict";Object.defineProperty(Un,"__esModule",{value:!0});Un.boolOrEmptySchema=Un.topBoolOrEmptySchema=void 0;var Ev=Xi(),Av=H(),kv=vt(),xv={message:"boolean schema is false"};function Pv(r){let{gen:e,schema:t,validateName:n}=r;t===!1?Lp(r,!1):typeof t=="object"&&t.$async===!0?e.return(kv.default.data):(e.assign((0,Av._)`${n}.errors`,null),e.return(!0))}Un.topBoolOrEmptySchema=Pv;function Iv(r,e){let{gen:t,schema:n}=r;n===!1?(t.var(e,!1),Lp(r)):t.var(e,!0)}Un.boolOrEmptySchema=Iv;function Lp(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,Ev.reportError)(i,xv,void 0,e)}});var fl=E(Bn=>{"use strict";Object.defineProperty(Bn,"__esModule",{value:!0});Bn.getRules=Bn.isJSONType=void 0;var Ov=["string","number","integer","boolean","null","object","array"],Rv=new Set(Ov);function Tv(r){return typeof r=="string"&&Rv.has(r)}Bn.isJSONType=Tv;function Cv(){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:{}}}Bn.getRules=Cv});var pl=E(Vr=>{"use strict";Object.defineProperty(Vr,"__esModule",{value:!0});Vr.shouldUseRule=Vr.shouldUseGroup=Vr.schemaHasRulesForType=void 0;function Mv({schema:r,self:e},t){let n=e.RULES.types[t];return n&&n!==!0&&Dp(r,n)}Vr.schemaHasRulesForType=Mv;function Dp(r,e){return e.rules.some(t=>qp(r,t))}Vr.shouldUseGroup=Dp;function qp(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))}Vr.shouldUseRule=qp});var Qi=E(ze=>{"use strict";Object.defineProperty(ze,"__esModule",{value:!0});ze.reportTypeError=ze.checkDataTypes=ze.checkDataType=ze.coerceAndCheckDataType=ze.getJSONTypes=ze.getSchemaTypes=ze.DataType=void 0;var Nv=fl(),Lv=pl(),jv=Xi(),W=H(),Fp=Q(),zn;(function(r){r[r.Correct=0]="Correct",r[r.Wrong=1]="Wrong"})(zn||(ze.DataType=zn={}));function Dv(r){let e=Vp(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}ze.getSchemaTypes=Dv;function Vp(r){let e=Array.isArray(r)?r:r?[r]:[];if(e.every(Nv.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}ze.getJSONTypes=Vp;function qv(r,e){let{gen:t,data:n,opts:i}=r,s=Fv(e,i.coerceTypes),o=e.length>0&&!(s.length===0&&e.length===1&&(0,Lv.schemaHasRulesForType)(r,e[0]));if(o){let a=ml(e,n,i.strictNumbers,zn.Wrong);t.if(a,()=>{s.length?Vv(r,e,s):yl(r)})}return o}ze.coerceAndCheckDataType=qv;var Up=new Set(["string","number","integer","boolean","null"]);function Fv(r,e){return e?r.filter(t=>Up.has(t)||e==="array"&&t==="array"):[]}function Vv(r,e,t){let{gen:n,data:i,opts:s}=r,o=n.let("dataType",(0,W._)`typeof ${i}`),a=n.let("coerced",(0,W._)`undefined`);s.coerceTypes==="array"&&n.if((0,W._)`${o} == 'object' && Array.isArray(${i}) && ${i}.length == 1`,()=>n.assign(i,(0,W._)`${i}[0]`).assign(o,(0,W._)`typeof ${i}`).if(ml(e,i,s.strictNumbers),()=>n.assign(a,i))),n.if((0,W._)`${a} !== undefined`);for(let l of t)(Up.has(l)||l==="array"&&s.coerceTypes==="array")&&c(l);n.else(),yl(r),n.endIf(),n.if((0,W._)`${a} !== undefined`,()=>{n.assign(i,a),Uv(r,a)});function c(l){switch(l){case"string":n.elseIf((0,W._)`${o} == "number" || ${o} == "boolean"`).assign(a,(0,W._)`"" + ${i}`).elseIf((0,W._)`${i} === null`).assign(a,(0,W._)`""`);return;case"number":n.elseIf((0,W._)`${o} == "boolean" || ${i} === null || (${o} == "string" && ${i} && ${i} == +${i})`).assign(a,(0,W._)`+${i}`);return;case"integer":n.elseIf((0,W._)`${o} === "boolean" || ${i} === null || (${o} === "string" && ${i} && ${i} == +${i} && !(${i} % 1))`).assign(a,(0,W._)`+${i}`);return;case"boolean":n.elseIf((0,W._)`${i} === "false" || ${i} === 0 || ${i} === null`).assign(a,!1).elseIf((0,W._)`${i} === "true" || ${i} === 1`).assign(a,!0);return;case"null":n.elseIf((0,W._)`${i} === "" || ${i} === 0 || ${i} === false`),n.assign(a,null);return;case"array":n.elseIf((0,W._)`${o} === "string" || ${o} === "number" - || ${o} === "boolean" || ${i} === null`).assign(a,(0,W._)`[${i}]`)}}}function Uv({gen:r,parentData:e,parentDataProperty:t},n){r.if((0,W._)`${e} !== undefined`,()=>r.assign((0,W._)`${e}[${t}]`,n))}function hl(r,e,t,n=zn.Correct){let i=n===zn.Correct?W.operators.EQ:W.operators.NEQ,s;switch(r){case"null":return(0,W._)`${e} ${i} null`;case"array":s=(0,W._)`Array.isArray(${e})`;break;case"object":s=(0,W._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=o((0,W._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=o();break;default:return(0,W._)`typeof ${e} ${i} ${r}`}return n===zn.Correct?s:(0,W.not)(s);function o(a=W.nil){return(0,W.and)((0,W._)`typeof ${e} == "number"`,a,t?(0,W._)`isFinite(${e})`:W.nil)}}ze.checkDataType=hl;function ml(r,e,t,n){if(r.length===1)return hl(r[0],e,t,n);let i,s=(0,Fp.toHash)(r);if(s.array&&s.object){let o=(0,W._)`typeof ${e} != "object"`;i=s.null?o:(0,W._)`!${e} || ${o}`,delete s.null,delete s.array,delete s.object}else i=W.nil;s.number&&delete s.integer;for(let o in s)i=(0,W.and)(i,hl(o,e,t,n));return i}ze.checkDataTypes=ml;var Bv={message:({schema:r})=>`must be ${r}`,params:({schema:r,schemaValue:e})=>typeof r=="string"?(0,W._)`{type: ${r}}`:(0,W._)`{type: ${e}}`};function yl(r){let e=zv(r);(0,jv.reportError)(e,Bv)}ze.reportTypeError=yl;function zv(r){let{gen:e,data:t,schema:n}=r,i=(0,Fp.schemaRefOrVal)(r,n,"type");return{gen:e,keyword:"type",data:t,schema:n.type,schemaCode:i,schemaValue:i,parentSchema:n,params:{},it:r}}});var zp=A(xo=>{"use strict";Object.defineProperty(xo,"__esModule",{value:!0});xo.assignDefaults=void 0;var Hn=H(),Hv=Q();function Kv(r,e){let{properties:t,items:n}=r.schema;if(e==="object"&&t)for(let i in t)Bp(r,i,t[i].default);else e==="array"&&Array.isArray(n)&&n.forEach((i,s)=>Bp(r,s,i.default))}xo.assignDefaults=Kv;function Bp(r,e,t){let{gen:n,compositeRule:i,data:s,opts:o}=r;if(t===void 0)return;let a=(0,Hn._)`${s}${(0,Hn.getProperty)(e)}`;if(i){(0,Hv.checkStrictMode)(r,`default is ignored for: ${a}`);return}let c=(0,Hn._)`${a} === undefined`;o.useDefaults==="empty"&&(c=(0,Hn._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,Hn._)`${a} = ${(0,Hn.stringify)(t)}`)}});var $t=A(ue=>{"use strict";Object.defineProperty(ue,"__esModule",{value:!0});ue.validateUnion=ue.validateArray=ue.usePattern=ue.callValidateCode=ue.schemaProperties=ue.allSchemaProperties=ue.noPropertyInData=ue.propertyInData=ue.isOwnProperty=ue.hasPropFunc=ue.reportMissingProp=ue.checkMissingProp=ue.checkReportMissingProp=void 0;var ge=H(),gl=Q(),Ur=vt(),Wv=Q();function Gv(r,e){let{gen:t,data:n,it:i}=r;t.if(bl(t,n,e,i.opts.ownProperties),()=>{r.setParams({missingProperty:(0,ge._)`${e}`},!0),r.error()})}ue.checkReportMissingProp=Gv;function Jv({gen:r,data:e,it:{opts:t}},n,i){return(0,ge.or)(...n.map(s=>(0,ge.and)(bl(r,e,s,t.ownProperties),(0,ge._)`${i} = ${s}`)))}ue.checkMissingProp=Jv;function Yv(r,e){r.setParams({missingProperty:e},!0),r.error()}ue.reportMissingProp=Yv;function Hp(r){return r.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,ge._)`Object.prototype.hasOwnProperty`})}ue.hasPropFunc=Hp;function _l(r,e,t){return(0,ge._)`${Hp(r)}.call(${e}, ${t})`}ue.isOwnProperty=_l;function Xv(r,e,t,n){let i=(0,ge._)`${e}${(0,ge.getProperty)(t)} !== undefined`;return n?(0,ge._)`${i} && ${_l(r,e,t)}`:i}ue.propertyInData=Xv;function bl(r,e,t,n){let i=(0,ge._)`${e}${(0,ge.getProperty)(t)} === undefined`;return n?(0,ge.or)(i,(0,ge.not)(_l(r,e,t))):i}ue.noPropertyInData=bl;function Kp(r){return r?Object.keys(r).filter(e=>e!=="__proto__"):[]}ue.allSchemaProperties=Kp;function Qv(r,e){return Kp(e).filter(t=>!(0,gl.alwaysValidSchema)(r,e[t]))}ue.schemaProperties=Qv;function Zv({schemaCode:r,data:e,it:{gen:t,topSchemaRef:n,schemaPath:i,errorPath:s},it:o},a,c,l){let d=l?(0,ge._)`${r}, ${e}, ${n}${i}`:e,u=[[Ur.default.instancePath,(0,ge.strConcat)(Ur.default.instancePath,s)],[Ur.default.parentData,o.parentData],[Ur.default.parentDataProperty,o.parentDataProperty],[Ur.default.rootData,Ur.default.rootData]];o.opts.dynamicRef&&u.push([Ur.default.dynamicAnchors,Ur.default.dynamicAnchors]);let f=(0,ge._)`${d}, ${t.object(...u)}`;return c!==ge.nil?(0,ge._)`${a}.call(${c}, ${f})`:(0,ge._)`${a}(${f})`}ue.callValidateCode=Zv;var e$=(0,ge._)`new RegExp`;function t$({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,ge._)`${i.code==="new RegExp"?e$:(0,Wv.useFunc)(r,i)}(${t}, ${n})`})}ue.usePattern=t$;function r$(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,ge._)`${t}.length`);e.forRange("i",0,c,l=>{r.subschema({keyword:n,dataProp:l,dataPropType:gl.Type.Num},s),e.if((0,ge.not)(s),a)})}}ue.validateArray=r$;function n$(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,gl.alwaysValidSchema)(i,c))&&!i.opts.unevaluated)return;let o=e.let("valid",!1),a=e.name("_valid");e.block(()=>t.forEach((c,l)=>{let d=r.subschema({keyword:n,schemaProp:l,compositeRule:!0},a);e.assign(o,(0,ge._)`${o} || ${a}`),r.mergeValidEvaluated(d,a)||e.if((0,ge.not)(o))})),r.result(o,()=>r.reset(),()=>r.error(!0))}ue.validateUnion=n$});var Jp=A(Qt=>{"use strict";Object.defineProperty(Qt,"__esModule",{value:!0});Qt.validateKeywordUsage=Qt.validSchemaType=Qt.funcKeywordCode=Qt.macroKeywordCode=void 0;var Ye=H(),_n=vt(),i$=$t(),s$=Xi();function o$(r,e){let{gen:t,keyword:n,schema:i,parentSchema:s,it:o}=r,a=e.macro.call(o.self,i,s,o),c=Gp(t,n,a);o.opts.validateSchema!==!1&&o.self.validateSchema(a,!0);let l=t.name("valid");r.subschema({schema:a,schemaPath:Ye.nil,errSchemaPath:`${o.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},l),r.pass(l,()=>r.error(!0))}Qt.macroKeywordCode=o$;function a$(r,e){var t;let{gen:n,keyword:i,schema:s,parentSchema:o,$data:a,it:c}=r;l$(c,e);let l=!a&&e.compile?e.compile.call(c.self,s,o,c):e.validate,d=Gp(n,i,l),u=n.let("valid");r.block$data(u,f),r.ok((t=e.valid)!==null&&t!==void 0?t:u);function f(){if(e.errors===!1)h(),e.modifying&&Wp(r),m(()=>r.error());else{let g=e.async?p():y();e.modifying&&Wp(r),m(()=>c$(r,g))}}function p(){let g=n.let("ruleErrs",null);return n.try(()=>h((0,Ye._)`await `),_=>n.assign(u,!1).if((0,Ye._)`${_} instanceof ${c.ValidationError}`,()=>n.assign(g,(0,Ye._)`${_}.errors`),()=>n.throw(_))),g}function y(){let g=(0,Ye._)`${d}.errors`;return n.assign(g,null),h(Ye.nil),g}function h(g=e.async?(0,Ye._)`await `:Ye.nil){let _=c.opts.passContext?_n.default.this:_n.default.self,w=!("compile"in e&&!a||e.schema===!1);n.assign(u,(0,Ye._)`${g}${(0,i$.callValidateCode)(r,d,_,w)}`,e.modifying)}function m(g){var _;n.if((0,Ye.not)((_=e.valid)!==null&&_!==void 0?_:u),g)}}Qt.funcKeywordCode=a$;function Wp(r){let{gen:e,data:t,it:n}=r;e.if(n.parentData,()=>e.assign(t,(0,Ye._)`${n.parentData}[${n.parentDataProperty}]`))}function c$(r,e){let{gen:t}=r;t.if((0,Ye._)`Array.isArray(${e})`,()=>{t.assign(_n.default.vErrors,(0,Ye._)`${_n.default.vErrors} === null ? ${e} : ${_n.default.vErrors}.concat(${e})`).assign(_n.default.errors,(0,Ye._)`${_n.default.vErrors}.length`),(0,s$.extendErrors)(r)},()=>r.error())}function l$({schemaEnv:r},e){if(e.async&&!r.$async)throw new Error("async keyword in sync schema")}function Gp(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,Ye.stringify)(t)})}function d$(r,e,t=!1){return!e.length||e.some(n=>n==="array"?Array.isArray(r):n==="object"?r&&typeof r=="object"&&!Array.isArray(r):typeof r==n||t&&typeof r=="undefined")}Qt.validSchemaType=d$;function u$({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!=null&&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)}}Qt.validateKeywordUsage=u$});var Xp=A(Br=>{"use strict";Object.defineProperty(Br,"__esModule",{value:!0});Br.extendSubschemaMode=Br.extendSubschemaData=Br.getSubschema=void 0;var Zt=H(),Yp=Q();function f$(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,Zt._)`${r.schemaPath}${(0,Zt.getProperty)(e)}`,errSchemaPath:`${r.errSchemaPath}/${e}`}:{schema:a[t],schemaPath:(0,Zt._)`${r.schemaPath}${(0,Zt.getProperty)(e)}${(0,Zt.getProperty)(t)}`,errSchemaPath:`${r.errSchemaPath}/${e}/${(0,Yp.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')}Br.getSubschema=f$;function p$(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:d,opts:u}=e,f=a.let("data",(0,Zt._)`${e.data}${(0,Zt.getProperty)(t)}`,!0);c(f),r.errorPath=(0,Zt.str)`${l}${(0,Yp.getErrorPath)(t,n,u.jsPropertySyntax)}`,r.parentDataProperty=(0,Zt._)`${t}`,r.dataPathArr=[...d,r.parentDataProperty]}if(i!==void 0){let l=i instanceof Zt.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]}}Br.extendSubschemaData=p$;function h$(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}Br.extendSubschemaMode=h$});var wl=A((zM,Qp)=>{"use strict";Qp.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 eh=A((HM,Zp)=>{"use strict";var zr=Zp.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(){};Po(e,n,i,r,"",r)};zr.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};zr.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};zr.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};zr.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 Po(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 d in n){var u=n[d];if(Array.isArray(u)){if(d in zr.arrayKeywords)for(var f=0;f{"use strict";Object.defineProperty(ot,"__esModule",{value:!0});ot.getSchemaRefs=ot.resolveUrl=ot.normalizeId=ot._getFullPath=ot.getFullPath=ot.inlineRef=void 0;var y$=Q(),g$=wl(),_$=eh(),b$=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function w$(r,e=!0){return typeof r=="boolean"?!0:e===!0?!vl(r):e?th(r)<=e:!1}ot.inlineRef=w$;var v$=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function vl(r){for(let e in r){if(v$.has(e))return!0;let t=r[e];if(Array.isArray(t)&&t.some(vl)||typeof t=="object"&&vl(t))return!0}return!1}function th(r){let e=0;for(let t in r){if(t==="$ref")return 1/0;if(e++,!b$.has(t)&&(typeof r[t]=="object"&&(0,y$.eachItem)(r[t],n=>e+=th(n)),e===1/0))return 1/0}return e}function rh(r,e="",t){t!==!1&&(e=Kn(e));let n=r.parse(e);return nh(r,n)}ot.getFullPath=rh;function nh(r,e){return r.serialize(e).split("#")[0]+"#"}ot._getFullPath=nh;var $$=/#\/?$/;function Kn(r){return r?r.replace($$,""):""}ot.normalizeId=Kn;function S$(r,e,t){return t=Kn(t),r.resolve(e,t)}ot.resolveUrl=S$;var E$=/^[a-z_][-a-z0-9._]*$/i;function A$(r,e){if(typeof r=="boolean")return{};let{schemaId:t,uriResolver:n}=this.opts,i=Kn(r[t]||e),s={"":i},o=rh(n,i,!1),a={},c=new Set;return _$(r,{allKeys:!0},(u,f,p,y)=>{if(y===void 0)return;let h=o+f,m=s[y];typeof u[t]=="string"&&(m=g.call(this,u[t])),_.call(this,u.$anchor),_.call(this,u.$dynamicAnchor),s[f]=m;function g(w){let x=this.opts.uriResolver.resolve;if(w=Kn(m?x(m,w):w),c.has(w))throw d(w);c.add(w);let v=this.refs[w];return typeof v=="string"&&(v=this.refs[v]),typeof v=="object"?l(u,v.schema,w):w!==Kn(h)&&(w[0]==="#"?(l(u,a[w],w),a[w]=u):this.refs[w]=h),w}function _(w){if(typeof w=="string"){if(!E$.test(w))throw new Error(`invalid anchor "${w}"`);g.call(this,`#${w}`)}}}),a;function l(u,f,p){if(f!==void 0&&!g$(u,f))throw d(p)}function d(u){return new Error(`reference "${u}" resolves to more than one schema`)}}ot.getSchemaRefs=A$});var Wn=A(Hr=>{"use strict";Object.defineProperty(Hr,"__esModule",{value:!0});Hr.getData=Hr.KeywordCxt=Hr.validateFunctionCode=void 0;var ch=jp(),ih=Qi(),Sl=pl(),Io=Qi(),k$=zp(),ts=Jp(),$l=Xp(),F=H(),z=vt(),x$=Zi(),_r=Q(),es=Xi();function P$(r){if(uh(r)&&(fh(r),dh(r))){R$(r);return}lh(r,()=>(0,ch.topBoolOrEmptySchema)(r))}Hr.validateFunctionCode=P$;function lh({gen:r,validateName:e,schema:t,schemaEnv:n,opts:i},s){i.code.es5?r.func(e,(0,F._)`${z.default.data}, ${z.default.valCxt}`,n.$async,()=>{r.code((0,F._)`"use strict"; ${sh(t,i)}`),O$(r,i),r.code(s)}):r.func(e,(0,F._)`${z.default.data}, ${I$(i)}`,n.$async,()=>r.code(sh(t,i)).code(s))}function I$(r){return(0,F._)`{${z.default.instancePath}="", ${z.default.parentData}, ${z.default.parentDataProperty}, ${z.default.rootData}=${z.default.data}${r.dynamicRef?(0,F._)`, ${z.default.dynamicAnchors}={}`:F.nil}}={}`}function O$(r,e){r.if(z.default.valCxt,()=>{r.var(z.default.instancePath,(0,F._)`${z.default.valCxt}.${z.default.instancePath}`),r.var(z.default.parentData,(0,F._)`${z.default.valCxt}.${z.default.parentData}`),r.var(z.default.parentDataProperty,(0,F._)`${z.default.valCxt}.${z.default.parentDataProperty}`),r.var(z.default.rootData,(0,F._)`${z.default.valCxt}.${z.default.rootData}`),e.dynamicRef&&r.var(z.default.dynamicAnchors,(0,F._)`${z.default.valCxt}.${z.default.dynamicAnchors}`)},()=>{r.var(z.default.instancePath,(0,F._)`""`),r.var(z.default.parentData,(0,F._)`undefined`),r.var(z.default.parentDataProperty,(0,F._)`undefined`),r.var(z.default.rootData,z.default.data),e.dynamicRef&&r.var(z.default.dynamicAnchors,(0,F._)`{}`)})}function R$(r){let{schema:e,opts:t,gen:n}=r;lh(r,()=>{t.$comment&&e.$comment&&hh(r),L$(r),n.let(z.default.vErrors,null),n.let(z.default.errors,0),t.unevaluated&&T$(r),ph(r),q$(r)})}function T$(r){let{gen:e,validateName:t}=r;r.evaluated=e.const("evaluated",(0,F._)`${t}.evaluated`),e.if((0,F._)`${r.evaluated}.dynamicProps`,()=>e.assign((0,F._)`${r.evaluated}.props`,(0,F._)`undefined`)),e.if((0,F._)`${r.evaluated}.dynamicItems`,()=>e.assign((0,F._)`${r.evaluated}.items`,(0,F._)`undefined`))}function sh(r,e){let t=typeof r=="object"&&r[e.schemaId];return t&&(e.code.source||e.code.process)?(0,F._)`/*# sourceURL=${t} */`:F.nil}function C$(r,e){if(uh(r)&&(fh(r),dh(r))){M$(r,e);return}(0,ch.boolOrEmptySchema)(r,e)}function dh({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 uh(r){return typeof r.schema!="boolean"}function M$(r,e){let{schema:t,gen:n,opts:i}=r;i.$comment&&t.$comment&&hh(r),j$(r),D$(r);let s=n.const("_errs",z.default.errors);ph(r,s),n.var(e,(0,F._)`${s} === ${z.default.errors}`)}function fh(r){(0,_r.checkUnknownRules)(r),N$(r)}function ph(r,e){if(r.opts.jtd)return oh(r,[],!1,e);let t=(0,ih.getSchemaTypes)(r.schema),n=(0,ih.coerceAndCheckDataType)(r,t);oh(r,t,!n,e)}function N$(r){let{schema:e,errSchemaPath:t,opts:n,self:i}=r;e.$ref&&n.ignoreKeywordsWithRef&&(0,_r.schemaHasRulesButRef)(e,i.RULES)&&i.logger.warn(`$ref: keywords ignored in schema at path "${t}"`)}function L$(r){let{schema:e,opts:t}=r;e.default!==void 0&&t.useDefaults&&t.strictSchema&&(0,_r.checkStrictMode)(r,"default is ignored in the schema root")}function j$(r){let e=r.schema[r.opts.schemaId];e&&(r.baseId=(0,x$.resolveUrl)(r.opts.uriResolver,r.baseId,e))}function D$(r){if(r.schema.$async&&!r.schemaEnv.$async)throw new Error("async schema in sync schema")}function hh({gen:r,schemaEnv:e,schema:t,errSchemaPath:n,opts:i}){let s=t.$comment;if(i.$comment===!0)r.code((0,F._)`${z.default.self}.logger.log(${s})`);else if(typeof i.$comment=="function"){let o=(0,F.str)`${n}/$comment`,a=r.scopeValue("root",{ref:e.root});r.code((0,F._)`${z.default.self}.opts.$comment(${s}, ${o}, ${a}.schema)`)}}function q$(r){let{gen:e,schemaEnv:t,validateName:n,ValidationError:i,opts:s}=r;t.$async?e.if((0,F._)`${z.default.errors} === 0`,()=>e.return(z.default.data),()=>e.throw((0,F._)`new ${i}(${z.default.vErrors})`)):(e.assign((0,F._)`${n}.errors`,z.default.vErrors),s.unevaluated&&F$(r),e.return((0,F._)`${z.default.errors} === 0`))}function F$({gen:r,evaluated:e,props:t,items:n}){t instanceof F.Name&&r.assign((0,F._)`${e}.props`,t),n instanceof F.Name&&r.assign((0,F._)`${e}.items`,n)}function oh(r,e,t,n){let{gen:i,schema:s,data:o,allErrors:a,opts:c,self:l}=r,{RULES:d}=l;if(s.$ref&&(c.ignoreKeywordsWithRef||!(0,_r.schemaHasRulesButRef)(s,d))){i.block(()=>yh(r,"$ref",d.all.$ref.definition));return}c.jtd||V$(r,e),i.block(()=>{for(let f of d.rules)u(f);u(d.post)});function u(f){(0,Sl.shouldUseGroup)(s,f)&&(f.type?(i.if((0,Io.checkDataType)(f.type,o,c.strictNumbers)),ah(r,f),e.length===1&&e[0]===f.type&&t&&(i.else(),(0,Io.reportTypeError)(r)),i.endIf()):ah(r,f),a||i.if((0,F._)`${z.default.errors} === ${n||0}`))}}function ah(r,e){let{gen:t,schema:n,opts:{useDefaults:i}}=r;i&&(0,k$.assignDefaults)(r,e.type),t.block(()=>{for(let s of e.rules)(0,Sl.shouldUseRule)(n,s)&&yh(r,s.keyword,s.definition,e.type)})}function V$(r,e){r.schemaEnv.meta||!r.opts.strictTypes||(U$(r,e),r.opts.allowUnionTypes||B$(r,e),z$(r,r.dataTypes))}function U$(r,e){if(e.length){if(!r.dataTypes.length){r.dataTypes=e;return}e.forEach(t=>{mh(r.dataTypes,t)||El(r,`type "${t}" not allowed by context "${r.dataTypes.join(",")}"`)}),K$(r,e)}}function B$(r,e){e.length>1&&!(e.length===2&&e.includes("null"))&&El(r,"use allowUnionTypes to allow union type keyword")}function z$(r,e){let t=r.self.RULES.all;for(let n in t){let i=t[n];if(typeof i=="object"&&(0,Sl.shouldUseRule)(r.schema,i)){let{type:s}=i.definition;s.length&&!s.some(o=>H$(e,o))&&El(r,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function H$(r,e){return r.includes(e)||e==="number"&&r.includes("integer")}function mh(r,e){return r.includes(e)||e==="integer"&&r.includes("number")}function K$(r,e){let t=[];for(let n of r.dataTypes)mh(e,n)?t.push(n):e.includes("integer")&&n==="number"&&t.push("integer");r.dataTypes=t}function El(r,e){let t=r.schemaEnv.baseId+r.errSchemaPath;e+=` at "${t}" (strictTypes)`,(0,_r.checkStrictMode)(r,e,r.opts.strictTypes)}var Oo=class{constructor(e,t,n){if((0,ts.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,_r.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",gh(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,ts.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",z.default.errors))}result(e,t,n){this.failResult((0,F.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,F.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,F._)`${t} !== undefined && (${(0,F.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?es.reportExtraError:es.reportError)(this,this.def.error,t)}$dataError(){(0,es.reportError)(this,this.def.$dataError||es.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,es.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=F.nil){this.gen.block(()=>{this.check$data(e,n),t()})}check$data(e=F.nil,t=F.nil){if(!this.$data)return;let{gen:n,schemaCode:i,schemaType:s,def:o}=this;n.if((0,F.or)((0,F._)`${i} === undefined`,t)),e!==F.nil&&n.assign(e,!0),(s.length||o.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==F.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:t,schemaType:n,def:i,it:s}=this;return(0,F.or)(o(),a());function o(){if(n.length){if(!(t instanceof F.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,F._)`${(0,Io.checkDataTypes)(c,t,s.opts.strictNumbers,Io.DataType.Wrong)}`}return F.nil}function a(){if(i.validateSchema){let c=e.scopeValue("validate$data",{ref:i.validateSchema});return(0,F._)`!${c}(${t})`}return F.nil}}subschema(e,t){let n=(0,$l.getSubschema)(this.it,e);(0,$l.extendSubschemaData)(n,this.it,e),(0,$l.extendSubschemaMode)(n,e);let i={...this.it,...n,items:void 0,props:void 0};return C$(i,t),i}mergeEvaluated(e,t){let{it:n,gen:i}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=_r.mergeEvaluated.props(i,e.props,n.props,t)),n.items!==!0&&e.items!==void 0&&(n.items=_r.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,F.Name)),!0}};Hr.KeywordCxt=Oo;function yh(r,e,t,n){let i=new Oo(r,t,e);"code"in t?t.code(i,n):i.$data&&t.validate?(0,ts.funcKeywordCode)(i,t):"macro"in t?(0,ts.macroKeywordCode)(i,t):(t.compile||t.validate)&&(0,ts.funcKeywordCode)(i,t)}var W$=/^\/(?:[^~]|~0|~1)*$/,G$=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function gh(r,{dataLevel:e,dataNames:t,dataPathArr:n}){let i,s;if(r==="")return z.default.rootData;if(r[0]==="/"){if(!W$.test(r))throw new Error(`Invalid JSON-pointer: ${r}`);i=r,s=z.default.rootData}else{let l=G$.exec(r);if(!l)throw new Error(`Invalid JSON-pointer: ${r}`);let d=+l[1];if(i=l[2],i==="#"){if(d>=e)throw new Error(c("property/index",d));return n[e-d]}if(d>e)throw new Error(c("data",d));if(s=t[e-d],!i)return s}let o=s,a=i.split("/");for(let l of a)l&&(s=(0,F._)`${s}${(0,F.getProperty)((0,_r.unescapeJsonPointer)(l))}`,o=(0,F._)`${o} && ${s}`);return o;function c(l,d){return`Cannot access ${l} ${d} levels up, current level is ${e}`}}Hr.getData=gh});var rs=A(kl=>{"use strict";Object.defineProperty(kl,"__esModule",{value:!0});var Al=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};kl.default=Al});var Gn=A(Il=>{"use strict";Object.defineProperty(Il,"__esModule",{value:!0});var xl=Zi(),Pl=class extends Error{constructor(e,t,n,i){super(i||`can't resolve reference ${n} from id ${t}`),this.missingRef=(0,xl.resolveUrl)(e,t,n),this.missingSchema=(0,xl.normalizeId)((0,xl.getFullPath)(e,this.missingRef))}};Il.default=Pl});var ns=A(St=>{"use strict";Object.defineProperty(St,"__esModule",{value:!0});St.resolveSchema=St.getCompilingSchema=St.resolveRef=St.compileSchema=St.SchemaEnv=void 0;var Tt=H(),J$=rs(),bn=vt(),Ct=Zi(),_h=Q(),Y$=Wn(),Jn=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,Ct.normalizeId)(n==null?void 0:n[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n==null?void 0:n.$async,this.refs={}}};St.SchemaEnv=Jn;function Rl(r){let e=bh.call(this,r);if(e)return e;let t=(0,Ct.getFullPath)(this.opts.uriResolver,r.root.baseId),{es5:n,lines:i}=this.opts.code,{ownProperties:s}=this.opts,o=new Tt.CodeGen(this.scope,{es5:n,lines:i,ownProperties:s}),a;r.$async&&(a=o.scopeValue("Error",{ref:J$.default,code:(0,Tt._)`require("ajv/dist/runtime/validation_error").default`}));let c=o.scopeName("validate");r.validateName=c;let l={gen:o,allErrors:this.opts.allErrors,data:bn.default.data,parentData:bn.default.parentData,parentDataProperty:bn.default.parentDataProperty,dataNames:[bn.default.data],dataPathArr:[Tt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:o.scopeValue("schema",this.opts.code.source===!0?{ref:r.schema,code:(0,Tt.stringify)(r.schema)}:{ref:r.schema}),validateName:c,ValidationError:a,schema:r.schema,schemaEnv:r,rootId:t,baseId:r.baseId||t,schemaPath:Tt.nil,errSchemaPath:r.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Tt._)`""`,opts:this.opts,self:this},d;try{this._compilations.add(r),(0,Y$.validateFunctionCode)(l),o.optimize(this.opts.code.optimize);let u=o.toString();d=`${o.scopeRefs(bn.default.scope)}return ${u}`,this.opts.code.process&&(d=this.opts.code.process(d,r));let p=new Function(`${bn.default.self}`,`${bn.default.scope}`,d)(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:u,scopeValues:o._values}),this.opts.unevaluated){let{props:y,items:h}=l;p.evaluated={props:y instanceof Tt.Name?void 0:y,items:h instanceof Tt.Name?void 0:h,dynamicProps:y instanceof Tt.Name,dynamicItems:h instanceof Tt.Name},p.source&&(p.source.evaluated=(0,Tt.stringify)(p.evaluated))}return r.validate=p,r}catch(u){throw delete r.validate,delete r.validateName,d&&this.logger.error("Error compiling schema, function code:",d),u}finally{this._compilations.delete(r)}}St.compileSchema=Rl;function X$(r,e,t){var n;t=(0,Ct.resolveUrl)(this.opts.uriResolver,e,t);let i=r.refs[t];if(i)return i;let s=eS.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 Jn({schema:o,schemaId:a,root:r,baseId:e}))}if(s!==void 0)return r.refs[t]=Q$.call(this,s)}St.resolveRef=X$;function Q$(r){return(0,Ct.inlineRef)(r.schema,this.opts.inlineRefs)?r.schema:r.validate?r:Rl.call(this,r)}function bh(r){for(let e of this._compilations)if(Z$(e,r))return e}St.getCompilingSchema=bh;function Z$(r,e){return r.schema===e.schema&&r.root===e.root&&r.baseId===e.baseId}function eS(r,e){let t;for(;typeof(t=this.refs[e])=="string";)e=t;return t||this.schemas[e]||Ro.call(this,r,e)}function Ro(r,e){let t=this.opts.uriResolver.parse(e),n=(0,Ct._getFullPath)(this.opts.uriResolver,t),i=(0,Ct.getFullPath)(this.opts.uriResolver,r.baseId,void 0);if(Object.keys(r.schema).length>0&&n===i)return Ol.call(this,t,r);let s=(0,Ct.normalizeId)(n),o=this.refs[s]||this.schemas[s];if(typeof o=="string"){let a=Ro.call(this,r,o);return typeof(a==null?void 0:a.schema)!="object"?void 0:Ol.call(this,t,a)}if(typeof(o==null?void 0:o.schema)=="object"){if(o.validate||Rl.call(this,o),s===(0,Ct.normalizeId)(e)){let{schema:a}=o,{schemaId:c}=this.opts,l=a[c];return l&&(i=(0,Ct.resolveUrl)(this.opts.uriResolver,i,l)),new Jn({schema:a,schemaId:c,root:r,baseId:i})}return Ol.call(this,t,o)}}St.resolveSchema=Ro;var tS=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Ol(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,_h.unescapeFragment)(a)];if(c===void 0)return;t=c;let l=typeof t=="object"&&t[this.opts.schemaId];!tS.has(a)&&l&&(e=(0,Ct.resolveUrl)(this.opts.uriResolver,e,l))}let s;if(typeof t!="boolean"&&t.$ref&&!(0,_h.schemaHasRulesButRef)(t,this.RULES)){let a=(0,Ct.resolveUrl)(this.opts.uriResolver,e,t.$ref);s=Ro.call(this,n,a)}let{schemaId:o}=this.opts;if(s=s||new Jn({schema:t,schemaId:o,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var wh=A((XM,rS)=>{rS.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 Ml=A((QM,kh)=>{"use strict";var nS=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),$h=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),Tl=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),Sh=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),iS=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function Cl(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 sS=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function vh(r){return r.length=0,!0}function oS(r,e,t){if(r.length){let n=Cl(r);if(n!=="")e.push(n);else return t.error=!0,!1;r.length=0}return!0}function aS(r){let e=0,t={error:!1,address:"",zone:""},n=[],i=[],s=!1,o=!1,a=oS;for(let c=0;c7){t.error=!0;break}c>0&&r[c-1]===":"&&(s=!0),n.push(":");continue}else if(l==="%"){if(!a(i,n,t))break;a=vh}else{i.push(l);continue}}return i.length&&(a===vh?t.zone=i.join(""):o?n.push(i.join("")):n.push(Cl(i))),t.address=n.join(""),t}function Eh(r){if(cS(r,":")<2)return{host:r,isIPV6:!1};let e=aS(r);if(e.error)return{host:r,isIPV6:!1};{let t=e.address,n=e.address;return e.zone&&(t+="%"+e.zone,n+="%25"+e.zone),{host:t,isIPV6:!0,escapedHost:n}}}function cS(r,e){let t=0;for(let n=0;ndS[n])}function pS(r,e=!1){if(r.indexOf("%")===-1)return r;let t="";for(let n=0;n{"use strict";var{isUUID:gS}=Ml(),_S=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,bS=["http","https","ws","wss","urn","urn:uuid"];function wS(r){return bS.indexOf(r)!==-1}function Nl(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 xh(r){return r.host||(r.error=r.error||"HTTP URIs must have a host."),r}function Ph(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 vS(r){return r.secure=Nl(r),r.resourceName=(r.path||"/")+(r.query?"?"+r.query:""),r.path=void 0,r.query=void 0,r}function $S(r){if((r.port===(Nl(r)?443:80)||r.port==="")&&(r.port=void 0),typeof r.secure=="boolean"&&(r.scheme=r.secure?"wss":"ws",r.secure=void 0),r.resourceName){let[e,t]=r.resourceName.split("?");r.path=e&&e!=="/"?e:void 0,r.query=t,r.resourceName=void 0}return r.fragment=void 0,r}function SS(r,e){if(!r.path)return r.error="URN can not be parsed",r;let t=r.path.match(_S);if(t){let n=e.scheme||r.scheme||"urn";r.nid=t[1].toLowerCase(),r.nss=t[2];let i=`${n}:${e.nid||r.nid}`,s=Ll(i);r.path=void 0,s&&(r=s.parse(r,e))}else r.error=r.error||"URN can not be parsed.";return r}function ES(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=Ll(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 AS(r,e){let t=r;return t.uuid=t.nss,t.nss=void 0,!e.tolerant&&(!t.uuid||!gS(t.uuid))&&(t.error=t.error||"UUID is not valid."),t}function kS(r){let e=r;return e.nss=(r.uuid||"").toLowerCase(),e}var Ih={scheme:"http",domainHost:!0,parse:xh,serialize:Ph},xS={scheme:"https",domainHost:Ih.domainHost,parse:xh,serialize:Ph},To={scheme:"ws",domainHost:!0,parse:vS,serialize:$S},PS={scheme:"wss",domainHost:To.domainHost,parse:To.parse,serialize:To.serialize},IS={scheme:"urn",parse:SS,serialize:ES,skipNormalize:!0},OS={scheme:"urn:uuid",parse:AS,serialize:kS,skipNormalize:!0},Co={http:Ih,https:xS,ws:To,wss:PS,urn:IS,"urn:uuid":OS};Object.setPrototypeOf(Co,null);function Ll(r){return r&&(Co[r]||Co[r.toLowerCase()])||void 0}Oh.exports={wsIsSecure:Nl,SCHEMES:Co,isValidSchemeName:wS,getSchemeHandler:Ll}});var Lh=A((eN,Lo)=>{"use strict";var{normalizeIPv6:RS,removeDotSegments:is,recomposeAuthority:TS,normalizePercentEncoding:CS,normalizePathEncoding:MS,escapePreservingEscapes:NS,reescapeHostDelimiters:LS,isIPv4:jS,nonSimpleDomain:DS}=Ml(),{SCHEMES:qS,getSchemeHandler:Ch}=Rh();function FS(r,e){return typeof r=="string"?r=WS(r,e):typeof r=="object"&&(r=No(wn(r,e),e)),r}function VS(r,e,t){let n=t?Object.assign({scheme:"null"},t):{scheme:"null"},{parsed:i,malformedAuthorityOrPort:s}=Mo(r,n),{parsed:o,malformedAuthorityOrPort:a}=Mo(e,n);if(s||a)throw new Error(i.error||o.error||"URI is malformed.");let c=Mh(i,o,n,!0);return n.skipEscape=!0,wn(c,n)}function Mh(r,e,t,n){let i={};return n||(r=No(wn(r,t),t),e=No(wn(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=is(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=is(e.path||""),i.query=e.query):(e.path?(e.path[0]==="/"?i.path=is(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=is(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 US(r,e,t){let n=Th(r,t),i=Th(e,t);return n!==void 0&&i!==void 0&&n.toLowerCase()===i.toLowerCase()}function wn(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=[],s=Ch(n.scheme||t.scheme);s&&s.serialize&&s.serialize(t,n),t.path!==void 0&&(n.skipEscape?t.path=CS(t.path):(t.path=NS(t.path),t.scheme!==void 0&&(t.path=t.path.split("%3A").join(":")))),n.reference!=="suffix"&&t.scheme&&i.push(t.scheme,":");let o=TS(t);if(o!==void 0&&(n.reference!=="suffix"&&i.push("//"),i.push(o),t.path&&t.path[0]!=="/"&&i.push("/")),t.path!==void 0){let a=t.path;!n.absolutePath&&(!s||!s.absolutePath)&&(a=is(a)),o===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),i.push(a)}return t.query!==void 0&&i.push("?",t.query),t.fragment!==void 0&&i.push("#",t.fragment),i.join("")}var BS=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,zS=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,HS=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function KS(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 Mo(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;t.reference==="suffix"&&(t.scheme?r=t.scheme+":"+r:r="//"+r);let o=r.match(zS);o!==null&&o[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",i=!0);let a=r.match(HS);if(a!==null){let l=a[1],d=l.replace(/[\t\n\r]/g,"");d.length>=2&&(d.slice(0,2)!=="//"?(n.error=n.error||"URI authority must not contain a literal backslash.",i=!0):l.length!==d.length&&(n.error=n.error||"URI authority introducer must not contain whitespace.",i=!0))}let c=r.match(BS);if(c){n.scheme=c[1],n.userinfo=c[3],n.host=c[4],n.port=parseInt(c[5],10),n.path=c[6]||"",n.query=c[7],n.fragment=c[8],isNaN(n.port)&&(n.port=c[5]);let l=KS(n,c);if(l!==void 0&&(n.error=n.error||l,i=!0),n.host)if(jS(n.host)===!1){let f=RS(n.host);n.host=f.host.toLowerCase(),s=f.isIPV6}else s=!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 d=Ch(t.scheme||n.scheme);if(!t.unicodeSupport&&(!d||!d.unicodeSupport)&&n.host&&(t.domainHost||d&&d.domainHost)&&s===!1&&DS(n.host))try{n.host=new URL("http://"+n.host).hostname}catch(u){n.error=n.error||"Host's domain name can not be converted to ASCII: "+u}if((!d||d&&!d.skipNormalize)&&(r.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=LS(unescape(n.host),s))),n.path&&(n.path=MS(n.path)),n.fragment))try{n.fragment=encodeURI(decodeURIComponent(n.fragment))}catch(u){n.error=n.error||"URI malformed"}d&&d.parse&&d.parse(n,t)}else n.error=n.error||"URI can not be parsed.";return{parsed:n,malformedAuthorityOrPort:i}}function No(r,e){return Mo(r,e).parsed}function WS(r,e){return Nh(r,e).normalized}function Nh(r,e){let{parsed:t,malformedAuthorityOrPort:n}=Mo(r,e);return{normalized:n?r:wn(t,e),malformedAuthorityOrPort:n}}function Th(r,e){if(typeof r=="string"){let{normalized:t,malformedAuthorityOrPort:n}=Nh(r,e);return n?void 0:t}if(typeof r=="object")return wn(r,e)}var jl={SCHEMES:qS,normalize:FS,resolve:VS,resolveComponent:Mh,equal:US,serialize:wn,parse:No};Lo.exports=jl;Lo.exports.default=jl;Lo.exports.fastUri=jl});var Dh=A(Dl=>{"use strict";Object.defineProperty(Dl,"__esModule",{value:!0});var jh=Lh();jh.code='require("ajv/dist/runtime/uri").default';Dl.default=jh});var Vl=A(Le=>{"use strict";Object.defineProperty(Le,"__esModule",{value:!0});Le.CodeGen=Le.Name=Le.nil=Le.stringify=Le.str=Le._=Le.KeywordCxt=void 0;var GS=Wn();Object.defineProperty(Le,"KeywordCxt",{enumerable:!0,get:function(){return GS.KeywordCxt}});var Yn=H();Object.defineProperty(Le,"_",{enumerable:!0,get:function(){return Yn._}});Object.defineProperty(Le,"str",{enumerable:!0,get:function(){return Yn.str}});Object.defineProperty(Le,"stringify",{enumerable:!0,get:function(){return Yn.stringify}});Object.defineProperty(Le,"nil",{enumerable:!0,get:function(){return Yn.nil}});Object.defineProperty(Le,"Name",{enumerable:!0,get:function(){return Yn.Name}});Object.defineProperty(Le,"CodeGen",{enumerable:!0,get:function(){return Yn.CodeGen}});var JS=rs(),Bh=Gn(),YS=fl(),ss=ns(),XS=H(),os=Zi(),jo=Qi(),Fl=Q(),qh=wh(),QS=Dh(),zh=(r,e)=>new RegExp(r,e);zh.code="new RegExp";var ZS=["removeAdditional","useDefaults","coerceTypes"],eE=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),tE={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."},rE={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Fh=200;function nE(r){var e,t,n,i,s,o,a,c,l,d,u,f,p,y,h,m,g,_,w,x,v,P,O,$,R;let S=r.strict,U=(e=r.code)===null||e===void 0?void 0:e.optimize,B=U===!0||U===void 0?1:U||0,T=(n=(t=r.code)===null||t===void 0?void 0:t.regExp)!==null&&n!==void 0?n:zh,E=(i=r.uriResolver)!==null&&i!==void 0?i:QS.default;return{strictSchema:(o=(s=r.strictSchema)!==null&&s!==void 0?s:S)!==null&&o!==void 0?o:!0,strictNumbers:(c=(a=r.strictNumbers)!==null&&a!==void 0?a:S)!==null&&c!==void 0?c:!0,strictTypes:(d=(l=r.strictTypes)!==null&&l!==void 0?l:S)!==null&&d!==void 0?d:"log",strictTuples:(f=(u=r.strictTuples)!==null&&u!==void 0?u:S)!==null&&f!==void 0?f:"log",strictRequired:(y=(p=r.strictRequired)!==null&&p!==void 0?p:S)!==null&&y!==void 0?y:!1,code:r.code?{...r.code,optimize:B,regExp:T}:{optimize:B,regExp:T},loopRequired:(h=r.loopRequired)!==null&&h!==void 0?h:Fh,loopEnum:(m=r.loopEnum)!==null&&m!==void 0?m:Fh,meta:(g=r.meta)!==null&&g!==void 0?g:!0,messages:(_=r.messages)!==null&&_!==void 0?_:!0,inlineRefs:(w=r.inlineRefs)!==null&&w!==void 0?w:!0,schemaId:(x=r.schemaId)!==null&&x!==void 0?x:"$id",addUsedSchema:(v=r.addUsedSchema)!==null&&v!==void 0?v:!0,validateSchema:(P=r.validateSchema)!==null&&P!==void 0?P:!0,validateFormats:(O=r.validateFormats)!==null&&O!==void 0?O:!0,unicodeRegExp:($=r.unicodeRegExp)!==null&&$!==void 0?$:!0,int32range:(R=r.int32range)!==null&&R!==void 0?R:!0,uriResolver:E}}var as=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,...nE(e)};let{es5:t,lines:n}=this.opts.code;this.scope=new XS.ValueScope({scope:{},prefixes:eE,es5:t,lines:n}),this.logger=lE(e.logger);let i=e.validateFormats;e.validateFormats=!1,this.RULES=(0,YS.getRules)(),Vh.call(this,tE,e,"NOT SUPPORTED"),Vh.call(this,rE,e,"DEPRECATED","warn"),this._metaOpts=aE.call(this),e.formats&&sE.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&oE.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),iE.call(this),e.validateFormats=i}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:t,schemaId:n}=this.opts,i=qh;n==="id"&&(i={...qh},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(d,u){await s.call(this,d.$schema);let f=this._addSchema(d,u);return f.validate||o.call(this,f)}async function s(d){d&&!this.getSchema(d)&&await i.call(this,{$ref:d},!0)}async function o(d){try{return this._compileSchemaEnv(d)}catch(u){if(!(u instanceof Bh.default))throw u;return a.call(this,u),await c.call(this,u.missingSchema),o.call(this,d)}}function a({missingSchema:d,missingRef:u}){if(this.refs[d])throw new Error(`AnySchema ${d} is loaded but ${u} cannot be resolved`)}async function c(d){let u=await l.call(this,d);this.refs[d]||await s.call(this,u.$schema),this.refs[d]||this.addSchema(u,d,t)}async function l(d){let u=this._loading[d];if(u)return u;try{return await(this._loading[d]=n(d))}finally{delete this._loading[d]}}}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,os.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=Uh.call(this,e))=="string";)e=t;if(t===void 0){let{schemaId:n}=this.opts,i=new ss.SchemaEnv({schema:{},schemaId:n});if(t=ss.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=Uh.call(this,e);return typeof t=="object"&&this._cache.delete(t.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let t=e;this._cache.delete(t);let n=e[this.opts.schemaId];return n&&(n=(0,os.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let t of e)this.addKeyword(t);return this}addKeyword(e,t){let n;if(typeof e=="string")n=e,typeof t=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),t.keyword=n);else if(typeof e=="object"&&t===void 0){if(t=e,n=t.keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(uE.call(this,n,t),!t)return(0,Fl.eachItem)(n,s=>ql.call(this,s)),this;pE.call(this,t);let i={...t,type:(0,jo.getJSONTypes)(t.type),schemaType:(0,jo.getJSONTypes)(t.schemaType)};return(0,Fl.eachItem)(n,i.type.length===0?s=>ql.call(this,s,i):s=>i.type.forEach(o=>ql.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,d=o[a];l&&d&&(o[a]=Hh(d))}}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,os.normalizeId)(o||n);let l=os.getSchemaRefs.call(this,e,n);return c=new ss.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):ss.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{ss.compileSchema.call(this,e)}finally{this.opts=t}}};as.ValidationError=JS.default;as.MissingRefError=Bh.default;Le.default=as;function Vh(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 Uh(r){return r=(0,os.normalizeId)(r),this.schemas[r]||this.refs[r]}function iE(){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 sE(){for(let r in this.opts.formats){let e=this.opts.formats[r];e&&this.addFormat(r,e)}}function oE(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 aE(){let r={...this.opts};for(let e of ZS)delete r[e];return r}var cE={log(){},warn(){},error(){}};function lE(r){if(r===!1)return cE;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 dE=/^[a-z_$][a-z0-9_$:-]*$/i;function uE(r,e){let{RULES:t}=this;if((0,Fl.eachItem)(r,n=>{if(t.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!dE.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 ql(r,e,t){var n;let i=e==null?void 0: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,jo.getJSONTypes)(e.type),schemaType:(0,jo.getJSONTypes)(e.schemaType)}};e.before?fE.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 fE(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 pE(r){let{metaSchema:e}=r;e!==void 0&&(r.$data&&this.opts.$data&&(e=Hh(e)),r.validateSchema=this.compile(e,!0))}var hE={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Hh(r){return{anyOf:[r,hE]}}});var Kh=A(Ul=>{"use strict";Object.defineProperty(Ul,"__esModule",{value:!0});var mE={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Ul.default=mE});var Fo=A(vn=>{"use strict";Object.defineProperty(vn,"__esModule",{value:!0});vn.callRef=vn.getValidate=void 0;var yE=Gn(),Wh=$t(),at=H(),Xn=vt(),Gh=ns(),Do=Q(),gE={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 u();let d=Gh.resolveRef.call(c,l,i,t);if(d===void 0)throw new yE.default(n.opts.uriResolver,i,t);if(d instanceof Gh.SchemaEnv)return f(d);return p(d);function u(){if(s===l)return qo(r,o,s,s.$async);let y=e.scopeValue("root",{ref:l});return qo(r,(0,at._)`${y}.validate`,l,l.$async)}function f(y){let h=Jh(r,y);qo(r,h,y,y.$async)}function p(y){let h=e.scopeValue("schema",a.code.source===!0?{ref:y,code:(0,at.stringify)(y)}:{ref:y}),m=e.name("valid"),g=r.subschema({schema:y,dataTypes:[],schemaPath:at.nil,topSchemaRef:h,errSchemaPath:t},m);r.mergeEvaluated(g),r.ok(m)}}};function Jh(r,e){let{gen:t}=r;return e.validate?t.scopeValue("validate",{ref:e.validate}):(0,at._)`${t.scopeValue("wrapper",{ref:e})}.validate`}vn.getValidate=Jh;function qo(r,e,t,n){let{gen:i,it:s}=r,{allErrors:o,schemaEnv:a,opts:c}=s,l=c.passContext?Xn.default.this:at.nil;n?d():u();function d(){if(!a.$async)throw new Error("async schema referenced by sync schema");let y=i.let("valid");i.try(()=>{i.code((0,at._)`await ${(0,Wh.callValidateCode)(r,e,l)}`),p(e),o||i.assign(y,!0)},h=>{i.if((0,at._)`!(${h} instanceof ${s.ValidationError})`,()=>i.throw(h)),f(h),o||i.assign(y,!1)}),r.ok(y)}function u(){r.result((0,Wh.callValidateCode)(r,e,l),()=>p(e),()=>f(e))}function f(y){let h=(0,at._)`${y}.errors`;i.assign(Xn.default.vErrors,(0,at._)`${Xn.default.vErrors} === null ? ${h} : ${Xn.default.vErrors}.concat(${h})`),i.assign(Xn.default.errors,(0,at._)`${Xn.default.vErrors}.length`)}function p(y){var h;if(!s.opts.unevaluated)return;let m=(h=t==null?void 0:t.validate)===null||h===void 0?void 0:h.evaluated;if(s.props!==!0)if(m&&!m.dynamicProps)m.props!==void 0&&(s.props=Do.mergeEvaluated.props(i,m.props,s.props));else{let g=i.var("props",(0,at._)`${y}.evaluated.props`);s.props=Do.mergeEvaluated.props(i,g,s.props,at.Name)}if(s.items!==!0)if(m&&!m.dynamicItems)m.items!==void 0&&(s.items=Do.mergeEvaluated.items(i,m.items,s.items));else{let g=i.var("items",(0,at._)`${y}.evaluated.items`);s.items=Do.mergeEvaluated.items(i,g,s.items,at.Name)}}}vn.callRef=qo;vn.default=gE});var zl=A(Bl=>{"use strict";Object.defineProperty(Bl,"__esModule",{value:!0});var _E=Kh(),bE=Fo(),wE=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",_E.default,bE.default];Bl.default=wE});var Yh=A(Hl=>{"use strict";Object.defineProperty(Hl,"__esModule",{value:!0});var Vo=H(),Kr=Vo.operators,Uo={maximum:{okStr:"<=",ok:Kr.LTE,fail:Kr.GT},minimum:{okStr:">=",ok:Kr.GTE,fail:Kr.LT},exclusiveMaximum:{okStr:"<",ok:Kr.LT,fail:Kr.GTE},exclusiveMinimum:{okStr:">",ok:Kr.GT,fail:Kr.LTE}},vE={message:({keyword:r,schemaCode:e})=>(0,Vo.str)`must be ${Uo[r].okStr} ${e}`,params:({keyword:r,schemaCode:e})=>(0,Vo._)`{comparison: ${Uo[r].okStr}, limit: ${e}}`},$E={keyword:Object.keys(Uo),type:"number",schemaType:"number",$data:!0,error:vE,code(r){let{keyword:e,data:t,schemaCode:n}=r;r.fail$data((0,Vo._)`${t} ${Uo[e].fail} ${n} || isNaN(${t})`)}};Hl.default=$E});var Xh=A(Kl=>{"use strict";Object.defineProperty(Kl,"__esModule",{value:!0});var cs=H(),SE={message:({schemaCode:r})=>(0,cs.str)`must be multiple of ${r}`,params:({schemaCode:r})=>(0,cs._)`{multipleOf: ${r}}`},EE={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:SE,code(r){let{gen:e,data:t,schemaCode:n,it:i}=r,s=i.opts.multipleOfPrecision,o=e.let("res"),a=s?(0,cs._)`Math.abs(Math.round(${o}) - ${o}) > 1e-${s}`:(0,cs._)`${o} !== parseInt(${o})`;r.fail$data((0,cs._)`(${n} === 0 || (${o} = ${t}/${n}, ${a}))`)}};Kl.default=EE});var Zh=A(Wl=>{"use strict";Object.defineProperty(Wl,"__esModule",{value:!0});function Qh(r){let e=r.length,t=0,n=0,i;for(;n=55296&&i<=56319&&n{"use strict";Object.defineProperty(Gl,"__esModule",{value:!0});var $n=H(),AE=Q(),kE=Zh(),xE={message({keyword:r,schemaCode:e}){let t=r==="maxLength"?"more":"fewer";return(0,$n.str)`must NOT have ${t} than ${e} characters`},params:({schemaCode:r})=>(0,$n._)`{limit: ${r}}`},PE={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:xE,code(r){let{keyword:e,data:t,schemaCode:n,it:i}=r,s=e==="maxLength"?$n.operators.GT:$n.operators.LT,o=i.opts.unicode===!1?(0,$n._)`${t}.length`:(0,$n._)`${(0,AE.useFunc)(r.gen,kE.default)}(${t})`;r.fail$data((0,$n._)`${o} ${s} ${n}`)}};Gl.default=PE});var tm=A(Jl=>{"use strict";Object.defineProperty(Jl,"__esModule",{value:!0});var IE=$t(),OE=Q(),Qn=H(),RE={message:({schemaCode:r})=>(0,Qn.str)`must match pattern "${r}"`,params:({schemaCode:r})=>(0,Qn._)`{pattern: ${r}}`},TE={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:RE,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,Qn._)`new RegExp`:(0,OE.useFunc)(e,c),d=e.let("valid");e.try(()=>e.assign(d,(0,Qn._)`${l}(${s}, ${a}).test(${t})`),()=>e.assign(d,!1)),r.fail$data((0,Qn._)`!${d}`)}else{let c=(0,IE.usePattern)(r,i);r.fail$data((0,Qn._)`!${c}.test(${t})`)}}};Jl.default=TE});var rm=A(Yl=>{"use strict";Object.defineProperty(Yl,"__esModule",{value:!0});var ls=H(),CE={message({keyword:r,schemaCode:e}){let t=r==="maxProperties"?"more":"fewer";return(0,ls.str)`must NOT have ${t} than ${e} properties`},params:({schemaCode:r})=>(0,ls._)`{limit: ${r}}`},ME={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:CE,code(r){let{keyword:e,data:t,schemaCode:n}=r,i=e==="maxProperties"?ls.operators.GT:ls.operators.LT;r.fail$data((0,ls._)`Object.keys(${t}).length ${i} ${n}`)}};Yl.default=ME});var nm=A(Xl=>{"use strict";Object.defineProperty(Xl,"__esModule",{value:!0});var ds=$t(),us=H(),NE=Q(),LE={message:({params:{missingProperty:r}})=>(0,us.str)`must have required property '${r}'`,params:({params:{missingProperty:r}})=>(0,us._)`{missingProperty: ${r}}`},jE={keyword:"required",type:"object",schemaType:"array",$data:!0,error:LE,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():d(),a.strictRequired){let p=r.parentSchema.properties,{definedProperties:y}=r.it;for(let h of t)if((p==null?void 0:p[h])===void 0&&!y.has(h)){let m=o.schemaEnv.baseId+o.errSchemaPath,g=`required property "${h}" is not defined at "${m}" (strictRequired)`;(0,NE.checkStrictMode)(o,g,o.opts.strictRequired)}}function l(){if(c||s)r.block$data(us.nil,u);else for(let p of t)(0,ds.checkReportMissingProp)(r,p)}function d(){let p=e.let("missing");if(c||s){let y=e.let("valid",!0);r.block$data(y,()=>f(p,y)),r.ok(y)}else e.if((0,ds.checkMissingProp)(r,t,p)),(0,ds.reportMissingProp)(r,p),e.else()}function u(){e.forOf("prop",n,p=>{r.setParams({missingProperty:p}),e.if((0,ds.noPropertyInData)(e,i,p,a.ownProperties),()=>r.error())})}function f(p,y){r.setParams({missingProperty:p}),e.forOf(p,n,()=>{e.assign(y,(0,ds.propertyInData)(e,i,p,a.ownProperties)),e.if((0,us.not)(y),()=>{r.error(),e.break()})},us.nil)}}};Xl.default=jE});var im=A(Ql=>{"use strict";Object.defineProperty(Ql,"__esModule",{value:!0});var fs=H(),DE={message({keyword:r,schemaCode:e}){let t=r==="maxItems"?"more":"fewer";return(0,fs.str)`must NOT have ${t} than ${e} items`},params:({schemaCode:r})=>(0,fs._)`{limit: ${r}}`},qE={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:DE,code(r){let{keyword:e,data:t,schemaCode:n}=r,i=e==="maxItems"?fs.operators.GT:fs.operators.LT;r.fail$data((0,fs._)`${t}.length ${i} ${n}`)}};Ql.default=qE});var Bo=A(Zl=>{"use strict";Object.defineProperty(Zl,"__esModule",{value:!0});var sm=wl();sm.code='require("ajv/dist/runtime/equal").default';Zl.default=sm});var om=A(td=>{"use strict";Object.defineProperty(td,"__esModule",{value:!0});var ed=Qi(),je=H(),FE=Q(),VE=Bo(),UE={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}}`},BE={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:UE,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,ed.getSchemaTypes)(s.items):[];r.block$data(c,d,(0,je._)`${o} === false`),r.ok(c);function d(){let y=e.let("i",(0,je._)`${t}.length`),h=e.let("j");r.setParams({i:y,j:h}),e.assign(c,!0),e.if((0,je._)`${y} > 1`,()=>(u()?f:p)(y,h))}function u(){return l.length>0&&!l.some(y=>y==="object"||y==="array")}function f(y,h){let m=e.name("item"),g=(0,ed.checkDataTypes)(l,m,a.opts.strictNumbers,ed.DataType.Wrong),_=e.const("indices",(0,je._)`{}`);e.for((0,je._)`;${y}--;`,()=>{e.let(m,(0,je._)`${t}[${y}]`),e.if(g,(0,je._)`continue`),l.length>1&&e.if((0,je._)`typeof ${m} == "string"`,(0,je._)`${m} += "_"`),e.if((0,je._)`typeof ${_}[${m}] == "number"`,()=>{e.assign(h,(0,je._)`${_}[${m}]`),r.error(),e.assign(c,!1).break()}).code((0,je._)`${_}[${m}] = ${y}`)})}function p(y,h){let m=(0,FE.useFunc)(e,VE.default),g=e.name("outer");e.label(g).for((0,je._)`;${y}--;`,()=>e.for((0,je._)`${h} = ${y}; ${h}--;`,()=>e.if((0,je._)`${m}(${t}[${y}], ${t}[${h}])`,()=>{r.error(),e.assign(c,!1).break(g)})))}}};td.default=BE});var am=A(nd=>{"use strict";Object.defineProperty(nd,"__esModule",{value:!0});var rd=H(),zE=Q(),HE=Bo(),KE={message:"must be equal to constant",params:({schemaCode:r})=>(0,rd._)`{allowedValue: ${r}}`},WE={keyword:"const",$data:!0,error:KE,code(r){let{gen:e,data:t,$data:n,schemaCode:i,schema:s}=r;n||s&&typeof s=="object"?r.fail$data((0,rd._)`!${(0,zE.useFunc)(e,HE.default)}(${t}, ${i})`):r.fail((0,rd._)`${s} !== ${t}`)}};nd.default=WE});var cm=A(id=>{"use strict";Object.defineProperty(id,"__esModule",{value:!0});var ps=H(),GE=Q(),JE=Bo(),YE={message:"must be equal to one of the allowed values",params:({schemaCode:r})=>(0,ps._)`{allowedValues: ${r}}`},XE={keyword:"enum",schemaType:"array",$data:!0,error:YE,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!=null?c:c=(0,GE.useFunc)(e,JE.default),d;if(a||n)d=e.let("valid"),r.block$data(d,u);else{if(!Array.isArray(i))throw new Error("ajv implementation error");let p=e.const("vSchema",s);d=(0,ps.or)(...i.map((y,h)=>f(p,h)))}r.pass(d);function u(){e.assign(d,!1),e.forOf("v",s,p=>e.if((0,ps._)`${l()}(${t}, ${p})`,()=>e.assign(d,!0).break()))}function f(p,y){let h=i[y];return typeof h=="object"&&h!==null?(0,ps._)`${l()}(${t}, ${p}[${y}])`:(0,ps._)`${t} === ${h}`}}};id.default=XE});var od=A(sd=>{"use strict";Object.defineProperty(sd,"__esModule",{value:!0});var QE=Yh(),ZE=Xh(),eA=em(),tA=tm(),rA=rm(),nA=nm(),iA=im(),sA=om(),oA=am(),aA=cm(),cA=[QE.default,ZE.default,eA.default,tA.default,rA.default,nA.default,iA.default,sA.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},oA.default,aA.default];sd.default=cA});var cd=A(hs=>{"use strict";Object.defineProperty(hs,"__esModule",{value:!0});hs.validateAdditionalItems=void 0;var Sn=H(),ad=Q(),lA={message:({params:{len:r}})=>(0,Sn.str)`must NOT have more than ${r} items`,params:({params:{len:r}})=>(0,Sn._)`{limit: ${r}}`},dA={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:lA,code(r){let{parentSchema:e,it:t}=r,{items:n}=e;if(!Array.isArray(n)){(0,ad.checkStrictMode)(t,'"additionalItems" is ignored when "items" is not an array of schemas');return}lm(r,n)}};function lm(r,e){let{gen:t,schema:n,data:i,keyword:s,it:o}=r;o.items=!0;let a=t.const("len",(0,Sn._)`${i}.length`);if(n===!1)r.setParams({len:e.length}),r.pass((0,Sn._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,ad.alwaysValidSchema)(o,n)){let l=t.var("valid",(0,Sn._)`${a} <= ${e.length}`);t.if((0,Sn.not)(l),()=>c(l)),r.ok(l)}function c(l){t.forRange("i",e.length,a,d=>{r.subschema({keyword:s,dataProp:d,dataPropType:ad.Type.Num},l),o.allErrors||t.if((0,Sn.not)(l),()=>t.break())})}}hs.validateAdditionalItems=lm;hs.default=dA});var ld=A(ms=>{"use strict";Object.defineProperty(ms,"__esModule",{value:!0});ms.validateTuple=void 0;var dm=H(),zo=Q(),uA=$t(),fA={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(r){let{schema:e,it:t}=r;if(Array.isArray(e))return um(r,"additionalItems",e);t.items=!0,!(0,zo.alwaysValidSchema)(t,e)&&r.ok((0,uA.validateArray)(r))}};function um(r,e,t=r.schema){let{gen:n,parentSchema:i,data:s,keyword:o,it:a}=r;d(i),a.opts.unevaluated&&t.length&&a.items!==!0&&(a.items=zo.mergeEvaluated.items(n,t.length,a.items));let c=n.name("valid"),l=n.const("len",(0,dm._)`${s}.length`);t.forEach((u,f)=>{(0,zo.alwaysValidSchema)(a,u)||(n.if((0,dm._)`${l} > ${f}`,()=>r.subschema({keyword:o,schemaProp:f,dataProp:f},c)),r.ok(c))});function d(u){let{opts:f,errSchemaPath:p}=a,y=t.length,h=y===u.minItems&&(y===u.maxItems||u[e]===!1);if(f.strictTuples&&!h){let m=`"${o}" is ${y}-tuple, but minItems or maxItems/${e} are not specified or different at path "${p}"`;(0,zo.checkStrictMode)(a,m,f.strictTuples)}}}ms.validateTuple=um;ms.default=fA});var fm=A(dd=>{"use strict";Object.defineProperty(dd,"__esModule",{value:!0});var pA=ld(),hA={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:r=>(0,pA.validateTuple)(r,"items")};dd.default=hA});var hm=A(ud=>{"use strict";Object.defineProperty(ud,"__esModule",{value:!0});var pm=H(),mA=Q(),yA=$t(),gA=cd(),_A={message:({params:{len:r}})=>(0,pm.str)`must NOT have more than ${r} items`,params:({params:{len:r}})=>(0,pm._)`{limit: ${r}}`},bA={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:_A,code(r){let{schema:e,parentSchema:t,it:n}=r,{prefixItems:i}=t;n.items=!0,!(0,mA.alwaysValidSchema)(n,e)&&(i?(0,gA.validateAdditionalItems)(r,i):r.ok((0,yA.validateArray)(r)))}};ud.default=bA});var mm=A(fd=>{"use strict";Object.defineProperty(fd,"__esModule",{value:!0});var Et=H(),Ho=Q(),wA={message:({params:{min:r,max:e}})=>e===void 0?(0,Et.str)`must contain at least ${r} valid item(s)`:(0,Et.str)`must contain at least ${r} and no more than ${e} valid item(s)`,params:({params:{min:r,max:e}})=>e===void 0?(0,Et._)`{minContains: ${r}}`:(0,Et._)`{minContains: ${r}, maxContains: ${e}}`},vA={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:wA,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 d=e.const("len",(0,Et._)`${i}.length`);if(r.setParams({min:o,max:a}),a===void 0&&o===0){(0,Ho.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&o>a){(0,Ho.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),r.fail();return}if((0,Ho.alwaysValidSchema)(s,t)){let h=(0,Et._)`${d} >= ${o}`;a!==void 0&&(h=(0,Et._)`${h} && ${d} <= ${a}`),r.pass(h);return}s.items=!0;let u=e.name("valid");a===void 0&&o===1?p(u,()=>e.if(u,()=>e.break())):o===0?(e.let(u,!0),a!==void 0&&e.if((0,Et._)`${i}.length > 0`,f)):(e.let(u,!1),f()),r.result(u,()=>r.reset());function f(){let h=e.name("_valid"),m=e.let("count",0);p(h,()=>e.if(h,()=>y(m)))}function p(h,m){e.forRange("i",0,d,g=>{r.subschema({keyword:"contains",dataProp:g,dataPropType:Ho.Type.Num,compositeRule:!0},h),m()})}function y(h){e.code((0,Et._)`${h}++`),a===void 0?e.if((0,Et._)`${h} >= ${o}`,()=>e.assign(u,!0).break()):(e.if((0,Et._)`${h} > ${a}`,()=>e.assign(u,!1).break()),o===1?e.assign(u,!0):e.if((0,Et._)`${h} >= ${o}`,()=>e.assign(u,!0)))}}};fd.default=vA});var Ko=A(er=>{"use strict";Object.defineProperty(er,"__esModule",{value:!0});er.validateSchemaDeps=er.validatePropertyDeps=er.error=void 0;var pd=H(),$A=Q(),ys=$t();er.error={message:({params:{property:r,depsCount:e,deps:t}})=>{let n=e===1?"property":"properties";return(0,pd.str)`must have ${n} ${t} when property ${r} is present`},params:({params:{property:r,depsCount:e,deps:t,missingProperty:n}})=>(0,pd._)`{property: ${r}, + || ${o} === "boolean" || ${i} === null`).assign(a,(0,W._)`[${i}]`)}}}function Uv({gen:r,parentData:e,parentDataProperty:t},n){r.if((0,W._)`${e} !== undefined`,()=>r.assign((0,W._)`${e}[${t}]`,n))}function hl(r,e,t,n=zn.Correct){let i=n===zn.Correct?W.operators.EQ:W.operators.NEQ,s;switch(r){case"null":return(0,W._)`${e} ${i} null`;case"array":s=(0,W._)`Array.isArray(${e})`;break;case"object":s=(0,W._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=o((0,W._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=o();break;default:return(0,W._)`typeof ${e} ${i} ${r}`}return n===zn.Correct?s:(0,W.not)(s);function o(a=W.nil){return(0,W.and)((0,W._)`typeof ${e} == "number"`,a,t?(0,W._)`isFinite(${e})`:W.nil)}}ze.checkDataType=hl;function ml(r,e,t,n){if(r.length===1)return hl(r[0],e,t,n);let i,s=(0,Fp.toHash)(r);if(s.array&&s.object){let o=(0,W._)`typeof ${e} != "object"`;i=s.null?o:(0,W._)`!${e} || ${o}`,delete s.null,delete s.array,delete s.object}else i=W.nil;s.number&&delete s.integer;for(let o in s)i=(0,W.and)(i,hl(o,e,t,n));return i}ze.checkDataTypes=ml;var Bv={message:({schema:r})=>`must be ${r}`,params:({schema:r,schemaValue:e})=>typeof r=="string"?(0,W._)`{type: ${r}}`:(0,W._)`{type: ${e}}`};function yl(r){let e=zv(r);(0,jv.reportError)(e,Bv)}ze.reportTypeError=yl;function zv(r){let{gen:e,data:t,schema:n}=r,i=(0,Fp.schemaRefOrVal)(r,n,"type");return{gen:e,keyword:"type",data:t,schema:n.type,schemaCode:i,schemaValue:i,parentSchema:n,params:{},it:r}}});var zp=E(xo=>{"use strict";Object.defineProperty(xo,"__esModule",{value:!0});xo.assignDefaults=void 0;var Hn=H(),Hv=Q();function Kv(r,e){let{properties:t,items:n}=r.schema;if(e==="object"&&t)for(let i in t)Bp(r,i,t[i].default);else e==="array"&&Array.isArray(n)&&n.forEach((i,s)=>Bp(r,s,i.default))}xo.assignDefaults=Kv;function Bp(r,e,t){let{gen:n,compositeRule:i,data:s,opts:o}=r;if(t===void 0)return;let a=(0,Hn._)`${s}${(0,Hn.getProperty)(e)}`;if(i){(0,Hv.checkStrictMode)(r,`default is ignored for: ${a}`);return}let c=(0,Hn._)`${a} === undefined`;o.useDefaults==="empty"&&(c=(0,Hn._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,Hn._)`${a} = ${(0,Hn.stringify)(t)}`)}});var $t=E(ue=>{"use strict";Object.defineProperty(ue,"__esModule",{value:!0});ue.validateUnion=ue.validateArray=ue.usePattern=ue.callValidateCode=ue.schemaProperties=ue.allSchemaProperties=ue.noPropertyInData=ue.propertyInData=ue.isOwnProperty=ue.hasPropFunc=ue.reportMissingProp=ue.checkMissingProp=ue.checkReportMissingProp=void 0;var ge=H(),gl=Q(),Ur=vt(),Wv=Q();function Gv(r,e){let{gen:t,data:n,it:i}=r;t.if(bl(t,n,e,i.opts.ownProperties),()=>{r.setParams({missingProperty:(0,ge._)`${e}`},!0),r.error()})}ue.checkReportMissingProp=Gv;function Jv({gen:r,data:e,it:{opts:t}},n,i){return(0,ge.or)(...n.map(s=>(0,ge.and)(bl(r,e,s,t.ownProperties),(0,ge._)`${i} = ${s}`)))}ue.checkMissingProp=Jv;function Yv(r,e){r.setParams({missingProperty:e},!0),r.error()}ue.reportMissingProp=Yv;function Hp(r){return r.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,ge._)`Object.prototype.hasOwnProperty`})}ue.hasPropFunc=Hp;function _l(r,e,t){return(0,ge._)`${Hp(r)}.call(${e}, ${t})`}ue.isOwnProperty=_l;function Xv(r,e,t,n){let i=(0,ge._)`${e}${(0,ge.getProperty)(t)} !== undefined`;return n?(0,ge._)`${i} && ${_l(r,e,t)}`:i}ue.propertyInData=Xv;function bl(r,e,t,n){let i=(0,ge._)`${e}${(0,ge.getProperty)(t)} === undefined`;return n?(0,ge.or)(i,(0,ge.not)(_l(r,e,t))):i}ue.noPropertyInData=bl;function Kp(r){return r?Object.keys(r).filter(e=>e!=="__proto__"):[]}ue.allSchemaProperties=Kp;function Qv(r,e){return Kp(e).filter(t=>!(0,gl.alwaysValidSchema)(r,e[t]))}ue.schemaProperties=Qv;function Zv({schemaCode:r,data:e,it:{gen:t,topSchemaRef:n,schemaPath:i,errorPath:s},it:o},a,c,l){let d=l?(0,ge._)`${r}, ${e}, ${n}${i}`:e,u=[[Ur.default.instancePath,(0,ge.strConcat)(Ur.default.instancePath,s)],[Ur.default.parentData,o.parentData],[Ur.default.parentDataProperty,o.parentDataProperty],[Ur.default.rootData,Ur.default.rootData]];o.opts.dynamicRef&&u.push([Ur.default.dynamicAnchors,Ur.default.dynamicAnchors]);let f=(0,ge._)`${d}, ${t.object(...u)}`;return c!==ge.nil?(0,ge._)`${a}.call(${c}, ${f})`:(0,ge._)`${a}(${f})`}ue.callValidateCode=Zv;var e$=(0,ge._)`new RegExp`;function t$({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,ge._)`${i.code==="new RegExp"?e$:(0,Wv.useFunc)(r,i)}(${t}, ${n})`})}ue.usePattern=t$;function r$(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,ge._)`${t}.length`);e.forRange("i",0,c,l=>{r.subschema({keyword:n,dataProp:l,dataPropType:gl.Type.Num},s),e.if((0,ge.not)(s),a)})}}ue.validateArray=r$;function n$(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,gl.alwaysValidSchema)(i,c))&&!i.opts.unevaluated)return;let o=e.let("valid",!1),a=e.name("_valid");e.block(()=>t.forEach((c,l)=>{let d=r.subschema({keyword:n,schemaProp:l,compositeRule:!0},a);e.assign(o,(0,ge._)`${o} || ${a}`),r.mergeValidEvaluated(d,a)||e.if((0,ge.not)(o))})),r.result(o,()=>r.reset(),()=>r.error(!0))}ue.validateUnion=n$});var Jp=E(Qt=>{"use strict";Object.defineProperty(Qt,"__esModule",{value:!0});Qt.validateKeywordUsage=Qt.validSchemaType=Qt.funcKeywordCode=Qt.macroKeywordCode=void 0;var Ye=H(),_n=vt(),i$=$t(),s$=Xi();function o$(r,e){let{gen:t,keyword:n,schema:i,parentSchema:s,it:o}=r,a=e.macro.call(o.self,i,s,o),c=Gp(t,n,a);o.opts.validateSchema!==!1&&o.self.validateSchema(a,!0);let l=t.name("valid");r.subschema({schema:a,schemaPath:Ye.nil,errSchemaPath:`${o.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},l),r.pass(l,()=>r.error(!0))}Qt.macroKeywordCode=o$;function a$(r,e){var t;let{gen:n,keyword:i,schema:s,parentSchema:o,$data:a,it:c}=r;l$(c,e);let l=!a&&e.compile?e.compile.call(c.self,s,o,c):e.validate,d=Gp(n,i,l),u=n.let("valid");r.block$data(u,f),r.ok((t=e.valid)!==null&&t!==void 0?t:u);function f(){if(e.errors===!1)h(),e.modifying&&Wp(r),m(()=>r.error());else{let g=e.async?p():y();e.modifying&&Wp(r),m(()=>c$(r,g))}}function p(){let g=n.let("ruleErrs",null);return n.try(()=>h((0,Ye._)`await `),_=>n.assign(u,!1).if((0,Ye._)`${_} instanceof ${c.ValidationError}`,()=>n.assign(g,(0,Ye._)`${_}.errors`),()=>n.throw(_))),g}function y(){let g=(0,Ye._)`${d}.errors`;return n.assign(g,null),h(Ye.nil),g}function h(g=e.async?(0,Ye._)`await `:Ye.nil){let _=c.opts.passContext?_n.default.this:_n.default.self,w=!("compile"in e&&!a||e.schema===!1);n.assign(u,(0,Ye._)`${g}${(0,i$.callValidateCode)(r,d,_,w)}`,e.modifying)}function m(g){var _;n.if((0,Ye.not)((_=e.valid)!==null&&_!==void 0?_:u),g)}}Qt.funcKeywordCode=a$;function Wp(r){let{gen:e,data:t,it:n}=r;e.if(n.parentData,()=>e.assign(t,(0,Ye._)`${n.parentData}[${n.parentDataProperty}]`))}function c$(r,e){let{gen:t}=r;t.if((0,Ye._)`Array.isArray(${e})`,()=>{t.assign(_n.default.vErrors,(0,Ye._)`${_n.default.vErrors} === null ? ${e} : ${_n.default.vErrors}.concat(${e})`).assign(_n.default.errors,(0,Ye._)`${_n.default.vErrors}.length`),(0,s$.extendErrors)(r)},()=>r.error())}function l$({schemaEnv:r},e){if(e.async&&!r.$async)throw new Error("async keyword in sync schema")}function Gp(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,Ye.stringify)(t)})}function d$(r,e,t=!1){return!e.length||e.some(n=>n==="array"?Array.isArray(r):n==="object"?r&&typeof r=="object"&&!Array.isArray(r):typeof r==n||t&&typeof r=="undefined")}Qt.validSchemaType=d$;function u$({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!=null&&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)}}Qt.validateKeywordUsage=u$});var Xp=E(Br=>{"use strict";Object.defineProperty(Br,"__esModule",{value:!0});Br.extendSubschemaMode=Br.extendSubschemaData=Br.getSubschema=void 0;var Zt=H(),Yp=Q();function f$(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,Zt._)`${r.schemaPath}${(0,Zt.getProperty)(e)}`,errSchemaPath:`${r.errSchemaPath}/${e}`}:{schema:a[t],schemaPath:(0,Zt._)`${r.schemaPath}${(0,Zt.getProperty)(e)}${(0,Zt.getProperty)(t)}`,errSchemaPath:`${r.errSchemaPath}/${e}/${(0,Yp.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')}Br.getSubschema=f$;function p$(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:d,opts:u}=e,f=a.let("data",(0,Zt._)`${e.data}${(0,Zt.getProperty)(t)}`,!0);c(f),r.errorPath=(0,Zt.str)`${l}${(0,Yp.getErrorPath)(t,n,u.jsPropertySyntax)}`,r.parentDataProperty=(0,Zt._)`${t}`,r.dataPathArr=[...d,r.parentDataProperty]}if(i!==void 0){let l=i instanceof Zt.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]}}Br.extendSubschemaData=p$;function h$(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}Br.extendSubschemaMode=h$});var wl=E((zM,Qp)=>{"use strict";Qp.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 eh=E((HM,Zp)=>{"use strict";var zr=Zp.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(){};Po(e,n,i,r,"",r)};zr.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};zr.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};zr.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};zr.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 Po(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 d in n){var u=n[d];if(Array.isArray(u)){if(d in zr.arrayKeywords)for(var f=0;f{"use strict";Object.defineProperty(ot,"__esModule",{value:!0});ot.getSchemaRefs=ot.resolveUrl=ot.normalizeId=ot._getFullPath=ot.getFullPath=ot.inlineRef=void 0;var y$=Q(),g$=wl(),_$=eh(),b$=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function w$(r,e=!0){return typeof r=="boolean"?!0:e===!0?!vl(r):e?th(r)<=e:!1}ot.inlineRef=w$;var v$=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function vl(r){for(let e in r){if(v$.has(e))return!0;let t=r[e];if(Array.isArray(t)&&t.some(vl)||typeof t=="object"&&vl(t))return!0}return!1}function th(r){let e=0;for(let t in r){if(t==="$ref")return 1/0;if(e++,!b$.has(t)&&(typeof r[t]=="object"&&(0,y$.eachItem)(r[t],n=>e+=th(n)),e===1/0))return 1/0}return e}function rh(r,e="",t){t!==!1&&(e=Kn(e));let n=r.parse(e);return nh(r,n)}ot.getFullPath=rh;function nh(r,e){return r.serialize(e).split("#")[0]+"#"}ot._getFullPath=nh;var $$=/#\/?$/;function Kn(r){return r?r.replace($$,""):""}ot.normalizeId=Kn;function S$(r,e,t){return t=Kn(t),r.resolve(e,t)}ot.resolveUrl=S$;var E$=/^[a-z_][-a-z0-9._]*$/i;function A$(r,e){if(typeof r=="boolean")return{};let{schemaId:t,uriResolver:n}=this.opts,i=Kn(r[t]||e),s={"":i},o=rh(n,i,!1),a={},c=new Set;return _$(r,{allKeys:!0},(u,f,p,y)=>{if(y===void 0)return;let h=o+f,m=s[y];typeof u[t]=="string"&&(m=g.call(this,u[t])),_.call(this,u.$anchor),_.call(this,u.$dynamicAnchor),s[f]=m;function g(w){let x=this.opts.uriResolver.resolve;if(w=Kn(m?x(m,w):w),c.has(w))throw d(w);c.add(w);let v=this.refs[w];return typeof v=="string"&&(v=this.refs[v]),typeof v=="object"?l(u,v.schema,w):w!==Kn(h)&&(w[0]==="#"?(l(u,a[w],w),a[w]=u):this.refs[w]=h),w}function _(w){if(typeof w=="string"){if(!E$.test(w))throw new Error(`invalid anchor "${w}"`);g.call(this,`#${w}`)}}}),a;function l(u,f,p){if(f!==void 0&&!g$(u,f))throw d(p)}function d(u){return new Error(`reference "${u}" resolves to more than one schema`)}}ot.getSchemaRefs=A$});var Wn=E(Hr=>{"use strict";Object.defineProperty(Hr,"__esModule",{value:!0});Hr.getData=Hr.KeywordCxt=Hr.validateFunctionCode=void 0;var ch=jp(),ih=Qi(),Sl=pl(),Io=Qi(),k$=zp(),ts=Jp(),$l=Xp(),U=H(),z=vt(),x$=Zi(),_r=Q(),es=Xi();function P$(r){if(uh(r)&&(fh(r),dh(r))){R$(r);return}lh(r,()=>(0,ch.topBoolOrEmptySchema)(r))}Hr.validateFunctionCode=P$;function lh({gen:r,validateName:e,schema:t,schemaEnv:n,opts:i},s){i.code.es5?r.func(e,(0,U._)`${z.default.data}, ${z.default.valCxt}`,n.$async,()=>{r.code((0,U._)`"use strict"; ${sh(t,i)}`),O$(r,i),r.code(s)}):r.func(e,(0,U._)`${z.default.data}, ${I$(i)}`,n.$async,()=>r.code(sh(t,i)).code(s))}function I$(r){return(0,U._)`{${z.default.instancePath}="", ${z.default.parentData}, ${z.default.parentDataProperty}, ${z.default.rootData}=${z.default.data}${r.dynamicRef?(0,U._)`, ${z.default.dynamicAnchors}={}`:U.nil}}={}`}function O$(r,e){r.if(z.default.valCxt,()=>{r.var(z.default.instancePath,(0,U._)`${z.default.valCxt}.${z.default.instancePath}`),r.var(z.default.parentData,(0,U._)`${z.default.valCxt}.${z.default.parentData}`),r.var(z.default.parentDataProperty,(0,U._)`${z.default.valCxt}.${z.default.parentDataProperty}`),r.var(z.default.rootData,(0,U._)`${z.default.valCxt}.${z.default.rootData}`),e.dynamicRef&&r.var(z.default.dynamicAnchors,(0,U._)`${z.default.valCxt}.${z.default.dynamicAnchors}`)},()=>{r.var(z.default.instancePath,(0,U._)`""`),r.var(z.default.parentData,(0,U._)`undefined`),r.var(z.default.parentDataProperty,(0,U._)`undefined`),r.var(z.default.rootData,z.default.data),e.dynamicRef&&r.var(z.default.dynamicAnchors,(0,U._)`{}`)})}function R$(r){let{schema:e,opts:t,gen:n}=r;lh(r,()=>{t.$comment&&e.$comment&&hh(r),L$(r),n.let(z.default.vErrors,null),n.let(z.default.errors,0),t.unevaluated&&T$(r),ph(r),q$(r)})}function T$(r){let{gen:e,validateName:t}=r;r.evaluated=e.const("evaluated",(0,U._)`${t}.evaluated`),e.if((0,U._)`${r.evaluated}.dynamicProps`,()=>e.assign((0,U._)`${r.evaluated}.props`,(0,U._)`undefined`)),e.if((0,U._)`${r.evaluated}.dynamicItems`,()=>e.assign((0,U._)`${r.evaluated}.items`,(0,U._)`undefined`))}function sh(r,e){let t=typeof r=="object"&&r[e.schemaId];return t&&(e.code.source||e.code.process)?(0,U._)`/*# sourceURL=${t} */`:U.nil}function C$(r,e){if(uh(r)&&(fh(r),dh(r))){M$(r,e);return}(0,ch.boolOrEmptySchema)(r,e)}function dh({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 uh(r){return typeof r.schema!="boolean"}function M$(r,e){let{schema:t,gen:n,opts:i}=r;i.$comment&&t.$comment&&hh(r),j$(r),D$(r);let s=n.const("_errs",z.default.errors);ph(r,s),n.var(e,(0,U._)`${s} === ${z.default.errors}`)}function fh(r){(0,_r.checkUnknownRules)(r),N$(r)}function ph(r,e){if(r.opts.jtd)return oh(r,[],!1,e);let t=(0,ih.getSchemaTypes)(r.schema),n=(0,ih.coerceAndCheckDataType)(r,t);oh(r,t,!n,e)}function N$(r){let{schema:e,errSchemaPath:t,opts:n,self:i}=r;e.$ref&&n.ignoreKeywordsWithRef&&(0,_r.schemaHasRulesButRef)(e,i.RULES)&&i.logger.warn(`$ref: keywords ignored in schema at path "${t}"`)}function L$(r){let{schema:e,opts:t}=r;e.default!==void 0&&t.useDefaults&&t.strictSchema&&(0,_r.checkStrictMode)(r,"default is ignored in the schema root")}function j$(r){let e=r.schema[r.opts.schemaId];e&&(r.baseId=(0,x$.resolveUrl)(r.opts.uriResolver,r.baseId,e))}function D$(r){if(r.schema.$async&&!r.schemaEnv.$async)throw new Error("async schema in sync schema")}function hh({gen:r,schemaEnv:e,schema:t,errSchemaPath:n,opts:i}){let s=t.$comment;if(i.$comment===!0)r.code((0,U._)`${z.default.self}.logger.log(${s})`);else if(typeof i.$comment=="function"){let o=(0,U.str)`${n}/$comment`,a=r.scopeValue("root",{ref:e.root});r.code((0,U._)`${z.default.self}.opts.$comment(${s}, ${o}, ${a}.schema)`)}}function q$(r){let{gen:e,schemaEnv:t,validateName:n,ValidationError:i,opts:s}=r;t.$async?e.if((0,U._)`${z.default.errors} === 0`,()=>e.return(z.default.data),()=>e.throw((0,U._)`new ${i}(${z.default.vErrors})`)):(e.assign((0,U._)`${n}.errors`,z.default.vErrors),s.unevaluated&&F$(r),e.return((0,U._)`${z.default.errors} === 0`))}function F$({gen:r,evaluated:e,props:t,items:n}){t instanceof U.Name&&r.assign((0,U._)`${e}.props`,t),n instanceof U.Name&&r.assign((0,U._)`${e}.items`,n)}function oh(r,e,t,n){let{gen:i,schema:s,data:o,allErrors:a,opts:c,self:l}=r,{RULES:d}=l;if(s.$ref&&(c.ignoreKeywordsWithRef||!(0,_r.schemaHasRulesButRef)(s,d))){i.block(()=>yh(r,"$ref",d.all.$ref.definition));return}c.jtd||V$(r,e),i.block(()=>{for(let f of d.rules)u(f);u(d.post)});function u(f){(0,Sl.shouldUseGroup)(s,f)&&(f.type?(i.if((0,Io.checkDataType)(f.type,o,c.strictNumbers)),ah(r,f),e.length===1&&e[0]===f.type&&t&&(i.else(),(0,Io.reportTypeError)(r)),i.endIf()):ah(r,f),a||i.if((0,U._)`${z.default.errors} === ${n||0}`))}}function ah(r,e){let{gen:t,schema:n,opts:{useDefaults:i}}=r;i&&(0,k$.assignDefaults)(r,e.type),t.block(()=>{for(let s of e.rules)(0,Sl.shouldUseRule)(n,s)&&yh(r,s.keyword,s.definition,e.type)})}function V$(r,e){r.schemaEnv.meta||!r.opts.strictTypes||(U$(r,e),r.opts.allowUnionTypes||B$(r,e),z$(r,r.dataTypes))}function U$(r,e){if(e.length){if(!r.dataTypes.length){r.dataTypes=e;return}e.forEach(t=>{mh(r.dataTypes,t)||El(r,`type "${t}" not allowed by context "${r.dataTypes.join(",")}"`)}),K$(r,e)}}function B$(r,e){e.length>1&&!(e.length===2&&e.includes("null"))&&El(r,"use allowUnionTypes to allow union type keyword")}function z$(r,e){let t=r.self.RULES.all;for(let n in t){let i=t[n];if(typeof i=="object"&&(0,Sl.shouldUseRule)(r.schema,i)){let{type:s}=i.definition;s.length&&!s.some(o=>H$(e,o))&&El(r,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function H$(r,e){return r.includes(e)||e==="number"&&r.includes("integer")}function mh(r,e){return r.includes(e)||e==="integer"&&r.includes("number")}function K$(r,e){let t=[];for(let n of r.dataTypes)mh(e,n)?t.push(n):e.includes("integer")&&n==="number"&&t.push("integer");r.dataTypes=t}function El(r,e){let t=r.schemaEnv.baseId+r.errSchemaPath;e+=` at "${t}" (strictTypes)`,(0,_r.checkStrictMode)(r,e,r.opts.strictTypes)}var Oo=class{constructor(e,t,n){if((0,ts.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,_r.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",gh(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,ts.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",z.default.errors))}result(e,t,n){this.failResult((0,U.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,U.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,U._)`${t} !== undefined && (${(0,U.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?es.reportExtraError:es.reportError)(this,this.def.error,t)}$dataError(){(0,es.reportError)(this,this.def.$dataError||es.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,es.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=U.nil){this.gen.block(()=>{this.check$data(e,n),t()})}check$data(e=U.nil,t=U.nil){if(!this.$data)return;let{gen:n,schemaCode:i,schemaType:s,def:o}=this;n.if((0,U.or)((0,U._)`${i} === undefined`,t)),e!==U.nil&&n.assign(e,!0),(s.length||o.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==U.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:t,schemaType:n,def:i,it:s}=this;return(0,U.or)(o(),a());function o(){if(n.length){if(!(t instanceof U.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,U._)`${(0,Io.checkDataTypes)(c,t,s.opts.strictNumbers,Io.DataType.Wrong)}`}return U.nil}function a(){if(i.validateSchema){let c=e.scopeValue("validate$data",{ref:i.validateSchema});return(0,U._)`!${c}(${t})`}return U.nil}}subschema(e,t){let n=(0,$l.getSubschema)(this.it,e);(0,$l.extendSubschemaData)(n,this.it,e),(0,$l.extendSubschemaMode)(n,e);let i={...this.it,...n,items:void 0,props:void 0};return C$(i,t),i}mergeEvaluated(e,t){let{it:n,gen:i}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=_r.mergeEvaluated.props(i,e.props,n.props,t)),n.items!==!0&&e.items!==void 0&&(n.items=_r.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,U.Name)),!0}};Hr.KeywordCxt=Oo;function yh(r,e,t,n){let i=new Oo(r,t,e);"code"in t?t.code(i,n):i.$data&&t.validate?(0,ts.funcKeywordCode)(i,t):"macro"in t?(0,ts.macroKeywordCode)(i,t):(t.compile||t.validate)&&(0,ts.funcKeywordCode)(i,t)}var W$=/^\/(?:[^~]|~0|~1)*$/,G$=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function gh(r,{dataLevel:e,dataNames:t,dataPathArr:n}){let i,s;if(r==="")return z.default.rootData;if(r[0]==="/"){if(!W$.test(r))throw new Error(`Invalid JSON-pointer: ${r}`);i=r,s=z.default.rootData}else{let l=G$.exec(r);if(!l)throw new Error(`Invalid JSON-pointer: ${r}`);let d=+l[1];if(i=l[2],i==="#"){if(d>=e)throw new Error(c("property/index",d));return n[e-d]}if(d>e)throw new Error(c("data",d));if(s=t[e-d],!i)return s}let o=s,a=i.split("/");for(let l of a)l&&(s=(0,U._)`${s}${(0,U.getProperty)((0,_r.unescapeJsonPointer)(l))}`,o=(0,U._)`${o} && ${s}`);return o;function c(l,d){return`Cannot access ${l} ${d} levels up, current level is ${e}`}}Hr.getData=gh});var rs=E(kl=>{"use strict";Object.defineProperty(kl,"__esModule",{value:!0});var Al=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};kl.default=Al});var Gn=E(Il=>{"use strict";Object.defineProperty(Il,"__esModule",{value:!0});var xl=Zi(),Pl=class extends Error{constructor(e,t,n,i){super(i||`can't resolve reference ${n} from id ${t}`),this.missingRef=(0,xl.resolveUrl)(e,t,n),this.missingSchema=(0,xl.normalizeId)((0,xl.getFullPath)(e,this.missingRef))}};Il.default=Pl});var ns=E(St=>{"use strict";Object.defineProperty(St,"__esModule",{value:!0});St.resolveSchema=St.getCompilingSchema=St.resolveRef=St.compileSchema=St.SchemaEnv=void 0;var Tt=H(),J$=rs(),bn=vt(),Ct=Zi(),_h=Q(),Y$=Wn(),Jn=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,Ct.normalizeId)(n==null?void 0:n[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n==null?void 0:n.$async,this.refs={}}};St.SchemaEnv=Jn;function Rl(r){let e=bh.call(this,r);if(e)return e;let t=(0,Ct.getFullPath)(this.opts.uriResolver,r.root.baseId),{es5:n,lines:i}=this.opts.code,{ownProperties:s}=this.opts,o=new Tt.CodeGen(this.scope,{es5:n,lines:i,ownProperties:s}),a;r.$async&&(a=o.scopeValue("Error",{ref:J$.default,code:(0,Tt._)`require("ajv/dist/runtime/validation_error").default`}));let c=o.scopeName("validate");r.validateName=c;let l={gen:o,allErrors:this.opts.allErrors,data:bn.default.data,parentData:bn.default.parentData,parentDataProperty:bn.default.parentDataProperty,dataNames:[bn.default.data],dataPathArr:[Tt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:o.scopeValue("schema",this.opts.code.source===!0?{ref:r.schema,code:(0,Tt.stringify)(r.schema)}:{ref:r.schema}),validateName:c,ValidationError:a,schema:r.schema,schemaEnv:r,rootId:t,baseId:r.baseId||t,schemaPath:Tt.nil,errSchemaPath:r.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Tt._)`""`,opts:this.opts,self:this},d;try{this._compilations.add(r),(0,Y$.validateFunctionCode)(l),o.optimize(this.opts.code.optimize);let u=o.toString();d=`${o.scopeRefs(bn.default.scope)}return ${u}`,this.opts.code.process&&(d=this.opts.code.process(d,r));let p=new Function(`${bn.default.self}`,`${bn.default.scope}`,d)(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:u,scopeValues:o._values}),this.opts.unevaluated){let{props:y,items:h}=l;p.evaluated={props:y instanceof Tt.Name?void 0:y,items:h instanceof Tt.Name?void 0:h,dynamicProps:y instanceof Tt.Name,dynamicItems:h instanceof Tt.Name},p.source&&(p.source.evaluated=(0,Tt.stringify)(p.evaluated))}return r.validate=p,r}catch(u){throw delete r.validate,delete r.validateName,d&&this.logger.error("Error compiling schema, function code:",d),u}finally{this._compilations.delete(r)}}St.compileSchema=Rl;function X$(r,e,t){var n;t=(0,Ct.resolveUrl)(this.opts.uriResolver,e,t);let i=r.refs[t];if(i)return i;let s=eS.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 Jn({schema:o,schemaId:a,root:r,baseId:e}))}if(s!==void 0)return r.refs[t]=Q$.call(this,s)}St.resolveRef=X$;function Q$(r){return(0,Ct.inlineRef)(r.schema,this.opts.inlineRefs)?r.schema:r.validate?r:Rl.call(this,r)}function bh(r){for(let e of this._compilations)if(Z$(e,r))return e}St.getCompilingSchema=bh;function Z$(r,e){return r.schema===e.schema&&r.root===e.root&&r.baseId===e.baseId}function eS(r,e){let t;for(;typeof(t=this.refs[e])=="string";)e=t;return t||this.schemas[e]||Ro.call(this,r,e)}function Ro(r,e){let t=this.opts.uriResolver.parse(e),n=(0,Ct._getFullPath)(this.opts.uriResolver,t),i=(0,Ct.getFullPath)(this.opts.uriResolver,r.baseId,void 0);if(Object.keys(r.schema).length>0&&n===i)return Ol.call(this,t,r);let s=(0,Ct.normalizeId)(n),o=this.refs[s]||this.schemas[s];if(typeof o=="string"){let a=Ro.call(this,r,o);return typeof(a==null?void 0:a.schema)!="object"?void 0:Ol.call(this,t,a)}if(typeof(o==null?void 0:o.schema)=="object"){if(o.validate||Rl.call(this,o),s===(0,Ct.normalizeId)(e)){let{schema:a}=o,{schemaId:c}=this.opts,l=a[c];return l&&(i=(0,Ct.resolveUrl)(this.opts.uriResolver,i,l)),new Jn({schema:a,schemaId:c,root:r,baseId:i})}return Ol.call(this,t,o)}}St.resolveSchema=Ro;var tS=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Ol(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,_h.unescapeFragment)(a)];if(c===void 0)return;t=c;let l=typeof t=="object"&&t[this.opts.schemaId];!tS.has(a)&&l&&(e=(0,Ct.resolveUrl)(this.opts.uriResolver,e,l))}let s;if(typeof t!="boolean"&&t.$ref&&!(0,_h.schemaHasRulesButRef)(t,this.RULES)){let a=(0,Ct.resolveUrl)(this.opts.uriResolver,e,t.$ref);s=Ro.call(this,n,a)}let{schemaId:o}=this.opts;if(s=s||new Jn({schema:t,schemaId:o,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var wh=E((XM,rS)=>{rS.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 Ml=E((QM,kh)=>{"use strict";var nS=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),$h=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),Tl=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),Sh=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),iS=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function Cl(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 sS=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function vh(r){return r.length=0,!0}function oS(r,e,t){if(r.length){let n=Cl(r);if(n!=="")e.push(n);else return t.error=!0,!1;r.length=0}return!0}function aS(r){let e=0,t={error:!1,address:"",zone:""},n=[],i=[],s=!1,o=!1,a=oS;for(let c=0;c7){t.error=!0;break}c>0&&r[c-1]===":"&&(s=!0),n.push(":");continue}else if(l==="%"){if(!a(i,n,t))break;a=vh}else{i.push(l);continue}}return i.length&&(a===vh?t.zone=i.join(""):o?n.push(i.join("")):n.push(Cl(i))),t.address=n.join(""),t}function Eh(r){if(cS(r,":")<2)return{host:r,isIPV6:!1};let e=aS(r);if(e.error)return{host:r,isIPV6:!1};{let t=e.address,n=e.address;return e.zone&&(t+="%"+e.zone,n+="%25"+e.zone),{host:t,isIPV6:!0,escapedHost:n}}}function cS(r,e){let t=0;for(let n=0;ndS[n])}function pS(r,e=!1){if(r.indexOf("%")===-1)return r;let t="";for(let n=0;n{"use strict";var{isUUID:gS}=Ml(),_S=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,bS=["http","https","ws","wss","urn","urn:uuid"];function wS(r){return bS.indexOf(r)!==-1}function Nl(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 xh(r){return r.host||(r.error=r.error||"HTTP URIs must have a host."),r}function Ph(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 vS(r){return r.secure=Nl(r),r.resourceName=(r.path||"/")+(r.query?"?"+r.query:""),r.path=void 0,r.query=void 0,r}function $S(r){if((r.port===(Nl(r)?443:80)||r.port==="")&&(r.port=void 0),typeof r.secure=="boolean"&&(r.scheme=r.secure?"wss":"ws",r.secure=void 0),r.resourceName){let[e,t]=r.resourceName.split("?");r.path=e&&e!=="/"?e:void 0,r.query=t,r.resourceName=void 0}return r.fragment=void 0,r}function SS(r,e){if(!r.path)return r.error="URN can not be parsed",r;let t=r.path.match(_S);if(t){let n=e.scheme||r.scheme||"urn";r.nid=t[1].toLowerCase(),r.nss=t[2];let i=`${n}:${e.nid||r.nid}`,s=Ll(i);r.path=void 0,s&&(r=s.parse(r,e))}else r.error=r.error||"URN can not be parsed.";return r}function ES(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=Ll(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 AS(r,e){let t=r;return t.uuid=t.nss,t.nss=void 0,!e.tolerant&&(!t.uuid||!gS(t.uuid))&&(t.error=t.error||"UUID is not valid."),t}function kS(r){let e=r;return e.nss=(r.uuid||"").toLowerCase(),e}var Ih={scheme:"http",domainHost:!0,parse:xh,serialize:Ph},xS={scheme:"https",domainHost:Ih.domainHost,parse:xh,serialize:Ph},To={scheme:"ws",domainHost:!0,parse:vS,serialize:$S},PS={scheme:"wss",domainHost:To.domainHost,parse:To.parse,serialize:To.serialize},IS={scheme:"urn",parse:SS,serialize:ES,skipNormalize:!0},OS={scheme:"urn:uuid",parse:AS,serialize:kS,skipNormalize:!0},Co={http:Ih,https:xS,ws:To,wss:PS,urn:IS,"urn:uuid":OS};Object.setPrototypeOf(Co,null);function Ll(r){return r&&(Co[r]||Co[r.toLowerCase()])||void 0}Oh.exports={wsIsSecure:Nl,SCHEMES:Co,isValidSchemeName:wS,getSchemeHandler:Ll}});var Lh=E((eN,Lo)=>{"use strict";var{normalizeIPv6:RS,removeDotSegments:is,recomposeAuthority:TS,normalizePercentEncoding:CS,normalizePathEncoding:MS,escapePreservingEscapes:NS,reescapeHostDelimiters:LS,isIPv4:jS,nonSimpleDomain:DS}=Ml(),{SCHEMES:qS,getSchemeHandler:Ch}=Rh();function FS(r,e){return typeof r=="string"?r=WS(r,e):typeof r=="object"&&(r=No(wn(r,e),e)),r}function VS(r,e,t){let n=t?Object.assign({scheme:"null"},t):{scheme:"null"},{parsed:i,malformedAuthorityOrPort:s}=Mo(r,n),{parsed:o,malformedAuthorityOrPort:a}=Mo(e,n);if(s||a)throw new Error(i.error||o.error||"URI is malformed.");let c=Mh(i,o,n,!0);return n.skipEscape=!0,wn(c,n)}function Mh(r,e,t,n){let i={};return n||(r=No(wn(r,t),t),e=No(wn(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=is(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=is(e.path||""),i.query=e.query):(e.path?(e.path[0]==="/"?i.path=is(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=is(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 US(r,e,t){let n=Th(r,t),i=Th(e,t);return n!==void 0&&i!==void 0&&n.toLowerCase()===i.toLowerCase()}function wn(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=[],s=Ch(n.scheme||t.scheme);s&&s.serialize&&s.serialize(t,n),t.path!==void 0&&(n.skipEscape?t.path=CS(t.path):(t.path=NS(t.path),t.scheme!==void 0&&(t.path=t.path.split("%3A").join(":")))),n.reference!=="suffix"&&t.scheme&&i.push(t.scheme,":");let o=TS(t);if(o!==void 0&&(n.reference!=="suffix"&&i.push("//"),i.push(o),t.path&&t.path[0]!=="/"&&i.push("/")),t.path!==void 0){let a=t.path;!n.absolutePath&&(!s||!s.absolutePath)&&(a=is(a)),o===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),i.push(a)}return t.query!==void 0&&i.push("?",t.query),t.fragment!==void 0&&i.push("#",t.fragment),i.join("")}var BS=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,zS=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,HS=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function KS(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 Mo(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;t.reference==="suffix"&&(t.scheme?r=t.scheme+":"+r:r="//"+r);let o=r.match(zS);o!==null&&o[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",i=!0);let a=r.match(HS);if(a!==null){let l=a[1],d=l.replace(/[\t\n\r]/g,"");d.length>=2&&(d.slice(0,2)!=="//"?(n.error=n.error||"URI authority must not contain a literal backslash.",i=!0):l.length!==d.length&&(n.error=n.error||"URI authority introducer must not contain whitespace.",i=!0))}let c=r.match(BS);if(c){n.scheme=c[1],n.userinfo=c[3],n.host=c[4],n.port=parseInt(c[5],10),n.path=c[6]||"",n.query=c[7],n.fragment=c[8],isNaN(n.port)&&(n.port=c[5]);let l=KS(n,c);if(l!==void 0&&(n.error=n.error||l,i=!0),n.host)if(jS(n.host)===!1){let f=RS(n.host);n.host=f.host.toLowerCase(),s=f.isIPV6}else s=!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 d=Ch(t.scheme||n.scheme);if(!t.unicodeSupport&&(!d||!d.unicodeSupport)&&n.host&&(t.domainHost||d&&d.domainHost)&&s===!1&&DS(n.host))try{n.host=new URL("http://"+n.host).hostname}catch(u){n.error=n.error||"Host's domain name can not be converted to ASCII: "+u}if((!d||d&&!d.skipNormalize)&&(r.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=LS(unescape(n.host),s))),n.path&&(n.path=MS(n.path)),n.fragment))try{n.fragment=encodeURI(decodeURIComponent(n.fragment))}catch(u){n.error=n.error||"URI malformed"}d&&d.parse&&d.parse(n,t)}else n.error=n.error||"URI can not be parsed.";return{parsed:n,malformedAuthorityOrPort:i}}function No(r,e){return Mo(r,e).parsed}function WS(r,e){return Nh(r,e).normalized}function Nh(r,e){let{parsed:t,malformedAuthorityOrPort:n}=Mo(r,e);return{normalized:n?r:wn(t,e),malformedAuthorityOrPort:n}}function Th(r,e){if(typeof r=="string"){let{normalized:t,malformedAuthorityOrPort:n}=Nh(r,e);return n?void 0:t}if(typeof r=="object")return wn(r,e)}var jl={SCHEMES:qS,normalize:FS,resolve:VS,resolveComponent:Mh,equal:US,serialize:wn,parse:No};Lo.exports=jl;Lo.exports.default=jl;Lo.exports.fastUri=jl});var Dh=E(Dl=>{"use strict";Object.defineProperty(Dl,"__esModule",{value:!0});var jh=Lh();jh.code='require("ajv/dist/runtime/uri").default';Dl.default=jh});var Vl=E(Le=>{"use strict";Object.defineProperty(Le,"__esModule",{value:!0});Le.CodeGen=Le.Name=Le.nil=Le.stringify=Le.str=Le._=Le.KeywordCxt=void 0;var GS=Wn();Object.defineProperty(Le,"KeywordCxt",{enumerable:!0,get:function(){return GS.KeywordCxt}});var Yn=H();Object.defineProperty(Le,"_",{enumerable:!0,get:function(){return Yn._}});Object.defineProperty(Le,"str",{enumerable:!0,get:function(){return Yn.str}});Object.defineProperty(Le,"stringify",{enumerable:!0,get:function(){return Yn.stringify}});Object.defineProperty(Le,"nil",{enumerable:!0,get:function(){return Yn.nil}});Object.defineProperty(Le,"Name",{enumerable:!0,get:function(){return Yn.Name}});Object.defineProperty(Le,"CodeGen",{enumerable:!0,get:function(){return Yn.CodeGen}});var JS=rs(),Bh=Gn(),YS=fl(),ss=ns(),XS=H(),os=Zi(),jo=Qi(),Fl=Q(),qh=wh(),QS=Dh(),zh=(r,e)=>new RegExp(r,e);zh.code="new RegExp";var ZS=["removeAdditional","useDefaults","coerceTypes"],eE=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),tE={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."},rE={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Fh=200;function nE(r){var e,t,n,i,s,o,a,c,l,d,u,f,p,y,h,m,g,_,w,x,v,P,O,A,R;let $=r.strict,M=(e=r.code)===null||e===void 0?void 0:e.optimize,V=M===!0||M===void 0?1:M||0,T=(n=(t=r.code)===null||t===void 0?void 0:t.regExp)!==null&&n!==void 0?n:zh,S=(i=r.uriResolver)!==null&&i!==void 0?i:QS.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:(d=(l=r.strictTypes)!==null&&l!==void 0?l:$)!==null&&d!==void 0?d:"log",strictTuples:(f=(u=r.strictTuples)!==null&&u!==void 0?u:$)!==null&&f!==void 0?f:"log",strictRequired:(y=(p=r.strictRequired)!==null&&p!==void 0?p:$)!==null&&y!==void 0?y:!1,code:r.code?{...r.code,optimize:V,regExp:T}:{optimize:V,regExp:T},loopRequired:(h=r.loopRequired)!==null&&h!==void 0?h:Fh,loopEnum:(m=r.loopEnum)!==null&&m!==void 0?m:Fh,meta:(g=r.meta)!==null&&g!==void 0?g:!0,messages:(_=r.messages)!==null&&_!==void 0?_:!0,inlineRefs:(w=r.inlineRefs)!==null&&w!==void 0?w:!0,schemaId:(x=r.schemaId)!==null&&x!==void 0?x:"$id",addUsedSchema:(v=r.addUsedSchema)!==null&&v!==void 0?v:!0,validateSchema:(P=r.validateSchema)!==null&&P!==void 0?P:!0,validateFormats:(O=r.validateFormats)!==null&&O!==void 0?O:!0,unicodeRegExp:(A=r.unicodeRegExp)!==null&&A!==void 0?A:!0,int32range:(R=r.int32range)!==null&&R!==void 0?R:!0,uriResolver:S}}var as=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,...nE(e)};let{es5:t,lines:n}=this.opts.code;this.scope=new XS.ValueScope({scope:{},prefixes:eE,es5:t,lines:n}),this.logger=lE(e.logger);let i=e.validateFormats;e.validateFormats=!1,this.RULES=(0,YS.getRules)(),Vh.call(this,tE,e,"NOT SUPPORTED"),Vh.call(this,rE,e,"DEPRECATED","warn"),this._metaOpts=aE.call(this),e.formats&&sE.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&oE.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),iE.call(this),e.validateFormats=i}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:t,schemaId:n}=this.opts,i=qh;n==="id"&&(i={...qh},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(d,u){await s.call(this,d.$schema);let f=this._addSchema(d,u);return f.validate||o.call(this,f)}async function s(d){d&&!this.getSchema(d)&&await i.call(this,{$ref:d},!0)}async function o(d){try{return this._compileSchemaEnv(d)}catch(u){if(!(u instanceof Bh.default))throw u;return a.call(this,u),await c.call(this,u.missingSchema),o.call(this,d)}}function a({missingSchema:d,missingRef:u}){if(this.refs[d])throw new Error(`AnySchema ${d} is loaded but ${u} cannot be resolved`)}async function c(d){let u=await l.call(this,d);this.refs[d]||await s.call(this,u.$schema),this.refs[d]||this.addSchema(u,d,t)}async function l(d){let u=this._loading[d];if(u)return u;try{return await(this._loading[d]=n(d))}finally{delete this._loading[d]}}}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,os.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=Uh.call(this,e))=="string";)e=t;if(t===void 0){let{schemaId:n}=this.opts,i=new ss.SchemaEnv({schema:{},schemaId:n});if(t=ss.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=Uh.call(this,e);return typeof t=="object"&&this._cache.delete(t.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let t=e;this._cache.delete(t);let n=e[this.opts.schemaId];return n&&(n=(0,os.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let t of e)this.addKeyword(t);return this}addKeyword(e,t){let n;if(typeof e=="string")n=e,typeof t=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),t.keyword=n);else if(typeof e=="object"&&t===void 0){if(t=e,n=t.keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(uE.call(this,n,t),!t)return(0,Fl.eachItem)(n,s=>ql.call(this,s)),this;pE.call(this,t);let i={...t,type:(0,jo.getJSONTypes)(t.type),schemaType:(0,jo.getJSONTypes)(t.schemaType)};return(0,Fl.eachItem)(n,i.type.length===0?s=>ql.call(this,s,i):s=>i.type.forEach(o=>ql.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,d=o[a];l&&d&&(o[a]=Hh(d))}}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,os.normalizeId)(o||n);let l=os.getSchemaRefs.call(this,e,n);return c=new ss.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):ss.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{ss.compileSchema.call(this,e)}finally{this.opts=t}}};as.ValidationError=JS.default;as.MissingRefError=Bh.default;Le.default=as;function Vh(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 Uh(r){return r=(0,os.normalizeId)(r),this.schemas[r]||this.refs[r]}function iE(){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 sE(){for(let r in this.opts.formats){let e=this.opts.formats[r];e&&this.addFormat(r,e)}}function oE(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 aE(){let r={...this.opts};for(let e of ZS)delete r[e];return r}var cE={log(){},warn(){},error(){}};function lE(r){if(r===!1)return cE;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 dE=/^[a-z_$][a-z0-9_$:-]*$/i;function uE(r,e){let{RULES:t}=this;if((0,Fl.eachItem)(r,n=>{if(t.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!dE.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 ql(r,e,t){var n;let i=e==null?void 0: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,jo.getJSONTypes)(e.type),schemaType:(0,jo.getJSONTypes)(e.schemaType)}};e.before?fE.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 fE(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 pE(r){let{metaSchema:e}=r;e!==void 0&&(r.$data&&this.opts.$data&&(e=Hh(e)),r.validateSchema=this.compile(e,!0))}var hE={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Hh(r){return{anyOf:[r,hE]}}});var Kh=E(Ul=>{"use strict";Object.defineProperty(Ul,"__esModule",{value:!0});var mE={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Ul.default=mE});var Fo=E(vn=>{"use strict";Object.defineProperty(vn,"__esModule",{value:!0});vn.callRef=vn.getValidate=void 0;var yE=Gn(),Wh=$t(),at=H(),Xn=vt(),Gh=ns(),Do=Q(),gE={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 u();let d=Gh.resolveRef.call(c,l,i,t);if(d===void 0)throw new yE.default(n.opts.uriResolver,i,t);if(d instanceof Gh.SchemaEnv)return f(d);return p(d);function u(){if(s===l)return qo(r,o,s,s.$async);let y=e.scopeValue("root",{ref:l});return qo(r,(0,at._)`${y}.validate`,l,l.$async)}function f(y){let h=Jh(r,y);qo(r,h,y,y.$async)}function p(y){let h=e.scopeValue("schema",a.code.source===!0?{ref:y,code:(0,at.stringify)(y)}:{ref:y}),m=e.name("valid"),g=r.subschema({schema:y,dataTypes:[],schemaPath:at.nil,topSchemaRef:h,errSchemaPath:t},m);r.mergeEvaluated(g),r.ok(m)}}};function Jh(r,e){let{gen:t}=r;return e.validate?t.scopeValue("validate",{ref:e.validate}):(0,at._)`${t.scopeValue("wrapper",{ref:e})}.validate`}vn.getValidate=Jh;function qo(r,e,t,n){let{gen:i,it:s}=r,{allErrors:o,schemaEnv:a,opts:c}=s,l=c.passContext?Xn.default.this:at.nil;n?d():u();function d(){if(!a.$async)throw new Error("async schema referenced by sync schema");let y=i.let("valid");i.try(()=>{i.code((0,at._)`await ${(0,Wh.callValidateCode)(r,e,l)}`),p(e),o||i.assign(y,!0)},h=>{i.if((0,at._)`!(${h} instanceof ${s.ValidationError})`,()=>i.throw(h)),f(h),o||i.assign(y,!1)}),r.ok(y)}function u(){r.result((0,Wh.callValidateCode)(r,e,l),()=>p(e),()=>f(e))}function f(y){let h=(0,at._)`${y}.errors`;i.assign(Xn.default.vErrors,(0,at._)`${Xn.default.vErrors} === null ? ${h} : ${Xn.default.vErrors}.concat(${h})`),i.assign(Xn.default.errors,(0,at._)`${Xn.default.vErrors}.length`)}function p(y){var h;if(!s.opts.unevaluated)return;let m=(h=t==null?void 0:t.validate)===null||h===void 0?void 0:h.evaluated;if(s.props!==!0)if(m&&!m.dynamicProps)m.props!==void 0&&(s.props=Do.mergeEvaluated.props(i,m.props,s.props));else{let g=i.var("props",(0,at._)`${y}.evaluated.props`);s.props=Do.mergeEvaluated.props(i,g,s.props,at.Name)}if(s.items!==!0)if(m&&!m.dynamicItems)m.items!==void 0&&(s.items=Do.mergeEvaluated.items(i,m.items,s.items));else{let g=i.var("items",(0,at._)`${y}.evaluated.items`);s.items=Do.mergeEvaluated.items(i,g,s.items,at.Name)}}}vn.callRef=qo;vn.default=gE});var zl=E(Bl=>{"use strict";Object.defineProperty(Bl,"__esModule",{value:!0});var _E=Kh(),bE=Fo(),wE=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",_E.default,bE.default];Bl.default=wE});var Yh=E(Hl=>{"use strict";Object.defineProperty(Hl,"__esModule",{value:!0});var Vo=H(),Kr=Vo.operators,Uo={maximum:{okStr:"<=",ok:Kr.LTE,fail:Kr.GT},minimum:{okStr:">=",ok:Kr.GTE,fail:Kr.LT},exclusiveMaximum:{okStr:"<",ok:Kr.LT,fail:Kr.GTE},exclusiveMinimum:{okStr:">",ok:Kr.GT,fail:Kr.LTE}},vE={message:({keyword:r,schemaCode:e})=>(0,Vo.str)`must be ${Uo[r].okStr} ${e}`,params:({keyword:r,schemaCode:e})=>(0,Vo._)`{comparison: ${Uo[r].okStr}, limit: ${e}}`},$E={keyword:Object.keys(Uo),type:"number",schemaType:"number",$data:!0,error:vE,code(r){let{keyword:e,data:t,schemaCode:n}=r;r.fail$data((0,Vo._)`${t} ${Uo[e].fail} ${n} || isNaN(${t})`)}};Hl.default=$E});var Xh=E(Kl=>{"use strict";Object.defineProperty(Kl,"__esModule",{value:!0});var cs=H(),SE={message:({schemaCode:r})=>(0,cs.str)`must be multiple of ${r}`,params:({schemaCode:r})=>(0,cs._)`{multipleOf: ${r}}`},EE={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:SE,code(r){let{gen:e,data:t,schemaCode:n,it:i}=r,s=i.opts.multipleOfPrecision,o=e.let("res"),a=s?(0,cs._)`Math.abs(Math.round(${o}) - ${o}) > 1e-${s}`:(0,cs._)`${o} !== parseInt(${o})`;r.fail$data((0,cs._)`(${n} === 0 || (${o} = ${t}/${n}, ${a}))`)}};Kl.default=EE});var Zh=E(Wl=>{"use strict";Object.defineProperty(Wl,"__esModule",{value:!0});function Qh(r){let e=r.length,t=0,n=0,i;for(;n=55296&&i<=56319&&n{"use strict";Object.defineProperty(Gl,"__esModule",{value:!0});var $n=H(),AE=Q(),kE=Zh(),xE={message({keyword:r,schemaCode:e}){let t=r==="maxLength"?"more":"fewer";return(0,$n.str)`must NOT have ${t} than ${e} characters`},params:({schemaCode:r})=>(0,$n._)`{limit: ${r}}`},PE={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:xE,code(r){let{keyword:e,data:t,schemaCode:n,it:i}=r,s=e==="maxLength"?$n.operators.GT:$n.operators.LT,o=i.opts.unicode===!1?(0,$n._)`${t}.length`:(0,$n._)`${(0,AE.useFunc)(r.gen,kE.default)}(${t})`;r.fail$data((0,$n._)`${o} ${s} ${n}`)}};Gl.default=PE});var tm=E(Jl=>{"use strict";Object.defineProperty(Jl,"__esModule",{value:!0});var IE=$t(),OE=Q(),Qn=H(),RE={message:({schemaCode:r})=>(0,Qn.str)`must match pattern "${r}"`,params:({schemaCode:r})=>(0,Qn._)`{pattern: ${r}}`},TE={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:RE,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,Qn._)`new RegExp`:(0,OE.useFunc)(e,c),d=e.let("valid");e.try(()=>e.assign(d,(0,Qn._)`${l}(${s}, ${a}).test(${t})`),()=>e.assign(d,!1)),r.fail$data((0,Qn._)`!${d}`)}else{let c=(0,IE.usePattern)(r,i);r.fail$data((0,Qn._)`!${c}.test(${t})`)}}};Jl.default=TE});var rm=E(Yl=>{"use strict";Object.defineProperty(Yl,"__esModule",{value:!0});var ls=H(),CE={message({keyword:r,schemaCode:e}){let t=r==="maxProperties"?"more":"fewer";return(0,ls.str)`must NOT have ${t} than ${e} properties`},params:({schemaCode:r})=>(0,ls._)`{limit: ${r}}`},ME={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:CE,code(r){let{keyword:e,data:t,schemaCode:n}=r,i=e==="maxProperties"?ls.operators.GT:ls.operators.LT;r.fail$data((0,ls._)`Object.keys(${t}).length ${i} ${n}`)}};Yl.default=ME});var nm=E(Xl=>{"use strict";Object.defineProperty(Xl,"__esModule",{value:!0});var ds=$t(),us=H(),NE=Q(),LE={message:({params:{missingProperty:r}})=>(0,us.str)`must have required property '${r}'`,params:({params:{missingProperty:r}})=>(0,us._)`{missingProperty: ${r}}`},jE={keyword:"required",type:"object",schemaType:"array",$data:!0,error:LE,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():d(),a.strictRequired){let p=r.parentSchema.properties,{definedProperties:y}=r.it;for(let h of t)if((p==null?void 0:p[h])===void 0&&!y.has(h)){let m=o.schemaEnv.baseId+o.errSchemaPath,g=`required property "${h}" is not defined at "${m}" (strictRequired)`;(0,NE.checkStrictMode)(o,g,o.opts.strictRequired)}}function l(){if(c||s)r.block$data(us.nil,u);else for(let p of t)(0,ds.checkReportMissingProp)(r,p)}function d(){let p=e.let("missing");if(c||s){let y=e.let("valid",!0);r.block$data(y,()=>f(p,y)),r.ok(y)}else e.if((0,ds.checkMissingProp)(r,t,p)),(0,ds.reportMissingProp)(r,p),e.else()}function u(){e.forOf("prop",n,p=>{r.setParams({missingProperty:p}),e.if((0,ds.noPropertyInData)(e,i,p,a.ownProperties),()=>r.error())})}function f(p,y){r.setParams({missingProperty:p}),e.forOf(p,n,()=>{e.assign(y,(0,ds.propertyInData)(e,i,p,a.ownProperties)),e.if((0,us.not)(y),()=>{r.error(),e.break()})},us.nil)}}};Xl.default=jE});var im=E(Ql=>{"use strict";Object.defineProperty(Ql,"__esModule",{value:!0});var fs=H(),DE={message({keyword:r,schemaCode:e}){let t=r==="maxItems"?"more":"fewer";return(0,fs.str)`must NOT have ${t} than ${e} items`},params:({schemaCode:r})=>(0,fs._)`{limit: ${r}}`},qE={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:DE,code(r){let{keyword:e,data:t,schemaCode:n}=r,i=e==="maxItems"?fs.operators.GT:fs.operators.LT;r.fail$data((0,fs._)`${t}.length ${i} ${n}`)}};Ql.default=qE});var Bo=E(Zl=>{"use strict";Object.defineProperty(Zl,"__esModule",{value:!0});var sm=wl();sm.code='require("ajv/dist/runtime/equal").default';Zl.default=sm});var om=E(td=>{"use strict";Object.defineProperty(td,"__esModule",{value:!0});var ed=Qi(),je=H(),FE=Q(),VE=Bo(),UE={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}}`},BE={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:UE,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,ed.getSchemaTypes)(s.items):[];r.block$data(c,d,(0,je._)`${o} === false`),r.ok(c);function d(){let y=e.let("i",(0,je._)`${t}.length`),h=e.let("j");r.setParams({i:y,j:h}),e.assign(c,!0),e.if((0,je._)`${y} > 1`,()=>(u()?f:p)(y,h))}function u(){return l.length>0&&!l.some(y=>y==="object"||y==="array")}function f(y,h){let m=e.name("item"),g=(0,ed.checkDataTypes)(l,m,a.opts.strictNumbers,ed.DataType.Wrong),_=e.const("indices",(0,je._)`{}`);e.for((0,je._)`;${y}--;`,()=>{e.let(m,(0,je._)`${t}[${y}]`),e.if(g,(0,je._)`continue`),l.length>1&&e.if((0,je._)`typeof ${m} == "string"`,(0,je._)`${m} += "_"`),e.if((0,je._)`typeof ${_}[${m}] == "number"`,()=>{e.assign(h,(0,je._)`${_}[${m}]`),r.error(),e.assign(c,!1).break()}).code((0,je._)`${_}[${m}] = ${y}`)})}function p(y,h){let m=(0,FE.useFunc)(e,VE.default),g=e.name("outer");e.label(g).for((0,je._)`;${y}--;`,()=>e.for((0,je._)`${h} = ${y}; ${h}--;`,()=>e.if((0,je._)`${m}(${t}[${y}], ${t}[${h}])`,()=>{r.error(),e.assign(c,!1).break(g)})))}}};td.default=BE});var am=E(nd=>{"use strict";Object.defineProperty(nd,"__esModule",{value:!0});var rd=H(),zE=Q(),HE=Bo(),KE={message:"must be equal to constant",params:({schemaCode:r})=>(0,rd._)`{allowedValue: ${r}}`},WE={keyword:"const",$data:!0,error:KE,code(r){let{gen:e,data:t,$data:n,schemaCode:i,schema:s}=r;n||s&&typeof s=="object"?r.fail$data((0,rd._)`!${(0,zE.useFunc)(e,HE.default)}(${t}, ${i})`):r.fail((0,rd._)`${s} !== ${t}`)}};nd.default=WE});var cm=E(id=>{"use strict";Object.defineProperty(id,"__esModule",{value:!0});var ps=H(),GE=Q(),JE=Bo(),YE={message:"must be equal to one of the allowed values",params:({schemaCode:r})=>(0,ps._)`{allowedValues: ${r}}`},XE={keyword:"enum",schemaType:"array",$data:!0,error:YE,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!=null?c:c=(0,GE.useFunc)(e,JE.default),d;if(a||n)d=e.let("valid"),r.block$data(d,u);else{if(!Array.isArray(i))throw new Error("ajv implementation error");let p=e.const("vSchema",s);d=(0,ps.or)(...i.map((y,h)=>f(p,h)))}r.pass(d);function u(){e.assign(d,!1),e.forOf("v",s,p=>e.if((0,ps._)`${l()}(${t}, ${p})`,()=>e.assign(d,!0).break()))}function f(p,y){let h=i[y];return typeof h=="object"&&h!==null?(0,ps._)`${l()}(${t}, ${p}[${y}])`:(0,ps._)`${t} === ${h}`}}};id.default=XE});var od=E(sd=>{"use strict";Object.defineProperty(sd,"__esModule",{value:!0});var QE=Yh(),ZE=Xh(),eA=em(),tA=tm(),rA=rm(),nA=nm(),iA=im(),sA=om(),oA=am(),aA=cm(),cA=[QE.default,ZE.default,eA.default,tA.default,rA.default,nA.default,iA.default,sA.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},oA.default,aA.default];sd.default=cA});var cd=E(hs=>{"use strict";Object.defineProperty(hs,"__esModule",{value:!0});hs.validateAdditionalItems=void 0;var Sn=H(),ad=Q(),lA={message:({params:{len:r}})=>(0,Sn.str)`must NOT have more than ${r} items`,params:({params:{len:r}})=>(0,Sn._)`{limit: ${r}}`},dA={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:lA,code(r){let{parentSchema:e,it:t}=r,{items:n}=e;if(!Array.isArray(n)){(0,ad.checkStrictMode)(t,'"additionalItems" is ignored when "items" is not an array of schemas');return}lm(r,n)}};function lm(r,e){let{gen:t,schema:n,data:i,keyword:s,it:o}=r;o.items=!0;let a=t.const("len",(0,Sn._)`${i}.length`);if(n===!1)r.setParams({len:e.length}),r.pass((0,Sn._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,ad.alwaysValidSchema)(o,n)){let l=t.var("valid",(0,Sn._)`${a} <= ${e.length}`);t.if((0,Sn.not)(l),()=>c(l)),r.ok(l)}function c(l){t.forRange("i",e.length,a,d=>{r.subschema({keyword:s,dataProp:d,dataPropType:ad.Type.Num},l),o.allErrors||t.if((0,Sn.not)(l),()=>t.break())})}}hs.validateAdditionalItems=lm;hs.default=dA});var ld=E(ms=>{"use strict";Object.defineProperty(ms,"__esModule",{value:!0});ms.validateTuple=void 0;var dm=H(),zo=Q(),uA=$t(),fA={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(r){let{schema:e,it:t}=r;if(Array.isArray(e))return um(r,"additionalItems",e);t.items=!0,!(0,zo.alwaysValidSchema)(t,e)&&r.ok((0,uA.validateArray)(r))}};function um(r,e,t=r.schema){let{gen:n,parentSchema:i,data:s,keyword:o,it:a}=r;d(i),a.opts.unevaluated&&t.length&&a.items!==!0&&(a.items=zo.mergeEvaluated.items(n,t.length,a.items));let c=n.name("valid"),l=n.const("len",(0,dm._)`${s}.length`);t.forEach((u,f)=>{(0,zo.alwaysValidSchema)(a,u)||(n.if((0,dm._)`${l} > ${f}`,()=>r.subschema({keyword:o,schemaProp:f,dataProp:f},c)),r.ok(c))});function d(u){let{opts:f,errSchemaPath:p}=a,y=t.length,h=y===u.minItems&&(y===u.maxItems||u[e]===!1);if(f.strictTuples&&!h){let m=`"${o}" is ${y}-tuple, but minItems or maxItems/${e} are not specified or different at path "${p}"`;(0,zo.checkStrictMode)(a,m,f.strictTuples)}}}ms.validateTuple=um;ms.default=fA});var fm=E(dd=>{"use strict";Object.defineProperty(dd,"__esModule",{value:!0});var pA=ld(),hA={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:r=>(0,pA.validateTuple)(r,"items")};dd.default=hA});var hm=E(ud=>{"use strict";Object.defineProperty(ud,"__esModule",{value:!0});var pm=H(),mA=Q(),yA=$t(),gA=cd(),_A={message:({params:{len:r}})=>(0,pm.str)`must NOT have more than ${r} items`,params:({params:{len:r}})=>(0,pm._)`{limit: ${r}}`},bA={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:_A,code(r){let{schema:e,parentSchema:t,it:n}=r,{prefixItems:i}=t;n.items=!0,!(0,mA.alwaysValidSchema)(n,e)&&(i?(0,gA.validateAdditionalItems)(r,i):r.ok((0,yA.validateArray)(r)))}};ud.default=bA});var mm=E(fd=>{"use strict";Object.defineProperty(fd,"__esModule",{value:!0});var Et=H(),Ho=Q(),wA={message:({params:{min:r,max:e}})=>e===void 0?(0,Et.str)`must contain at least ${r} valid item(s)`:(0,Et.str)`must contain at least ${r} and no more than ${e} valid item(s)`,params:({params:{min:r,max:e}})=>e===void 0?(0,Et._)`{minContains: ${r}}`:(0,Et._)`{minContains: ${r}, maxContains: ${e}}`},vA={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:wA,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 d=e.const("len",(0,Et._)`${i}.length`);if(r.setParams({min:o,max:a}),a===void 0&&o===0){(0,Ho.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&o>a){(0,Ho.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),r.fail();return}if((0,Ho.alwaysValidSchema)(s,t)){let h=(0,Et._)`${d} >= ${o}`;a!==void 0&&(h=(0,Et._)`${h} && ${d} <= ${a}`),r.pass(h);return}s.items=!0;let u=e.name("valid");a===void 0&&o===1?p(u,()=>e.if(u,()=>e.break())):o===0?(e.let(u,!0),a!==void 0&&e.if((0,Et._)`${i}.length > 0`,f)):(e.let(u,!1),f()),r.result(u,()=>r.reset());function f(){let h=e.name("_valid"),m=e.let("count",0);p(h,()=>e.if(h,()=>y(m)))}function p(h,m){e.forRange("i",0,d,g=>{r.subschema({keyword:"contains",dataProp:g,dataPropType:Ho.Type.Num,compositeRule:!0},h),m()})}function y(h){e.code((0,Et._)`${h}++`),a===void 0?e.if((0,Et._)`${h} >= ${o}`,()=>e.assign(u,!0).break()):(e.if((0,Et._)`${h} > ${a}`,()=>e.assign(u,!1).break()),o===1?e.assign(u,!0):e.if((0,Et._)`${h} >= ${o}`,()=>e.assign(u,!0)))}}};fd.default=vA});var Ko=E(er=>{"use strict";Object.defineProperty(er,"__esModule",{value:!0});er.validateSchemaDeps=er.validatePropertyDeps=er.error=void 0;var pd=H(),$A=Q(),ys=$t();er.error={message:({params:{property:r,depsCount:e,deps:t}})=>{let n=e===1?"property":"properties";return(0,pd.str)`must have ${n} ${t} when property ${r} is present`},params:({params:{property:r,depsCount:e,deps:t,missingProperty:n}})=>(0,pd._)`{property: ${r}, missingProperty: ${n}, depsCount: ${e}, - deps: ${t}}`};var SA={keyword:"dependencies",type:"object",schemaType:"object",error:er.error,code(r){let[e,t]=EA(r);ym(r,e),gm(r,t)}};function EA({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 ym(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,ys.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,ys.checkReportMissingProp)(r,l)}):(t.if((0,pd._)`${c} && (${(0,ys.checkMissingProp)(r,a,s)})`),(0,ys.reportMissingProp)(r,s),t.else())}}er.validatePropertyDeps=ym;function gm(r,e=r.schema){let{gen:t,data:n,keyword:i,it:s}=r,o=t.name("valid");for(let a in e)(0,$A.alwaysValidSchema)(s,e[a])||(t.if((0,ys.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))}er.validateSchemaDeps=gm;er.default=SA});var bm=A(hd=>{"use strict";Object.defineProperty(hd,"__esModule",{value:!0});var _m=H(),AA=Q(),kA={message:"property name must be valid",params:({params:r})=>(0,_m._)`{propertyName: ${r.propertyName}}`},xA={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:kA,code(r){let{gen:e,schema:t,data:n,it:i}=r;if((0,AA.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,_m.not)(s),()=>{r.error(!0),i.allErrors||e.break()})}),r.ok(s)}};hd.default=xA});var yd=A(md=>{"use strict";Object.defineProperty(md,"__esModule",{value:!0});var Wo=$t(),Mt=H(),PA=vt(),Go=Q(),IA={message:"must NOT have additional properties",params:({params:r})=>(0,Mt._)`{additionalProperty: ${r.additionalProperty}}`},OA={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:IA,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,Go.alwaysValidSchema)(o,t))return;let l=(0,Wo.allSchemaProperties)(n.properties),d=(0,Wo.allSchemaProperties)(n.patternProperties);u(),r.ok((0,Mt._)`${s} === ${PA.default.errors}`);function u(){e.forIn("key",i,m=>{!l.length&&!d.length?y(m):e.if(f(m),()=>y(m))})}function f(m){let g;if(l.length>8){let _=(0,Go.schemaRefOrVal)(o,n.properties,"properties");g=(0,Wo.isOwnProperty)(e,_,m)}else l.length?g=(0,Mt.or)(...l.map(_=>(0,Mt._)`${m} === ${_}`)):g=Mt.nil;return d.length&&(g=(0,Mt.or)(g,...d.map(_=>(0,Mt._)`${(0,Wo.usePattern)(r,_)}.test(${m})`))),(0,Mt.not)(g)}function p(m){e.code((0,Mt._)`delete ${i}[${m}]`)}function y(m){if(c.removeAdditional==="all"||c.removeAdditional&&t===!1){p(m);return}if(t===!1){r.setParams({additionalProperty:m}),r.error(),a||e.break();return}if(typeof t=="object"&&!(0,Go.alwaysValidSchema)(o,t)){let g=e.name("valid");c.removeAdditional==="failing"?(h(m,g,!1),e.if((0,Mt.not)(g),()=>{r.reset(),p(m)})):(h(m,g),a||e.if((0,Mt.not)(g),()=>e.break()))}}function h(m,g,_){let w={keyword:"additionalProperties",dataProp:m,dataPropType:Go.Type.Str};_===!1&&Object.assign(w,{compositeRule:!0,createErrors:!1,allErrors:!1}),r.subschema(w,g)}}};md.default=OA});var $m=A(_d=>{"use strict";Object.defineProperty(_d,"__esModule",{value:!0});var RA=Wn(),wm=$t(),gd=Q(),vm=yd(),TA={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&&vm.default.code(new RA.KeywordCxt(s,vm.default,"additionalProperties"));let o=(0,wm.allSchemaProperties)(t);for(let u of o)s.definedProperties.add(u);s.opts.unevaluated&&o.length&&s.props!==!0&&(s.props=gd.mergeEvaluated.props(e,(0,gd.toHash)(o),s.props));let a=o.filter(u=>!(0,gd.alwaysValidSchema)(s,t[u]));if(a.length===0)return;let c=e.name("valid");for(let u of a)l(u)?d(u):(e.if((0,wm.propertyInData)(e,i,u,s.opts.ownProperties)),d(u),s.allErrors||e.else().var(c,!0),e.endIf()),r.it.definedProperties.add(u),r.ok(c);function l(u){return s.opts.useDefaults&&!s.compositeRule&&t[u].default!==void 0}function d(u){r.subschema({keyword:"properties",schemaProp:u,dataProp:u},c)}}};_d.default=TA});var km=A(bd=>{"use strict";Object.defineProperty(bd,"__esModule",{value:!0});var Sm=$t(),Jo=H(),Em=Q(),Am=Q(),CA={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,Sm.allSchemaProperties)(t),c=a.filter(h=>(0,Em.alwaysValidSchema)(s,t[h]));if(a.length===0||c.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let l=o.strictSchema&&!o.allowMatchingProperties&&i.properties,d=e.name("valid");s.props!==!0&&!(s.props instanceof Jo.Name)&&(s.props=(0,Am.evaluatedPropsToName)(e,s.props));let{props:u}=s;f();function f(){for(let h of a)l&&p(h),s.allErrors?y(h):(e.var(d,!0),y(h),e.if(d))}function p(h){for(let m in l)new RegExp(h).test(m)&&(0,Em.checkStrictMode)(s,`property ${m} matches pattern ${h} (use allowMatchingProperties)`)}function y(h){e.forIn("key",n,m=>{e.if((0,Jo._)`${(0,Sm.usePattern)(r,h)}.test(${m})`,()=>{let g=c.includes(h);g||r.subschema({keyword:"patternProperties",schemaProp:h,dataProp:m,dataPropType:Am.Type.Str},d),s.opts.unevaluated&&u!==!0?e.assign((0,Jo._)`${u}[${m}]`,!0):!g&&!s.allErrors&&e.if((0,Jo.not)(d),()=>e.break())})})}}};bd.default=CA});var xm=A(wd=>{"use strict";Object.defineProperty(wd,"__esModule",{value:!0});var MA=Q(),NA={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(r){let{gen:e,schema:t,it:n}=r;if((0,MA.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"}};wd.default=NA});var Pm=A(vd=>{"use strict";Object.defineProperty(vd,"__esModule",{value:!0});var LA=$t(),jA={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:LA.validateUnion,error:{message:"must match a schema in anyOf"}};vd.default=jA});var Im=A($d=>{"use strict";Object.defineProperty($d,"__esModule",{value:!0});var Yo=H(),DA=Q(),qA={message:"must match exactly one schema in oneOf",params:({params:r})=>(0,Yo._)`{passingSchemas: ${r.passing}}`},FA={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:qA,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((d,u)=>{let f;(0,DA.alwaysValidSchema)(i,d)?e.var(c,!0):f=r.subschema({keyword:"oneOf",schemaProp:u,compositeRule:!0},c),u>0&&e.if((0,Yo._)`${c} && ${o}`).assign(o,!1).assign(a,(0,Yo._)`[${a}, ${u}]`).else(),e.if(c,()=>{e.assign(o,!0),e.assign(a,u),f&&r.mergeEvaluated(f,Yo.Name)})})}}};$d.default=FA});var Om=A(Sd=>{"use strict";Object.defineProperty(Sd,"__esModule",{value:!0});var VA=Q(),UA={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,VA.alwaysValidSchema)(n,s))return;let a=r.subschema({keyword:"allOf",schemaProp:o},i);r.ok(i),r.mergeEvaluated(a)})}};Sd.default=UA});var Cm=A(Ed=>{"use strict";Object.defineProperty(Ed,"__esModule",{value:!0});var Xo=H(),Tm=Q(),BA={message:({params:r})=>(0,Xo.str)`must match "${r.ifClause}" schema`,params:({params:r})=>(0,Xo._)`{failingKeyword: ${r.ifClause}}`},zA={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:BA,code(r){let{gen:e,parentSchema:t,it:n}=r;t.then===void 0&&t.else===void 0&&(0,Tm.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let i=Rm(n,"then"),s=Rm(n,"else");if(!i&&!s)return;let o=e.let("valid",!0),a=e.name("_valid");if(c(),r.reset(),i&&s){let d=e.let("ifClause");r.setParams({ifClause:d}),e.if(a,l("then",d),l("else",d))}else i?e.if(a,l("then")):e.if((0,Xo.not)(a),l("else"));r.pass(o,()=>r.error(!0));function c(){let d=r.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);r.mergeEvaluated(d)}function l(d,u){return()=>{let f=r.subschema({keyword:d},a);e.assign(o,a),r.mergeValidEvaluated(f,o),u?e.assign(u,(0,Xo._)`${d}`):r.setParams({ifClause:d})}}}};function Rm(r,e){let t=r.schema[e];return t!==void 0&&!(0,Tm.alwaysValidSchema)(r,t)}Ed.default=zA});var Mm=A(Ad=>{"use strict";Object.defineProperty(Ad,"__esModule",{value:!0});var HA=Q(),KA={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:r,parentSchema:e,it:t}){e.if===void 0&&(0,HA.checkStrictMode)(t,`"${r}" without "if" is ignored`)}};Ad.default=KA});var xd=A(kd=>{"use strict";Object.defineProperty(kd,"__esModule",{value:!0});var WA=cd(),GA=fm(),JA=ld(),YA=hm(),XA=mm(),QA=Ko(),ZA=bm(),e1=yd(),t1=$m(),r1=km(),n1=xm(),i1=Pm(),s1=Im(),o1=Om(),a1=Cm(),c1=Mm();function l1(r=!1){let e=[n1.default,i1.default,s1.default,o1.default,a1.default,c1.default,ZA.default,e1.default,QA.default,t1.default,r1.default];return r?e.push(GA.default,YA.default):e.push(WA.default,JA.default),e.push(XA.default),e}kd.default=l1});var Id=A(gs=>{"use strict";Object.defineProperty(gs,"__esModule",{value:!0});gs.dynamicAnchor=void 0;var Pd=H(),d1=vt(),Nm=ns(),u1=Fo(),f1={keyword:"$dynamicAnchor",schemaType:"string",code:r=>Lm(r,r.schema)};function Lm(r,e){let{gen:t,it:n}=r;n.schemaEnv.root.dynamicAnchors[e]=!0;let i=(0,Pd._)`${d1.default.dynamicAnchors}${(0,Pd.getProperty)(e)}`,s=n.errSchemaPath==="#"?n.validateName:p1(r);t.if((0,Pd._)`!${i}`,()=>t.assign(i,s))}gs.dynamicAnchor=Lm;function p1(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 Nm.SchemaEnv({schema:t,schemaId:c,root:i,baseId:s,localRefs:o,meta:a});return Nm.compileSchema.call(n,l),(0,u1.getValidate)(r,l)}gs.default=f1});var Od=A(_s=>{"use strict";Object.defineProperty(_s,"__esModule",{value:!0});_s.dynamicRef=void 0;var jm=H(),h1=vt(),Dm=Fo(),m1={keyword:"$dynamicRef",schemaType:"string",code:r=>qm(r,r.schema)};function qm(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,jm._)`${h1.default.dynamicAnchors}${(0,jm.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,Dm.callRef)(r,c),t.let(l,!0)}):()=>(0,Dm.callRef)(r,c)}}_s.dynamicRef=qm;_s.default=m1});var Fm=A(Rd=>{"use strict";Object.defineProperty(Rd,"__esModule",{value:!0});var y1=Id(),g1=Q(),_1={keyword:"$recursiveAnchor",schemaType:"boolean",code(r){r.schema?(0,y1.dynamicAnchor)(r,""):(0,g1.checkStrictMode)(r.it,"$recursiveAnchor: false is ignored")}};Rd.default=_1});var Vm=A(Td=>{"use strict";Object.defineProperty(Td,"__esModule",{value:!0});var b1=Od(),w1={keyword:"$recursiveRef",schemaType:"string",code:r=>(0,b1.dynamicRef)(r,r.schema)};Td.default=w1});var Um=A(Cd=>{"use strict";Object.defineProperty(Cd,"__esModule",{value:!0});var v1=Id(),$1=Od(),S1=Fm(),E1=Vm(),A1=[v1.default,$1.default,S1.default,E1.default];Cd.default=A1});var zm=A(Md=>{"use strict";Object.defineProperty(Md,"__esModule",{value:!0});var Bm=Ko(),k1={keyword:"dependentRequired",type:"object",schemaType:"object",error:Bm.error,code:r=>(0,Bm.validatePropertyDeps)(r)};Md.default=k1});var Hm=A(Nd=>{"use strict";Object.defineProperty(Nd,"__esModule",{value:!0});var x1=Ko(),P1={keyword:"dependentSchemas",type:"object",schemaType:"object",code:r=>(0,x1.validateSchemaDeps)(r)};Nd.default=P1});var Km=A(Ld=>{"use strict";Object.defineProperty(Ld,"__esModule",{value:!0});var I1=Q(),O1={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword:r,parentSchema:e,it:t}){e.contains===void 0&&(0,I1.checkStrictMode)(t,`"${r}" without "contains" is ignored`)}};Ld.default=O1});var Wm=A(jd=>{"use strict";Object.defineProperty(jd,"__esModule",{value:!0});var R1=zm(),T1=Hm(),C1=Km(),M1=[R1.default,T1.default,C1.default];jd.default=M1});var Jm=A(Dd=>{"use strict";Object.defineProperty(Dd,"__esModule",{value:!0});var Wr=H(),Gm=Q(),N1=vt(),L1={message:"must NOT have unevaluated properties",params:({params:r})=>(0,Wr._)`{unevaluatedProperty: ${r.unevaluatedProperty}}`},j1={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 Wr.Name?e.if((0,Wr._)`${a} !== true`,()=>e.forIn("key",n,u=>e.if(l(a,u),()=>c(u)))):a!==!0&&e.forIn("key",n,u=>a===void 0?c(u):e.if(d(a,u),()=>c(u))),s.props=!0,r.ok((0,Wr._)`${i} === ${N1.default.errors}`);function c(u){if(t===!1){r.setParams({unevaluatedProperty:u}),r.error(),o||e.break();return}if(!(0,Gm.alwaysValidSchema)(s,t)){let f=e.name("valid");r.subschema({keyword:"unevaluatedProperties",dataProp:u,dataPropType:Gm.Type.Str},f),o||e.if((0,Wr.not)(f),()=>e.break())}}function l(u,f){return(0,Wr._)`!${u} || !${u}[${f}]`}function d(u,f){let p=[];for(let y in u)u[y]===!0&&p.push((0,Wr._)`${f} !== ${y}`);return(0,Wr.and)(...p)}}};Dd.default=j1});var Xm=A(qd=>{"use strict";Object.defineProperty(qd,"__esModule",{value:!0});var En=H(),Ym=Q(),D1={message:({params:{len:r}})=>(0,En.str)`must NOT have more than ${r} items`,params:({params:{len:r}})=>(0,En._)`{limit: ${r}}`},q1={keyword:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error:D1,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,En._)`${n}.length`);if(t===!1)r.setParams({len:s}),r.fail((0,En._)`${o} > ${s}`);else if(typeof t=="object"&&!(0,Ym.alwaysValidSchema)(i,t)){let c=e.var("valid",(0,En._)`${o} <= ${s}`);e.if((0,En.not)(c),()=>a(c,s)),r.ok(c)}i.items=!0;function a(c,l){e.forRange("i",l,o,d=>{r.subschema({keyword:"unevaluatedItems",dataProp:d,dataPropType:Ym.Type.Num},c),i.allErrors||e.if((0,En.not)(c),()=>e.break())})}}};qd.default=q1});var Qm=A(Fd=>{"use strict";Object.defineProperty(Fd,"__esModule",{value:!0});var F1=Jm(),V1=Xm(),U1=[F1.default,V1.default];Fd.default=U1});var Zm=A(Vd=>{"use strict";Object.defineProperty(Vd,"__esModule",{value:!0});var Ae=H(),B1={message:({schemaCode:r})=>(0,Ae.str)`must match format "${r}"`,params:({schemaCode:r})=>(0,Ae._)`{format: ${r}}`},z1={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:B1,code(r,e){let{gen:t,data:n,$data:i,schema:s,schemaCode:o,it:a}=r,{opts:c,errSchemaPath:l,schemaEnv:d,self:u}=a;if(!c.validateFormats)return;i?f():p();function f(){let y=t.scopeValue("formats",{ref:u.formats,code:c.code.formats}),h=t.const("fDef",(0,Ae._)`${y}[${o}]`),m=t.let("fType"),g=t.let("format");t.if((0,Ae._)`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>t.assign(m,(0,Ae._)`${h}.type || "string"`).assign(g,(0,Ae._)`${h}.validate`),()=>t.assign(m,(0,Ae._)`"string"`).assign(g,h)),r.fail$data((0,Ae.or)(_(),w()));function _(){return c.strictSchema===!1?Ae.nil:(0,Ae._)`${o} && !${g}`}function w(){let x=d.$async?(0,Ae._)`(${h}.async ? await ${g}(${n}) : ${g}(${n}))`:(0,Ae._)`${g}(${n})`,v=(0,Ae._)`(typeof ${g} == "function" ? ${x} : ${g}.test(${n}))`;return(0,Ae._)`${g} && ${g} !== true && ${m} === ${e} && !${v}`}}function p(){let y=u.formats[s];if(!y){_();return}if(y===!0)return;let[h,m,g]=w(y);h===e&&r.pass(x());function _(){if(c.strictSchema===!1){u.logger.warn(v());return}throw new Error(v());function v(){return`unknown format "${s}" ignored in schema at path "${l}"`}}function w(v){let P=v instanceof RegExp?(0,Ae.regexpCode)(v):c.code.formats?(0,Ae._)`${c.code.formats}${(0,Ae.getProperty)(s)}`:void 0,O=t.scopeValue("formats",{key:s,ref:v,code:P});return typeof v=="object"&&!(v instanceof RegExp)?[v.type||"string",v.validate,(0,Ae._)`${O}.validate`]:["string",v,O]}function x(){if(typeof y=="object"&&!(y instanceof RegExp)&&y.async){if(!d.$async)throw new Error("async format in sync schema");return(0,Ae._)`await ${g}(${n})`}return typeof m=="function"?(0,Ae._)`${g}(${n})`:(0,Ae._)`${g}.test(${n})`}}}};Vd.default=z1});var Bd=A(Ud=>{"use strict";Object.defineProperty(Ud,"__esModule",{value:!0});var H1=Zm(),K1=[H1.default];Ud.default=K1});var zd=A(Zn=>{"use strict";Object.defineProperty(Zn,"__esModule",{value:!0});Zn.contentVocabulary=Zn.metadataVocabulary=void 0;Zn.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Zn.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var ty=A(Hd=>{"use strict";Object.defineProperty(Hd,"__esModule",{value:!0});var W1=zl(),G1=od(),J1=xd(),Y1=Um(),X1=Wm(),Q1=Qm(),Z1=Bd(),ey=zd(),ek=[Y1.default,W1.default,G1.default,(0,J1.default)(!0),Z1.default,ey.metadataVocabulary,ey.contentVocabulary,X1.default,Q1.default];Hd.default=ek});var ny=A(Qo=>{"use strict";Object.defineProperty(Qo,"__esModule",{value:!0});Qo.DiscrError=void 0;var ry;(function(r){r.Tag="tag",r.Mapping="mapping"})(ry||(Qo.DiscrError=ry={}))});var Gd=A(Wd=>{"use strict";Object.defineProperty(Wd,"__esModule",{value:!0});var ei=H(),Kd=ny(),iy=ns(),tk=Gn(),rk=Q(),nk={message:({params:{discrError:r,tagName:e}})=>r===Kd.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:r,tag:e,tagName:t}})=>(0,ei._)`{error: ${r}, tag: ${t}, tagValue: ${e}}`},ik={keyword:"discriminator",type:"object",schemaType:"object",error:nk,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,ei._)`${t}${(0,ei.getProperty)(a)}`);e.if((0,ei._)`typeof ${l} == "string"`,()=>d(),()=>r.error(!1,{discrError:Kd.DiscrError.Tag,tag:l,tagName:a})),r.ok(c);function d(){let p=f();e.if(!1);for(let y in p)e.elseIf((0,ei._)`${l} === ${y}`),e.assign(c,u(p[y]));e.else(),r.error(!1,{discrError:Kd.DiscrError.Mapping,tag:l,tagName:a}),e.endIf()}function u(p){let y=e.name("valid"),h=r.subschema({keyword:"oneOf",schemaProp:p},y);return r.mergeEvaluated(h,ei.Name),y}function f(){var p;let y={},h=g(i),m=!0;for(let x=0;x{sk.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 oy=A((t2,ok)=>{ok.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 ay=A((r2,ak)=>{ak.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 cy=A((n2,ck)=>{ck.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 ly=A((i2,lk)=>{lk.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 dy=A((s2,dk)=>{dk.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 uy=A((o2,uk)=>{uk.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 fy=A((a2,fk)=>{fk.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 py=A(Jd=>{"use strict";Object.defineProperty(Jd,"__esModule",{value:!0});var pk=sy(),hk=oy(),mk=ay(),yk=cy(),gk=ly(),_k=dy(),bk=uy(),wk=fy(),vk=["/properties"];function $k(r){return[pk,hk,mk,yk,gk,e(this,_k),bk,e(this,wk)].forEach(t=>this.addMetaSchema(t,void 0,!1)),this;function e(t,n){return r?t.$dataMetaSchema(n,vk):n}}Jd.default=$k});var Qd=A((_e,Xd)=>{"use strict";Object.defineProperty(_e,"__esModule",{value:!0});_e.MissingRefError=_e.ValidationError=_e.CodeGen=_e.Name=_e.nil=_e.stringify=_e.str=_e._=_e.KeywordCxt=_e.Ajv2020=void 0;var Sk=Vl(),Ek=ty(),Ak=Gd(),kk=py(),Yd="https://json-schema.org/draft/2020-12/schema",ti=class extends Sk.default{constructor(e={}){super({...e,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){super._addVocabularies(),Ek.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(Ak.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data:e,meta:t}=this.opts;t&&(kk.default.call(this,e),this.refs["http://json-schema.org/schema"]=Yd)}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Yd)?Yd:void 0)}};_e.Ajv2020=ti;Xd.exports=_e=ti;Xd.exports.Ajv2020=ti;Object.defineProperty(_e,"__esModule",{value:!0});_e.default=ti;var xk=Wn();Object.defineProperty(_e,"KeywordCxt",{enumerable:!0,get:function(){return xk.KeywordCxt}});var ri=H();Object.defineProperty(_e,"_",{enumerable:!0,get:function(){return ri._}});Object.defineProperty(_e,"str",{enumerable:!0,get:function(){return ri.str}});Object.defineProperty(_e,"stringify",{enumerable:!0,get:function(){return ri.stringify}});Object.defineProperty(_e,"nil",{enumerable:!0,get:function(){return ri.nil}});Object.defineProperty(_e,"Name",{enumerable:!0,get:function(){return ri.Name}});Object.defineProperty(_e,"CodeGen",{enumerable:!0,get:function(){return ri.CodeGen}});var Pk=rs();Object.defineProperty(_e,"ValidationError",{enumerable:!0,get:function(){return Pk.default}});var Ik=Gn();Object.defineProperty(_e,"MissingRefError",{enumerable:!0,get:function(){return Ik.default}})});var vy=A(rr=>{"use strict";Object.defineProperty(rr,"__esModule",{value:!0});rr.formatNames=rr.fastFormats=rr.fullFormats=void 0;function tr(r,e){return{validate:r,compare:e}}rr.fullFormats={date:tr(gy,ru),time:tr(eu(!0),nu),"date-time":tr(hy(!0),by),"iso-time":tr(eu(),_y),"iso-date-time":tr(hy(),wy),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:Nk,"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:Uk,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:Lk,int32:{type:"number",validate:qk},int64:{type:"number",validate:Fk},float:{type:"number",validate:yy},double:{type:"number",validate:yy},password:!0,binary:!0};rr.fastFormats={...rr.fullFormats,date:tr(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,ru),time:tr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,nu),"date-time":tr(/^\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,by),"iso-time":tr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,_y),"iso-date-time":tr(/^\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,wy),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};rr.formatNames=Object.keys(rr.fullFormats);function Ok(r){return r%4===0&&(r%100!==0||r%400===0)}var Rk=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,Tk=[0,31,28,31,30,31,30,31,31,30,31,30,31];function gy(r){let e=Rk.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&&Ok(t)?29:Tk[n])}function ru(r,e){if(r&&e)return r>e?1:r23||d>59||r&&!a)return!1;if(i<=23&&s<=59&&o<60)return!0;let u=s-d*c,f=i-l*c-(u<0?1:0);return(f===23||f===-1)&&(u===59||u===-1)&&o<61}}function nu(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 _y(r,e){if(!(r&&e))return;let t=Zd.exec(r),n=Zd.exec(e);if(t&&n)return r=t[1]+t[2]+t[3],e=n[1]+n[2]+n[3],r>e?1:r=jk}function Fk(r){return Number.isInteger(r)}function yy(){return!0}var Vk=/[^\\]\\Z/;function Uk(r){if(Vk.test(r))return!1;try{return new RegExp(r),!0}catch(e){return!1}}});var Sy=A(iu=>{"use strict";Object.defineProperty(iu,"__esModule",{value:!0});var Bk=zl(),zk=od(),Hk=xd(),Kk=Bd(),$y=zd(),Wk=[Bk.default,zk.default,(0,Hk.default)(),Kk.default,$y.metadataVocabulary,$y.contentVocabulary];iu.default=Wk});var Ey=A((u2,Gk)=>{Gk.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 ky=A((be,su)=>{"use strict";Object.defineProperty(be,"__esModule",{value:!0});be.MissingRefError=be.ValidationError=be.CodeGen=be.Name=be.nil=be.stringify=be.str=be._=be.KeywordCxt=be.Ajv=void 0;var Jk=Vl(),Yk=Sy(),Xk=Gd(),Ay=Ey(),Qk=["/properties"],Zo="http://json-schema.org/draft-07/schema",ni=class extends Jk.default{_addVocabularies(){super._addVocabularies(),Yk.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(Xk.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(Ay,Qk):Ay;this.addMetaSchema(e,Zo,!1),this.refs["http://json-schema.org/schema"]=Zo}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Zo)?Zo:void 0)}};be.Ajv=ni;su.exports=be=ni;su.exports.Ajv=ni;Object.defineProperty(be,"__esModule",{value:!0});be.default=ni;var Zk=Wn();Object.defineProperty(be,"KeywordCxt",{enumerable:!0,get:function(){return Zk.KeywordCxt}});var ii=H();Object.defineProperty(be,"_",{enumerable:!0,get:function(){return ii._}});Object.defineProperty(be,"str",{enumerable:!0,get:function(){return ii.str}});Object.defineProperty(be,"stringify",{enumerable:!0,get:function(){return ii.stringify}});Object.defineProperty(be,"nil",{enumerable:!0,get:function(){return ii.nil}});Object.defineProperty(be,"Name",{enumerable:!0,get:function(){return ii.Name}});Object.defineProperty(be,"CodeGen",{enumerable:!0,get:function(){return ii.CodeGen}});var ex=rs();Object.defineProperty(be,"ValidationError",{enumerable:!0,get:function(){return ex.default}});var tx=Gn();Object.defineProperty(be,"MissingRefError",{enumerable:!0,get:function(){return tx.default}})});var xy=A(si=>{"use strict";Object.defineProperty(si,"__esModule",{value:!0});si.formatLimitDefinition=void 0;var rx=ky(),Nt=H(),Gr=Nt.operators,ea={formatMaximum:{okStr:"<=",ok:Gr.LTE,fail:Gr.GT},formatMinimum:{okStr:">=",ok:Gr.GTE,fail:Gr.LT},formatExclusiveMaximum:{okStr:"<",ok:Gr.LT,fail:Gr.GTE},formatExclusiveMinimum:{okStr:">",ok:Gr.GT,fail:Gr.LTE}},nx={message:({keyword:r,schemaCode:e})=>(0,Nt.str)`should be ${ea[r].okStr} ${e}`,params:({keyword:r,schemaCode:e})=>(0,Nt._)`{comparison: ${ea[r].okStr}, limit: ${e}}`};si.formatLimitDefinition={keyword:Object.keys(ea),type:"string",schemaType:"string",$data:!0,error:nx,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 rx.KeywordCxt(s,a.RULES.all.format.definition,"format");c.$data?l():d();function l(){let f=e.scopeValue("formats",{ref:a.formats,code:o.code.formats}),p=e.const("fmt",(0,Nt._)`${f}[${c.schemaCode}]`);r.fail$data((0,Nt.or)((0,Nt._)`typeof ${p} != "object"`,(0,Nt._)`${p} instanceof RegExp`,(0,Nt._)`typeof ${p}.compare != "function"`,u(p)))}function d(){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 y=e.scopeValue("formats",{key:f,ref:p,code:o.code.formats?(0,Nt._)`${o.code.formats}${(0,Nt.getProperty)(f)}`:void 0});r.fail$data(u(y))}function u(f){return(0,Nt._)`${f}.compare(${t}, ${n}) ${ea[i].fail} 0`}},dependencies:["format"]};var ix=r=>(r.addKeyword(si.formatLimitDefinition),r);si.default=ix});var cu=A((bs,Oy)=>{"use strict";Object.defineProperty(bs,"__esModule",{value:!0});var oi=vy(),sx=xy(),ou=H(),Py=new ou.Name("fullFormats"),ox=new ou.Name("fastFormats"),au=(r,e={keywords:!0})=>{if(Array.isArray(e))return Iy(r,e,oi.fullFormats,Py),r;let[t,n]=e.mode==="fast"?[oi.fastFormats,ox]:[oi.fullFormats,Py],i=e.formats||oi.formatNames;return Iy(r,i,t,n),e.keywords&&(0,sx.default)(r),r};au.get=(r,e="full")=>{let n=(e==="fast"?oi.fastFormats:oi.fullFormats)[r];if(!n)throw new Error(`Unknown format "${r}"`);return n};function Iy(r,e,t,n){var i,s;(i=(s=r.opts.code).formats)!==null&&i!==void 0||(s.formats=(0,ou._)`require("ajv-formats/dist/formats").${n}`);for(let o of e)r.addFormat(o,t[o])}Oy.exports=bs=au;Object.defineProperty(bs,"__esModule",{value:!0});bs.default=au});var li=A((b2,jy)=>{"use strict";var lx="2.0.0",dx=Number.MAX_SAFE_INTEGER||9007199254740991,ux=16,fx=250,px=["major","premajor","minor","preminor","patch","prepatch","prerelease"];jy.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:ux,MAX_SAFE_BUILD_LENGTH:fx,MAX_SAFE_INTEGER:dx,RELEASE_TYPES:px,SEMVER_SPEC_VERSION:lx,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var ws=A((w2,Dy)=>{"use strict";var hx=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...r)=>console.error("SEMVER",...r):()=>{};Dy.exports=hx});var di=A((ir,qy)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:fu,MAX_SAFE_BUILD_LENGTH:mx,MAX_LENGTH:yx}=li(),gx=ws();ir=qy.exports={};var _x=ir.re=[],bx=ir.safeRe=[],j=ir.src=[],wx=ir.safeSrc=[],D=ir.t={},vx=0,pu="[a-zA-Z0-9-]",$x=[["\\s",1],["\\d",yx],[pu,mx]],Sx=r=>{for(let[e,t]of $x)r=r.split(`${e}*`).join(`${e}{0,${t}}`).split(`${e}+`).join(`${e}{1,${t}}`);return r},K=(r,e,t)=>{let n=Sx(e),i=vx++;gx(r,i,e),D[r]=i,j[i]=e,wx[i]=n,_x[i]=new RegExp(e,t?"g":void 0),bx[i]=new RegExp(n,t?"g":void 0)};K("NUMERICIDENTIFIER","0|[1-9]\\d*");K("NUMERICIDENTIFIERLOOSE","\\d+");K("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${pu}*`);K("MAINVERSION",`(${j[D.NUMERICIDENTIFIER]})\\.(${j[D.NUMERICIDENTIFIER]})\\.(${j[D.NUMERICIDENTIFIER]})`);K("MAINVERSIONLOOSE",`(${j[D.NUMERICIDENTIFIERLOOSE]})\\.(${j[D.NUMERICIDENTIFIERLOOSE]})\\.(${j[D.NUMERICIDENTIFIERLOOSE]})`);K("PRERELEASEIDENTIFIER",`(?:${j[D.NONNUMERICIDENTIFIER]}|${j[D.NUMERICIDENTIFIER]})`);K("PRERELEASEIDENTIFIERLOOSE",`(?:${j[D.NONNUMERICIDENTIFIER]}|${j[D.NUMERICIDENTIFIERLOOSE]})`);K("PRERELEASE",`(?:-(${j[D.PRERELEASEIDENTIFIER]}(?:\\.${j[D.PRERELEASEIDENTIFIER]})*))`);K("PRERELEASELOOSE",`(?:-?(${j[D.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${j[D.PRERELEASEIDENTIFIERLOOSE]})*))`);K("BUILDIDENTIFIER",`${pu}+`);K("BUILD",`(?:\\+(${j[D.BUILDIDENTIFIER]}(?:\\.${j[D.BUILDIDENTIFIER]})*))`);K("FULLPLAIN",`v?${j[D.MAINVERSION]}${j[D.PRERELEASE]}?${j[D.BUILD]}?`);K("FULL",`^${j[D.FULLPLAIN]}$`);K("LOOSEPLAIN",`[v=\\s]*${j[D.MAINVERSIONLOOSE]}${j[D.PRERELEASELOOSE]}?${j[D.BUILD]}?`);K("LOOSE",`^${j[D.LOOSEPLAIN]}$`);K("GTLT","((?:<|>)?=?)");K("XRANGEIDENTIFIERLOOSE",`${j[D.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);K("XRANGEIDENTIFIER",`${j[D.NUMERICIDENTIFIER]}|x|X|\\*`);K("XRANGEPLAIN",`[v=\\s]*(${j[D.XRANGEIDENTIFIER]})(?:\\.(${j[D.XRANGEIDENTIFIER]})(?:\\.(${j[D.XRANGEIDENTIFIER]})(?:${j[D.PRERELEASE]})?${j[D.BUILD]}?)?)?`);K("XRANGEPLAINLOOSE",`[v=\\s]*(${j[D.XRANGEIDENTIFIERLOOSE]})(?:\\.(${j[D.XRANGEIDENTIFIERLOOSE]})(?:\\.(${j[D.XRANGEIDENTIFIERLOOSE]})(?:${j[D.PRERELEASELOOSE]})?${j[D.BUILD]}?)?)?`);K("XRANGE",`^${j[D.GTLT]}\\s*${j[D.XRANGEPLAIN]}$`);K("XRANGELOOSE",`^${j[D.GTLT]}\\s*${j[D.XRANGEPLAINLOOSE]}$`);K("COERCEPLAIN",`(^|[^\\d])(\\d{1,${fu}})(?:\\.(\\d{1,${fu}}))?(?:\\.(\\d{1,${fu}}))?`);K("COERCE",`${j[D.COERCEPLAIN]}(?:$|[^\\d])`);K("COERCEFULL",j[D.COERCEPLAIN]+`(?:${j[D.PRERELEASE]})?(?:${j[D.BUILD]})?(?:$|[^\\d])`);K("COERCERTL",j[D.COERCE],!0);K("COERCERTLFULL",j[D.COERCEFULL],!0);K("LONETILDE","(?:~>?)");K("TILDETRIM",`(\\s*)${j[D.LONETILDE]}\\s+`,!0);ir.tildeTrimReplace="$1~";K("TILDE",`^${j[D.LONETILDE]}${j[D.XRANGEPLAIN]}$`);K("TILDELOOSE",`^${j[D.LONETILDE]}${j[D.XRANGEPLAINLOOSE]}$`);K("LONECARET","(?:\\^)");K("CARETTRIM",`(\\s*)${j[D.LONECARET]}\\s+`,!0);ir.caretTrimReplace="$1^";K("CARET",`^${j[D.LONECARET]}${j[D.XRANGEPLAIN]}$`);K("CARETLOOSE",`^${j[D.LONECARET]}${j[D.XRANGEPLAINLOOSE]}$`);K("COMPARATORLOOSE",`^${j[D.GTLT]}\\s*(${j[D.LOOSEPLAIN]})$|^$`);K("COMPARATOR",`^${j[D.GTLT]}\\s*(${j[D.FULLPLAIN]})$|^$`);K("COMPARATORTRIM",`(\\s*)${j[D.GTLT]}\\s*(${j[D.LOOSEPLAIN]}|${j[D.XRANGEPLAIN]})`,!0);ir.comparatorTrimReplace="$1$2$3";K("HYPHENRANGE",`^\\s*(${j[D.XRANGEPLAIN]})\\s+-\\s+(${j[D.XRANGEPLAIN]})\\s*$`);K("HYPHENRANGELOOSE",`^\\s*(${j[D.XRANGEPLAINLOOSE]})\\s+-\\s+(${j[D.XRANGEPLAINLOOSE]})\\s*$`);K("STAR","(<|>)?=?\\s*\\*");K("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");K("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")});var na=A((v2,Fy)=>{"use strict";var Ex=Object.freeze({loose:!0}),Ax=Object.freeze({}),kx=r=>r?typeof r!="object"?Ex:r:Ax;Fy.exports=kx});var hu=A(($2,By)=>{"use strict";var Vy=/^[0-9]+$/,Uy=(r,e)=>{if(typeof r=="number"&&typeof e=="number")return r===e?0:rUy(e,r);By.exports={compareIdentifiers:Uy,rcompareIdentifiers:xx}});var De=A((S2,Hy)=>{"use strict";var ia=ws(),{MAX_LENGTH:zy,MAX_SAFE_INTEGER:sa}=li(),{safeRe:oa,t:aa}=di(),Px=na(),{compareIdentifiers:mu}=hu(),Ix=(r,e)=>{let t=e.split(".");if(t.length>r.length)return!1;for(let n=0;nzy)throw new TypeError(`version is longer than ${zy} characters`);ia("SemVer",e,t),this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease;let n=e.trim().match(t.loose?oa[aa.LOOSE]:oa[aa.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>sa||this.major<0)throw new TypeError("Invalid major version");if(this.minor>sa||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>sa||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(ia("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 mu(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(ia("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 mu(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?oa[aa.PRERELEASELOOSE]:oa[aa.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]),Ix(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}};Hy.exports=yu});var Yr=A((E2,Wy)=>{"use strict";var Ky=De(),Ox=(r,e,t=!1)=>{if(r instanceof Ky)return r;try{return new Ky(r,e)}catch(n){if(!t)return null;throw n}};Wy.exports=Ox});var Jy=A((A2,Gy)=>{"use strict";var Rx=Yr(),Tx=(r,e)=>{let t=Rx(r,e);return t?t.version:null};Gy.exports=Tx});var Xy=A((k2,Yy)=>{"use strict";var Cx=Yr(),Mx=(r,e)=>{let t=Cx(r.trim().replace(/^[=v]+/,""),e);return t?t.version:null};Yy.exports=Mx});var eg=A((x2,Zy)=>{"use strict";var Qy=De(),Nx=(r,e,t,n,i)=>{typeof t=="string"&&(i=n,n=t,t=void 0);try{return new Qy(r instanceof Qy?r.version:r,t).inc(e,n,i).version}catch(s){return null}};Zy.exports=Nx});var ng=A((P2,rg)=>{"use strict";var tg=Yr(),Lx=(r,e)=>{let t=tg(r,null,!0),n=tg(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 d=c?"pre":"";return t.major!==n.major?d+"major":t.minor!==n.minor?d+"minor":t.patch!==n.patch?d+"patch":"prerelease"};rg.exports=Lx});var sg=A((I2,ig)=>{"use strict";var jx=De(),Dx=(r,e)=>new jx(r,e).major;ig.exports=Dx});var ag=A((O2,og)=>{"use strict";var qx=De(),Fx=(r,e)=>new qx(r,e).minor;og.exports=Fx});var lg=A((R2,cg)=>{"use strict";var Vx=De(),Ux=(r,e)=>new Vx(r,e).patch;cg.exports=Ux});var ug=A((T2,dg)=>{"use strict";var Bx=Yr(),zx=(r,e)=>{let t=Bx(r,e);return t&&t.prerelease.length?t.prerelease:null};dg.exports=zx});var At=A((C2,pg)=>{"use strict";var fg=De(),Hx=(r,e,t)=>new fg(r,t).compare(new fg(e,t));pg.exports=Hx});var mg=A((M2,hg)=>{"use strict";var Kx=At(),Wx=(r,e,t)=>Kx(e,r,t);hg.exports=Wx});var gg=A((N2,yg)=>{"use strict";var Gx=At(),Jx=(r,e)=>Gx(r,e,!0);yg.exports=Jx});var ca=A((L2,bg)=>{"use strict";var _g=De(),Yx=(r,e,t)=>{let n=new _g(r,t),i=new _g(e,t);return n.compare(i)||n.compareBuild(i)};bg.exports=Yx});var vg=A((j2,wg)=>{"use strict";var Xx=ca(),Qx=(r,e)=>r.sort((t,n)=>Xx(t,n,e));wg.exports=Qx});var Sg=A((D2,$g)=>{"use strict";var Zx=ca(),eP=(r,e)=>r.sort((t,n)=>Zx(n,t,e));$g.exports=eP});var vs=A((q2,Eg)=>{"use strict";var tP=At(),rP=(r,e,t)=>tP(r,e,t)>0;Eg.exports=rP});var la=A((F2,Ag)=>{"use strict";var nP=At(),iP=(r,e,t)=>nP(r,e,t)<0;Ag.exports=iP});var gu=A((V2,kg)=>{"use strict";var sP=At(),oP=(r,e,t)=>sP(r,e,t)===0;kg.exports=oP});var _u=A((U2,xg)=>{"use strict";var aP=At(),cP=(r,e,t)=>aP(r,e,t)!==0;xg.exports=cP});var da=A((B2,Pg)=>{"use strict";var lP=At(),dP=(r,e,t)=>lP(r,e,t)>=0;Pg.exports=dP});var ua=A((z2,Ig)=>{"use strict";var uP=At(),fP=(r,e,t)=>uP(r,e,t)<=0;Ig.exports=fP});var bu=A((H2,Og)=>{"use strict";var pP=gu(),hP=_u(),mP=vs(),yP=da(),gP=la(),_P=ua(),bP=(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 pP(r,t,n);case"!=":return hP(r,t,n);case">":return mP(r,t,n);case">=":return yP(r,t,n);case"<":return gP(r,t,n);case"<=":return _P(r,t,n);default:throw new TypeError(`Invalid operator: ${e}`)}};Og.exports=bP});var Tg=A((K2,Rg)=>{"use strict";var wP=De(),vP=Yr(),{safeRe:fa,t:pa}=di(),$P=(r,e)=>{if(r instanceof wP)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?fa[pa.COERCEFULL]:fa[pa.COERCE]);else{let c=e.includePrerelease?fa[pa.COERCERTLFULL]:fa[pa.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 vP(`${n}.${i}.${s}${o}${a}`,e)};Rg.exports=$P});var Mg=A((W2,Cg)=>{"use strict";var SP=Yr(),EP=li(),AP=De(),kP=(r,e,t)=>{if(!EP.RELEASE_TYPES.includes(e))return null;let n=xP(r,t);return n&&PP(n,e)},xP=(r,e)=>{let t=r instanceof AP?r.version:r;return SP(t,e)},PP=(r,e)=>{if(IP(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()},IP=r=>r.startsWith("pre");Cg.exports=kP});var Lg=A((G2,Ng)=>{"use strict";var wu=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}};Ng.exports=wu});var kt=A((J2,Fg)=>{"use strict";var OP=/\s+/g,vu=class r{constructor(e,t){if(t=TP(t),e instanceof r)return e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease?e:new r(e.raw,t);if(e instanceof $u)return this.raw=e.value,this.set=[[e]],this.formatted=void 0,this;if(this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease,this.raw=e.trim().replace(OP," "),this.set=this.raw.split("||").map(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=>!Dg(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&&VP(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(FP,"");let n=((this.options.includePrerelease&&DP)|(this.options.loose&&qP))+":"+e,i=jg.get(n);if(i)return i;let s=this.options.loose,o=s?Xe[qe.HYPHENRANGELOOSE]:Xe[qe.HYPHENRANGE];e=e.replace(o,QP(this.options.includePrerelease)),we("hyphen replace",e),e=e.replace(Xe[qe.COMPARATORTRIM],NP),we("comparator trim",e),e=e.replace(Xe[qe.TILDETRIM],LP),we("tilde trim",e),e=e.replace(Xe[qe.CARETTRIM],jP),we("caret trim",e);let a=e.split(" ").map(u=>UP(u,this.options)).join(" ").split(/\s+/).map(u=>XP(u,this.options));s&&(a=a.filter(u=>(we("loose invalid filter",u,this.options),!!u.match(Xe[qe.COMPARATORLOOSE])))),we("range list",a);let c=new Map,l=a.map(u=>new $u(u,this.options));for(let u of l){if(Dg(u))return[u];c.set(u.value,u)}c.size>1&&c.has("")&&c.delete("");let d=[...c.values()];return jg.set(n,d),d}intersects(e,t){if(!(e instanceof r))throw new TypeError("a Range is required");return this.set.some(n=>qg(n,t)&&e.set.some(i=>qg(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 CP(e,this.options)}catch(t){return!1}for(let t=0;tr.value==="<0.0.0-0",VP=r=>r.value==="",qg=(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},UP=(r,e)=>(r=r.replace(Xe[qe.BUILD],""),we("comp",r,e),r=KP(r,e),we("caret",r),r=zP(r,e),we("tildes",r),r=GP(r,e),we("xrange",r),r=YP(r,e),we("stars",r),r),Oe=r=>!r||r.toLowerCase()==="x"||r==="*",BP=(r,e,t)=>Oe(r)&&!Oe(e)||Oe(e)&&t&&!Oe(t),zP=(r,e)=>r.trim().split(/\s+/).map(t=>HP(t,e)).join(" "),HP=(r,e)=>{let t=e.loose?Xe[qe.TILDELOOSE]:Xe[qe.TILDE],n=e.includePrerelease?"-0":"";return r.replace(t,(i,s,o,a,c)=>{we("tilde",r,i,s,o,a,c);let l;return Oe(s)?l="":Oe(o)?l=`>=${s}.0.0${n} <${+s+1}.0.0-0`:Oe(a)?l=`>=${s}.${o}.0${n} <${s}.${+o+1}.0-0`:c?(we("replaceTilde pr",c),l=`>=${s}.${o}.${a}-${c} <${s}.${+o+1}.0-0`):l=`>=${s}.${o}.${a} <${s}.${+o+1}.0-0`,we("tilde return",l),l})},KP=(r,e)=>r.trim().split(/\s+/).map(t=>WP(t,e)).join(" "),WP=(r,e)=>{we("caret",r,e);let t=e.loose?Xe[qe.CARETLOOSE]:Xe[qe.CARET],n=e.includePrerelease?"-0":"";return r.replace(t,(i,s,o,a,c)=>{we("caret",r,i,s,o,a,c);let l;return Oe(s)?l="":Oe(o)?l=`>=${s}.0.0${n} <${+s+1}.0.0-0`:Oe(a)?s==="0"?l=`>=${s}.${o}.0${n} <${s}.${+o+1}.0-0`:l=`>=${s}.${o}.0${n} <${+s+1}.0.0-0`:c?(we("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`):(we("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`),we("caret return",l),l})},GP=(r,e)=>(we("replaceXRanges",r,e),r.split(/\s+/).map(t=>JP(t,e)).join(" ")),JP=(r,e)=>{r=r.trim();let t=e.loose?Xe[qe.XRANGELOOSE]:Xe[qe.XRANGE];return r.replace(t,(n,i,s,o,a,c)=>{if(we("xRange",r,n,i,s,o,a,c),BP(s,o,a))return r;let l=Oe(s),d=l||Oe(o),u=d||Oe(a),f=u;return i==="="&&f&&(i=""),c=e.includePrerelease?"-0":"",l?i===">"||i==="<"?n="<0.0.0-0":n="*":i&&f?(d&&(o=0),a=0,i===">"?(i=">=",d?(s=+s+1,o=0,a=0):(o=+o+1,a=0)):i==="<="&&(i="<",d?s=+s+1:o=+o+1),i==="<"&&(c="-0"),n=`${i+s}.${o}.${a}${c}`):d?n=`>=${s}.0.0${c} <${+s+1}.0.0-0`:u&&(n=`>=${s}.${o}.0${c} <${s}.${+o+1}.0-0`),we("xRange return",n),n})},YP=(r,e)=>(we("replaceStars",r,e),r.trim().replace(Xe[qe.STAR],"")),XP=(r,e)=>(we("replaceGTE0",r,e),r.trim().replace(Xe[e.includePrerelease?qe.GTE0PRE:qe.GTE0],"")),QP=r=>(e,t,n,i,s,o,a,c,l,d,u,f)=>(Oe(n)?t="":Oe(i)?t=`>=${n}.0.0${r?"-0":""}`:Oe(s)?t=`>=${n}.${i}.0${r?"-0":""}`:o?t=`>=${t}`:t=`>=${t}${r?"-0":""}`,Oe(l)?c="":Oe(d)?c=`<${+l+1}.0.0-0`:Oe(u)?c=`<${l}.${+d+1}.0-0`:f?c=`<=${l}.${d}.${u}-${f}`:r?c=`<${l}.${d}.${+u+1}-0`:c=`<=${c}`,`${t} ${c}`.trim()),ZP=(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 $s=A((Y2,Kg)=>{"use strict";var Ss=Symbol("SemVer ANY"),Au=class r{static get ANY(){return Ss}constructor(e,t){if(t=Vg(t),e instanceof r){if(e.loose===!!t.loose)return e;e=e.value}e=e.trim().split(/\s+/).join(" "),Eu("comparator",e,t),this.options=t,this.loose=!!t.loose,this.parse(e),this.semver===Ss?this.value="":this.value=this.operator+this.semver.version,Eu("comp",this)}parse(e){let t=this.options.loose?Ug[Bg.COMPARATORLOOSE]:Ug[Bg.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 zg(n[2],this.options.loose):this.semver=Ss}toString(){return this.value}test(e){if(Eu("Comparator.test",e,this.options.loose),this.semver===Ss||e===Ss)return!0;if(typeof e=="string")try{e=new zg(e,this.options)}catch(t){return!1}return Su(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 Hg(e.value,t).test(this.value):e.operator===""?e.value===""?!0:new Hg(this.value,t).test(e.semver):(t=Vg(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("=")||Su(this.semver,"<",e.semver,t)&&this.operator.startsWith(">")&&e.operator.startsWith("<")||Su(this.semver,">",e.semver,t)&&this.operator.startsWith("<")&&e.operator.startsWith(">")))}};Kg.exports=Au;var Vg=na(),{safeRe:Ug,t:Bg}=di(),Su=bu(),Eu=ws(),zg=De(),Hg=kt()});var Es=A((X2,Wg)=>{"use strict";var eI=kt(),tI=(r,e,t)=>{try{e=new eI(e,t)}catch(n){return!1}return e.test(r)};Wg.exports=tI});var Jg=A((Q2,Gg)=>{"use strict";var rI=kt(),nI=(r,e)=>new rI(r,e).set.map(t=>t.map(n=>n.value).join(" ").trim().split(" "));Gg.exports=nI});var Xg=A((Z2,Yg)=>{"use strict";var iI=De(),sI=kt(),oI=(r,e,t)=>{let n=null,i=null,s=null;try{s=new sI(e,t)}catch(o){return null}return r.forEach(o=>{s.test(o)&&(!n||i.compare(o)===-1)&&(n=o,i=new iI(n,t))}),n};Yg.exports=oI});var Zg=A((eL,Qg)=>{"use strict";var aI=De(),cI=kt(),lI=(r,e,t)=>{let n=null,i=null,s=null;try{s=new cI(e,t)}catch(o){return null}return r.forEach(o=>{s.test(o)&&(!n||i.compare(o)===1)&&(n=o,i=new aI(n,t))}),n};Qg.exports=lI});var r_=A((tL,t_)=>{"use strict";var ku=De(),dI=kt(),e_=vs(),uI=(r,e)=>{r=new dI(r,e);let t=new ku("0.0.0");if(r.test(t)||(t=new ku("0.0.0-0"),r.test(t)))return t;t=null;for(let n=0;n{let a=new ku(o.semver.version);switch(o.operator){case">":a.prerelease.length===0?a.patch++:a.prerelease.push(0),a.raw=a.format();case"":case">=":(!s||e_(a,s))&&(s=a);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${o.operator}`)}}),s&&(!t||e_(t,s))&&(t=s)}return t&&r.test(t)?t:null};t_.exports=uI});var i_=A((rL,n_)=>{"use strict";var fI=kt(),pI=(r,e)=>{try{return new fI(r,e).range||"*"}catch(t){return null}};n_.exports=pI});var ha=A((nL,c_)=>{"use strict";var hI=De(),a_=$s(),{ANY:mI}=a_,yI=kt(),gI=Es(),s_=vs(),o_=la(),_I=ua(),bI=da(),wI=(r,e,t,n)=>{r=new hI(r,n),e=new yI(e,n);let i,s,o,a,c;switch(t){case">":i=s_,s=_I,o=o_,a=">",c=">=";break;case"<":i=o_,s=bI,o=s_,a="<",c="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(gI(r,e,n))return!1;for(let l=0;l{p.semver===mI&&(p=new a_(">=0.0.0")),u=u||p,f=f||p,i(p.semver,u.semver,n)?u=p:o(p.semver,f.semver,n)&&(f=p)}),u.operator===a||u.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};c_.exports=wI});var d_=A((iL,l_)=>{"use strict";var vI=ha(),$I=(r,e,t)=>vI(r,e,">",t);l_.exports=$I});var f_=A((sL,u_)=>{"use strict";var SI=ha(),EI=(r,e,t)=>SI(r,e,"<",t);u_.exports=EI});var m_=A((oL,h_)=>{"use strict";var p_=kt(),AI=(r,e,t)=>(r=new p_(r,t),e=new p_(e,t),r.intersects(e,t));h_.exports=AI});var g_=A((aL,y_)=>{"use strict";var kI=Es(),xI=At();y_.exports=(r,e,t)=>{let n=[],i=null,s=null,o=r.sort((d,u)=>xI(d,u,t));for(let d of o)kI(d,e,t)?(s=d,i||(i=d)):(s&&n.push([i,s]),s=null,i=null);i&&n.push([i,null]);let a=[];for(let[d,u]of n)d===u?a.push(d):!u&&d===o[0]?a.push("*"):u?d===o[0]?a.push(`<=${u}`):a.push(`${d} - ${u}`):a.push(`>=${d}`);let c=a.join(" || "),l=typeof e.raw=="string"?e.raw:String(e);return c.length{"use strict";var __=kt(),Iu=$s(),{ANY:xu}=Iu,Pu=Es(),Ou=At(),PI=(r,e,t={})=>{if(r===e)return!0;r=new __(r,t),e=new __(e,t);let n=!1;e:for(let i of r.set){for(let s of e.set){let o=OI(i,s,t);if(n=n||o!==null,o)continue e}if(n)return!1}return!0},II=[new Iu(">=0.0.0-0")],b_=[new Iu(">=0.0.0")],OI=(r,e,t)=>{if(r===e)return!0;if(r.length===1&&r[0].semver===xu){if(e.length===1&&e[0].semver===xu)return!0;t.includePrerelease?r=II:r=b_}if(e.length===1&&e[0].semver===xu){if(t.includePrerelease)return!0;e=b_}let n=new Set,i,s;for(let p of r)p.operator===">"||p.operator===">="?i=w_(i,p,t):p.operator==="<"||p.operator==="<="?s=v_(s,p,t):n.add(p.semver);if(n.size>1)return null;let o;if(i&&s){if(o=Ou(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&&!Pu(p,String(i),t)||s&&!Pu(p,String(s),t))return null;for(let y of e)if(!Pu(p,String(y),t))return!1;return!0}let a,c,l,d,u=s&&!t.includePrerelease&&s.semver.prerelease.length?s.semver:!1,f=i&&!t.includePrerelease&&i.semver.prerelease.length?i.semver:!1;u&&u.prerelease.length===1&&s.operator==="<"&&u.prerelease[0]===0&&(u=!1);for(let p of e){if(d=d||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=w_(i,p,t),a===p&&a!==i)return!1}else if(i.operator===">="&&!p.test(i.semver))return!1}if(s){if(u&&p.semver.prerelease&&p.semver.prerelease.length&&p.semver.major===u.major&&p.semver.minor===u.minor&&p.semver.patch===u.patch&&(u=!1),p.operator==="<"||p.operator==="<="){if(c=v_(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&&d&&!i&&o!==0||f||u)},w_=(r,e,t)=>{if(!r)return e;let n=Ou(r.semver,e.semver,t);return n>0?r:n<0||e.operator===">"&&r.operator===">="?e:r},v_=(r,e,t)=>{if(!r)return e;let n=Ou(r.semver,e.semver,t);return n<0?r:n>0||e.operator==="<"&&r.operator==="<="?e:r};$_.exports=PI});var x_=A((lL,k_)=>{"use strict";var Ru=di(),E_=li(),RI=De(),A_=hu(),TI=Yr(),CI=Jy(),MI=Xy(),NI=eg(),LI=ng(),jI=sg(),DI=ag(),qI=lg(),FI=ug(),VI=At(),UI=mg(),BI=gg(),zI=ca(),HI=vg(),KI=Sg(),WI=vs(),GI=la(),JI=gu(),YI=_u(),XI=da(),QI=ua(),ZI=bu(),eO=Tg(),tO=Mg(),rO=$s(),nO=kt(),iO=Es(),sO=Jg(),oO=Xg(),aO=Zg(),cO=r_(),lO=i_(),dO=ha(),uO=d_(),fO=f_(),pO=m_(),hO=g_(),mO=S_();k_.exports={parse:TI,valid:CI,clean:MI,inc:NI,diff:LI,major:jI,minor:DI,patch:qI,prerelease:FI,compare:VI,rcompare:UI,compareLoose:BI,compareBuild:zI,sort:HI,rsort:KI,gt:WI,lt:GI,eq:JI,neq:YI,gte:XI,lte:QI,cmp:ZI,coerce:eO,truncate:tO,Comparator:rO,Range:nO,satisfies:iO,toComparators:sO,maxSatisfying:oO,minSatisfying:aO,minVersion:cO,validRange:lO,outside:dO,gtr:uO,ltr:fO,intersects:pO,simplifyRange:hO,subset:mO,SemVer:RI,re:Ru.re,src:Ru.src,tokens:Ru.t,SEMVER_SPEC_VERSION:E_.SEMVER_SPEC_VERSION,RELEASE_TYPES:E_.RELEASE_TYPES,compareIdentifiers:A_.compareIdentifiers,rcompareIdentifiers:A_.rcompareIdentifiers}});var ks=A((xL,j_)=>{"use strict";var C_="[^\\\\/]",EO="(?=.)",M_="[^/]",Lu="(?:\\/|$)",N_="(?:^|\\/)",ju=`\\.{1,2}${Lu}`,AO="(?!\\.)",kO=`(?!${N_}${ju})`,xO=`(?!\\.{0,1}${Lu})`,PO=`(?!${ju})`,IO="[^.\\/]",OO=`${M_}*?`,RO="/",L_={DOT_LITERAL:"\\.",PLUS_LITERAL:"\\+",QMARK_LITERAL:"\\?",SLASH_LITERAL:"\\/",ONE_CHAR:EO,QMARK:M_,END_ANCHOR:Lu,DOTS_SLASH:ju,NO_DOT:AO,NO_DOTS:kO,NO_DOT_SLASH:xO,NO_DOTS_SLASH:PO,QMARK_NO_DOT:IO,STAR:OO,START_ANCHOR:N_,SEP:RO},TO={...L_,SLASH_LITERAL:"[\\\\/]",QMARK:C_,STAR:`${C_}*?`,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:"\\"},CO={__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"};j_.exports={DEFAULT_MAX_EXTGLOB_RECURSION:0,MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:CO,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?TO:L_}}});var xs=A(ct=>{"use strict";var{REGEX_BACKSLASH:MO,REGEX_REMOVE_BACKSLASH:NO,REGEX_SPECIAL_CHARS:LO,REGEX_SPECIAL_CHARS_GLOBAL:jO}=ks();ct.isObject=r=>r!==null&&typeof r=="object"&&!Array.isArray(r);ct.hasRegexChars=r=>LO.test(r);ct.isRegexChar=r=>r.length===1&&ct.hasRegexChars(r);ct.escapeRegex=r=>r.replace(jO,"\\$1");ct.toPosixSlashes=r=>r.replace(MO,"/");ct.isWindows=()=>{if(typeof navigator!="undefined"&&navigator.platform){let r=navigator.platform.toLowerCase();return r==="win32"||r==="windows"}return typeof process!="undefined"&&process.platform?process.platform==="win32":!1};ct.removeBackslashes=r=>r.replace(NO,e=>e==="\\"?"":e);ct.escapeLast=(r,e,t)=>{let n=r.lastIndexOf(e,t);return n===-1?r:r[n-1]==="\\"?ct.escapeLast(r,e,n-1):`${r.slice(0,n)}\\${r.slice(n)}`};ct.removePrefix=(r,e={})=>{let t=r;return t.startsWith("./")&&(t=t.slice(2),e.prefix="./"),t};ct.wrapOutput=(r,e={},t={})=>{let n=t.contains?"":"^",i=t.contains?"":"$",s=`${n}(?:${r})${i}`;return e.negated===!0&&(s=`(?:^(?!${s}).*$)`),s};ct.basename=(r,{windows:e}={})=>{let t=r.split(e?/[\\/]/:"/"),n=t[t.length-1];return n===""?t[t.length-2]:n}});var H_=A((IL,z_)=>{"use strict";var D_=xs(),{CHAR_ASTERISK:Du,CHAR_AT:DO,CHAR_BACKWARD_SLASH:Ps,CHAR_COMMA:qO,CHAR_DOT:qu,CHAR_EXCLAMATION_MARK:Fu,CHAR_FORWARD_SLASH:B_,CHAR_LEFT_CURLY_BRACE:Vu,CHAR_LEFT_PARENTHESES:Uu,CHAR_LEFT_SQUARE_BRACKET:FO,CHAR_PLUS:VO,CHAR_QUESTION_MARK:q_,CHAR_RIGHT_CURLY_BRACE:UO,CHAR_RIGHT_PARENTHESES:F_,CHAR_RIGHT_SQUARE_BRACKET:BO}=ks(),V_=r=>r===B_||r===Ps,U_=r=>{r.isPrefix!==!0&&(r.depth=r.isGlobstar?1/0:1)},zO=(r,e)=>{let t=e||{},n=r.length-1,i=t.parts===!0||t.scanToEnd===!0,s=[],o=[],a=[],c=r,l=-1,d=0,u=0,f=!1,p=!1,y=!1,h=!1,m=!1,g=!1,_=!1,w=!1,x=!1,v=!1,P=0,O,$,R={value:"",depth:0,isGlob:!1},S=()=>l>=n,U=()=>c.charCodeAt(l+1),B=()=>(O=$,c.charCodeAt(++l));for(;l0&&(E=c.slice(0,d),c=c.slice(d),u-=d),T&&y===!0&&u>0?(T=c.slice(0,u),k=c.slice(u)):y===!0?(T="",k=c):T=c,T&&T!==""&&T!=="/"&&T!==c&&V_(T.charCodeAt(T.length-1))&&(T=T.slice(0,-1)),t.unescape===!0&&(k&&(k=D_.removeBackslashes(k)),T&&_===!0&&(T=D_.removeBackslashes(T)));let de={prefix:E,input:r,start:d,base:T,glob:k,isBrace:f,isBracket:p,isGlob:y,isExtglob:h,isGlobstar:m,negated:w,negatedExtglob:x};if(t.tokens===!0&&(de.maxDepth=0,V_($)||o.push(R),de.tokens=o),t.parts===!0||t.tokens===!0){let Z;for(let V=0;V{"use strict";var Is=ks(),ht=xs(),{MAX_LENGTH:_a,POSIX_REGEX_SOURCE:HO,REGEX_NON_SPECIAL_CHARS:KO,REGEX_SPECIAL_CHARS_BACKREF:WO,REPLACEMENTS:K_}=Is,GO=(r,e)=>{if(typeof e.expandRange=="function")return e.expandRange(...r,e);r.sort();let t=`[${r.join("-")}]`;try{new RegExp(t)}catch(n){return r.map(i=>ht.escapeRegex(i)).join("..")}return t},ui=(r,e)=>`Missing ${r}: "${e}" - use "\\\\${e}" to match literal characters`,W_=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},JO=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},zu=r=>{let e=r.trim(),t=!0;for(;t===!0;)t=!1,/^@\([^\\()[\]{}|]+\)$/.test(e)&&(e=e.slice(2,-1),t=!0);if(JO(e))return e.replace(/\\(.)/g,"$1")},YO=r=>{let e=r.map(zu).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}}}}},XO=r=>`${r.length===1?ht.escapeRegex(r[0]):`[${r.map(t=>ht.escapeRegex(t)).join("")}]`}*`,QO=r=>{let e=0,t=[];for(;eo.trim());if(i.length!==1)return;let s=zu(i[0]);if(!s||s.length!==1)return;t.push(s),e+=n.end+1}if(!(t.length<1))return t},ZO=r=>{let e=0,t=r.trim(),n=Bu(t);for(;n;)e++,t=n.body.trim(),n=Bu(t);return e},eR=(r,e)=>{if(e.maxExtglobRecursion===!1)return{risky:!1};let t=typeof e.maxExtglobRecursion=="number"?e.maxExtglobRecursion:Is.DEFAULT_MAX_EXTGLOB_RECURSION,n=W_(r).map(a=>a.trim());if(n.length>1&&(n.some(a=>a==="")||n.some(a=>/^[*?]+$/.test(a))||YO(n)))return{risky:!0};let i=[],s=!1,o=!0;for(let a of n){let c=QO(a);if(c){s=!0,i.push(...c);continue}let l=zu(a);if(l&&l.length===1){i.push(l);continue}if(o=!1,ZO(a)>t)return{risky:!0}}return s?o?{risky:!0,safeOutput:XO([...new Set(i)])}:{risky:!0}:{risky:!1}},Hu=(r,e)=>{if(typeof r!="string")throw new TypeError("Expected a string");r=K_[r]||r;let t={...e},n=typeof t.maxLength=="number"?Math.min(_a,t.maxLength):_a,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=Is.globChars(t.windows),l=Is.extglobChars(c),{DOT_LITERAL:d,PLUS_LITERAL:u,SLASH_LITERAL:f,ONE_CHAR:p,DOTS_SLASH:y,NO_DOT:h,NO_DOT_SLASH:m,NO_DOTS_SLASH:g,QMARK:_,QMARK_NO_DOT:w,STAR:x,START_ANCHOR:v}=c,P=M=>`(${a}(?:(?!${v}${M.dot?y:d}).)*?)`,O=t.dot?"":h,$=t.dot?_:w,R=t.bash===!0?P(t):x;t.capture&&(R=`(${R})`),typeof t.noext=="boolean"&&(t.noextglob=t.noext);let S={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=ht.removePrefix(r,S),i=r.length;let U=[],B=[],T=[],E=s,k,de=()=>S.index===i-1,Z=S.peek=(M=1)=>r[S.index+M],V=S.advance=()=>r[++S.index]||"",fe=()=>r.slice(S.index+1),Ve=(M="",$e=0)=>{S.consumed+=M,S.index+=$e},Jt=M=>{S.output+=M.output!=null?M.output:M.value,Ve(M.value)},Dr=()=>{let M=1;for(;Z()==="!"&&(Z(2)!=="("||Z(3)==="?");)V(),S.start++,M++;return M%2===0?!1:(S.negated=!0,S.start++,!0)},un=M=>{S[M]++,T.push(M)},qr=M=>{S[M]--,T.pop()},ee=M=>{if(E.type==="globstar"){let $e=S.braces>0&&(M.type==="comma"||M.type==="brace"),C=M.extglob===!0||U.length&&(M.type==="pipe"||M.type==="paren");M.type!=="slash"&&M.type!=="paren"&&!$e&&!C&&(S.output=S.output.slice(0,-E.output.length),E.type="star",E.value="*",E.output=R,S.output+=E.output)}if(U.length&&M.type!=="paren"&&(U[U.length-1].inner+=M.value),(M.value||M.output)&&Jt(M),E&&E.type==="text"&&M.type==="text"){E.output=(E.output||E.value)+M.value,E.value+=M.value;return}M.prev=E,o.push(M),E=M},_o=(M,$e)=>{let C={...l[$e],conditions:1,inner:""};C.prev=E,C.parens=S.parens,C.output=S.output,C.startIndex=S.index,C.tokensIndex=o.length;let te=(t.capture?"(":"")+C.open;un("parens"),ee({type:M,value:$e,output:S.output?"":p}),ee({type:"paren",extglob:!0,value:V(),output:te}),U.push(C)},L0=M=>{let $e=r.slice(M.startIndex,S.index+1),C=r.slice(M.startIndex+2,S.index),te=eR(C,t);if((M.type==="plus"||M.type==="star")&&te.risky){let he=te.safeOutput?(M.output?"":p)+(t.capture?`(${te.safeOutput})`:te.safeOutput):void 0,Yt=o[M.tokensIndex];Yt.type="text",Yt.value=$e,Yt.output=he||ht.escapeRegex($e);for(let Xt=M.tokensIndex+1;Xt1&&M.inner.includes("/")&&(he=P(t)),(he!==R||de()||/^\)+$/.test(fe()))&&(ye=M.close=`)$))${he}`),M.inner.includes("*")&&(Ie=fe())&&/^\.[^\\/.]+$/.test(Ie)){let Yt=Hu(Ie,{...e,fastpaths:!1}).output;ye=M.close=`)${Yt})${he})`}M.prev.type==="bos"&&(S.negatedExtglob=!0)}ee({type:"paren",extglob:!0,value:k,output:ye}),qr("parens")};if(t.fastpaths!==!1&&!/(^[*!]|[/()[\]{}"])/.test(r)){let M=!1,$e=r.replace(WO,(C,te,ye,Ie,he,Yt)=>Ie==="\\"?(M=!0,C):Ie==="?"?te?te+Ie+(he?_.repeat(he.length):""):Yt===0?$+(he?_.repeat(he.length):""):_.repeat(ye.length):Ie==="."?d.repeat(ye.length):Ie==="*"?te?te+Ie+(he?R:""):R:te?C:`\\${C}`);return M===!0&&(t.unescape===!0?$e=$e.replace(/\\/g,""):$e=$e.replace(/\\+/g,C=>C.length%2===0?"\\\\":C?"\\":"")),$e===r&&t.contains===!0?(S.output=r,S):(S.output=ht.wrapOutput($e,S,e),S)}for(;!de();){if(k=V(),k==="\0")continue;if(k==="\\"){let C=Z();if(C==="/"&&t.bash!==!0||C==="."||C===";")continue;if(!C){k+="\\",ee({type:"text",value:k});continue}let te=/^\\+/.exec(fe()),ye=0;if(te&&te[0].length>2&&(ye=te[0].length,S.index+=ye,ye%2!==0&&(k+="\\")),t.unescape===!0?k=V():k+=V(),S.brackets===0){ee({type:"text",value:k});continue}}if(S.brackets>0&&(k!=="]"||E.value==="["||E.value==="[^")){if(t.posix!==!1&&k===":"){let C=E.value.slice(1);if(C.includes("[")&&(E.posix=!0,C.includes(":"))){let te=E.value.lastIndexOf("["),ye=E.value.slice(0,te),Ie=E.value.slice(te+2),he=HO[Ie];if(he){E.value=ye+he,S.backtrack=!0,V(),!s.output&&o.indexOf(E)===1&&(s.output=p);continue}}}(k==="["&&Z()!==":"||k==="-"&&Z()==="]")&&(k=`\\${k}`),k==="]"&&(E.value==="["||E.value==="[^")&&(k=`\\${k}`),t.posix===!0&&k==="!"&&E.value==="["&&(k="^"),E.value+=k,Jt({value:k});continue}if(S.quotes===1&&k!=='"'){k=ht.escapeRegex(k),E.value+=k,Jt({value:k});continue}if(k==='"'){S.quotes=S.quotes===1?0:1,t.keepQuotes===!0&&ee({type:"text",value:k});continue}if(k==="("){un("parens"),ee({type:"paren",value:k});continue}if(k===")"){if(S.parens===0&&t.strictBrackets===!0)throw new SyntaxError(ui("opening","("));let C=U[U.length-1];if(C&&S.parens===C.parens+1){L0(U.pop());continue}ee({type:"paren",value:k,output:S.parens?")":"\\)"}),qr("parens");continue}if(k==="["){if(t.nobracket===!0||!fe().includes("]")){if(t.nobracket!==!0&&t.strictBrackets===!0)throw new SyntaxError(ui("closing","]"));k=`\\${k}`}else un("brackets");ee({type:"bracket",value:k});continue}if(k==="]"){if(t.nobracket===!0||E&&E.type==="bracket"&&E.value.length===1){ee({type:"text",value:k,output:`\\${k}`});continue}if(S.brackets===0){if(t.strictBrackets===!0)throw new SyntaxError(ui("opening","["));ee({type:"text",value:k,output:`\\${k}`});continue}qr("brackets");let C=E.value.slice(1);if(E.posix!==!0&&C[0]==="^"&&!C.includes("/")&&(k=`/${k}`),E.value+=k,Jt({value:k}),t.literalBrackets===!1||ht.hasRegexChars(C))continue;let te=ht.escapeRegex(E.value);if(S.output=S.output.slice(0,-E.value.length),t.literalBrackets===!0){S.output+=te,E.value=te;continue}E.value=`(${a}${te}|${E.value})`,S.output+=E.value;continue}if(k==="{"&&t.nobrace!==!0){un("braces");let C={type:"brace",value:k,output:"(",outputIndex:S.output.length,tokensIndex:S.tokens.length};B.push(C),ee(C);continue}if(k==="}"){let C=B[B.length-1];if(t.nobrace===!0||!C){ee({type:"text",value:k,output:k});continue}let te=")";if(C.dots===!0){let ye=o.slice(),Ie=[];for(let he=ye.length-1;he>=0&&(o.pop(),ye[he].type!=="brace");he--)ye[he].type!=="dots"&&Ie.unshift(ye[he].value);te=GO(Ie,t),S.backtrack=!0}if(C.comma!==!0&&C.dots!==!0){let ye=S.output.slice(0,C.outputIndex),Ie=S.tokens.slice(C.tokensIndex);C.value=C.output="\\{",k=te="\\}",S.output=ye;for(let he of Ie)S.output+=he.output||he.value}ee({type:"brace",value:k,output:te}),qr("braces"),B.pop();continue}if(k==="|"){U.length>0&&U[U.length-1].conditions++,ee({type:"text",value:k});continue}if(k===","){let C=k,te=B[B.length-1];te&&T[T.length-1]==="braces"&&(te.comma=!0,C="|"),ee({type:"comma",value:k,output:C});continue}if(k==="/"){if(E.type==="dot"&&S.index===S.start+1){S.start=S.index+1,S.consumed="",S.output="",o.pop(),E=s;continue}ee({type:"slash",value:k,output:f});continue}if(k==="."){if(S.braces>0&&E.type==="dot"){E.value==="."&&(E.output=d);let C=B[B.length-1];E.type="dots",E.output+=k,E.value+=k,C.dots=!0;continue}if(S.braces+S.parens===0&&E.type!=="bos"&&E.type!=="slash"){ee({type:"text",value:k,output:d});continue}ee({type:"dot",value:k,output:d});continue}if(k==="?"){if(!(E&&E.value==="(")&&t.noextglob!==!0&&Z()==="("&&Z(2)!=="?"){_o("qmark",k);continue}if(E&&E.type==="paren"){let te=Z(),ye=k;(E.value==="("&&!/[!=<:]/.test(te)||te==="<"&&!/<([!=]|\w+>)/.test(fe()))&&(ye=`\\${k}`),ee({type:"text",value:k,output:ye});continue}if(t.dot!==!0&&(E.type==="slash"||E.type==="bos")){ee({type:"qmark",value:k,output:w});continue}ee({type:"qmark",value:k,output:_});continue}if(k==="!"){if(t.noextglob!==!0&&Z()==="("&&(Z(2)!=="?"||!/[!=<:]/.test(Z(3)))){_o("negate",k);continue}if(t.nonegate!==!0&&S.index===0){Dr();continue}}if(k==="+"){if(t.noextglob!==!0&&Z()==="("&&Z(2)!=="?"){_o("plus",k);continue}if(E&&E.value==="("||t.regex===!1){ee({type:"plus",value:k,output:u});continue}if(E&&(E.type==="bracket"||E.type==="paren"||E.type==="brace")||S.parens>0){ee({type:"plus",value:k});continue}ee({type:"plus",value:u});continue}if(k==="@"){if(t.noextglob!==!0&&Z()==="("&&Z(2)!=="?"){ee({type:"at",extglob:!0,value:k,output:""});continue}ee({type:"text",value:k});continue}if(k!=="*"){(k==="$"||k==="^")&&(k=`\\${k}`);let C=KO.exec(fe());C&&(k+=C[0],S.index+=C[0].length),ee({type:"text",value:k});continue}if(E&&(E.type==="globstar"||E.star===!0)){E.type="star",E.star=!0,E.value+=k,E.output=R,S.backtrack=!0,S.globstar=!0,Ve(k);continue}let M=fe();if(t.noextglob!==!0&&/^\([^?]/.test(M)){_o("star",k);continue}if(E.type==="star"){if(t.noglobstar===!0){Ve(k);continue}let C=E.prev,te=C.prev,ye=C.type==="slash"||C.type==="bos",Ie=te&&(te.type==="star"||te.type==="globstar");if(t.bash===!0&&(!ye||M[0]&&M[0]!=="/")){ee({type:"star",value:k,output:""});continue}let he=S.braces>0&&(C.type==="comma"||C.type==="brace"),Yt=U.length&&(C.type==="pipe"||C.type==="paren");if(!ye&&C.type!=="paren"&&!he&&!Yt){ee({type:"star",value:k,output:""});continue}for(;M.slice(0,3)==="/**";){let Xt=r[S.index+4];if(Xt&&Xt!=="/")break;M=M.slice(3),Ve("/**",3)}if(C.type==="bos"&&de()){E.type="globstar",E.value+=k,E.output=P(t),S.output=E.output,S.globstar=!0,Ve(k);continue}if(C.type==="slash"&&C.prev.type!=="bos"&&!Ie&&de()){S.output=S.output.slice(0,-(C.output+E.output).length),C.output=`(?:${C.output}`,E.type="globstar",E.output=P(t)+(t.strictSlashes?")":"|$)"),E.value+=k,S.globstar=!0,S.output+=C.output+E.output,Ve(k);continue}if(C.type==="slash"&&C.prev.type!=="bos"&&M[0]==="/"){let Xt=M[1]!==void 0?"|$":"";S.output=S.output.slice(0,-(C.output+E.output).length),C.output=`(?:${C.output}`,E.type="globstar",E.output=`${P(t)}${f}|${f}${Xt})`,E.value+=k,S.output+=C.output+E.output,S.globstar=!0,Ve(k+V()),ee({type:"slash",value:"/",output:""});continue}if(C.type==="bos"&&M[0]==="/"){E.type="globstar",E.value+=k,E.output=`(?:^|${f}|${P(t)}${f})`,S.output=E.output,S.globstar=!0,Ve(k+V()),ee({type:"slash",value:"/",output:""});continue}S.output=S.output.slice(0,-E.output.length),E.type="globstar",E.output=P(t),E.value+=k,S.output+=E.output,S.globstar=!0,Ve(k);continue}let $e={type:"star",value:k,output:R};if(t.bash===!0){$e.output=".*?",(E.type==="bos"||E.type==="slash")&&($e.output=O+$e.output),ee($e);continue}if(E&&(E.type==="bracket"||E.type==="paren")&&t.regex===!0){$e.output=k,ee($e);continue}(S.index===S.start||E.type==="slash"||E.type==="dot")&&(E.type==="dot"?(S.output+=m,E.output+=m):t.dot===!0?(S.output+=g,E.output+=g):(S.output+=O,E.output+=O),Z()!=="*"&&(S.output+=p,E.output+=p)),ee($e)}for(;S.brackets>0;){if(t.strictBrackets===!0)throw new SyntaxError(ui("closing","]"));S.output=ht.escapeLast(S.output,"["),qr("brackets")}for(;S.parens>0;){if(t.strictBrackets===!0)throw new SyntaxError(ui("closing",")"));S.output=ht.escapeLast(S.output,"("),qr("parens")}for(;S.braces>0;){if(t.strictBrackets===!0)throw new SyntaxError(ui("closing","}"));S.output=ht.escapeLast(S.output,"{"),qr("braces")}if(t.strictSlashes!==!0&&(E.type==="star"||E.type==="bracket")&&ee({type:"maybe_slash",value:"",output:`${f}?`}),S.backtrack===!0){S.output="";for(let M of S.tokens)S.output+=M.output!=null?M.output:M.value,M.suffix&&(S.output+=M.suffix)}return S};Hu.fastpaths=(r,e)=>{let t={...e},n=typeof t.maxLength=="number"?Math.min(_a,t.maxLength):_a,i=r.length;if(i>n)throw new SyntaxError(`Input length: ${i}, exceeds maximum allowed length: ${n}`);r=K_[r]||r;let{DOT_LITERAL:s,SLASH_LITERAL:o,ONE_CHAR:a,DOTS_SLASH:c,NO_DOT:l,NO_DOTS:d,NO_DOTS_SLASH:u,STAR:f,START_ANCHOR:p}=Is.globChars(t.windows),y=t.dot?d:l,h=t.dot?u:l,m=t.capture?"":"?:",g={negated:!1,prefix:""},_=t.bash===!0?".*?":f;t.capture&&(_=`(${_})`);let w=O=>O.noglobstar===!0?_:`(${m}(?:(?!${p}${O.dot?c:s}).)*?)`,x=O=>{switch(O){case"*":return`${y}${a}${_}`;case".*":return`${s}${a}${_}`;case"*.*":return`${y}${_}${s}${a}${_}`;case"*/*":return`${y}${_}${o}${a}${h}${_}`;case"**":return y+w(t);case"**/*":return`(?:${y}${w(t)}${o})?${h}${a}${_}`;case"**/*.*":return`(?:${y}${w(t)}${o})?${h}${_}${s}${a}${_}`;case"**/.*":return`(?:${y}${w(t)}${o})?${s}${a}${_}`;default:{let $=/^(.*?)\.(\w+)$/.exec(O);if(!$)return;let R=x($[1]);return R?R+s+$[2]:void 0}}},v=ht.removePrefix(r,g),P=x(v);return P&&t.strictSlashes!==!0&&(P+=`${o}?`),P};G_.exports=Hu});var Q_=A((RL,X_)=>{"use strict";var tR=H_(),Ku=J_(),Y_=xs(),rR=ks(),nR=r=>r&&typeof r=="object"&&!Array.isArray(r),ke=(r,e,t=!1)=>{if(Array.isArray(r)){let d=r.map(f=>ke(f,e,t));return f=>{for(let p of d){let y=p(f);if(y)return y}return!1}}let n=nR(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?ke.compileRe(r,e):ke.makeRe(r,e,!1,!0),a=o.state;delete o.state;let c=()=>!1;if(i.ignore){let d={...e,ignore:null,onMatch:null,onResult:null};c=ke(i.ignore,d,t)}let l=(d,u=!1)=>{let{isMatch:f,match:p,output:y}=ke.test(d,o,e,{glob:r,posix:s}),h={glob:r,state:a,regex:o,posix:s,input:d,output:y,match:p,isMatch:f};return typeof i.onResult=="function"&&i.onResult(h),f===!1?(h.isMatch=!1,u?h:!1):c(d)?(typeof i.onIgnore=="function"&&i.onIgnore(h),h.isMatch=!1,u?h:!1):(typeof i.onMatch=="function"&&i.onMatch(h),u?h:!0)};return t&&(l.state=a),l};ke.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?Y_.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=ke.matchBase(r,e,t,i):a=e.exec(c)),{isMatch:!!a,match:a,output:c}};ke.matchBase=(r,e,t,n=t&&t.windows)=>(e instanceof RegExp?e:ke.makeRe(e,t)).test(Y_.basename(r,{windows:n}));ke.isMatch=(r,e,t)=>ke(e,t)(r);ke.parse=(r,e)=>Array.isArray(r)?r.map(t=>ke.parse(t,e)):Ku(r,{...e,fastpaths:!1});ke.scan=(r,e)=>tR(r,e);ke.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=ke.toRegex(a,e);return n===!0&&(c.state=r),c};ke.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=Ku.fastpaths(r,e)),i.output||(i=Ku(r,e)),ke.compileRe(i,e,t,n)};ke.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/$^/}};ke.constants=rR;X_.exports=ke});var Wu=A((TL,tb)=>{"use strict";var Z_=Q_(),iR=xs();function eb(r,e,t=!1){return e&&(e.windows===null||e.windows===void 0)&&(e={...e,windows:iR.isWindows()}),Z_(r,e,t)}Object.assign(eb,Z_);tb.exports=eb});var kM={};B0(kM,{default:()=>zc});module.exports=z0(kM);var L=require("obsidian");var N=class extends Error{constructor(t,n,i){super(n);I(this,"code");I(this,"details");this.code=t,this.details=i,this.name="InteropError"}toPortableError(t){return{code:this.code,message:this.message,...this.details===void 0?{}:{details:this.details},...t===void 0?{}:{retryable:t}}}},Ui=class extends Error{constructor(t,n){super(n.message);I(this,"status");I(this,"error");this.status=t,this.error=n,this.name="ActionHandlerError"}};var Ry=fn(Qd(),1),Ty=fn(cu(),1);var lu={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 ax=Ty.default;function Cy(){return Object.fromEntries(Object.entries(lu).map(([r,e])=>[r,structuredClone(e)]))}function du(){let r=new Ry.Ajv2020({allErrors:!0,strict:!1,validateFormats:!0});ax(r);let e=Cy();r.addSchema(e.profile);for(let[t,n]of Object.entries(e))t!=="profile"&&r.addSchema(n);return r}function br(r,e){let t=String(lu[e].$id),n=r.getSchema(t);if(!n)throw new Error(`Canonical interoperability schema is unavailable: ${e}`);return n}function Jr(r){return(r!=null?r:[]).map(e=>{var t;return`${e.instancePath||"/"} ${(t=e.message)!=null?t:e.keyword}`}).join("; ")}function nr(r,e){if(!("value"in r))throw new N("contract_digest_conflict",`${e} must be resolved to an inline JSON Schema before runtime registration.`);return structuredClone(r.value)}function My(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=nr(r.record_schema,"record_schema"),r.binding_schema&&(e.binding_schema=nr(r.binding_schema,"binding_schema"));break;case"event":e.data_schema=nr(r.data_schema,"data_schema"),r.source_schema&&(e.source_schema=nr(r.source_schema,"source_schema"));break;case"action":e.input_schema=nr(r.input_schema,"input_schema"),r.output_schema&&(e.output_schema=nr(r.output_schema,"output_schema")),r.error_schema&&(e.error_schema=nr(r.error_schema,"error_schema")),r.provider_schema&&(e.provider_schema=nr(r.provider_schema,"provider_schema")),r.behavior&&(e.behavior=structuredClone(r.behavior));break}return e}async function ta(r){return ci(My(r))}async function ci(r){return`sha256:${await cx(uu(r))}`}function Ny(r,e){return{data:ai(r,e.data_schema,`${e.id} data_schema`),...e.source_schema?{source:ai(r,e.source_schema,`${e.id} source_schema`)}:{}}}function Ly(r,e){return{input:ai(r,e.input_schema,`${e.id} input_schema`),...e.output_schema?{output:ai(r,e.output_schema,`${e.id} output_schema`)}:{},...e.error_schema?{error:ai(r,e.error_schema,`${e.id} error_schema`)}:{},...e.provider_schema?{provider:ai(r,e.provider_schema,`${e.id} provider_schema`)}:{}}}function ra(r,e,t,n){if(!(!r||r(e)))throw new N(t,`${n} failed JSON Schema validation: ${Jr(r.errors)}`)}function ai(r,e,t){try{return r.compile(nr(e,t))}catch(n){throw new N("contract_digest_conflict",`${t} could not be compiled: ${n instanceof Error?n.message:String(n)}`)}}function uu(r){return r===null||typeof r!="object"?JSON.stringify(r):Array.isArray(r)?`[${r.map(uu).join(",")}]`:`{${Object.entries(r).filter(([,t])=>t!==void 0).sort(([t],[n])=>tn?1:0).map(([t,n])=>`${JSON.stringify(t)}:${uu(n)}`).join(",")}}`}async function cx(r){let e=new TextEncoder().encode(r),t=await globalThis.crypto.subtle.digest("SHA-256",e);return[...new Uint8Array(t)].map(n=>n.toString(16).padStart(2,"0")).join("")}var vr=fn(x_(),1);var Tu={delivery:["ephemeral"],ordering:["none"],cancellation:!0,deadlines:!0,provider_discovery:!0,request_deduplication:!0,cross_process_identity:!1},yO=new Set(["specversion","id","source","type","time","subject","datacontenttype","dataschema","data","mdbaseprofile","mdbasecontractversion","mdbasecontractdigest","mdbaseapplication","mdbaseimplementation","mdbaseimplementationversion","mdbaseinstanceid","correlationid","causationid"]),As=class{constructor(e={}){I(this,"options");I(this,"profileVersion","0.1");I(this,"transport");I(this,"ajv",du());I(this,"contractValidator",br(this.ajv,"contract"));I(this,"eventValidator",br(this.ajv,"event"));I(this,"actionRequestValidator",br(this.ajv,"actionRequest"));I(this,"actionInvocationValidator",br(this.ajv,"actionInvocation"));I(this,"actionOutcomeValidator",br(this.ajv,"actionOutcome"));I(this,"eventSourceDeclarationValidator",br(this.ajv,"eventSourceDeclaration"));I(this,"actionProviderDeclarationValidator",br(this.ajv,"actionProviderDeclaration"));I(this,"contracts",new Map);I(this,"clients",new Map);I(this,"eventSources",new Map);I(this,"actionProviders",new Map);I(this,"subscriptions",new Map);I(this,"activeActions",new Map);I(this,"completedActions",new Map);I(this,"admissionLocks",new Map);I(this,"recentEvents",new Map);I(this,"authorize");I(this,"now");I(this,"idFactory");I(this,"recentEventLimit");I(this,"completedRequestLimit");I(this,"nextSequence",0);I(this,"disposed",!1);var t,n,i,s,o,a,c,l,d,u;this.options=e,this.authorize=(t=e.authorize)!=null?t:(()=>!1),this.now=(n=e.now)!=null?n:(()=>new Date),this.idFactory=(i=e.idFactory)!=null?i:(f=>{var y;this.nextSequence+=1;let p=typeof((y=globalThis.crypto)==null?void 0:y.randomUUID)=="function"?globalThis.crypto.randomUUID():`${this.now().getTime().toString(36)}-${this.nextSequence.toString(36)}`;return`${f}_${p}`}),this.recentEventLimit=Math.max(1,(s=e.recentEventLimit)!=null?s:1e3),this.completedRequestLimit=Math.max(1,(o=e.completedRequestLimit)!=null?o:1e3),this.transport={...Tu,...structuredClone((a=e.transport)!=null?a:{}),delivery:[...(l=(c=e.transport)==null?void 0:c.delivery)!=null?l:Tu.delivery],ordering:[...(u=(d=e.transport)==null?void 0:d.ordering)!=null?u:Tu.ordering]}}connect(e){this.assertActive(),gO(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){var l;let n=this.requireClient(e);if(t.contracts.length===0)throw new N("request_rejected","An event-source declaration must include a contract.");let i=`${e}:${t.declaration_id}`;if(this.eventSources.has(i))throw new N("request_rejected",`Event-source declaration ${t.declaration_id} is already registered.`);let s=new Map;for(let d of t.contracts){let u=await this.prepareEventContract(d.contract),f=P_(d.requirement,u.reference);if(I_(f,u.reference),await this.assertAuthorized({operation:"register_event_source",principal:n.identity,contract:u.reference}),u.sourceValidator&&!u.sourceValidator((l=d.binding)!=null?l:{}))throw new N("request_rejected",`${u.reference.id} source binding is invalid: ${Jr(u.sourceValidator.errors)}`);let p=ma(u.reference);if(s.has(p))throw new N("contract_digest_conflict",`Event contract ${p} is repeated by one declaration.`);s.set(p,{contract:u,requirement:f,...d.binding===void 0?{}:{binding:structuredClone(d.binding)},...d.ordering===void 0?{}:{ordering:[...d.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:d,requirement:u,binding:f,ordering:p})=>({requirement:structuredClone(u),resolved:structuredClone(d.reference),...f===void 0?{}:{binding:f},...p===void 0?{}:{ordering:p}}))},a={...o,declaration_digest:await ci(o)};Xr(this.eventSourceDeclarationValidator,a,"request_rejected","Event-source declaration"),this.commitContracts([...s.values()].map(({contract:d})=>d)),this.eventSources.set(i,{id:i,clientId:e,declaration:structuredClone(a),contracts:new Map([...s.entries()].map(([d,u])=>[d,{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){var y,h,m,g;let n=this.requireClient(e),i=ma(t.contract),s=[...n.sources].map(_=>this.eventSources.get(_)).find(_=>_==null?void 0:_.contracts.has(i));if(!s)throw new N("unknown_contract",`This client has not registered event contract ${t.contract.id} ${t.contract.version}.`);let o=(y=s.contracts.get(i))==null?void 0:y.contract;if(!o)throw new N("unknown_contract",`Event contract ${i} is unavailable.`);if(t.contract.digest&&t.contract.digest!==o.reference.digest)throw new N("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}}),Cu(t.data,"invalid_event_data",`Event ${o.reference.id} data`),ra(o.dataValidator,t.data,"invalid_event_data",`Event ${o.reference.id} data`);let a=(h=t.extensions)!=null?h:{};for(let _ of Object.keys(a))if(yO.has(_))throw new N("request_rejected",`Event extension ${_} is reserved.`);let c={...structuredClone(a),specversion:"1.0",id:(m=t.id)!=null?m:this.idFactory("evt"),source:_O(n.identity),type:o.reference.id,time:(g=t.time)!=null?g:this.now().toISOString(),...t.subject===void 0?{}:{subject:t.subject},datacontenttype:"application/json",dataschema:T_(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}};Xr(this.eventValidator,c,"invalid_event_data","Event envelope"),Mu(this.transport,c),bO(c,o.reference);let l=`${c.source}\0${c.id}`,d=this.recentEvents.get(l);if(d){if(JSON.stringify(d)!==JSON.stringify(c))throw new N("contract_digest_conflict",`Event ${c.source} ${c.id} was reused with different content.`);return{event:structuredClone(d),deliveries:0,duplicate:!0}}this.recentEvents.set(l,structuredClone(c)),R_(this.recentEvents,this.recentEventLimit);let u=[...this.subscriptions.values()].filter(({subscription:_})=>ya(_.contract,o.reference)),f=await Promise.allSettled(u.map(async _=>await this.isAuthorized({operation:"subscribe_event",principal:_.principal,contract:o.reference,...c.subject===void 0?{}:{subject:c.subject}})?(await _.handler(structuredClone(c)),!0):!1)),p=0;for(let _ of f)_.status==="fulfilled"&&_.value?p+=1:_.status==="rejected"&&this.report({severity:"error",code:"event_consumer_failed",message:`An event consumer failed while handling ${c.type}.`,contract:o.reference,cause:_.reason});return{event:structuredClone(c),deliveries:p,duplicate:!1}}async subscribeEvents(e,t,n){let i=this.requireClient(e);Nu(t.contract),$O(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){var u,f,p,y,h,m,g;let n=this.requireClient(e);if(t.handlers.length===0)throw new N("request_rejected","An action-provider declaration must include a handler.");let i=`${e}:${t.declaration_id}`;if(this.actionProviders.has(i))throw new N("request_rejected",`Action-provider declaration ${t.declaration_id} is already registered.`);let s=[],o=new Set;for(let _ of t.handlers){if(o.has(_.handler_id))throw new N("request_rejected",`Handler ${_.handler_id} is repeated.`);o.add(_.handler_id);let w=await this.prepareActionContract(_.contract),x=P_(_.requirement,w.reference);if(I_(x,w.reference),await this.assertAuthorized({operation:"register_action_provider",principal:n.identity,contract:w.reference,provider:n.identity}),w.providerValidator&&!w.providerValidator((u=_.binding)!=null?u:{}))throw new N("request_rejected",`${w.reference.id} provider binding is invalid: ${Jr(w.providerValidator.errors)}`);let v=(p=(f=_.contract.behavior)==null?void 0:f.idempotency)!=null?p:"none";if(((y=_.idempotency)==null?void 0:y.mode)==="request"&&v==="none")throw new N("request_rejected",`${w.reference.id} does not permit request deduplication.`);if(v==="required"&&((h=_.idempotency)==null?void 0:h.mode)!=="request")throw new N("request_rejected",`${w.reference.id} requires a provider with request deduplication.`);let P=(g=(m=_.contract.behavior)==null?void 0:m.cancellation)!=null?g:"none";if(_.cancellation==="cooperative"&&P!=="cooperative")throw new N("request_rejected",`${w.reference.id} does not declare cooperative cancellation.`);s.push({contract:w,declaration:{handler_id:_.handler_id,requirement:x,resolved:structuredClone(w.reference),..._.binding===void 0?{}:{binding:structuredClone(_.binding)},..._.idempotency===void 0?{}:{idempotency:structuredClone(_.idempotency)},..._.cancellation===void 0?{}:{cancellation:_.cancellation},..._.max_concurrency===void 0?{}:{max_concurrency:_.max_concurrency}},handler:_.handler})}let a={kind:"mdbase.action-provider",profile_version:"0.1",declaration_id:t.declaration_id,provider:structuredClone(n.identity),handlers:s.map(({declaration:_})=>structuredClone(_))},c={...a,declaration_digest:await ci(a)};Xr(this.actionProviderDeclarationValidator,c,"request_rejected","Action-provider declaration"),this.commitContracts(s.map(({contract:_})=>_));let l=s.map(({contract:_,declaration:w,handler:x})=>({registrationId:i,clientId:e,declaration:structuredClone(c),handlerDeclaration:structuredClone(w),contract:_,handler:x,active:0}));this.actionProviders.set(i,{id:i,clientId:e,declaration:structuredClone(c),handlers:l}),n.providers.add(i);let d=!0;return{declaration:structuredClone(c),dispose:()=>{d&&(d=!1,this.removeActionProvider(i))}}}async invokeAction(e,t){var a,c,l,d,u,f,p,y,h,m,g,_;let n=this.requireClient(e);Nu(t.contract);let i=(a=t.request_id)!=null?a:this.idFactory("req");this.cleanCompletedActions(),Cu(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:(c=t.created_at)!=null?c:this.now().toISOString(),...t.correlation_id===void 0?{}:{correlation_id:t.correlation_id},...t.causation_id===void 0?{}:{causation_id:t.causation_id},...t.subject===void 0?{}:{subject:t.subject},...t.idempotency_key===void 0?{}:{idempotency_key:t.idempotency_key},...t.deadline===void 0?{}:{deadline:t.deadline},...t.requested_provider===void 0?{}:{requested_provider:structuredClone(t.requested_provider)},input:structuredClone(t.input)};Xr(this.actionRequestValidator,s,"request_rejected","Action request"),Mu(this.transport,s);let o=await this.acquireAdmission(i);try{let w=await ci(wO(s)),x=this.activeActions.get(i);if(x){if(O_(e,i,w,x),((l=x.handler.handlerDeclaration.idempotency)==null?void 0:l.mode)!=="request")throw new N("request_rejected",`Action request ${i} is already active without deduplication.`);return structuredClone(await x.promise)}let v=this.completedActions.get(i);if(v){if(O_(e,i,w,v),!v.reusable)throw new N("request_rejected",`Action request ${i} was already completed without deduplication.`);return structuredClone(v.outcome)}if(s.deadline&&new Date(s.deadline).getTime()<=this.now().getTime())throw new N("deadline_exceeded",`Action request ${i} passed its deadline before admission.`);if(s.deadline&&!this.transport.deadlines)throw new N("unsupported_transport_capability","The active transport cannot enforce action deadlines.");let P=this.resolveActionCandidates(s.contract,s.requested_provider);P.length===0&&this.throwResolutionFailure(s.contract,s.requested_provider);let O=[];for(let V of P)await this.isAuthorized({operation:"invoke_action",principal:n.identity,contract:V.contract.reference,provider:V.declaration.provider,...s.subject===void 0?{}:{subject:s.subject}})&&O.push(V);if(O.length===0)throw new N("unauthorized",`No authorized provider can execute ${s.contract.id}.`);if(O.length>1)throw new N("ambiguous_provider",`Action ${s.contract.id} has ${O.length} eligible providers; select one explicitly.`);let $=O[0];if($.handlerDeclaration.max_concurrency!==void 0&&$.active>=$.handlerDeclaration.max_concurrency)throw new N("request_rejected",`Provider ${$.declaration.provider.implementation} is at capacity.`);if(((u=(d=$.contract.artifact.behavior)==null?void 0:d.idempotency)!=null?u:"none")==="required"&&!s.idempotency_key)throw new N("request_rejected",`${$.contract.reference.id} requires an idempotency key.`);ra($.contract.inputValidator,s.input,"invalid_action_input",`Action ${$.contract.reference.id} input`);let S={operation:"invoke_action",principal:n.identity,contract:$.contract.reference,provider:$.declaration.provider,...s.subject===void 0?{}:{subject:s.subject}},U=await((p=(f=this.options).authorizationContext)==null?void 0:p.call(f,S)),B={kind:"mdbase.action.invocation",profile_version:"0.1",invocation_id:this.idFactory("inv"),attempt_id:this.idFactory("attempt"),request_id:i,contract:structuredClone($.contract.reference),caller:structuredClone(n.identity),provider:structuredClone($.declaration.provider),provider_declaration_digest:$.declaration.declaration_digest,handler_id:$.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},...U===void 0?{}:{authorization_context:U},input:structuredClone(s.input)};Xr(this.actionInvocationValidator,B,"request_rejected","Action invocation"),await((h=(y=this.options).onInvocation)==null?void 0:h.call(y,structuredClone(B)));let T=new AbortController,E;if(B.deadline){let V=Math.max(0,new Date(B.deadline).getTime()-this.now().getTime());E=setTimeout(()=>T.abort(new N("deadline_exceeded",`Action request ${i} exceeded its deadline.`)),V)}$.active+=1;let k=this.executeAction($,B,T).finally(()=>{E!==void 0&&clearTimeout(E),$.active=Math.max(0,$.active-1),this.activeActions.delete(i)});this.activeActions.set(i,{clientId:e,requestId:i,requestDigest:w,handler:$,invocation:B,controller:T,promise:k}),o();let de=await k,Z=(g=(m=$.handlerDeclaration.idempotency)==null?void 0:m.retention_seconds)!=null?g:300;return this.completedActions.set(i,{clientId:e,requestDigest:w,outcome:structuredClone(de),reusable:((_=$.handlerDeclaration.idempotency)==null?void 0:_.mode)==="request",expiresAt:this.now().getTime()+Z*1e3}),R_(this.completedActions,this.completedRequestLimit),structuredClone(de)}finally{o()}}async executeAction(e,t,n){var i;try{let s=await e.handler(structuredClone(t.input),{invocation:structuredClone(t),signal:n.signal});if(n.signal.aborted){let a=n.signal.reason;return a instanceof N&&a.code==="deadline_exceeded"?this.failureOutcome(t,"failed",a.toPortableError()):this.failureOutcome(t,"cancelled",{code:"cancelled",message:`Action request ${t.request_id} was cancelled.`})}Cu(s,"invalid_action_output",`Action ${e.contract.reference.id} output`),ra(e.contract.outputValidator,s,"invalid_action_output",`Action ${e.contract.reference.id} output`);let o={kind:"mdbase.action.outcome",profile_version:"0.1",outcome_id:this.idFactory("outcome"),request_id:t.request_id,invocation_id:t.invocation_id,attempt_id:t.attempt_id,contract:structuredClone(t.contract),provider:structuredClone(t.provider),provider_declaration_digest:t.provider_declaration_digest,status:"succeeded",completed_at:this.now().toISOString(),output:structuredClone(s)};return Xr(this.actionOutcomeValidator,o,"invalid_action_output","Action outcome"),Mu(this.transport,o),o}catch(s){if(s instanceof Ui)return e.contract.errorValidator&&!e.contract.errorValidator((i=s.error.details)!=null?i:{})?this.failureOutcome(t,"failed",{code:"handler_failure",message:`Provider returned invalid declared error details: ${Jr(e.contract.errorValidator.errors)}`}):this.failureOutcome(t,s.status,s.error);if(s instanceof N)return this.failureOutcome(t,s.code==="cancelled"?"cancelled":s.code==="outcome_indeterminate"?"outcome_indeterminate":"failed",s.toPortableError());if(n.signal.aborted||SO(s)){let o=n.signal.reason;return o instanceof N&&o.code==="deadline_exceeded"?this.failureOutcome(t,"failed",o.toPortableError()):this.failureOutcome(t,"cancelled",{code:"cancelled",message:`Action request ${t.request_id} was cancelled.`})}return this.report({severity:"error",code:"action_handler_failed",message:`Provider ${t.provider.implementation} failed ${t.contract.id}.`,principal:t.provider,contract:t.contract,cause:s}),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 Xr(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 N("unauthorized",`Action request ${t} belongs to another caller.`);return a?structuredClone(a.outcome):null}if(o.clientId!==e)throw new N("unauthorized",`Action request ${t} belongs to another caller.`);if(await this.assertAuthorized({operation:"cancel_action",principal:i.identity,contract:o.invocation.contract,provider:o.invocation.provider,...o.invocation.subject===void 0?{}:{subject:o.invocation.subject}}),!this.transport.cancellation)throw new N("unsupported_transport_capability","The active transport cannot deliver cancellation.");if(o.handler.handlerDeclaration.cancellation!=="cooperative")throw new N("cancellation_unsupported",`Provider ${o.invocation.provider.implementation} does not support cancellation.`);return o.controller.abort(new N("cancelled",(n==null?void 0:n.trim())||`Action request ${t} was cancelled.`)),structuredClone(await o.promise)}resolveActionCandidates(e,t){let n=[...this.actionProviders.values()].flatMap(({handlers:s})=>s).filter(({contract:s,declaration:o})=>ya(e,s.reference)&&vO(t,o.provider)),i=(0,vr.maxSatisfying)([...new Set(n.map(({contract:s})=>s.reference.version))],e.version,{includePrerelease:!0});return i?n.filter(({contract:s})=>s.reference.version===i).sort((s,o)=>{var a,c;return s.declaration.provider.application.localeCompare(o.declaration.provider.application)||s.declaration.provider.implementation.localeCompare(o.declaration.provider.implementation)||((a=s.declaration.provider.instance_id)!=null?a:"").localeCompare((c=o.declaration.provider.instance_id)!=null?c:"")||s.handlerDeclaration.handler_id.localeCompare(o.handlerDeclaration.handler_id)}):[]}throwResolutionFailure(e,t){let n=[...this.contracts.values()].filter(i=>i.artifact.contract_type==="action"&&i.reference.id===e.id);throw n.length===0?new N("unknown_contract",`Action contract ${e.id} is unknown.`):n.some(({reference:i})=>ya(e,i))?t?new N("requested_provider_unavailable",`The requested provider is unavailable for ${e.id}.`):new N("no_provider",`No provider is registered for ${e.id}.`):new N("unsupported_contract_version",`No ${e.id} artifact satisfies ${e.version}.`)}async prepareEventContract(e){if(this.assertContractArtifact(e),e.contract_type!=="event")throw new N("unknown_contract",`${e.id} is not an event contract.`);let t={id:e.id,version:e.version,digest:await ta(e)};this.assertNoContractConflict(t);let n=Ny(this.ajv,e);return{artifact:structuredClone(e),reference:t,dataValidator:n.data,...n.source===void 0?{}:{sourceValidator:n.source}}}async prepareActionContract(e){if(this.assertContractArtifact(e),e.contract_type!=="action")throw new N("unknown_contract",`${e.id} is not an action contract.`);let t={id:e.id,version:e.version,digest:await ta(e)};this.assertNoContractConflict(t);let n=Ly(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(Xr(this.contractValidator,e,"contract_digest_conflict",`Contract ${e.id||""}`),!(0,vr.valid)(e.version))throw new N("unsupported_contract_version",`${e.id} version must be exact SemVer.`)}assertNoContractConflict(e){let t=this.contracts.get(ma(e));if(t&&t.reference.digest!==e.digest)throw new N("contract_digest_conflict",`Contract ${e.id} ${e.version} conflicts with the registered artifact.`)}commitContracts(e){var n;let t=new Map;for(let i of e){let s=ma(i.reference),o=(n=t.get(s))!=null?n:this.contracts.get(s);if(o&&o.reference.digest!==i.reference.digest)throw new N("contract_digest_conflict",`Contract ${i.reference.id} ${i.reference.version} conflicts within the registration.`);t.set(s,i)}for(let[i,s]of t)this.contracts.has(i)||this.contracts.set(i,s)}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 N("cancelled","The caller unloaded.")),i.handler.clientId===e&&i.handler.handlerDeclaration.cancellation==="cooperative"&&i.controller.abort(new N("cancelled","The provider unloaded."));this.clients.delete(e),t||this.assertActive()}}removeEventSource(e){var n;let t=this.eventSources.get(e);t&&(this.eventSources.delete(e),(n=this.clients.get(t.clientId))==null||n.sources.delete(e))}removeActionProvider(e){var n;let t=this.actionProviders.get(e);if(t){this.actionProviders.delete(e),(n=this.clients.get(t.clientId))==null||n.providers.delete(e);for(let i of this.activeActions.values())i.handler.registrationId===e&&i.handler.handlerDeclaration.cancellation==="cooperative"&&i.controller.abort(new N("cancelled","The provider unloaded."))}}removeSubscription(e){var n;let t=this.subscriptions.get(e);t&&(this.subscriptions.delete(e),(n=this.clients.get(t.clientId))==null||n.subscriptions.delete(e))}requireClient(e){this.assertActive();let t=this.clients.get(e);if(!t||t.disposed)throw new N("transport_unavailable","Interop client is disposed.");return t}assertActive(){if(this.disposed)throw new N("transport_unavailable","Interop bridge is disposed.")}async assertAuthorized(e){if(!await this.isAuthorized(e))throw new N("unauthorized",`${e.operation} is not authorized.`)}async isAuthorized(e){try{return await this.authorize(structuredClone(e))}catch(t){return this.report({severity:"error",code:"authorization_failed",message:`Authorization failed for ${e.operation}.`,principal:e.principal,cause:t}),!1}}cleanCompletedActions(){let e=this.now().getTime();for(let[t,n]of this.completedActions)n.expiresAt<=e&&this.completedActions.delete(t)}async acquireAdmission(e){var a;let t=(a=this.admissionLocks.get(e))!=null?a:Promise.resolve(),n,i=new Promise(c=>{n=c}),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){var t,n;(n=(t=this.options).onDiagnostic)==null||n.call(t,structuredClone(e))}};function Xr(r,e,t,n){if(!r(e))throw new N(t,`${n} is invalid: ${Jr(r.errors)}`)}function gO(r){for(let[e,t]of Object.entries(r))if(t!==void 0&&(typeof t!="string"||t.length===0||!/^[A-Za-z0-9][A-Za-z0-9._:@/-]*$/u.test(t)))throw new N("request_rejected",`Implementation identity ${e} is invalid.`);if(!(0,vr.valid)(r.version))throw new N("request_rejected","Implementation identity version must be exact SemVer.")}function Nu(r){if(!/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)+$/u.test(r.id))throw new N("unknown_contract",`Contract ID ${r.id} is invalid.`);if(!(0,vr.validRange)(r.version,{includePrerelease:!0}))throw new N("unsupported_contract_version",`Contract requirement ${r.version} is not a SemVer range.`);if(r.digest&&!/^sha256:[0-9a-f]{64}$/u.test(r.digest))throw new N("contract_digest_conflict","Contract digest is invalid.")}function P_(r,e){let t=r!=null?r:{id:e.id,version:e.version,digest:e.digest};return Nu(t),structuredClone(t)}function I_(r,e){if(!ya(r,e))throw new N("unsupported_contract_version",`${e.id} ${e.version} does not satisfy its implementation requirement.`)}function ya(r,e){return r.id===e.id&&(0,vr.satisfies)(e.version,r.version,{includePrerelease:!0})&&(!r.digest||r.digest===e.digest)}function ma(r){return`${r.id}@${r.version}`}function T_(r){return`urn:mdbase:contract:${r.id}:${r.version}:${r.digest}`}function _O(r){return`urn:mdbase:app:${[r.application,r.implementation,...r.instance_id?[r.instance_id]:[]].map(encodeURIComponent).join(":")}`}function bO(r,e){if(r.type!==e.id||r.mdbasecontractversion!==e.version||r.mdbasecontractdigest!==e.digest||r.dataschema!==T_(e))throw new N("contract_digest_conflict","Event contract evidence is inconsistent.")}function wO(r){let{created_at:e,...t}=r;return t}function O_(r,e,t,n){if(n.clientId!==r)throw new N("unauthorized",`Action request ${e} belongs to another caller.`);if(n.requestDigest!==t)throw new N("request_rejected",`Action request ${e} was reused with different content.`)}function Cu(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 N(e,`${t}${o} must be a finite JSON number.`)}if(typeof s!="object")throw new N(e,`${t}${o} is not a JSON value.`);if(n.has(s))throw new N(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 N(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 Mu(r,e){if(r.max_payload_bytes===void 0)return;let t=JSON.stringify(e),n=new TextEncoder().encode(t).byteLength;if(n>r.max_payload_bytes)throw new N("unsupported_transport_capability",`The portable envelope is ${n} bytes; the active transport allows ${r.max_payload_bytes}.`)}function vO(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 $O(r,e){var t,n;if(e){if((t=e.delivery)!=null&&t.some(i=>!r.delivery.includes(i)))throw new N("unsupported_transport_capability","The active transport lacks a required delivery capability.");if((n=e.ordering)!=null&&n.some(i=>!r.ordering.includes(i)))throw new N("unsupported_transport_capability","The active transport lacks a required ordering capability.");for(let i of["cancellation","deadlines","provider_discovery","request_deduplication","cross_process_identity"])if(e[i]===!0&&r[i]!==!0)throw new N("unsupported_transport_capability",`The active transport lacks ${i}.`);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 SO(r){return r instanceof Error&&r.name==="AbortError"}var ga=class{constructor(e,t){this.app=e;this.profileVersion="0.1";this.bridge=new As({authorize:()=>t(),transport:{delivery:["ephemeral"],ordering:["none"],cancellation:!0,deadlines:!0,provider_discovery:!0,request_deduplication:!0,cross_process_identity:!1},onDiagnostic:n=>{var s;(n.severity==="error"?console.error:console.warn)(`[mdbase/interop] ${n.code}: ${n.message}`,(s=n.cause)!=null?s:"")}}),this.transport=this.bridge.describe().transport}connect(e){var s,o;let t=(s=e.manifest)==null?void 0:s.id,n=(o=e.manifest)==null?void 0:o.version;if(!t||!n)throw new Error("Only a loaded Obsidian plugin with manifest identity can connect to mdbase interop.");let 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()}};var me=require("obsidian"),nb=fn(Qd(),1),ib=fn(cu(),1),Xu=fn(Wu(),1),va=class extends Error{constructor(t,n){super(n);this.code=t;this.name="MdbasePathError"}},Lt={spec_version:"0.3.0",name:"My mdbase collection",description:"Typed markdown collection",settings:{types_folder:"_types",explicit_type_keys:["type","types"],default_strict:!1,include_subfolders:!0,exclude:["_types",".obsidian",".git","node_modules",".trash",".mdbase"]}},Os=null;function sR(){return Os||(Os=new nb.Ajv2020({allErrors:!0,strict:!1,allowUnionTypes:!0}),(0,ib.default)(Os),Os)}function re(r){return!!r&&typeof r=="object"&&!Array.isArray(r)}function Qe(r){return JSON.parse(JSON.stringify(r))}function oR(r){if(r===!0)return!0;if(r===!1)return!1;if(r==="warn")return"warn"}function Gu(r){return Array.isArray(r)?`[${r.map(e=>Gu(e)).join(",")}]`:re(r)?`{${Object.keys(r).sort().map(t=>`${JSON.stringify(t)}:${Gu(r[t])}`).join(",")}}`:JSON.stringify(r)}function aR(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 cR(r){let e=new Map,t=new Set,n=i=>{var l,d,u,f;let s=e.get(i);if(s)return s;let o=r.get(i);if(!o)return null;if(t.has(i)){let p={...o,fields:Qe(o.fields)};return e.set(i,p),p}t.add(i);let a=o.extends?n(o.extends):null;t.delete(i);let c={...o,fields:a?{...Qe(a.fields),...Qe(o.fields)}:Qe(o.fields),display_name_key:(l=o.display_name_key)!=null?l:a==null?void 0:a.display_name_key,path_pattern:(d=o.path_pattern)!=null?d:a==null?void 0:a.path_pattern,filename_pattern:(u=o.filename_pattern)!=null?u:a==null?void 0:a.filename_pattern,strict:o.strict!==void 0?o.strict:a==null?void 0:a.strict,match:(f=o.match)!=null?f:a==null?void 0:a.match};return e.set(i,c),c};for(let i of r.keys())n(i);return e}function sb(r){let e=(0,me.normalizePath)(r),t=e.lastIndexOf("/");return t>=0?e.slice(0,t):""}function ob(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 ab(r){return/^[a-z][a-z0-9+.-]*:\/\//i.test(r)}function cb(r,e,t){var c;let n=ob(t);if(!n||ab(n))return null;let i=new Set,s=(0,me.normalizePath)(n);i.add(s),s.endsWith(".md")||i.add(`${s}.md`);let o=sb(e);if(o){let l=(0,me.normalizePath)(`${o}/${n}`);i.add(l),l.endsWith(".md")||i.add(`${l}.md`)}for(let l of i){let d=r.getAbstractFileByPath(l);if(d instanceof me.TFile)return d}let a=n.replace(/\.md$/i,"");return(c=r.getMarkdownFiles().find(l=>l.basename===a))!=null?c:null}function lR(r,e,t){return ab(ob(t))||cb(r,e,t)!==null}function Pt(r){let e=r.match(/^---[ \t]*\r?\n([\s\S]*?)^---[ \t]*(?:\r?\n|$)/m);if(!e)return{hasFrontmatter:!1,frontmatter:{},body:r};try{let t=e[1],n=(0,me.parseYaml)(t);return n==null&&t.trim()!==""?{hasFrontmatter:!0,frontmatter:{},body:r.slice(e[0].length),error:"Frontmatter must be a YAML object"}:n!=null&&!re(n)?{hasFrontmatter:!0,frontmatter:{},body:r.slice(e[0].length),error:"Frontmatter must be a YAML object"}:{hasFrontmatter:!0,frontmatter:n!=null?n:{},body:r.slice(e[0].length)}}catch(t){return{hasFrontmatter:!0,frontmatter:{},body:r.slice(e[0].length),error:t instanceof Error?t.message:String(t)}}}function mt(r,e=""){if(Object.keys(r).length===0)return e;let t=(0,me.stringifyYaml)(r).trimEnd(),n=e.replace(/^\n+/,"");return`--- + deps: ${t}}`};var SA={keyword:"dependencies",type:"object",schemaType:"object",error:er.error,code(r){let[e,t]=EA(r);ym(r,e),gm(r,t)}};function EA({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 ym(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,ys.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,ys.checkReportMissingProp)(r,l)}):(t.if((0,pd._)`${c} && (${(0,ys.checkMissingProp)(r,a,s)})`),(0,ys.reportMissingProp)(r,s),t.else())}}er.validatePropertyDeps=ym;function gm(r,e=r.schema){let{gen:t,data:n,keyword:i,it:s}=r,o=t.name("valid");for(let a in e)(0,$A.alwaysValidSchema)(s,e[a])||(t.if((0,ys.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))}er.validateSchemaDeps=gm;er.default=SA});var bm=E(hd=>{"use strict";Object.defineProperty(hd,"__esModule",{value:!0});var _m=H(),AA=Q(),kA={message:"property name must be valid",params:({params:r})=>(0,_m._)`{propertyName: ${r.propertyName}}`},xA={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:kA,code(r){let{gen:e,schema:t,data:n,it:i}=r;if((0,AA.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,_m.not)(s),()=>{r.error(!0),i.allErrors||e.break()})}),r.ok(s)}};hd.default=xA});var yd=E(md=>{"use strict";Object.defineProperty(md,"__esModule",{value:!0});var Wo=$t(),Mt=H(),PA=vt(),Go=Q(),IA={message:"must NOT have additional properties",params:({params:r})=>(0,Mt._)`{additionalProperty: ${r.additionalProperty}}`},OA={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:IA,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,Go.alwaysValidSchema)(o,t))return;let l=(0,Wo.allSchemaProperties)(n.properties),d=(0,Wo.allSchemaProperties)(n.patternProperties);u(),r.ok((0,Mt._)`${s} === ${PA.default.errors}`);function u(){e.forIn("key",i,m=>{!l.length&&!d.length?y(m):e.if(f(m),()=>y(m))})}function f(m){let g;if(l.length>8){let _=(0,Go.schemaRefOrVal)(o,n.properties,"properties");g=(0,Wo.isOwnProperty)(e,_,m)}else l.length?g=(0,Mt.or)(...l.map(_=>(0,Mt._)`${m} === ${_}`)):g=Mt.nil;return d.length&&(g=(0,Mt.or)(g,...d.map(_=>(0,Mt._)`${(0,Wo.usePattern)(r,_)}.test(${m})`))),(0,Mt.not)(g)}function p(m){e.code((0,Mt._)`delete ${i}[${m}]`)}function y(m){if(c.removeAdditional==="all"||c.removeAdditional&&t===!1){p(m);return}if(t===!1){r.setParams({additionalProperty:m}),r.error(),a||e.break();return}if(typeof t=="object"&&!(0,Go.alwaysValidSchema)(o,t)){let g=e.name("valid");c.removeAdditional==="failing"?(h(m,g,!1),e.if((0,Mt.not)(g),()=>{r.reset(),p(m)})):(h(m,g),a||e.if((0,Mt.not)(g),()=>e.break()))}}function h(m,g,_){let w={keyword:"additionalProperties",dataProp:m,dataPropType:Go.Type.Str};_===!1&&Object.assign(w,{compositeRule:!0,createErrors:!1,allErrors:!1}),r.subschema(w,g)}}};md.default=OA});var $m=E(_d=>{"use strict";Object.defineProperty(_d,"__esModule",{value:!0});var RA=Wn(),wm=$t(),gd=Q(),vm=yd(),TA={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&&vm.default.code(new RA.KeywordCxt(s,vm.default,"additionalProperties"));let o=(0,wm.allSchemaProperties)(t);for(let u of o)s.definedProperties.add(u);s.opts.unevaluated&&o.length&&s.props!==!0&&(s.props=gd.mergeEvaluated.props(e,(0,gd.toHash)(o),s.props));let a=o.filter(u=>!(0,gd.alwaysValidSchema)(s,t[u]));if(a.length===0)return;let c=e.name("valid");for(let u of a)l(u)?d(u):(e.if((0,wm.propertyInData)(e,i,u,s.opts.ownProperties)),d(u),s.allErrors||e.else().var(c,!0),e.endIf()),r.it.definedProperties.add(u),r.ok(c);function l(u){return s.opts.useDefaults&&!s.compositeRule&&t[u].default!==void 0}function d(u){r.subschema({keyword:"properties",schemaProp:u,dataProp:u},c)}}};_d.default=TA});var km=E(bd=>{"use strict";Object.defineProperty(bd,"__esModule",{value:!0});var Sm=$t(),Jo=H(),Em=Q(),Am=Q(),CA={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,Sm.allSchemaProperties)(t),c=a.filter(h=>(0,Em.alwaysValidSchema)(s,t[h]));if(a.length===0||c.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let l=o.strictSchema&&!o.allowMatchingProperties&&i.properties,d=e.name("valid");s.props!==!0&&!(s.props instanceof Jo.Name)&&(s.props=(0,Am.evaluatedPropsToName)(e,s.props));let{props:u}=s;f();function f(){for(let h of a)l&&p(h),s.allErrors?y(h):(e.var(d,!0),y(h),e.if(d))}function p(h){for(let m in l)new RegExp(h).test(m)&&(0,Em.checkStrictMode)(s,`property ${m} matches pattern ${h} (use allowMatchingProperties)`)}function y(h){e.forIn("key",n,m=>{e.if((0,Jo._)`${(0,Sm.usePattern)(r,h)}.test(${m})`,()=>{let g=c.includes(h);g||r.subschema({keyword:"patternProperties",schemaProp:h,dataProp:m,dataPropType:Am.Type.Str},d),s.opts.unevaluated&&u!==!0?e.assign((0,Jo._)`${u}[${m}]`,!0):!g&&!s.allErrors&&e.if((0,Jo.not)(d),()=>e.break())})})}}};bd.default=CA});var xm=E(wd=>{"use strict";Object.defineProperty(wd,"__esModule",{value:!0});var MA=Q(),NA={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(r){let{gen:e,schema:t,it:n}=r;if((0,MA.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"}};wd.default=NA});var Pm=E(vd=>{"use strict";Object.defineProperty(vd,"__esModule",{value:!0});var LA=$t(),jA={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:LA.validateUnion,error:{message:"must match a schema in anyOf"}};vd.default=jA});var Im=E($d=>{"use strict";Object.defineProperty($d,"__esModule",{value:!0});var Yo=H(),DA=Q(),qA={message:"must match exactly one schema in oneOf",params:({params:r})=>(0,Yo._)`{passingSchemas: ${r.passing}}`},FA={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:qA,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((d,u)=>{let f;(0,DA.alwaysValidSchema)(i,d)?e.var(c,!0):f=r.subschema({keyword:"oneOf",schemaProp:u,compositeRule:!0},c),u>0&&e.if((0,Yo._)`${c} && ${o}`).assign(o,!1).assign(a,(0,Yo._)`[${a}, ${u}]`).else(),e.if(c,()=>{e.assign(o,!0),e.assign(a,u),f&&r.mergeEvaluated(f,Yo.Name)})})}}};$d.default=FA});var Om=E(Sd=>{"use strict";Object.defineProperty(Sd,"__esModule",{value:!0});var VA=Q(),UA={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,VA.alwaysValidSchema)(n,s))return;let a=r.subschema({keyword:"allOf",schemaProp:o},i);r.ok(i),r.mergeEvaluated(a)})}};Sd.default=UA});var Cm=E(Ed=>{"use strict";Object.defineProperty(Ed,"__esModule",{value:!0});var Xo=H(),Tm=Q(),BA={message:({params:r})=>(0,Xo.str)`must match "${r.ifClause}" schema`,params:({params:r})=>(0,Xo._)`{failingKeyword: ${r.ifClause}}`},zA={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:BA,code(r){let{gen:e,parentSchema:t,it:n}=r;t.then===void 0&&t.else===void 0&&(0,Tm.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let i=Rm(n,"then"),s=Rm(n,"else");if(!i&&!s)return;let o=e.let("valid",!0),a=e.name("_valid");if(c(),r.reset(),i&&s){let d=e.let("ifClause");r.setParams({ifClause:d}),e.if(a,l("then",d),l("else",d))}else i?e.if(a,l("then")):e.if((0,Xo.not)(a),l("else"));r.pass(o,()=>r.error(!0));function c(){let d=r.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);r.mergeEvaluated(d)}function l(d,u){return()=>{let f=r.subschema({keyword:d},a);e.assign(o,a),r.mergeValidEvaluated(f,o),u?e.assign(u,(0,Xo._)`${d}`):r.setParams({ifClause:d})}}}};function Rm(r,e){let t=r.schema[e];return t!==void 0&&!(0,Tm.alwaysValidSchema)(r,t)}Ed.default=zA});var Mm=E(Ad=>{"use strict";Object.defineProperty(Ad,"__esModule",{value:!0});var HA=Q(),KA={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:r,parentSchema:e,it:t}){e.if===void 0&&(0,HA.checkStrictMode)(t,`"${r}" without "if" is ignored`)}};Ad.default=KA});var xd=E(kd=>{"use strict";Object.defineProperty(kd,"__esModule",{value:!0});var WA=cd(),GA=fm(),JA=ld(),YA=hm(),XA=mm(),QA=Ko(),ZA=bm(),e1=yd(),t1=$m(),r1=km(),n1=xm(),i1=Pm(),s1=Im(),o1=Om(),a1=Cm(),c1=Mm();function l1(r=!1){let e=[n1.default,i1.default,s1.default,o1.default,a1.default,c1.default,ZA.default,e1.default,QA.default,t1.default,r1.default];return r?e.push(GA.default,YA.default):e.push(WA.default,JA.default),e.push(XA.default),e}kd.default=l1});var Id=E(gs=>{"use strict";Object.defineProperty(gs,"__esModule",{value:!0});gs.dynamicAnchor=void 0;var Pd=H(),d1=vt(),Nm=ns(),u1=Fo(),f1={keyword:"$dynamicAnchor",schemaType:"string",code:r=>Lm(r,r.schema)};function Lm(r,e){let{gen:t,it:n}=r;n.schemaEnv.root.dynamicAnchors[e]=!0;let i=(0,Pd._)`${d1.default.dynamicAnchors}${(0,Pd.getProperty)(e)}`,s=n.errSchemaPath==="#"?n.validateName:p1(r);t.if((0,Pd._)`!${i}`,()=>t.assign(i,s))}gs.dynamicAnchor=Lm;function p1(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 Nm.SchemaEnv({schema:t,schemaId:c,root:i,baseId:s,localRefs:o,meta:a});return Nm.compileSchema.call(n,l),(0,u1.getValidate)(r,l)}gs.default=f1});var Od=E(_s=>{"use strict";Object.defineProperty(_s,"__esModule",{value:!0});_s.dynamicRef=void 0;var jm=H(),h1=vt(),Dm=Fo(),m1={keyword:"$dynamicRef",schemaType:"string",code:r=>qm(r,r.schema)};function qm(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,jm._)`${h1.default.dynamicAnchors}${(0,jm.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,Dm.callRef)(r,c),t.let(l,!0)}):()=>(0,Dm.callRef)(r,c)}}_s.dynamicRef=qm;_s.default=m1});var Fm=E(Rd=>{"use strict";Object.defineProperty(Rd,"__esModule",{value:!0});var y1=Id(),g1=Q(),_1={keyword:"$recursiveAnchor",schemaType:"boolean",code(r){r.schema?(0,y1.dynamicAnchor)(r,""):(0,g1.checkStrictMode)(r.it,"$recursiveAnchor: false is ignored")}};Rd.default=_1});var Vm=E(Td=>{"use strict";Object.defineProperty(Td,"__esModule",{value:!0});var b1=Od(),w1={keyword:"$recursiveRef",schemaType:"string",code:r=>(0,b1.dynamicRef)(r,r.schema)};Td.default=w1});var Um=E(Cd=>{"use strict";Object.defineProperty(Cd,"__esModule",{value:!0});var v1=Id(),$1=Od(),S1=Fm(),E1=Vm(),A1=[v1.default,$1.default,S1.default,E1.default];Cd.default=A1});var zm=E(Md=>{"use strict";Object.defineProperty(Md,"__esModule",{value:!0});var Bm=Ko(),k1={keyword:"dependentRequired",type:"object",schemaType:"object",error:Bm.error,code:r=>(0,Bm.validatePropertyDeps)(r)};Md.default=k1});var Hm=E(Nd=>{"use strict";Object.defineProperty(Nd,"__esModule",{value:!0});var x1=Ko(),P1={keyword:"dependentSchemas",type:"object",schemaType:"object",code:r=>(0,x1.validateSchemaDeps)(r)};Nd.default=P1});var Km=E(Ld=>{"use strict";Object.defineProperty(Ld,"__esModule",{value:!0});var I1=Q(),O1={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword:r,parentSchema:e,it:t}){e.contains===void 0&&(0,I1.checkStrictMode)(t,`"${r}" without "contains" is ignored`)}};Ld.default=O1});var Wm=E(jd=>{"use strict";Object.defineProperty(jd,"__esModule",{value:!0});var R1=zm(),T1=Hm(),C1=Km(),M1=[R1.default,T1.default,C1.default];jd.default=M1});var Jm=E(Dd=>{"use strict";Object.defineProperty(Dd,"__esModule",{value:!0});var Wr=H(),Gm=Q(),N1=vt(),L1={message:"must NOT have unevaluated properties",params:({params:r})=>(0,Wr._)`{unevaluatedProperty: ${r.unevaluatedProperty}}`},j1={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 Wr.Name?e.if((0,Wr._)`${a} !== true`,()=>e.forIn("key",n,u=>e.if(l(a,u),()=>c(u)))):a!==!0&&e.forIn("key",n,u=>a===void 0?c(u):e.if(d(a,u),()=>c(u))),s.props=!0,r.ok((0,Wr._)`${i} === ${N1.default.errors}`);function c(u){if(t===!1){r.setParams({unevaluatedProperty:u}),r.error(),o||e.break();return}if(!(0,Gm.alwaysValidSchema)(s,t)){let f=e.name("valid");r.subschema({keyword:"unevaluatedProperties",dataProp:u,dataPropType:Gm.Type.Str},f),o||e.if((0,Wr.not)(f),()=>e.break())}}function l(u,f){return(0,Wr._)`!${u} || !${u}[${f}]`}function d(u,f){let p=[];for(let y in u)u[y]===!0&&p.push((0,Wr._)`${f} !== ${y}`);return(0,Wr.and)(...p)}}};Dd.default=j1});var Xm=E(qd=>{"use strict";Object.defineProperty(qd,"__esModule",{value:!0});var En=H(),Ym=Q(),D1={message:({params:{len:r}})=>(0,En.str)`must NOT have more than ${r} items`,params:({params:{len:r}})=>(0,En._)`{limit: ${r}}`},q1={keyword:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error:D1,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,En._)`${n}.length`);if(t===!1)r.setParams({len:s}),r.fail((0,En._)`${o} > ${s}`);else if(typeof t=="object"&&!(0,Ym.alwaysValidSchema)(i,t)){let c=e.var("valid",(0,En._)`${o} <= ${s}`);e.if((0,En.not)(c),()=>a(c,s)),r.ok(c)}i.items=!0;function a(c,l){e.forRange("i",l,o,d=>{r.subschema({keyword:"unevaluatedItems",dataProp:d,dataPropType:Ym.Type.Num},c),i.allErrors||e.if((0,En.not)(c),()=>e.break())})}}};qd.default=q1});var Qm=E(Fd=>{"use strict";Object.defineProperty(Fd,"__esModule",{value:!0});var F1=Jm(),V1=Xm(),U1=[F1.default,V1.default];Fd.default=U1});var Zm=E(Vd=>{"use strict";Object.defineProperty(Vd,"__esModule",{value:!0});var Ae=H(),B1={message:({schemaCode:r})=>(0,Ae.str)`must match format "${r}"`,params:({schemaCode:r})=>(0,Ae._)`{format: ${r}}`},z1={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:B1,code(r,e){let{gen:t,data:n,$data:i,schema:s,schemaCode:o,it:a}=r,{opts:c,errSchemaPath:l,schemaEnv:d,self:u}=a;if(!c.validateFormats)return;i?f():p();function f(){let y=t.scopeValue("formats",{ref:u.formats,code:c.code.formats}),h=t.const("fDef",(0,Ae._)`${y}[${o}]`),m=t.let("fType"),g=t.let("format");t.if((0,Ae._)`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>t.assign(m,(0,Ae._)`${h}.type || "string"`).assign(g,(0,Ae._)`${h}.validate`),()=>t.assign(m,(0,Ae._)`"string"`).assign(g,h)),r.fail$data((0,Ae.or)(_(),w()));function _(){return c.strictSchema===!1?Ae.nil:(0,Ae._)`${o} && !${g}`}function w(){let x=d.$async?(0,Ae._)`(${h}.async ? await ${g}(${n}) : ${g}(${n}))`:(0,Ae._)`${g}(${n})`,v=(0,Ae._)`(typeof ${g} == "function" ? ${x} : ${g}.test(${n}))`;return(0,Ae._)`${g} && ${g} !== true && ${m} === ${e} && !${v}`}}function p(){let y=u.formats[s];if(!y){_();return}if(y===!0)return;let[h,m,g]=w(y);h===e&&r.pass(x());function _(){if(c.strictSchema===!1){u.logger.warn(v());return}throw new Error(v());function v(){return`unknown format "${s}" ignored in schema at path "${l}"`}}function w(v){let P=v instanceof RegExp?(0,Ae.regexpCode)(v):c.code.formats?(0,Ae._)`${c.code.formats}${(0,Ae.getProperty)(s)}`:void 0,O=t.scopeValue("formats",{key:s,ref:v,code:P});return typeof v=="object"&&!(v instanceof RegExp)?[v.type||"string",v.validate,(0,Ae._)`${O}.validate`]:["string",v,O]}function x(){if(typeof y=="object"&&!(y instanceof RegExp)&&y.async){if(!d.$async)throw new Error("async format in sync schema");return(0,Ae._)`await ${g}(${n})`}return typeof m=="function"?(0,Ae._)`${g}(${n})`:(0,Ae._)`${g}.test(${n})`}}}};Vd.default=z1});var Bd=E(Ud=>{"use strict";Object.defineProperty(Ud,"__esModule",{value:!0});var H1=Zm(),K1=[H1.default];Ud.default=K1});var zd=E(Zn=>{"use strict";Object.defineProperty(Zn,"__esModule",{value:!0});Zn.contentVocabulary=Zn.metadataVocabulary=void 0;Zn.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Zn.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var ty=E(Hd=>{"use strict";Object.defineProperty(Hd,"__esModule",{value:!0});var W1=zl(),G1=od(),J1=xd(),Y1=Um(),X1=Wm(),Q1=Qm(),Z1=Bd(),ey=zd(),ek=[Y1.default,W1.default,G1.default,(0,J1.default)(!0),Z1.default,ey.metadataVocabulary,ey.contentVocabulary,X1.default,Q1.default];Hd.default=ek});var ny=E(Qo=>{"use strict";Object.defineProperty(Qo,"__esModule",{value:!0});Qo.DiscrError=void 0;var ry;(function(r){r.Tag="tag",r.Mapping="mapping"})(ry||(Qo.DiscrError=ry={}))});var Gd=E(Wd=>{"use strict";Object.defineProperty(Wd,"__esModule",{value:!0});var ei=H(),Kd=ny(),iy=ns(),tk=Gn(),rk=Q(),nk={message:({params:{discrError:r,tagName:e}})=>r===Kd.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:r,tag:e,tagName:t}})=>(0,ei._)`{error: ${r}, tag: ${t}, tagValue: ${e}}`},ik={keyword:"discriminator",type:"object",schemaType:"object",error:nk,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,ei._)`${t}${(0,ei.getProperty)(a)}`);e.if((0,ei._)`typeof ${l} == "string"`,()=>d(),()=>r.error(!1,{discrError:Kd.DiscrError.Tag,tag:l,tagName:a})),r.ok(c);function d(){let p=f();e.if(!1);for(let y in p)e.elseIf((0,ei._)`${l} === ${y}`),e.assign(c,u(p[y]));e.else(),r.error(!1,{discrError:Kd.DiscrError.Mapping,tag:l,tagName:a}),e.endIf()}function u(p){let y=e.name("valid"),h=r.subschema({keyword:"oneOf",schemaProp:p},y);return r.mergeEvaluated(h,ei.Name),y}function f(){var p;let y={},h=g(i),m=!0;for(let x=0;x{sk.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 oy=E((t2,ok)=>{ok.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 ay=E((r2,ak)=>{ak.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 cy=E((n2,ck)=>{ck.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 ly=E((i2,lk)=>{lk.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 dy=E((s2,dk)=>{dk.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 uy=E((o2,uk)=>{uk.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 fy=E((a2,fk)=>{fk.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 py=E(Jd=>{"use strict";Object.defineProperty(Jd,"__esModule",{value:!0});var pk=sy(),hk=oy(),mk=ay(),yk=cy(),gk=ly(),_k=dy(),bk=uy(),wk=fy(),vk=["/properties"];function $k(r){return[pk,hk,mk,yk,gk,e(this,_k),bk,e(this,wk)].forEach(t=>this.addMetaSchema(t,void 0,!1)),this;function e(t,n){return r?t.$dataMetaSchema(n,vk):n}}Jd.default=$k});var Qd=E((_e,Xd)=>{"use strict";Object.defineProperty(_e,"__esModule",{value:!0});_e.MissingRefError=_e.ValidationError=_e.CodeGen=_e.Name=_e.nil=_e.stringify=_e.str=_e._=_e.KeywordCxt=_e.Ajv2020=void 0;var Sk=Vl(),Ek=ty(),Ak=Gd(),kk=py(),Yd="https://json-schema.org/draft/2020-12/schema",ti=class extends Sk.default{constructor(e={}){super({...e,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){super._addVocabularies(),Ek.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(Ak.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data:e,meta:t}=this.opts;t&&(kk.default.call(this,e),this.refs["http://json-schema.org/schema"]=Yd)}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Yd)?Yd:void 0)}};_e.Ajv2020=ti;Xd.exports=_e=ti;Xd.exports.Ajv2020=ti;Object.defineProperty(_e,"__esModule",{value:!0});_e.default=ti;var xk=Wn();Object.defineProperty(_e,"KeywordCxt",{enumerable:!0,get:function(){return xk.KeywordCxt}});var ri=H();Object.defineProperty(_e,"_",{enumerable:!0,get:function(){return ri._}});Object.defineProperty(_e,"str",{enumerable:!0,get:function(){return ri.str}});Object.defineProperty(_e,"stringify",{enumerable:!0,get:function(){return ri.stringify}});Object.defineProperty(_e,"nil",{enumerable:!0,get:function(){return ri.nil}});Object.defineProperty(_e,"Name",{enumerable:!0,get:function(){return ri.Name}});Object.defineProperty(_e,"CodeGen",{enumerable:!0,get:function(){return ri.CodeGen}});var Pk=rs();Object.defineProperty(_e,"ValidationError",{enumerable:!0,get:function(){return Pk.default}});var Ik=Gn();Object.defineProperty(_e,"MissingRefError",{enumerable:!0,get:function(){return Ik.default}})});var vy=E(rr=>{"use strict";Object.defineProperty(rr,"__esModule",{value:!0});rr.formatNames=rr.fastFormats=rr.fullFormats=void 0;function tr(r,e){return{validate:r,compare:e}}rr.fullFormats={date:tr(gy,ru),time:tr(eu(!0),nu),"date-time":tr(hy(!0),by),"iso-time":tr(eu(),_y),"iso-date-time":tr(hy(),wy),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:Nk,"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:Uk,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:Lk,int32:{type:"number",validate:qk},int64:{type:"number",validate:Fk},float:{type:"number",validate:yy},double:{type:"number",validate:yy},password:!0,binary:!0};rr.fastFormats={...rr.fullFormats,date:tr(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,ru),time:tr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,nu),"date-time":tr(/^\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,by),"iso-time":tr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,_y),"iso-date-time":tr(/^\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,wy),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};rr.formatNames=Object.keys(rr.fullFormats);function Ok(r){return r%4===0&&(r%100!==0||r%400===0)}var Rk=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,Tk=[0,31,28,31,30,31,30,31,31,30,31,30,31];function gy(r){let e=Rk.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&&Ok(t)?29:Tk[n])}function ru(r,e){if(r&&e)return r>e?1:r23||d>59||r&&!a)return!1;if(i<=23&&s<=59&&o<60)return!0;let u=s-d*c,f=i-l*c-(u<0?1:0);return(f===23||f===-1)&&(u===59||u===-1)&&o<61}}function nu(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 _y(r,e){if(!(r&&e))return;let t=Zd.exec(r),n=Zd.exec(e);if(t&&n)return r=t[1]+t[2]+t[3],e=n[1]+n[2]+n[3],r>e?1:r=jk}function Fk(r){return Number.isInteger(r)}function yy(){return!0}var Vk=/[^\\]\\Z/;function Uk(r){if(Vk.test(r))return!1;try{return new RegExp(r),!0}catch(e){return!1}}});var Sy=E(iu=>{"use strict";Object.defineProperty(iu,"__esModule",{value:!0});var Bk=zl(),zk=od(),Hk=xd(),Kk=Bd(),$y=zd(),Wk=[Bk.default,zk.default,(0,Hk.default)(),Kk.default,$y.metadataVocabulary,$y.contentVocabulary];iu.default=Wk});var Ey=E((u2,Gk)=>{Gk.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 ky=E((be,su)=>{"use strict";Object.defineProperty(be,"__esModule",{value:!0});be.MissingRefError=be.ValidationError=be.CodeGen=be.Name=be.nil=be.stringify=be.str=be._=be.KeywordCxt=be.Ajv=void 0;var Jk=Vl(),Yk=Sy(),Xk=Gd(),Ay=Ey(),Qk=["/properties"],Zo="http://json-schema.org/draft-07/schema",ni=class extends Jk.default{_addVocabularies(){super._addVocabularies(),Yk.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(Xk.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(Ay,Qk):Ay;this.addMetaSchema(e,Zo,!1),this.refs["http://json-schema.org/schema"]=Zo}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Zo)?Zo:void 0)}};be.Ajv=ni;su.exports=be=ni;su.exports.Ajv=ni;Object.defineProperty(be,"__esModule",{value:!0});be.default=ni;var Zk=Wn();Object.defineProperty(be,"KeywordCxt",{enumerable:!0,get:function(){return Zk.KeywordCxt}});var ii=H();Object.defineProperty(be,"_",{enumerable:!0,get:function(){return ii._}});Object.defineProperty(be,"str",{enumerable:!0,get:function(){return ii.str}});Object.defineProperty(be,"stringify",{enumerable:!0,get:function(){return ii.stringify}});Object.defineProperty(be,"nil",{enumerable:!0,get:function(){return ii.nil}});Object.defineProperty(be,"Name",{enumerable:!0,get:function(){return ii.Name}});Object.defineProperty(be,"CodeGen",{enumerable:!0,get:function(){return ii.CodeGen}});var ex=rs();Object.defineProperty(be,"ValidationError",{enumerable:!0,get:function(){return ex.default}});var tx=Gn();Object.defineProperty(be,"MissingRefError",{enumerable:!0,get:function(){return tx.default}})});var xy=E(si=>{"use strict";Object.defineProperty(si,"__esModule",{value:!0});si.formatLimitDefinition=void 0;var rx=ky(),Nt=H(),Gr=Nt.operators,ea={formatMaximum:{okStr:"<=",ok:Gr.LTE,fail:Gr.GT},formatMinimum:{okStr:">=",ok:Gr.GTE,fail:Gr.LT},formatExclusiveMaximum:{okStr:"<",ok:Gr.LT,fail:Gr.GTE},formatExclusiveMinimum:{okStr:">",ok:Gr.GT,fail:Gr.LTE}},nx={message:({keyword:r,schemaCode:e})=>(0,Nt.str)`should be ${ea[r].okStr} ${e}`,params:({keyword:r,schemaCode:e})=>(0,Nt._)`{comparison: ${ea[r].okStr}, limit: ${e}}`};si.formatLimitDefinition={keyword:Object.keys(ea),type:"string",schemaType:"string",$data:!0,error:nx,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 rx.KeywordCxt(s,a.RULES.all.format.definition,"format");c.$data?l():d();function l(){let f=e.scopeValue("formats",{ref:a.formats,code:o.code.formats}),p=e.const("fmt",(0,Nt._)`${f}[${c.schemaCode}]`);r.fail$data((0,Nt.or)((0,Nt._)`typeof ${p} != "object"`,(0,Nt._)`${p} instanceof RegExp`,(0,Nt._)`typeof ${p}.compare != "function"`,u(p)))}function d(){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 y=e.scopeValue("formats",{key:f,ref:p,code:o.code.formats?(0,Nt._)`${o.code.formats}${(0,Nt.getProperty)(f)}`:void 0});r.fail$data(u(y))}function u(f){return(0,Nt._)`${f}.compare(${t}, ${n}) ${ea[i].fail} 0`}},dependencies:["format"]};var ix=r=>(r.addKeyword(si.formatLimitDefinition),r);si.default=ix});var cu=E((bs,Oy)=>{"use strict";Object.defineProperty(bs,"__esModule",{value:!0});var oi=vy(),sx=xy(),ou=H(),Py=new ou.Name("fullFormats"),ox=new ou.Name("fastFormats"),au=(r,e={keywords:!0})=>{if(Array.isArray(e))return Iy(r,e,oi.fullFormats,Py),r;let[t,n]=e.mode==="fast"?[oi.fastFormats,ox]:[oi.fullFormats,Py],i=e.formats||oi.formatNames;return Iy(r,i,t,n),e.keywords&&(0,sx.default)(r),r};au.get=(r,e="full")=>{let n=(e==="fast"?oi.fastFormats:oi.fullFormats)[r];if(!n)throw new Error(`Unknown format "${r}"`);return n};function Iy(r,e,t,n){var i,s;(i=(s=r.opts.code).formats)!==null&&i!==void 0||(s.formats=(0,ou._)`require("ajv-formats/dist/formats").${n}`);for(let o of e)r.addFormat(o,t[o])}Oy.exports=bs=au;Object.defineProperty(bs,"__esModule",{value:!0});bs.default=au});var li=E((b2,jy)=>{"use strict";var lx="2.0.0",dx=Number.MAX_SAFE_INTEGER||9007199254740991,ux=16,fx=250,px=["major","premajor","minor","preminor","patch","prepatch","prerelease"];jy.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:ux,MAX_SAFE_BUILD_LENGTH:fx,MAX_SAFE_INTEGER:dx,RELEASE_TYPES:px,SEMVER_SPEC_VERSION:lx,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var ws=E((w2,Dy)=>{"use strict";var hx=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...r)=>console.error("SEMVER",...r):()=>{};Dy.exports=hx});var di=E((ir,qy)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:fu,MAX_SAFE_BUILD_LENGTH:mx,MAX_LENGTH:yx}=li(),gx=ws();ir=qy.exports={};var _x=ir.re=[],bx=ir.safeRe=[],D=ir.src=[],wx=ir.safeSrc=[],q=ir.t={},vx=0,pu="[a-zA-Z0-9-]",$x=[["\\s",1],["\\d",yx],[pu,mx]],Sx=r=>{for(let[e,t]of $x)r=r.split(`${e}*`).join(`${e}{0,${t}}`).split(`${e}+`).join(`${e}{1,${t}}`);return r},K=(r,e,t)=>{let n=Sx(e),i=vx++;gx(r,i,e),q[r]=i,D[i]=e,wx[i]=n,_x[i]=new RegExp(e,t?"g":void 0),bx[i]=new RegExp(n,t?"g":void 0)};K("NUMERICIDENTIFIER","0|[1-9]\\d*");K("NUMERICIDENTIFIERLOOSE","\\d+");K("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${pu}*`);K("MAINVERSION",`(${D[q.NUMERICIDENTIFIER]})\\.(${D[q.NUMERICIDENTIFIER]})\\.(${D[q.NUMERICIDENTIFIER]})`);K("MAINVERSIONLOOSE",`(${D[q.NUMERICIDENTIFIERLOOSE]})\\.(${D[q.NUMERICIDENTIFIERLOOSE]})\\.(${D[q.NUMERICIDENTIFIERLOOSE]})`);K("PRERELEASEIDENTIFIER",`(?:${D[q.NONNUMERICIDENTIFIER]}|${D[q.NUMERICIDENTIFIER]})`);K("PRERELEASEIDENTIFIERLOOSE",`(?:${D[q.NONNUMERICIDENTIFIER]}|${D[q.NUMERICIDENTIFIERLOOSE]})`);K("PRERELEASE",`(?:-(${D[q.PRERELEASEIDENTIFIER]}(?:\\.${D[q.PRERELEASEIDENTIFIER]})*))`);K("PRERELEASELOOSE",`(?:-?(${D[q.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${D[q.PRERELEASEIDENTIFIERLOOSE]})*))`);K("BUILDIDENTIFIER",`${pu}+`);K("BUILD",`(?:\\+(${D[q.BUILDIDENTIFIER]}(?:\\.${D[q.BUILDIDENTIFIER]})*))`);K("FULLPLAIN",`v?${D[q.MAINVERSION]}${D[q.PRERELEASE]}?${D[q.BUILD]}?`);K("FULL",`^${D[q.FULLPLAIN]}$`);K("LOOSEPLAIN",`[v=\\s]*${D[q.MAINVERSIONLOOSE]}${D[q.PRERELEASELOOSE]}?${D[q.BUILD]}?`);K("LOOSE",`^${D[q.LOOSEPLAIN]}$`);K("GTLT","((?:<|>)?=?)");K("XRANGEIDENTIFIERLOOSE",`${D[q.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);K("XRANGEIDENTIFIER",`${D[q.NUMERICIDENTIFIER]}|x|X|\\*`);K("XRANGEPLAIN",`[v=\\s]*(${D[q.XRANGEIDENTIFIER]})(?:\\.(${D[q.XRANGEIDENTIFIER]})(?:\\.(${D[q.XRANGEIDENTIFIER]})(?:${D[q.PRERELEASE]})?${D[q.BUILD]}?)?)?`);K("XRANGEPLAINLOOSE",`[v=\\s]*(${D[q.XRANGEIDENTIFIERLOOSE]})(?:\\.(${D[q.XRANGEIDENTIFIERLOOSE]})(?:\\.(${D[q.XRANGEIDENTIFIERLOOSE]})(?:${D[q.PRERELEASELOOSE]})?${D[q.BUILD]}?)?)?`);K("XRANGE",`^${D[q.GTLT]}\\s*${D[q.XRANGEPLAIN]}$`);K("XRANGELOOSE",`^${D[q.GTLT]}\\s*${D[q.XRANGEPLAINLOOSE]}$`);K("COERCEPLAIN",`(^|[^\\d])(\\d{1,${fu}})(?:\\.(\\d{1,${fu}}))?(?:\\.(\\d{1,${fu}}))?`);K("COERCE",`${D[q.COERCEPLAIN]}(?:$|[^\\d])`);K("COERCEFULL",D[q.COERCEPLAIN]+`(?:${D[q.PRERELEASE]})?(?:${D[q.BUILD]})?(?:$|[^\\d])`);K("COERCERTL",D[q.COERCE],!0);K("COERCERTLFULL",D[q.COERCEFULL],!0);K("LONETILDE","(?:~>?)");K("TILDETRIM",`(\\s*)${D[q.LONETILDE]}\\s+`,!0);ir.tildeTrimReplace="$1~";K("TILDE",`^${D[q.LONETILDE]}${D[q.XRANGEPLAIN]}$`);K("TILDELOOSE",`^${D[q.LONETILDE]}${D[q.XRANGEPLAINLOOSE]}$`);K("LONECARET","(?:\\^)");K("CARETTRIM",`(\\s*)${D[q.LONECARET]}\\s+`,!0);ir.caretTrimReplace="$1^";K("CARET",`^${D[q.LONECARET]}${D[q.XRANGEPLAIN]}$`);K("CARETLOOSE",`^${D[q.LONECARET]}${D[q.XRANGEPLAINLOOSE]}$`);K("COMPARATORLOOSE",`^${D[q.GTLT]}\\s*(${D[q.LOOSEPLAIN]})$|^$`);K("COMPARATOR",`^${D[q.GTLT]}\\s*(${D[q.FULLPLAIN]})$|^$`);K("COMPARATORTRIM",`(\\s*)${D[q.GTLT]}\\s*(${D[q.LOOSEPLAIN]}|${D[q.XRANGEPLAIN]})`,!0);ir.comparatorTrimReplace="$1$2$3";K("HYPHENRANGE",`^\\s*(${D[q.XRANGEPLAIN]})\\s+-\\s+(${D[q.XRANGEPLAIN]})\\s*$`);K("HYPHENRANGELOOSE",`^\\s*(${D[q.XRANGEPLAINLOOSE]})\\s+-\\s+(${D[q.XRANGEPLAINLOOSE]})\\s*$`);K("STAR","(<|>)?=?\\s*\\*");K("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");K("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")});var na=E((v2,Fy)=>{"use strict";var Ex=Object.freeze({loose:!0}),Ax=Object.freeze({}),kx=r=>r?typeof r!="object"?Ex:r:Ax;Fy.exports=kx});var hu=E(($2,By)=>{"use strict";var Vy=/^[0-9]+$/,Uy=(r,e)=>{if(typeof r=="number"&&typeof e=="number")return r===e?0:rUy(e,r);By.exports={compareIdentifiers:Uy,rcompareIdentifiers:xx}});var De=E((S2,Hy)=>{"use strict";var ia=ws(),{MAX_LENGTH:zy,MAX_SAFE_INTEGER:sa}=li(),{safeRe:oa,t:aa}=di(),Px=na(),{compareIdentifiers:mu}=hu(),Ix=(r,e)=>{let t=e.split(".");if(t.length>r.length)return!1;for(let n=0;nzy)throw new TypeError(`version is longer than ${zy} characters`);ia("SemVer",e,t),this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease;let n=e.trim().match(t.loose?oa[aa.LOOSE]:oa[aa.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>sa||this.major<0)throw new TypeError("Invalid major version");if(this.minor>sa||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>sa||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(ia("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 mu(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(ia("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 mu(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?oa[aa.PRERELEASELOOSE]:oa[aa.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]),Ix(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}};Hy.exports=yu});var Yr=E((E2,Wy)=>{"use strict";var Ky=De(),Ox=(r,e,t=!1)=>{if(r instanceof Ky)return r;try{return new Ky(r,e)}catch(n){if(!t)return null;throw n}};Wy.exports=Ox});var Jy=E((A2,Gy)=>{"use strict";var Rx=Yr(),Tx=(r,e)=>{let t=Rx(r,e);return t?t.version:null};Gy.exports=Tx});var Xy=E((k2,Yy)=>{"use strict";var Cx=Yr(),Mx=(r,e)=>{let t=Cx(r.trim().replace(/^[=v]+/,""),e);return t?t.version:null};Yy.exports=Mx});var eg=E((x2,Zy)=>{"use strict";var Qy=De(),Nx=(r,e,t,n,i)=>{typeof t=="string"&&(i=n,n=t,t=void 0);try{return new Qy(r instanceof Qy?r.version:r,t).inc(e,n,i).version}catch(s){return null}};Zy.exports=Nx});var ng=E((P2,rg)=>{"use strict";var tg=Yr(),Lx=(r,e)=>{let t=tg(r,null,!0),n=tg(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 d=c?"pre":"";return t.major!==n.major?d+"major":t.minor!==n.minor?d+"minor":t.patch!==n.patch?d+"patch":"prerelease"};rg.exports=Lx});var sg=E((I2,ig)=>{"use strict";var jx=De(),Dx=(r,e)=>new jx(r,e).major;ig.exports=Dx});var ag=E((O2,og)=>{"use strict";var qx=De(),Fx=(r,e)=>new qx(r,e).minor;og.exports=Fx});var lg=E((R2,cg)=>{"use strict";var Vx=De(),Ux=(r,e)=>new Vx(r,e).patch;cg.exports=Ux});var ug=E((T2,dg)=>{"use strict";var Bx=Yr(),zx=(r,e)=>{let t=Bx(r,e);return t&&t.prerelease.length?t.prerelease:null};dg.exports=zx});var At=E((C2,pg)=>{"use strict";var fg=De(),Hx=(r,e,t)=>new fg(r,t).compare(new fg(e,t));pg.exports=Hx});var mg=E((M2,hg)=>{"use strict";var Kx=At(),Wx=(r,e,t)=>Kx(e,r,t);hg.exports=Wx});var gg=E((N2,yg)=>{"use strict";var Gx=At(),Jx=(r,e)=>Gx(r,e,!0);yg.exports=Jx});var ca=E((L2,bg)=>{"use strict";var _g=De(),Yx=(r,e,t)=>{let n=new _g(r,t),i=new _g(e,t);return n.compare(i)||n.compareBuild(i)};bg.exports=Yx});var vg=E((j2,wg)=>{"use strict";var Xx=ca(),Qx=(r,e)=>r.sort((t,n)=>Xx(t,n,e));wg.exports=Qx});var Sg=E((D2,$g)=>{"use strict";var Zx=ca(),eP=(r,e)=>r.sort((t,n)=>Zx(n,t,e));$g.exports=eP});var vs=E((q2,Eg)=>{"use strict";var tP=At(),rP=(r,e,t)=>tP(r,e,t)>0;Eg.exports=rP});var la=E((F2,Ag)=>{"use strict";var nP=At(),iP=(r,e,t)=>nP(r,e,t)<0;Ag.exports=iP});var gu=E((V2,kg)=>{"use strict";var sP=At(),oP=(r,e,t)=>sP(r,e,t)===0;kg.exports=oP});var _u=E((U2,xg)=>{"use strict";var aP=At(),cP=(r,e,t)=>aP(r,e,t)!==0;xg.exports=cP});var da=E((B2,Pg)=>{"use strict";var lP=At(),dP=(r,e,t)=>lP(r,e,t)>=0;Pg.exports=dP});var ua=E((z2,Ig)=>{"use strict";var uP=At(),fP=(r,e,t)=>uP(r,e,t)<=0;Ig.exports=fP});var bu=E((H2,Og)=>{"use strict";var pP=gu(),hP=_u(),mP=vs(),yP=da(),gP=la(),_P=ua(),bP=(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 pP(r,t,n);case"!=":return hP(r,t,n);case">":return mP(r,t,n);case">=":return yP(r,t,n);case"<":return gP(r,t,n);case"<=":return _P(r,t,n);default:throw new TypeError(`Invalid operator: ${e}`)}};Og.exports=bP});var Tg=E((K2,Rg)=>{"use strict";var wP=De(),vP=Yr(),{safeRe:fa,t:pa}=di(),$P=(r,e)=>{if(r instanceof wP)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?fa[pa.COERCEFULL]:fa[pa.COERCE]);else{let c=e.includePrerelease?fa[pa.COERCERTLFULL]:fa[pa.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 vP(`${n}.${i}.${s}${o}${a}`,e)};Rg.exports=$P});var Mg=E((W2,Cg)=>{"use strict";var SP=Yr(),EP=li(),AP=De(),kP=(r,e,t)=>{if(!EP.RELEASE_TYPES.includes(e))return null;let n=xP(r,t);return n&&PP(n,e)},xP=(r,e)=>{let t=r instanceof AP?r.version:r;return SP(t,e)},PP=(r,e)=>{if(IP(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()},IP=r=>r.startsWith("pre");Cg.exports=kP});var Lg=E((G2,Ng)=>{"use strict";var wu=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}};Ng.exports=wu});var kt=E((J2,Fg)=>{"use strict";var OP=/\s+/g,vu=class r{constructor(e,t){if(t=TP(t),e instanceof r)return e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease?e:new r(e.raw,t);if(e instanceof $u)return this.raw=e.value,this.set=[[e]],this.formatted=void 0,this;if(this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease,this.raw=e.trim().replace(OP," "),this.set=this.raw.split("||").map(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=>!Dg(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&&VP(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(FP,"");let n=((this.options.includePrerelease&&DP)|(this.options.loose&&qP))+":"+e,i=jg.get(n);if(i)return i;let s=this.options.loose,o=s?Xe[qe.HYPHENRANGELOOSE]:Xe[qe.HYPHENRANGE];e=e.replace(o,QP(this.options.includePrerelease)),we("hyphen replace",e),e=e.replace(Xe[qe.COMPARATORTRIM],NP),we("comparator trim",e),e=e.replace(Xe[qe.TILDETRIM],LP),we("tilde trim",e),e=e.replace(Xe[qe.CARETTRIM],jP),we("caret trim",e);let a=e.split(" ").map(u=>UP(u,this.options)).join(" ").split(/\s+/).map(u=>XP(u,this.options));s&&(a=a.filter(u=>(we("loose invalid filter",u,this.options),!!u.match(Xe[qe.COMPARATORLOOSE])))),we("range list",a);let c=new Map,l=a.map(u=>new $u(u,this.options));for(let u of l){if(Dg(u))return[u];c.set(u.value,u)}c.size>1&&c.has("")&&c.delete("");let d=[...c.values()];return jg.set(n,d),d}intersects(e,t){if(!(e instanceof r))throw new TypeError("a Range is required");return this.set.some(n=>qg(n,t)&&e.set.some(i=>qg(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 CP(e,this.options)}catch(t){return!1}for(let t=0;tr.value==="<0.0.0-0",VP=r=>r.value==="",qg=(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},UP=(r,e)=>(r=r.replace(Xe[qe.BUILD],""),we("comp",r,e),r=KP(r,e),we("caret",r),r=zP(r,e),we("tildes",r),r=GP(r,e),we("xrange",r),r=YP(r,e),we("stars",r),r),Oe=r=>!r||r.toLowerCase()==="x"||r==="*",BP=(r,e,t)=>Oe(r)&&!Oe(e)||Oe(e)&&t&&!Oe(t),zP=(r,e)=>r.trim().split(/\s+/).map(t=>HP(t,e)).join(" "),HP=(r,e)=>{let t=e.loose?Xe[qe.TILDELOOSE]:Xe[qe.TILDE],n=e.includePrerelease?"-0":"";return r.replace(t,(i,s,o,a,c)=>{we("tilde",r,i,s,o,a,c);let l;return Oe(s)?l="":Oe(o)?l=`>=${s}.0.0${n} <${+s+1}.0.0-0`:Oe(a)?l=`>=${s}.${o}.0${n} <${s}.${+o+1}.0-0`:c?(we("replaceTilde pr",c),l=`>=${s}.${o}.${a}-${c} <${s}.${+o+1}.0-0`):l=`>=${s}.${o}.${a} <${s}.${+o+1}.0-0`,we("tilde return",l),l})},KP=(r,e)=>r.trim().split(/\s+/).map(t=>WP(t,e)).join(" "),WP=(r,e)=>{we("caret",r,e);let t=e.loose?Xe[qe.CARETLOOSE]:Xe[qe.CARET],n=e.includePrerelease?"-0":"";return r.replace(t,(i,s,o,a,c)=>{we("caret",r,i,s,o,a,c);let l;return Oe(s)?l="":Oe(o)?l=`>=${s}.0.0${n} <${+s+1}.0.0-0`:Oe(a)?s==="0"?l=`>=${s}.${o}.0${n} <${s}.${+o+1}.0-0`:l=`>=${s}.${o}.0${n} <${+s+1}.0.0-0`:c?(we("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`):(we("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`),we("caret return",l),l})},GP=(r,e)=>(we("replaceXRanges",r,e),r.split(/\s+/).map(t=>JP(t,e)).join(" ")),JP=(r,e)=>{r=r.trim();let t=e.loose?Xe[qe.XRANGELOOSE]:Xe[qe.XRANGE];return r.replace(t,(n,i,s,o,a,c)=>{if(we("xRange",r,n,i,s,o,a,c),BP(s,o,a))return r;let l=Oe(s),d=l||Oe(o),u=d||Oe(a),f=u;return i==="="&&f&&(i=""),c=e.includePrerelease?"-0":"",l?i===">"||i==="<"?n="<0.0.0-0":n="*":i&&f?(d&&(o=0),a=0,i===">"?(i=">=",d?(s=+s+1,o=0,a=0):(o=+o+1,a=0)):i==="<="&&(i="<",d?s=+s+1:o=+o+1),i==="<"&&(c="-0"),n=`${i+s}.${o}.${a}${c}`):d?n=`>=${s}.0.0${c} <${+s+1}.0.0-0`:u&&(n=`>=${s}.${o}.0${c} <${s}.${+o+1}.0-0`),we("xRange return",n),n})},YP=(r,e)=>(we("replaceStars",r,e),r.trim().replace(Xe[qe.STAR],"")),XP=(r,e)=>(we("replaceGTE0",r,e),r.trim().replace(Xe[e.includePrerelease?qe.GTE0PRE:qe.GTE0],"")),QP=r=>(e,t,n,i,s,o,a,c,l,d,u,f)=>(Oe(n)?t="":Oe(i)?t=`>=${n}.0.0${r?"-0":""}`:Oe(s)?t=`>=${n}.${i}.0${r?"-0":""}`:o?t=`>=${t}`:t=`>=${t}${r?"-0":""}`,Oe(l)?c="":Oe(d)?c=`<${+l+1}.0.0-0`:Oe(u)?c=`<${l}.${+d+1}.0-0`:f?c=`<=${l}.${d}.${u}-${f}`:r?c=`<${l}.${d}.${+u+1}-0`:c=`<=${c}`,`${t} ${c}`.trim()),ZP=(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 $s=E((Y2,Kg)=>{"use strict";var Ss=Symbol("SemVer ANY"),Au=class r{static get ANY(){return Ss}constructor(e,t){if(t=Vg(t),e instanceof r){if(e.loose===!!t.loose)return e;e=e.value}e=e.trim().split(/\s+/).join(" "),Eu("comparator",e,t),this.options=t,this.loose=!!t.loose,this.parse(e),this.semver===Ss?this.value="":this.value=this.operator+this.semver.version,Eu("comp",this)}parse(e){let t=this.options.loose?Ug[Bg.COMPARATORLOOSE]:Ug[Bg.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 zg(n[2],this.options.loose):this.semver=Ss}toString(){return this.value}test(e){if(Eu("Comparator.test",e,this.options.loose),this.semver===Ss||e===Ss)return!0;if(typeof e=="string")try{e=new zg(e,this.options)}catch(t){return!1}return Su(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 Hg(e.value,t).test(this.value):e.operator===""?e.value===""?!0:new Hg(this.value,t).test(e.semver):(t=Vg(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("=")||Su(this.semver,"<",e.semver,t)&&this.operator.startsWith(">")&&e.operator.startsWith("<")||Su(this.semver,">",e.semver,t)&&this.operator.startsWith("<")&&e.operator.startsWith(">")))}};Kg.exports=Au;var Vg=na(),{safeRe:Ug,t:Bg}=di(),Su=bu(),Eu=ws(),zg=De(),Hg=kt()});var Es=E((X2,Wg)=>{"use strict";var eI=kt(),tI=(r,e,t)=>{try{e=new eI(e,t)}catch(n){return!1}return e.test(r)};Wg.exports=tI});var Jg=E((Q2,Gg)=>{"use strict";var rI=kt(),nI=(r,e)=>new rI(r,e).set.map(t=>t.map(n=>n.value).join(" ").trim().split(" "));Gg.exports=nI});var Xg=E((Z2,Yg)=>{"use strict";var iI=De(),sI=kt(),oI=(r,e,t)=>{let n=null,i=null,s=null;try{s=new sI(e,t)}catch(o){return null}return r.forEach(o=>{s.test(o)&&(!n||i.compare(o)===-1)&&(n=o,i=new iI(n,t))}),n};Yg.exports=oI});var Zg=E((eL,Qg)=>{"use strict";var aI=De(),cI=kt(),lI=(r,e,t)=>{let n=null,i=null,s=null;try{s=new cI(e,t)}catch(o){return null}return r.forEach(o=>{s.test(o)&&(!n||i.compare(o)===1)&&(n=o,i=new aI(n,t))}),n};Qg.exports=lI});var r_=E((tL,t_)=>{"use strict";var ku=De(),dI=kt(),e_=vs(),uI=(r,e)=>{r=new dI(r,e);let t=new ku("0.0.0");if(r.test(t)||(t=new ku("0.0.0-0"),r.test(t)))return t;t=null;for(let n=0;n{let a=new ku(o.semver.version);switch(o.operator){case">":a.prerelease.length===0?a.patch++:a.prerelease.push(0),a.raw=a.format();case"":case">=":(!s||e_(a,s))&&(s=a);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${o.operator}`)}}),s&&(!t||e_(t,s))&&(t=s)}return t&&r.test(t)?t:null};t_.exports=uI});var i_=E((rL,n_)=>{"use strict";var fI=kt(),pI=(r,e)=>{try{return new fI(r,e).range||"*"}catch(t){return null}};n_.exports=pI});var ha=E((nL,c_)=>{"use strict";var hI=De(),a_=$s(),{ANY:mI}=a_,yI=kt(),gI=Es(),s_=vs(),o_=la(),_I=ua(),bI=da(),wI=(r,e,t,n)=>{r=new hI(r,n),e=new yI(e,n);let i,s,o,a,c;switch(t){case">":i=s_,s=_I,o=o_,a=">",c=">=";break;case"<":i=o_,s=bI,o=s_,a="<",c="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(gI(r,e,n))return!1;for(let l=0;l{p.semver===mI&&(p=new a_(">=0.0.0")),u=u||p,f=f||p,i(p.semver,u.semver,n)?u=p:o(p.semver,f.semver,n)&&(f=p)}),u.operator===a||u.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};c_.exports=wI});var d_=E((iL,l_)=>{"use strict";var vI=ha(),$I=(r,e,t)=>vI(r,e,">",t);l_.exports=$I});var f_=E((sL,u_)=>{"use strict";var SI=ha(),EI=(r,e,t)=>SI(r,e,"<",t);u_.exports=EI});var m_=E((oL,h_)=>{"use strict";var p_=kt(),AI=(r,e,t)=>(r=new p_(r,t),e=new p_(e,t),r.intersects(e,t));h_.exports=AI});var g_=E((aL,y_)=>{"use strict";var kI=Es(),xI=At();y_.exports=(r,e,t)=>{let n=[],i=null,s=null,o=r.sort((d,u)=>xI(d,u,t));for(let d of o)kI(d,e,t)?(s=d,i||(i=d)):(s&&n.push([i,s]),s=null,i=null);i&&n.push([i,null]);let a=[];for(let[d,u]of n)d===u?a.push(d):!u&&d===o[0]?a.push("*"):u?d===o[0]?a.push(`<=${u}`):a.push(`${d} - ${u}`):a.push(`>=${d}`);let c=a.join(" || "),l=typeof e.raw=="string"?e.raw:String(e);return c.length{"use strict";var __=kt(),Iu=$s(),{ANY:xu}=Iu,Pu=Es(),Ou=At(),PI=(r,e,t={})=>{if(r===e)return!0;r=new __(r,t),e=new __(e,t);let n=!1;e:for(let i of r.set){for(let s of e.set){let o=OI(i,s,t);if(n=n||o!==null,o)continue e}if(n)return!1}return!0},II=[new Iu(">=0.0.0-0")],b_=[new Iu(">=0.0.0")],OI=(r,e,t)=>{if(r===e)return!0;if(r.length===1&&r[0].semver===xu){if(e.length===1&&e[0].semver===xu)return!0;t.includePrerelease?r=II:r=b_}if(e.length===1&&e[0].semver===xu){if(t.includePrerelease)return!0;e=b_}let n=new Set,i,s;for(let p of r)p.operator===">"||p.operator===">="?i=w_(i,p,t):p.operator==="<"||p.operator==="<="?s=v_(s,p,t):n.add(p.semver);if(n.size>1)return null;let o;if(i&&s){if(o=Ou(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&&!Pu(p,String(i),t)||s&&!Pu(p,String(s),t))return null;for(let y of e)if(!Pu(p,String(y),t))return!1;return!0}let a,c,l,d,u=s&&!t.includePrerelease&&s.semver.prerelease.length?s.semver:!1,f=i&&!t.includePrerelease&&i.semver.prerelease.length?i.semver:!1;u&&u.prerelease.length===1&&s.operator==="<"&&u.prerelease[0]===0&&(u=!1);for(let p of e){if(d=d||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=w_(i,p,t),a===p&&a!==i)return!1}else if(i.operator===">="&&!p.test(i.semver))return!1}if(s){if(u&&p.semver.prerelease&&p.semver.prerelease.length&&p.semver.major===u.major&&p.semver.minor===u.minor&&p.semver.patch===u.patch&&(u=!1),p.operator==="<"||p.operator==="<="){if(c=v_(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&&d&&!i&&o!==0||f||u)},w_=(r,e,t)=>{if(!r)return e;let n=Ou(r.semver,e.semver,t);return n>0?r:n<0||e.operator===">"&&r.operator===">="?e:r},v_=(r,e,t)=>{if(!r)return e;let n=Ou(r.semver,e.semver,t);return n<0?r:n>0||e.operator==="<"&&r.operator==="<="?e:r};$_.exports=PI});var x_=E((lL,k_)=>{"use strict";var Ru=di(),E_=li(),RI=De(),A_=hu(),TI=Yr(),CI=Jy(),MI=Xy(),NI=eg(),LI=ng(),jI=sg(),DI=ag(),qI=lg(),FI=ug(),VI=At(),UI=mg(),BI=gg(),zI=ca(),HI=vg(),KI=Sg(),WI=vs(),GI=la(),JI=gu(),YI=_u(),XI=da(),QI=ua(),ZI=bu(),eO=Tg(),tO=Mg(),rO=$s(),nO=kt(),iO=Es(),sO=Jg(),oO=Xg(),aO=Zg(),cO=r_(),lO=i_(),dO=ha(),uO=d_(),fO=f_(),pO=m_(),hO=g_(),mO=S_();k_.exports={parse:TI,valid:CI,clean:MI,inc:NI,diff:LI,major:jI,minor:DI,patch:qI,prerelease:FI,compare:VI,rcompare:UI,compareLoose:BI,compareBuild:zI,sort:HI,rsort:KI,gt:WI,lt:GI,eq:JI,neq:YI,gte:XI,lte:QI,cmp:ZI,coerce:eO,truncate:tO,Comparator:rO,Range:nO,satisfies:iO,toComparators:sO,maxSatisfying:oO,minSatisfying:aO,minVersion:cO,validRange:lO,outside:dO,gtr:uO,ltr:fO,intersects:pO,simplifyRange:hO,subset:mO,SemVer:RI,re:Ru.re,src:Ru.src,tokens:Ru.t,SEMVER_SPEC_VERSION:E_.SEMVER_SPEC_VERSION,RELEASE_TYPES:E_.RELEASE_TYPES,compareIdentifiers:A_.compareIdentifiers,rcompareIdentifiers:A_.rcompareIdentifiers}});var ks=E((xL,j_)=>{"use strict";var C_="[^\\\\/]",EO="(?=.)",M_="[^/]",Lu="(?:\\/|$)",N_="(?:^|\\/)",ju=`\\.{1,2}${Lu}`,AO="(?!\\.)",kO=`(?!${N_}${ju})`,xO=`(?!\\.{0,1}${Lu})`,PO=`(?!${ju})`,IO="[^.\\/]",OO=`${M_}*?`,RO="/",L_={DOT_LITERAL:"\\.",PLUS_LITERAL:"\\+",QMARK_LITERAL:"\\?",SLASH_LITERAL:"\\/",ONE_CHAR:EO,QMARK:M_,END_ANCHOR:Lu,DOTS_SLASH:ju,NO_DOT:AO,NO_DOTS:kO,NO_DOT_SLASH:xO,NO_DOTS_SLASH:PO,QMARK_NO_DOT:IO,STAR:OO,START_ANCHOR:N_,SEP:RO},TO={...L_,SLASH_LITERAL:"[\\\\/]",QMARK:C_,STAR:`${C_}*?`,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:"\\"},CO={__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"};j_.exports={DEFAULT_MAX_EXTGLOB_RECURSION:0,MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:CO,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?TO:L_}}});var xs=E(ct=>{"use strict";var{REGEX_BACKSLASH:MO,REGEX_REMOVE_BACKSLASH:NO,REGEX_SPECIAL_CHARS:LO,REGEX_SPECIAL_CHARS_GLOBAL:jO}=ks();ct.isObject=r=>r!==null&&typeof r=="object"&&!Array.isArray(r);ct.hasRegexChars=r=>LO.test(r);ct.isRegexChar=r=>r.length===1&&ct.hasRegexChars(r);ct.escapeRegex=r=>r.replace(jO,"\\$1");ct.toPosixSlashes=r=>r.replace(MO,"/");ct.isWindows=()=>{if(typeof navigator!="undefined"&&navigator.platform){let r=navigator.platform.toLowerCase();return r==="win32"||r==="windows"}return typeof process!="undefined"&&process.platform?process.platform==="win32":!1};ct.removeBackslashes=r=>r.replace(NO,e=>e==="\\"?"":e);ct.escapeLast=(r,e,t)=>{let n=r.lastIndexOf(e,t);return n===-1?r:r[n-1]==="\\"?ct.escapeLast(r,e,n-1):`${r.slice(0,n)}\\${r.slice(n)}`};ct.removePrefix=(r,e={})=>{let t=r;return t.startsWith("./")&&(t=t.slice(2),e.prefix="./"),t};ct.wrapOutput=(r,e={},t={})=>{let n=t.contains?"":"^",i=t.contains?"":"$",s=`${n}(?:${r})${i}`;return e.negated===!0&&(s=`(?:^(?!${s}).*$)`),s};ct.basename=(r,{windows:e}={})=>{let t=r.split(e?/[\\/]/:"/"),n=t[t.length-1];return n===""?t[t.length-2]:n}});var H_=E((IL,z_)=>{"use strict";var D_=xs(),{CHAR_ASTERISK:Du,CHAR_AT:DO,CHAR_BACKWARD_SLASH:Ps,CHAR_COMMA:qO,CHAR_DOT:qu,CHAR_EXCLAMATION_MARK:Fu,CHAR_FORWARD_SLASH:B_,CHAR_LEFT_CURLY_BRACE:Vu,CHAR_LEFT_PARENTHESES:Uu,CHAR_LEFT_SQUARE_BRACKET:FO,CHAR_PLUS:VO,CHAR_QUESTION_MARK:q_,CHAR_RIGHT_CURLY_BRACE:UO,CHAR_RIGHT_PARENTHESES:F_,CHAR_RIGHT_SQUARE_BRACKET:BO}=ks(),V_=r=>r===B_||r===Ps,U_=r=>{r.isPrefix!==!0&&(r.depth=r.isGlobstar?1/0:1)},zO=(r,e)=>{let t=e||{},n=r.length-1,i=t.parts===!0||t.scanToEnd===!0,s=[],o=[],a=[],c=r,l=-1,d=0,u=0,f=!1,p=!1,y=!1,h=!1,m=!1,g=!1,_=!1,w=!1,x=!1,v=!1,P=0,O,A,R={value:"",depth:0,isGlob:!1},$=()=>l>=n,M=()=>c.charCodeAt(l+1),V=()=>(O=A,c.charCodeAt(++l));for(;l0&&(S=c.slice(0,d),c=c.slice(d),u-=d),T&&y===!0&&u>0?(T=c.slice(0,u),k=c.slice(u)):y===!0?(T="",k=c):T=c,T&&T!==""&&T!=="/"&&T!==c&&V_(T.charCodeAt(T.length-1))&&(T=T.slice(0,-1)),t.unescape===!0&&(k&&(k=D_.removeBackslashes(k)),T&&_===!0&&(T=D_.removeBackslashes(T)));let de={prefix:S,input:r,start:d,base:T,glob:k,isBrace:f,isBracket:p,isGlob:y,isExtglob:h,isGlobstar:m,negated:w,negatedExtglob:x};if(t.tokens===!0&&(de.maxDepth=0,V_(A)||o.push(R),de.tokens=o),t.parts===!0||t.tokens===!0){let Z;for(let B=0;B{"use strict";var Is=ks(),ht=xs(),{MAX_LENGTH:_a,POSIX_REGEX_SOURCE:HO,REGEX_NON_SPECIAL_CHARS:KO,REGEX_SPECIAL_CHARS_BACKREF:WO,REPLACEMENTS:K_}=Is,GO=(r,e)=>{if(typeof e.expandRange=="function")return e.expandRange(...r,e);r.sort();let t=`[${r.join("-")}]`;try{new RegExp(t)}catch(n){return r.map(i=>ht.escapeRegex(i)).join("..")}return t},ui=(r,e)=>`Missing ${r}: "${e}" - use "\\\\${e}" to match literal characters`,W_=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},JO=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},zu=r=>{let e=r.trim(),t=!0;for(;t===!0;)t=!1,/^@\([^\\()[\]{}|]+\)$/.test(e)&&(e=e.slice(2,-1),t=!0);if(JO(e))return e.replace(/\\(.)/g,"$1")},YO=r=>{let e=r.map(zu).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}}}}},XO=r=>`${r.length===1?ht.escapeRegex(r[0]):`[${r.map(t=>ht.escapeRegex(t)).join("")}]`}*`,QO=r=>{let e=0,t=[];for(;eo.trim());if(i.length!==1)return;let s=zu(i[0]);if(!s||s.length!==1)return;t.push(s),e+=n.end+1}if(!(t.length<1))return t},ZO=r=>{let e=0,t=r.trim(),n=Bu(t);for(;n;)e++,t=n.body.trim(),n=Bu(t);return e},eR=(r,e)=>{if(e.maxExtglobRecursion===!1)return{risky:!1};let t=typeof e.maxExtglobRecursion=="number"?e.maxExtglobRecursion:Is.DEFAULT_MAX_EXTGLOB_RECURSION,n=W_(r).map(a=>a.trim());if(n.length>1&&(n.some(a=>a==="")||n.some(a=>/^[*?]+$/.test(a))||YO(n)))return{risky:!0};let i=[],s=!1,o=!0;for(let a of n){let c=QO(a);if(c){s=!0,i.push(...c);continue}let l=zu(a);if(l&&l.length===1){i.push(l);continue}if(o=!1,ZO(a)>t)return{risky:!0}}return s?o?{risky:!0,safeOutput:XO([...new Set(i)])}:{risky:!0}:{risky:!1}},Hu=(r,e)=>{if(typeof r!="string")throw new TypeError("Expected a string");r=K_[r]||r;let t={...e},n=typeof t.maxLength=="number"?Math.min(_a,t.maxLength):_a,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=Is.globChars(t.windows),l=Is.extglobChars(c),{DOT_LITERAL:d,PLUS_LITERAL:u,SLASH_LITERAL:f,ONE_CHAR:p,DOTS_SLASH:y,NO_DOT:h,NO_DOT_SLASH:m,NO_DOTS_SLASH:g,QMARK:_,QMARK_NO_DOT:w,STAR:x,START_ANCHOR:v}=c,P=N=>`(${a}(?:(?!${v}${N.dot?y:d}).)*?)`,O=t.dot?"":h,A=t.dot?_:w,R=t.bash===!0?P(t):x;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=ht.removePrefix(r,$),i=r.length;let M=[],V=[],T=[],S=s,k,de=()=>$.index===i-1,Z=$.peek=(N=1)=>r[$.index+N],B=$.advance=()=>r[++$.index]||"",fe=()=>r.slice($.index+1),Ve=(N="",$e=0)=>{$.consumed+=N,$.index+=$e},Jt=N=>{$.output+=N.output!=null?N.output:N.value,Ve(N.value)},Dr=()=>{let N=1;for(;Z()==="!"&&(Z(2)!=="("||Z(3)==="?");)B(),$.start++,N++;return N%2===0?!1:($.negated=!0,$.start++,!0)},un=N=>{$[N]++,T.push(N)},qr=N=>{$[N]--,T.pop()},ee=N=>{if(S.type==="globstar"){let $e=$.braces>0&&(N.type==="comma"||N.type==="brace"),C=N.extglob===!0||M.length&&(N.type==="pipe"||N.type==="paren");N.type!=="slash"&&N.type!=="paren"&&!$e&&!C&&($.output=$.output.slice(0,-S.output.length),S.type="star",S.value="*",S.output=R,$.output+=S.output)}if(M.length&&N.type!=="paren"&&(M[M.length-1].inner+=N.value),(N.value||N.output)&&Jt(N),S&&S.type==="text"&&N.type==="text"){S.output=(S.output||S.value)+N.value,S.value+=N.value;return}N.prev=S,o.push(N),S=N},_o=(N,$e)=>{let C={...l[$e],conditions:1,inner:""};C.prev=S,C.parens=$.parens,C.output=$.output,C.startIndex=$.index,C.tokensIndex=o.length;let te=(t.capture?"(":"")+C.open;un("parens"),ee({type:N,value:$e,output:$.output?"":p}),ee({type:"paren",extglob:!0,value:B(),output:te}),M.push(C)},L0=N=>{let $e=r.slice(N.startIndex,$.index+1),C=r.slice(N.startIndex+2,$.index),te=eR(C,t);if((N.type==="plus"||N.type==="star")&&te.risky){let he=te.safeOutput?(N.output?"":p)+(t.capture?`(${te.safeOutput})`:te.safeOutput):void 0,Yt=o[N.tokensIndex];Yt.type="text",Yt.value=$e,Yt.output=he||ht.escapeRegex($e);for(let Xt=N.tokensIndex+1;Xt1&&N.inner.includes("/")&&(he=P(t)),(he!==R||de()||/^\)+$/.test(fe()))&&(ye=N.close=`)$))${he}`),N.inner.includes("*")&&(Ie=fe())&&/^\.[^\\/.]+$/.test(Ie)){let Yt=Hu(Ie,{...e,fastpaths:!1}).output;ye=N.close=`)${Yt})${he})`}N.prev.type==="bos"&&($.negatedExtglob=!0)}ee({type:"paren",extglob:!0,value:k,output:ye}),qr("parens")};if(t.fastpaths!==!1&&!/(^[*!]|[/()[\]{}"])/.test(r)){let N=!1,$e=r.replace(WO,(C,te,ye,Ie,he,Yt)=>Ie==="\\"?(N=!0,C):Ie==="?"?te?te+Ie+(he?_.repeat(he.length):""):Yt===0?A+(he?_.repeat(he.length):""):_.repeat(ye.length):Ie==="."?d.repeat(ye.length):Ie==="*"?te?te+Ie+(he?R:""):R:te?C:`\\${C}`);return N===!0&&(t.unescape===!0?$e=$e.replace(/\\/g,""):$e=$e.replace(/\\+/g,C=>C.length%2===0?"\\\\":C?"\\":"")),$e===r&&t.contains===!0?($.output=r,$):($.output=ht.wrapOutput($e,$,e),$)}for(;!de();){if(k=B(),k==="\0")continue;if(k==="\\"){let C=Z();if(C==="/"&&t.bash!==!0||C==="."||C===";")continue;if(!C){k+="\\",ee({type:"text",value:k});continue}let te=/^\\+/.exec(fe()),ye=0;if(te&&te[0].length>2&&(ye=te[0].length,$.index+=ye,ye%2!==0&&(k+="\\")),t.unescape===!0?k=B():k+=B(),$.brackets===0){ee({type:"text",value:k});continue}}if($.brackets>0&&(k!=="]"||S.value==="["||S.value==="[^")){if(t.posix!==!1&&k===":"){let C=S.value.slice(1);if(C.includes("[")&&(S.posix=!0,C.includes(":"))){let te=S.value.lastIndexOf("["),ye=S.value.slice(0,te),Ie=S.value.slice(te+2),he=HO[Ie];if(he){S.value=ye+he,$.backtrack=!0,B(),!s.output&&o.indexOf(S)===1&&(s.output=p);continue}}}(k==="["&&Z()!==":"||k==="-"&&Z()==="]")&&(k=`\\${k}`),k==="]"&&(S.value==="["||S.value==="[^")&&(k=`\\${k}`),t.posix===!0&&k==="!"&&S.value==="["&&(k="^"),S.value+=k,Jt({value:k});continue}if($.quotes===1&&k!=='"'){k=ht.escapeRegex(k),S.value+=k,Jt({value:k});continue}if(k==='"'){$.quotes=$.quotes===1?0:1,t.keepQuotes===!0&&ee({type:"text",value:k});continue}if(k==="("){un("parens"),ee({type:"paren",value:k});continue}if(k===")"){if($.parens===0&&t.strictBrackets===!0)throw new SyntaxError(ui("opening","("));let C=M[M.length-1];if(C&&$.parens===C.parens+1){L0(M.pop());continue}ee({type:"paren",value:k,output:$.parens?")":"\\)"}),qr("parens");continue}if(k==="["){if(t.nobracket===!0||!fe().includes("]")){if(t.nobracket!==!0&&t.strictBrackets===!0)throw new SyntaxError(ui("closing","]"));k=`\\${k}`}else un("brackets");ee({type:"bracket",value:k});continue}if(k==="]"){if(t.nobracket===!0||S&&S.type==="bracket"&&S.value.length===1){ee({type:"text",value:k,output:`\\${k}`});continue}if($.brackets===0){if(t.strictBrackets===!0)throw new SyntaxError(ui("opening","["));ee({type:"text",value:k,output:`\\${k}`});continue}qr("brackets");let C=S.value.slice(1);if(S.posix!==!0&&C[0]==="^"&&!C.includes("/")&&(k=`/${k}`),S.value+=k,Jt({value:k}),t.literalBrackets===!1||ht.hasRegexChars(C))continue;let te=ht.escapeRegex(S.value);if($.output=$.output.slice(0,-S.value.length),t.literalBrackets===!0){$.output+=te,S.value=te;continue}S.value=`(${a}${te}|${S.value})`,$.output+=S.value;continue}if(k==="{"&&t.nobrace!==!0){un("braces");let C={type:"brace",value:k,output:"(",outputIndex:$.output.length,tokensIndex:$.tokens.length};V.push(C),ee(C);continue}if(k==="}"){let C=V[V.length-1];if(t.nobrace===!0||!C){ee({type:"text",value:k,output:k});continue}let te=")";if(C.dots===!0){let ye=o.slice(),Ie=[];for(let he=ye.length-1;he>=0&&(o.pop(),ye[he].type!=="brace");he--)ye[he].type!=="dots"&&Ie.unshift(ye[he].value);te=GO(Ie,t),$.backtrack=!0}if(C.comma!==!0&&C.dots!==!0){let ye=$.output.slice(0,C.outputIndex),Ie=$.tokens.slice(C.tokensIndex);C.value=C.output="\\{",k=te="\\}",$.output=ye;for(let he of Ie)$.output+=he.output||he.value}ee({type:"brace",value:k,output:te}),qr("braces"),V.pop();continue}if(k==="|"){M.length>0&&M[M.length-1].conditions++,ee({type:"text",value:k});continue}if(k===","){let C=k,te=V[V.length-1];te&&T[T.length-1]==="braces"&&(te.comma=!0,C="|"),ee({type:"comma",value:k,output:C});continue}if(k==="/"){if(S.type==="dot"&&$.index===$.start+1){$.start=$.index+1,$.consumed="",$.output="",o.pop(),S=s;continue}ee({type:"slash",value:k,output:f});continue}if(k==="."){if($.braces>0&&S.type==="dot"){S.value==="."&&(S.output=d);let C=V[V.length-1];S.type="dots",S.output+=k,S.value+=k,C.dots=!0;continue}if($.braces+$.parens===0&&S.type!=="bos"&&S.type!=="slash"){ee({type:"text",value:k,output:d});continue}ee({type:"dot",value:k,output:d});continue}if(k==="?"){if(!(S&&S.value==="(")&&t.noextglob!==!0&&Z()==="("&&Z(2)!=="?"){_o("qmark",k);continue}if(S&&S.type==="paren"){let te=Z(),ye=k;(S.value==="("&&!/[!=<:]/.test(te)||te==="<"&&!/<([!=]|\w+>)/.test(fe()))&&(ye=`\\${k}`),ee({type:"text",value:k,output:ye});continue}if(t.dot!==!0&&(S.type==="slash"||S.type==="bos")){ee({type:"qmark",value:k,output:w});continue}ee({type:"qmark",value:k,output:_});continue}if(k==="!"){if(t.noextglob!==!0&&Z()==="("&&(Z(2)!=="?"||!/[!=<:]/.test(Z(3)))){_o("negate",k);continue}if(t.nonegate!==!0&&$.index===0){Dr();continue}}if(k==="+"){if(t.noextglob!==!0&&Z()==="("&&Z(2)!=="?"){_o("plus",k);continue}if(S&&S.value==="("||t.regex===!1){ee({type:"plus",value:k,output:u});continue}if(S&&(S.type==="bracket"||S.type==="paren"||S.type==="brace")||$.parens>0){ee({type:"plus",value:k});continue}ee({type:"plus",value:u});continue}if(k==="@"){if(t.noextglob!==!0&&Z()==="("&&Z(2)!=="?"){ee({type:"at",extglob:!0,value:k,output:""});continue}ee({type:"text",value:k});continue}if(k!=="*"){(k==="$"||k==="^")&&(k=`\\${k}`);let C=KO.exec(fe());C&&(k+=C[0],$.index+=C[0].length),ee({type:"text",value:k});continue}if(S&&(S.type==="globstar"||S.star===!0)){S.type="star",S.star=!0,S.value+=k,S.output=R,$.backtrack=!0,$.globstar=!0,Ve(k);continue}let N=fe();if(t.noextglob!==!0&&/^\([^?]/.test(N)){_o("star",k);continue}if(S.type==="star"){if(t.noglobstar===!0){Ve(k);continue}let C=S.prev,te=C.prev,ye=C.type==="slash"||C.type==="bos",Ie=te&&(te.type==="star"||te.type==="globstar");if(t.bash===!0&&(!ye||N[0]&&N[0]!=="/")){ee({type:"star",value:k,output:""});continue}let he=$.braces>0&&(C.type==="comma"||C.type==="brace"),Yt=M.length&&(C.type==="pipe"||C.type==="paren");if(!ye&&C.type!=="paren"&&!he&&!Yt){ee({type:"star",value:k,output:""});continue}for(;N.slice(0,3)==="/**";){let Xt=r[$.index+4];if(Xt&&Xt!=="/")break;N=N.slice(3),Ve("/**",3)}if(C.type==="bos"&&de()){S.type="globstar",S.value+=k,S.output=P(t),$.output=S.output,$.globstar=!0,Ve(k);continue}if(C.type==="slash"&&C.prev.type!=="bos"&&!Ie&&de()){$.output=$.output.slice(0,-(C.output+S.output).length),C.output=`(?:${C.output}`,S.type="globstar",S.output=P(t)+(t.strictSlashes?")":"|$)"),S.value+=k,$.globstar=!0,$.output+=C.output+S.output,Ve(k);continue}if(C.type==="slash"&&C.prev.type!=="bos"&&N[0]==="/"){let Xt=N[1]!==void 0?"|$":"";$.output=$.output.slice(0,-(C.output+S.output).length),C.output=`(?:${C.output}`,S.type="globstar",S.output=`${P(t)}${f}|${f}${Xt})`,S.value+=k,$.output+=C.output+S.output,$.globstar=!0,Ve(k+B()),ee({type:"slash",value:"/",output:""});continue}if(C.type==="bos"&&N[0]==="/"){S.type="globstar",S.value+=k,S.output=`(?:^|${f}|${P(t)}${f})`,$.output=S.output,$.globstar=!0,Ve(k+B()),ee({type:"slash",value:"/",output:""});continue}$.output=$.output.slice(0,-S.output.length),S.type="globstar",S.output=P(t),S.value+=k,$.output+=S.output,$.globstar=!0,Ve(k);continue}let $e={type:"star",value:k,output:R};if(t.bash===!0){$e.output=".*?",(S.type==="bos"||S.type==="slash")&&($e.output=O+$e.output),ee($e);continue}if(S&&(S.type==="bracket"||S.type==="paren")&&t.regex===!0){$e.output=k,ee($e);continue}($.index===$.start||S.type==="slash"||S.type==="dot")&&(S.type==="dot"?($.output+=m,S.output+=m):t.dot===!0?($.output+=g,S.output+=g):($.output+=O,S.output+=O),Z()!=="*"&&($.output+=p,S.output+=p)),ee($e)}for(;$.brackets>0;){if(t.strictBrackets===!0)throw new SyntaxError(ui("closing","]"));$.output=ht.escapeLast($.output,"["),qr("brackets")}for(;$.parens>0;){if(t.strictBrackets===!0)throw new SyntaxError(ui("closing",")"));$.output=ht.escapeLast($.output,"("),qr("parens")}for(;$.braces>0;){if(t.strictBrackets===!0)throw new SyntaxError(ui("closing","}"));$.output=ht.escapeLast($.output,"{"),qr("braces")}if(t.strictSlashes!==!0&&(S.type==="star"||S.type==="bracket")&&ee({type:"maybe_slash",value:"",output:`${f}?`}),$.backtrack===!0){$.output="";for(let N of $.tokens)$.output+=N.output!=null?N.output:N.value,N.suffix&&($.output+=N.suffix)}return $};Hu.fastpaths=(r,e)=>{let t={...e},n=typeof t.maxLength=="number"?Math.min(_a,t.maxLength):_a,i=r.length;if(i>n)throw new SyntaxError(`Input length: ${i}, exceeds maximum allowed length: ${n}`);r=K_[r]||r;let{DOT_LITERAL:s,SLASH_LITERAL:o,ONE_CHAR:a,DOTS_SLASH:c,NO_DOT:l,NO_DOTS:d,NO_DOTS_SLASH:u,STAR:f,START_ANCHOR:p}=Is.globChars(t.windows),y=t.dot?d:l,h=t.dot?u:l,m=t.capture?"":"?:",g={negated:!1,prefix:""},_=t.bash===!0?".*?":f;t.capture&&(_=`(${_})`);let w=O=>O.noglobstar===!0?_:`(${m}(?:(?!${p}${O.dot?c:s}).)*?)`,x=O=>{switch(O){case"*":return`${y}${a}${_}`;case".*":return`${s}${a}${_}`;case"*.*":return`${y}${_}${s}${a}${_}`;case"*/*":return`${y}${_}${o}${a}${h}${_}`;case"**":return y+w(t);case"**/*":return`(?:${y}${w(t)}${o})?${h}${a}${_}`;case"**/*.*":return`(?:${y}${w(t)}${o})?${h}${_}${s}${a}${_}`;case"**/.*":return`(?:${y}${w(t)}${o})?${s}${a}${_}`;default:{let A=/^(.*?)\.(\w+)$/.exec(O);if(!A)return;let R=x(A[1]);return R?R+s+A[2]:void 0}}},v=ht.removePrefix(r,g),P=x(v);return P&&t.strictSlashes!==!0&&(P+=`${o}?`),P};G_.exports=Hu});var Q_=E((RL,X_)=>{"use strict";var tR=H_(),Ku=J_(),Y_=xs(),rR=ks(),nR=r=>r&&typeof r=="object"&&!Array.isArray(r),ke=(r,e,t=!1)=>{if(Array.isArray(r)){let d=r.map(f=>ke(f,e,t));return f=>{for(let p of d){let y=p(f);if(y)return y}return!1}}let n=nR(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?ke.compileRe(r,e):ke.makeRe(r,e,!1,!0),a=o.state;delete o.state;let c=()=>!1;if(i.ignore){let d={...e,ignore:null,onMatch:null,onResult:null};c=ke(i.ignore,d,t)}let l=(d,u=!1)=>{let{isMatch:f,match:p,output:y}=ke.test(d,o,e,{glob:r,posix:s}),h={glob:r,state:a,regex:o,posix:s,input:d,output:y,match:p,isMatch:f};return typeof i.onResult=="function"&&i.onResult(h),f===!1?(h.isMatch=!1,u?h:!1):c(d)?(typeof i.onIgnore=="function"&&i.onIgnore(h),h.isMatch=!1,u?h:!1):(typeof i.onMatch=="function"&&i.onMatch(h),u?h:!0)};return t&&(l.state=a),l};ke.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?Y_.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=ke.matchBase(r,e,t,i):a=e.exec(c)),{isMatch:!!a,match:a,output:c}};ke.matchBase=(r,e,t,n=t&&t.windows)=>(e instanceof RegExp?e:ke.makeRe(e,t)).test(Y_.basename(r,{windows:n}));ke.isMatch=(r,e,t)=>ke(e,t)(r);ke.parse=(r,e)=>Array.isArray(r)?r.map(t=>ke.parse(t,e)):Ku(r,{...e,fastpaths:!1});ke.scan=(r,e)=>tR(r,e);ke.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=ke.toRegex(a,e);return n===!0&&(c.state=r),c};ke.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=Ku.fastpaths(r,e)),i.output||(i=Ku(r,e)),ke.compileRe(i,e,t,n)};ke.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/$^/}};ke.constants=rR;X_.exports=ke});var Wu=E((TL,tb)=>{"use strict";var Z_=Q_(),iR=xs();function eb(r,e,t=!1){return e&&(e.windows===null||e.windows===void 0)&&(e={...e,windows:iR.isWindows()}),Z_(r,e,t)}Object.assign(eb,Z_);tb.exports=eb});var kM={};B0(kM,{default:()=>zc});module.exports=z0(kM);var j=require("obsidian");var L=class extends Error{constructor(t,n,i){super(n);I(this,"code");I(this,"details");this.code=t,this.details=i,this.name="InteropError"}toPortableError(t){return{code:this.code,message:this.message,...this.details===void 0?{}:{details:this.details},...t===void 0?{}:{retryable:t}}}},Ui=class extends Error{constructor(t,n){super(n.message);I(this,"status");I(this,"error");this.status=t,this.error=n,this.name="ActionHandlerError"}};var Ry=fn(Qd(),1),Ty=fn(cu(),1);var lu={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 ax=Ty.default;function Cy(){return Object.fromEntries(Object.entries(lu).map(([r,e])=>[r,structuredClone(e)]))}function du(){let r=new Ry.Ajv2020({allErrors:!0,strict:!1,validateFormats:!0});ax(r);let e=Cy();r.addSchema(e.profile);for(let[t,n]of Object.entries(e))t!=="profile"&&r.addSchema(n);return r}function br(r,e){let t=String(lu[e].$id),n=r.getSchema(t);if(!n)throw new Error(`Canonical interoperability schema is unavailable: ${e}`);return n}function Jr(r){return(r!=null?r:[]).map(e=>{var t;return`${e.instancePath||"/"} ${(t=e.message)!=null?t:e.keyword}`}).join("; ")}function nr(r,e){if(!("value"in r))throw new L("contract_digest_conflict",`${e} must be resolved to an inline JSON Schema before runtime registration.`);return structuredClone(r.value)}function My(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=nr(r.record_schema,"record_schema"),r.binding_schema&&(e.binding_schema=nr(r.binding_schema,"binding_schema"));break;case"event":e.data_schema=nr(r.data_schema,"data_schema"),r.source_schema&&(e.source_schema=nr(r.source_schema,"source_schema"));break;case"action":e.input_schema=nr(r.input_schema,"input_schema"),r.output_schema&&(e.output_schema=nr(r.output_schema,"output_schema")),r.error_schema&&(e.error_schema=nr(r.error_schema,"error_schema")),r.provider_schema&&(e.provider_schema=nr(r.provider_schema,"provider_schema")),r.behavior&&(e.behavior=structuredClone(r.behavior));break}return e}async function ta(r){return ci(My(r))}async function ci(r){return`sha256:${await cx(uu(r))}`}function Ny(r,e){return{data:ai(r,e.data_schema,`${e.id} data_schema`),...e.source_schema?{source:ai(r,e.source_schema,`${e.id} source_schema`)}:{}}}function Ly(r,e){return{input:ai(r,e.input_schema,`${e.id} input_schema`),...e.output_schema?{output:ai(r,e.output_schema,`${e.id} output_schema`)}:{},...e.error_schema?{error:ai(r,e.error_schema,`${e.id} error_schema`)}:{},...e.provider_schema?{provider:ai(r,e.provider_schema,`${e.id} provider_schema`)}:{}}}function ra(r,e,t,n){if(!(!r||r(e)))throw new L(t,`${n} failed JSON Schema validation: ${Jr(r.errors)}`)}function ai(r,e,t){try{return r.compile(nr(e,t))}catch(n){throw new L("contract_digest_conflict",`${t} could not be compiled: ${n instanceof Error?n.message:String(n)}`)}}function uu(r){return r===null||typeof r!="object"?JSON.stringify(r):Array.isArray(r)?`[${r.map(uu).join(",")}]`:`{${Object.entries(r).filter(([,t])=>t!==void 0).sort(([t],[n])=>tn?1:0).map(([t,n])=>`${JSON.stringify(t)}:${uu(n)}`).join(",")}}`}async function cx(r){let e=new TextEncoder().encode(r),t=await globalThis.crypto.subtle.digest("SHA-256",e);return[...new Uint8Array(t)].map(n=>n.toString(16).padStart(2,"0")).join("")}var vr=fn(x_(),1);var Tu={delivery:["ephemeral"],ordering:["none"],cancellation:!0,deadlines:!0,provider_discovery:!0,request_deduplication:!0,cross_process_identity:!1},yO=new Set(["specversion","id","source","type","time","subject","datacontenttype","dataschema","data","mdbaseprofile","mdbasecontractversion","mdbasecontractdigest","mdbaseapplication","mdbaseimplementation","mdbaseimplementationversion","mdbaseinstanceid","correlationid","causationid"]),As=class{constructor(e={}){I(this,"options");I(this,"profileVersion","0.1");I(this,"transport");I(this,"ajv",du());I(this,"contractValidator",br(this.ajv,"contract"));I(this,"eventValidator",br(this.ajv,"event"));I(this,"actionRequestValidator",br(this.ajv,"actionRequest"));I(this,"actionInvocationValidator",br(this.ajv,"actionInvocation"));I(this,"actionOutcomeValidator",br(this.ajv,"actionOutcome"));I(this,"eventSourceDeclarationValidator",br(this.ajv,"eventSourceDeclaration"));I(this,"actionProviderDeclarationValidator",br(this.ajv,"actionProviderDeclaration"));I(this,"contracts",new Map);I(this,"clients",new Map);I(this,"eventSources",new Map);I(this,"actionProviders",new Map);I(this,"subscriptions",new Map);I(this,"activeActions",new Map);I(this,"completedActions",new Map);I(this,"admissionLocks",new Map);I(this,"recentEvents",new Map);I(this,"authorize");I(this,"now");I(this,"idFactory");I(this,"recentEventLimit");I(this,"completedRequestLimit");I(this,"nextSequence",0);I(this,"disposed",!1);var t,n,i,s,o,a,c,l,d,u;this.options=e,this.authorize=(t=e.authorize)!=null?t:(()=>!1),this.now=(n=e.now)!=null?n:(()=>new Date),this.idFactory=(i=e.idFactory)!=null?i:(f=>{var y;this.nextSequence+=1;let p=typeof((y=globalThis.crypto)==null?void 0:y.randomUUID)=="function"?globalThis.crypto.randomUUID():`${this.now().getTime().toString(36)}-${this.nextSequence.toString(36)}`;return`${f}_${p}`}),this.recentEventLimit=Math.max(1,(s=e.recentEventLimit)!=null?s:1e3),this.completedRequestLimit=Math.max(1,(o=e.completedRequestLimit)!=null?o:1e3),this.transport={...Tu,...structuredClone((a=e.transport)!=null?a:{}),delivery:[...(l=(c=e.transport)==null?void 0:c.delivery)!=null?l:Tu.delivery],ordering:[...(u=(d=e.transport)==null?void 0:d.ordering)!=null?u:Tu.ordering]}}connect(e){this.assertActive(),gO(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){var l;let n=this.requireClient(e);if(t.contracts.length===0)throw new L("request_rejected","An event-source declaration must include a contract.");let i=`${e}:${t.declaration_id}`;if(this.eventSources.has(i))throw new L("request_rejected",`Event-source declaration ${t.declaration_id} is already registered.`);let s=new Map;for(let d of t.contracts){let u=await this.prepareEventContract(d.contract),f=P_(d.requirement,u.reference);if(I_(f,u.reference),await this.assertAuthorized({operation:"register_event_source",principal:n.identity,contract:u.reference}),u.sourceValidator&&!u.sourceValidator((l=d.binding)!=null?l:{}))throw new L("request_rejected",`${u.reference.id} source binding is invalid: ${Jr(u.sourceValidator.errors)}`);let p=ma(u.reference);if(s.has(p))throw new L("contract_digest_conflict",`Event contract ${p} is repeated by one declaration.`);s.set(p,{contract:u,requirement:f,...d.binding===void 0?{}:{binding:structuredClone(d.binding)},...d.ordering===void 0?{}:{ordering:[...d.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:d,requirement:u,binding:f,ordering:p})=>({requirement:structuredClone(u),resolved:structuredClone(d.reference),...f===void 0?{}:{binding:f},...p===void 0?{}:{ordering:p}}))},a={...o,declaration_digest:await ci(o)};Xr(this.eventSourceDeclarationValidator,a,"request_rejected","Event-source declaration"),this.commitContracts([...s.values()].map(({contract:d})=>d)),this.eventSources.set(i,{id:i,clientId:e,declaration:structuredClone(a),contracts:new Map([...s.entries()].map(([d,u])=>[d,{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){var y,h,m,g;let n=this.requireClient(e),i=ma(t.contract),s=[...n.sources].map(_=>this.eventSources.get(_)).find(_=>_==null?void 0:_.contracts.has(i));if(!s)throw new L("unknown_contract",`This client has not registered event contract ${t.contract.id} ${t.contract.version}.`);let o=(y=s.contracts.get(i))==null?void 0:y.contract;if(!o)throw new L("unknown_contract",`Event contract ${i} is unavailable.`);if(t.contract.digest&&t.contract.digest!==o.reference.digest)throw new L("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}}),Cu(t.data,"invalid_event_data",`Event ${o.reference.id} data`),ra(o.dataValidator,t.data,"invalid_event_data",`Event ${o.reference.id} data`);let a=(h=t.extensions)!=null?h:{};for(let _ of Object.keys(a))if(yO.has(_))throw new L("request_rejected",`Event extension ${_} is reserved.`);let c={...structuredClone(a),specversion:"1.0",id:(m=t.id)!=null?m:this.idFactory("evt"),source:_O(n.identity),type:o.reference.id,time:(g=t.time)!=null?g:this.now().toISOString(),...t.subject===void 0?{}:{subject:t.subject},datacontenttype:"application/json",dataschema:T_(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}};Xr(this.eventValidator,c,"invalid_event_data","Event envelope"),Mu(this.transport,c),bO(c,o.reference);let l=`${c.source}\0${c.id}`,d=this.recentEvents.get(l);if(d){if(JSON.stringify(d)!==JSON.stringify(c))throw new L("contract_digest_conflict",`Event ${c.source} ${c.id} was reused with different content.`);return{event:structuredClone(d),deliveries:0,duplicate:!0}}this.recentEvents.set(l,structuredClone(c)),R_(this.recentEvents,this.recentEventLimit);let u=[...this.subscriptions.values()].filter(({subscription:_})=>ya(_.contract,o.reference)),f=await Promise.allSettled(u.map(async _=>await this.isAuthorized({operation:"subscribe_event",principal:_.principal,contract:o.reference,...c.subject===void 0?{}:{subject:c.subject}})?(await _.handler(structuredClone(c)),!0):!1)),p=0;for(let _ of f)_.status==="fulfilled"&&_.value?p+=1:_.status==="rejected"&&this.report({severity:"error",code:"event_consumer_failed",message:`An event consumer failed while handling ${c.type}.`,contract:o.reference,cause:_.reason});return{event:structuredClone(c),deliveries:p,duplicate:!1}}async subscribeEvents(e,t,n){let i=this.requireClient(e);Nu(t.contract),$O(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){var u,f,p,y,h,m,g;let n=this.requireClient(e);if(t.handlers.length===0)throw new L("request_rejected","An action-provider declaration must include a handler.");let i=`${e}:${t.declaration_id}`;if(this.actionProviders.has(i))throw new L("request_rejected",`Action-provider declaration ${t.declaration_id} is already registered.`);let s=[],o=new Set;for(let _ of t.handlers){if(o.has(_.handler_id))throw new L("request_rejected",`Handler ${_.handler_id} is repeated.`);o.add(_.handler_id);let w=await this.prepareActionContract(_.contract),x=P_(_.requirement,w.reference);if(I_(x,w.reference),await this.assertAuthorized({operation:"register_action_provider",principal:n.identity,contract:w.reference,provider:n.identity}),w.providerValidator&&!w.providerValidator((u=_.binding)!=null?u:{}))throw new L("request_rejected",`${w.reference.id} provider binding is invalid: ${Jr(w.providerValidator.errors)}`);let v=(p=(f=_.contract.behavior)==null?void 0:f.idempotency)!=null?p:"none";if(((y=_.idempotency)==null?void 0:y.mode)==="request"&&v==="none")throw new L("request_rejected",`${w.reference.id} does not permit request deduplication.`);if(v==="required"&&((h=_.idempotency)==null?void 0:h.mode)!=="request")throw new L("request_rejected",`${w.reference.id} requires a provider with request deduplication.`);let P=(g=(m=_.contract.behavior)==null?void 0:m.cancellation)!=null?g:"none";if(_.cancellation==="cooperative"&&P!=="cooperative")throw new L("request_rejected",`${w.reference.id} does not declare cooperative cancellation.`);s.push({contract:w,declaration:{handler_id:_.handler_id,requirement:x,resolved:structuredClone(w.reference),..._.binding===void 0?{}:{binding:structuredClone(_.binding)},..._.idempotency===void 0?{}:{idempotency:structuredClone(_.idempotency)},..._.cancellation===void 0?{}:{cancellation:_.cancellation},..._.max_concurrency===void 0?{}:{max_concurrency:_.max_concurrency}},handler:_.handler})}let a={kind:"mdbase.action-provider",profile_version:"0.1",declaration_id:t.declaration_id,provider:structuredClone(n.identity),handlers:s.map(({declaration:_})=>structuredClone(_))},c={...a,declaration_digest:await ci(a)};Xr(this.actionProviderDeclarationValidator,c,"request_rejected","Action-provider declaration"),this.commitContracts(s.map(({contract:_})=>_));let l=s.map(({contract:_,declaration:w,handler:x})=>({registrationId:i,clientId:e,declaration:structuredClone(c),handlerDeclaration:structuredClone(w),contract:_,handler:x,active:0}));this.actionProviders.set(i,{id:i,clientId:e,declaration:structuredClone(c),handlers:l}),n.providers.add(i);let d=!0;return{declaration:structuredClone(c),dispose:()=>{d&&(d=!1,this.removeActionProvider(i))}}}async invokeAction(e,t){var a,c,l,d,u,f,p,y,h,m,g,_;let n=this.requireClient(e);Nu(t.contract);let i=(a=t.request_id)!=null?a:this.idFactory("req");this.cleanCompletedActions(),Cu(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:(c=t.created_at)!=null?c:this.now().toISOString(),...t.correlation_id===void 0?{}:{correlation_id:t.correlation_id},...t.causation_id===void 0?{}:{causation_id:t.causation_id},...t.subject===void 0?{}:{subject:t.subject},...t.idempotency_key===void 0?{}:{idempotency_key:t.idempotency_key},...t.deadline===void 0?{}:{deadline:t.deadline},...t.requested_provider===void 0?{}:{requested_provider:structuredClone(t.requested_provider)},input:structuredClone(t.input)};Xr(this.actionRequestValidator,s,"request_rejected","Action request"),Mu(this.transport,s);let o=await this.acquireAdmission(i);try{let w=await ci(wO(s)),x=this.activeActions.get(i);if(x){if(O_(e,i,w,x),((l=x.handler.handlerDeclaration.idempotency)==null?void 0:l.mode)!=="request")throw new L("request_rejected",`Action request ${i} is already active without deduplication.`);return structuredClone(await x.promise)}let v=this.completedActions.get(i);if(v){if(O_(e,i,w,v),!v.reusable)throw new L("request_rejected",`Action request ${i} was already completed without deduplication.`);return structuredClone(v.outcome)}if(s.deadline&&new Date(s.deadline).getTime()<=this.now().getTime())throw new L("deadline_exceeded",`Action request ${i} passed its deadline before admission.`);if(s.deadline&&!this.transport.deadlines)throw new L("unsupported_transport_capability","The active transport cannot enforce action deadlines.");let P=this.resolveActionCandidates(s.contract,s.requested_provider);P.length===0&&this.throwResolutionFailure(s.contract,s.requested_provider);let O=[];for(let B of P)await this.isAuthorized({operation:"invoke_action",principal:n.identity,contract:B.contract.reference,provider:B.declaration.provider,...s.subject===void 0?{}:{subject:s.subject}})&&O.push(B);if(O.length===0)throw new L("unauthorized",`No authorized provider can execute ${s.contract.id}.`);if(O.length>1)throw new L("ambiguous_provider",`Action ${s.contract.id} has ${O.length} eligible providers; select one explicitly.`);let A=O[0];if(A.handlerDeclaration.max_concurrency!==void 0&&A.active>=A.handlerDeclaration.max_concurrency)throw new L("request_rejected",`Provider ${A.declaration.provider.implementation} is at capacity.`);if(((u=(d=A.contract.artifact.behavior)==null?void 0:d.idempotency)!=null?u:"none")==="required"&&!s.idempotency_key)throw new L("request_rejected",`${A.contract.reference.id} requires an idempotency key.`);ra(A.contract.inputValidator,s.input,"invalid_action_input",`Action ${A.contract.reference.id} input`);let $={operation:"invoke_action",principal:n.identity,contract:A.contract.reference,provider:A.declaration.provider,...s.subject===void 0?{}:{subject:s.subject}},M=await((p=(f=this.options).authorizationContext)==null?void 0:p.call(f,$)),V={kind:"mdbase.action.invocation",profile_version:"0.1",invocation_id:this.idFactory("inv"),attempt_id:this.idFactory("attempt"),request_id:i,contract:structuredClone(A.contract.reference),caller:structuredClone(n.identity),provider:structuredClone(A.declaration.provider),provider_declaration_digest:A.declaration.declaration_digest,handler_id:A.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)};Xr(this.actionInvocationValidator,V,"request_rejected","Action invocation"),await((h=(y=this.options).onInvocation)==null?void 0:h.call(y,structuredClone(V)));let T=new AbortController,S;if(V.deadline){let B=Math.max(0,new Date(V.deadline).getTime()-this.now().getTime());S=setTimeout(()=>T.abort(new L("deadline_exceeded",`Action request ${i} exceeded its deadline.`)),B)}A.active+=1;let k=this.executeAction(A,V,T).finally(()=>{S!==void 0&&clearTimeout(S),A.active=Math.max(0,A.active-1),this.activeActions.delete(i)});this.activeActions.set(i,{clientId:e,requestId:i,requestDigest:w,handler:A,invocation:V,controller:T,promise:k}),o();let de=await k,Z=(g=(m=A.handlerDeclaration.idempotency)==null?void 0:m.retention_seconds)!=null?g:300;return this.completedActions.set(i,{clientId:e,requestDigest:w,outcome:structuredClone(de),reusable:((_=A.handlerDeclaration.idempotency)==null?void 0:_.mode)==="request",expiresAt:this.now().getTime()+Z*1e3}),R_(this.completedActions,this.completedRequestLimit),structuredClone(de)}finally{o()}}async executeAction(e,t,n){var i;try{let s=await e.handler(structuredClone(t.input),{invocation:structuredClone(t),signal:n.signal});if(n.signal.aborted){let a=n.signal.reason;return a instanceof L&&a.code==="deadline_exceeded"?this.failureOutcome(t,"failed",a.toPortableError()):this.failureOutcome(t,"cancelled",{code:"cancelled",message:`Action request ${t.request_id} was cancelled.`})}Cu(s,"invalid_action_output",`Action ${e.contract.reference.id} output`),ra(e.contract.outputValidator,s,"invalid_action_output",`Action ${e.contract.reference.id} output`);let o={kind:"mdbase.action.outcome",profile_version:"0.1",outcome_id:this.idFactory("outcome"),request_id:t.request_id,invocation_id:t.invocation_id,attempt_id:t.attempt_id,contract:structuredClone(t.contract),provider:structuredClone(t.provider),provider_declaration_digest:t.provider_declaration_digest,status:"succeeded",completed_at:this.now().toISOString(),output:structuredClone(s)};return Xr(this.actionOutcomeValidator,o,"invalid_action_output","Action outcome"),Mu(this.transport,o),o}catch(s){if(s instanceof Ui)return e.contract.errorValidator&&!e.contract.errorValidator((i=s.error.details)!=null?i:{})?this.failureOutcome(t,"failed",{code:"handler_failure",message:`Provider returned invalid declared error details: ${Jr(e.contract.errorValidator.errors)}`}):this.failureOutcome(t,s.status,s.error);if(s instanceof L)return this.failureOutcome(t,s.code==="cancelled"?"cancelled":s.code==="outcome_indeterminate"?"outcome_indeterminate":"failed",s.toPortableError());if(n.signal.aborted||SO(s)){let o=n.signal.reason;return o instanceof L&&o.code==="deadline_exceeded"?this.failureOutcome(t,"failed",o.toPortableError()):this.failureOutcome(t,"cancelled",{code:"cancelled",message:`Action request ${t.request_id} was cancelled.`})}return this.report({severity:"error",code:"action_handler_failed",message:`Provider ${t.provider.implementation} failed ${t.contract.id}.`,principal:t.provider,contract:t.contract,cause:s}),this.failureOutcome(t,"failed",{code:"handler_failure",message:"The selected provider failed while executing the action."})}}failureOutcome(e,t,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 Xr(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 L("unauthorized",`Action request ${t} belongs to another caller.`);return a?structuredClone(a.outcome):null}if(o.clientId!==e)throw new L("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 L("unsupported_transport_capability","The active transport cannot deliver cancellation.");if(o.handler.handlerDeclaration.cancellation!=="cooperative")throw new L("cancellation_unsupported",`Provider ${o.invocation.provider.implementation} does not support cancellation.`);return o.controller.abort(new L("cancelled",(n==null?void 0:n.trim())||`Action request ${t} was cancelled.`)),structuredClone(await o.promise)}resolveActionCandidates(e,t){let n=[...this.actionProviders.values()].flatMap(({handlers:s})=>s).filter(({contract:s,declaration:o})=>ya(e,s.reference)&&vO(t,o.provider)),i=(0,vr.maxSatisfying)([...new Set(n.map(({contract:s})=>s.reference.version))],e.version,{includePrerelease:!0});return i?n.filter(({contract:s})=>s.reference.version===i).sort((s,o)=>{var a,c;return s.declaration.provider.application.localeCompare(o.declaration.provider.application)||s.declaration.provider.implementation.localeCompare(o.declaration.provider.implementation)||((a=s.declaration.provider.instance_id)!=null?a:"").localeCompare((c=o.declaration.provider.instance_id)!=null?c:"")||s.handlerDeclaration.handler_id.localeCompare(o.handlerDeclaration.handler_id)}):[]}throwResolutionFailure(e,t){let n=[...this.contracts.values()].filter(i=>i.artifact.contract_type==="action"&&i.reference.id===e.id);throw n.length===0?new L("unknown_contract",`Action contract ${e.id} is unknown.`):n.some(({reference:i})=>ya(e,i))?t?new L("requested_provider_unavailable",`The requested provider is unavailable for ${e.id}.`):new L("no_provider",`No provider is registered for ${e.id}.`):new L("unsupported_contract_version",`No ${e.id} artifact satisfies ${e.version}.`)}async prepareEventContract(e){if(this.assertContractArtifact(e),e.contract_type!=="event")throw new L("unknown_contract",`${e.id} is not an event contract.`);let t={id:e.id,version:e.version,digest:await ta(e)};this.assertNoContractConflict(t);let n=Ny(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 L("unknown_contract",`${e.id} is not an action contract.`);let t={id:e.id,version:e.version,digest:await ta(e)};this.assertNoContractConflict(t);let n=Ly(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(Xr(this.contractValidator,e,"contract_digest_conflict",`Contract ${e.id||""}`),!(0,vr.valid)(e.version))throw new L("unsupported_contract_version",`${e.id} version must be exact SemVer.`)}assertNoContractConflict(e){let t=this.contracts.get(ma(e));if(t&&t.reference.digest!==e.digest)throw new L("contract_digest_conflict",`Contract ${e.id} ${e.version} conflicts with the registered artifact.`)}commitContracts(e){var n;let t=new Map;for(let i of e){let s=ma(i.reference),o=(n=t.get(s))!=null?n:this.contracts.get(s);if(o&&o.reference.digest!==i.reference.digest)throw new L("contract_digest_conflict",`Contract ${i.reference.id} ${i.reference.version} conflicts within the registration.`);t.set(s,i)}for(let[i,s]of t)this.contracts.has(i)||this.contracts.set(i,s)}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 L("cancelled","The caller unloaded.")),i.handler.clientId===e&&i.handler.handlerDeclaration.cancellation==="cooperative"&&i.controller.abort(new L("cancelled","The provider unloaded."));this.clients.delete(e),t||this.assertActive()}}removeEventSource(e){var n;let t=this.eventSources.get(e);t&&(this.eventSources.delete(e),(n=this.clients.get(t.clientId))==null||n.sources.delete(e))}removeActionProvider(e){var n;let t=this.actionProviders.get(e);if(t){this.actionProviders.delete(e),(n=this.clients.get(t.clientId))==null||n.providers.delete(e);for(let i of this.activeActions.values())i.handler.registrationId===e&&i.handler.handlerDeclaration.cancellation==="cooperative"&&i.controller.abort(new L("cancelled","The provider unloaded."))}}removeSubscription(e){var n;let t=this.subscriptions.get(e);t&&(this.subscriptions.delete(e),(n=this.clients.get(t.clientId))==null||n.subscriptions.delete(e))}requireClient(e){this.assertActive();let t=this.clients.get(e);if(!t||t.disposed)throw new L("transport_unavailable","Interop client is disposed.");return t}assertActive(){if(this.disposed)throw new L("transport_unavailable","Interop bridge is disposed.")}async assertAuthorized(e){if(!await this.isAuthorized(e))throw new L("unauthorized",`${e.operation} is not authorized.`)}async isAuthorized(e){try{return await this.authorize(structuredClone(e))}catch(t){return this.report({severity:"error",code:"authorization_failed",message:`Authorization failed for ${e.operation}.`,principal:e.principal,cause:t}),!1}}cleanCompletedActions(){let e=this.now().getTime();for(let[t,n]of this.completedActions)n.expiresAt<=e&&this.completedActions.delete(t)}async acquireAdmission(e){var a;let t=(a=this.admissionLocks.get(e))!=null?a:Promise.resolve(),n,i=new Promise(c=>{n=c}),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){var t,n;(n=(t=this.options).onDiagnostic)==null||n.call(t,structuredClone(e))}};function Xr(r,e,t,n){if(!r(e))throw new L(t,`${n} is invalid: ${Jr(r.errors)}`)}function gO(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 L("request_rejected",`Implementation identity ${e} is invalid.`);if(!(0,vr.valid)(r.version))throw new L("request_rejected","Implementation identity version must be exact SemVer.")}function Nu(r){if(!/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)+$/u.test(r.id))throw new L("unknown_contract",`Contract ID ${r.id} is invalid.`);if(!(0,vr.validRange)(r.version,{includePrerelease:!0}))throw new L("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 L("contract_digest_conflict","Contract digest is invalid.")}function P_(r,e){let t=r!=null?r:{id:e.id,version:e.version,digest:e.digest};return Nu(t),structuredClone(t)}function I_(r,e){if(!ya(r,e))throw new L("unsupported_contract_version",`${e.id} ${e.version} does not satisfy its implementation requirement.`)}function ya(r,e){return r.id===e.id&&(0,vr.satisfies)(e.version,r.version,{includePrerelease:!0})&&(!r.digest||r.digest===e.digest)}function ma(r){return`${r.id}@${r.version}`}function T_(r){return`urn:mdbase:contract:${r.id}:${r.version}:${r.digest}`}function _O(r){return`urn:mdbase:app:${[r.application,r.implementation,...r.instance_id?[r.instance_id]:[]].map(encodeURIComponent).join(":")}`}function bO(r,e){if(r.type!==e.id||r.mdbasecontractversion!==e.version||r.mdbasecontractdigest!==e.digest||r.dataschema!==T_(e))throw new L("contract_digest_conflict","Event contract evidence is inconsistent.")}function wO(r){let{created_at:e,...t}=r;return t}function O_(r,e,t,n){if(n.clientId!==r)throw new L("unauthorized",`Action request ${e} belongs to another caller.`);if(n.requestDigest!==t)throw new L("request_rejected",`Action request ${e} was reused with different content.`)}function Cu(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 L(e,`${t}${o} must be a finite JSON number.`)}if(typeof s!="object")throw new L(e,`${t}${o} is not a JSON value.`);if(n.has(s))throw new L(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 L(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 Mu(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 L("unsupported_transport_capability",`The portable envelope is ${n} bytes; the active transport allows ${r.max_payload_bytes}.`)}function vO(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 $O(r,e){var t,n;if(e){if((t=e.delivery)!=null&&t.some(i=>!r.delivery.includes(i)))throw new L("unsupported_transport_capability","The active transport lacks a required delivery capability.");if((n=e.ordering)!=null&&n.some(i=>!r.ordering.includes(i)))throw new L("unsupported_transport_capability","The active transport lacks a required ordering capability.");for(let i of["cancellation","deadlines","provider_discovery","request_deduplication","cross_process_identity"])if(e[i]===!0&&r[i]!==!0)throw new L("unsupported_transport_capability",`The active transport lacks ${i}.`);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 SO(r){return r instanceof Error&&r.name==="AbortError"}var ga=class{constructor(e,t){this.app=e;this.profileVersion="0.1";this.bridge=new As({authorize:()=>t(),transport:{delivery:["ephemeral"],ordering:["none"],cancellation:!0,deadlines:!0,provider_discovery:!0,request_deduplication:!0,cross_process_identity:!1},onDiagnostic:n=>{var s;(n.severity==="error"?console.error:console.warn)(`[mdbase/interop] ${n.code}: ${n.message}`,(s=n.cause)!=null?s:"")}}),this.transport=this.bridge.describe().transport}connect(e){var s,o;let t=(s=e.manifest)==null?void 0:s.id,n=(o=e.manifest)==null?void 0:o.version;if(!t||!n)throw new Error("Only a loaded Obsidian plugin with manifest identity can connect to mdbase interop.");let 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()}};var me=require("obsidian"),nb=fn(Qd(),1),ib=fn(cu(),1),Xu=fn(Wu(),1),va=class extends Error{constructor(t,n){super(n);this.code=t;this.name="MdbasePathError"}},Lt={spec_version:"0.3.0",name:"My mdbase collection",description:"Typed markdown collection",settings:{types_folder:"_types",explicit_type_keys:["type","types"],default_strict:!1,include_subfolders:!0,exclude:["_types",".obsidian",".git","node_modules",".trash",".mdbase"]}},Os=null;function sR(){return Os||(Os=new nb.Ajv2020({allErrors:!0,strict:!1,allowUnionTypes:!0}),(0,ib.default)(Os),Os)}function re(r){return!!r&&typeof r=="object"&&!Array.isArray(r)}function Qe(r){return JSON.parse(JSON.stringify(r))}function oR(r){if(r===!0)return!0;if(r===!1)return!1;if(r==="warn")return"warn"}function Gu(r){return Array.isArray(r)?`[${r.map(e=>Gu(e)).join(",")}]`:re(r)?`{${Object.keys(r).sort().map(t=>`${JSON.stringify(t)}:${Gu(r[t])}`).join(",")}}`:JSON.stringify(r)}function aR(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 cR(r){let e=new Map,t=new Set,n=i=>{var l,d,u,f;let s=e.get(i);if(s)return s;let o=r.get(i);if(!o)return null;if(t.has(i)){let p={...o,fields:Qe(o.fields)};return e.set(i,p),p}t.add(i);let a=o.extends?n(o.extends):null;t.delete(i);let c={...o,fields:a?{...Qe(a.fields),...Qe(o.fields)}:Qe(o.fields),display_name_key:(l=o.display_name_key)!=null?l:a==null?void 0:a.display_name_key,path_pattern:(d=o.path_pattern)!=null?d:a==null?void 0:a.path_pattern,filename_pattern:(u=o.filename_pattern)!=null?u:a==null?void 0:a.filename_pattern,strict:o.strict!==void 0?o.strict:a==null?void 0:a.strict,match:(f=o.match)!=null?f:a==null?void 0:a.match};return e.set(i,c),c};for(let i of r.keys())n(i);return e}function sb(r){let e=(0,me.normalizePath)(r),t=e.lastIndexOf("/");return t>=0?e.slice(0,t):""}function ob(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 ab(r){return/^[a-z][a-z0-9+.-]*:\/\//i.test(r)}function cb(r,e,t){var c;let n=ob(t);if(!n||ab(n))return null;let i=new Set,s=(0,me.normalizePath)(n);i.add(s),s.endsWith(".md")||i.add(`${s}.md`);let o=sb(e);if(o){let l=(0,me.normalizePath)(`${o}/${n}`);i.add(l),l.endsWith(".md")||i.add(`${l}.md`)}for(let l of i){let d=r.getAbstractFileByPath(l);if(d instanceof me.TFile)return d}let a=n.replace(/\.md$/i,"");return(c=r.getMarkdownFiles().find(l=>l.basename===a))!=null?c:null}function lR(r,e,t){return ab(ob(t))||cb(r,e,t)!==null}function Pt(r){let e=r.match(/^---[ \t]*\r?\n([\s\S]*?)^---[ \t]*(?:\r?\n|$)/m);if(!e)return{hasFrontmatter:!1,frontmatter:{},body:r};try{let t=e[1],n=(0,me.parseYaml)(t);return n==null&&t.trim()!==""?{hasFrontmatter:!0,frontmatter:{},body:r.slice(e[0].length),error:"Frontmatter must be a YAML object"}:n!=null&&!re(n)?{hasFrontmatter:!0,frontmatter:{},body:r.slice(e[0].length),error:"Frontmatter must be a YAML object"}:{hasFrontmatter:!0,frontmatter:n!=null?n:{},body:r.slice(e[0].length)}}catch(t){return{hasFrontmatter:!0,frontmatter:{},body:r.slice(e[0].length),error:t instanceof Error?t.message:String(t)}}}function mt(r,e=""){if(Object.keys(r).length===0)return e;let t=(0,me.stringifyYaml)(r).trimEnd(),n=e.replace(/^\n+/,"");return`--- ${t} --- @@ -23,7 +23,7 @@ Type definition for ${r}.`)} Type definition for ${r}.`)} `}function mb(r,e){var i;let t={},n=(i=e.settings.explicit_type_keys[0])!=null?i:"type";t[n]=n==="types"?[r.name]:r.name;for(let[s,o]of Object.entries(r.fields)){if(!re(o))continue;let a=o;a.default!==void 0&&(t[s]=Qe(a.default))}return t}function yb(r,e){let t=[];for(let[n,i]of Object.entries(r.fields)){if(!re(i))continue;let s=i;s.computed||s.required&&e[n]===void 0&&t.push([n,s])}return t}function tf(r,e){var i;let t=r.trim();switch((i=e.type)!=null?i:"string"){case"string":case"date":case"datetime":case"time":case"link":case"enum":case"any":return t;case"integer":{let s=Number.parseInt(t,10);if(!Number.isInteger(s))throw new Error("Expected integer input");return s}case"number":{let s=Number.parseFloat(t);if(Number.isNaN(s))throw new Error("Expected numeric input");return s}case"boolean":{let s=t.toLowerCase();if(["true","1","yes","y"].includes(s))return!0;if(["false","0","no","n"].includes(s))return!1;throw new Error("Expected boolean input: true/false")}case"list":{let s=t.split(",").map(o=>o.trim()).filter(o=>o.length>0);return e.items?s.map(o=>tf(o,e.items)):s}case"object":{let s=(0,me.parseYaml)(t);if(!re(s))throw new Error("Expected YAML object value");return s}case"tags":return t.split(",").map(s=>s.trim()).filter(s=>s.length>0);default:return t}}function rb(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 gb(r,e){let t=(0,me.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 RR(r,e){if(!r.path_pattern||r.path_pattern.trim().length===0)return null;let t=(0,me.normalizePath)(Zu(r.path_pattern,e));return t.endsWith(".md")?t:null}async function _b(r,e,t){var d;let n=RR(e,t),i=hR(e,t),s=n?(d=n.split("/").pop())!=null?d:n:mR(e,t),o=Rs(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;let l=a.lastIndexOf("/");return l>0&&await gb(r,a.slice(0,l)),a}async function bb(r,e,t,n=""){let i=Rs(e),s=i.lastIndexOf("/");if(s>0&&await gb(r,i.slice(0,s)),await r.adapter.exists(i))throw new Error(`File already exists: ${i}`);let o=`${mt(t,n)} `;return r.create(i,o)}function $a(r){return aR(r)}var oe=require("obsidian"),k0=fn(Wu(),1);var Sa=Symbol.for("yaml.alias"),Ea=Symbol.for("yaml.document"),jt=Symbol.for("yaml.map"),rf=Symbol.for("yaml.pair"),yt=Symbol.for("yaml.scalar"),$r=Symbol.for("yaml.seq"),Ze=Symbol.for("yaml.node.type"),Dt=r=>!!r&&typeof r=="object"&&r[Ze]===Sa,sr=r=>!!r&&typeof r=="object"&&r[Ze]===Ea,qt=r=>!!r&&typeof r=="object"&&r[Ze]===jt,ne=r=>!!r&&typeof r=="object"&&r[Ze]===rf,G=r=>!!r&&typeof r=="object"&&r[Ze]===yt,Ft=r=>!!r&&typeof r=="object"&&r[Ze]===$r;function le(r){if(r&&typeof r=="object")switch(r[Ze]){case jt:case $r:return!0}return!1}function se(r){if(r&&typeof r=="object")switch(r[Ze]){case Sa:case jt:case yt:case $r:return!0}return!1}var Aa=r=>(G(r)||le(r))&&!!r.anchor;var lt=Symbol("break visit"),wb=Symbol("skip children"),or=Symbol("remove node");function ar(r,e){let t=vb(e);sr(r)?mi(null,r.contents,t,Object.freeze([r]))===or&&(r.contents=null):mi(null,r,t,Object.freeze([]))}ar.BREAK=lt;ar.SKIP=wb;ar.REMOVE=or;function mi(r,e,t,n){let i=$b(r,e,t,n);if(se(i)||ne(i))return Sb(r,n,i),mi(r,i,t,n);if(typeof i!="symbol"){if(le(e)){n=Object.freeze(n.concat(e));for(let s=0;sr.replace(/[!,[\]{}]/g,e=>TR[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+CR(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&&se(e.contents)){let s={};ar(e.contents,(o,a)=>{se(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 xa(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 nf(r){let e=new Set;return ar(r,{Value(t,n){n.anchor&&e.add(n.anchor)}}),e}function sf(r,e){for(let t=1;;++t){let n=`${r}${t}`;if(!e.has(n))return n}}function Eb(r,e){let t=[],n=new Map,i=null;return{onAnchor:s=>{t.push(s),i!=null||(i=nf(r));let o=sf(e,i);return i.add(o),o},setAnchors:()=>{for(let s of t){let o=n.get(s);if(typeof o=="object"&&o.anchor&&(G(o.node)||le(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 Qr(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||!Aa(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!=null&&t.keep)?Number(r):r}var Zr=class{constructor(e){Object.defineProperty(this,Ze,{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(!sr(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"?Qr(s,{"":a},"",a):a}};var Sr=class extends Zr{constructor(e){super(Sa),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,t){if((t==null?void 0:t.maxAliasCount)===0)throw new ReferenceError("Alias resolution is disabled");let n;t!=null&&t.aliasResolveCache?n=t.aliasResolveCache:(n=[],ar(e,{Node:(s,o)=>{(Dt(o)||Aa(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)}return i}toJSON(e,t){if(!t)return{source:this.source};let{anchors:n,doc:i,maxAliasCount:s}=t,o=this.resolve(i,t);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let a=n.get(o);if(a||(Te(o,null,t),a=n.get(o)),(a==null?void 0:a.res)===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(s>=0&&(a.count+=1,a.aliasCount===0&&(a.aliasCount=Pa(i,o,n)),a.count*a.aliasCount>s)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return a.res}toString(e,t,n){let i=`*${this.source}`;if(e){if(xa(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 Pa(r,e,t){if(Dt(e)){let n=e.resolve(r),i=t&&n&&t.get(n);return i?i.count*i.aliasCount:0}else if(le(e)){let n=0;for(let i of e.items){let s=Pa(r,i,t);s>n&&(n=s)}return n}else if(ne(e)){let n=Pa(r,e.key,t),i=Pa(r,e.value,t);return Math.max(n,i)}return 1}var Ia=r=>!r||typeof r!="function"&&typeof r!="object",q=class extends Zr{constructor(e){super(yt),this.value=e}toJSON(e,t){return t!=null&&t.keep?this.value:Te(this.value,e,t)}toString(){return String(this.value)}};q.BLOCK_FOLDED="BLOCK_FOLDED";q.BLOCK_LITERAL="BLOCK_LITERAL";q.PLAIN="PLAIN";q.QUOTE_DOUBLE="QUOTE_DOUBLE";q.QUOTE_SINGLE="QUOTE_SINGLE";var MR="tag:yaml.org,2002:";function NR(r,e,t){var n;if(e){let i=t.filter(o=>o.tag===e),s=(n=i.find(o=>!o.format))!=null?n:i[0];if(!s)throw new Error(`Tag ${e} not found`);return s}return t.find(i=>{var s;return((s=i.identify)==null?void 0:s.call(i,r))&&!i.format})}function Er(r,e,t){var u,f,p,y;if(sr(r)&&(r=r.contents),se(r))return r;if(ne(r)){let h=(f=(u=t.schema[jt]).createNode)==null?void 0:f.call(u,t.schema,null,t);return h.items.push(r),h}(r instanceof String||r instanceof Number||r instanceof Boolean||typeof BigInt!="undefined"&&r instanceof BigInt)&&(r=r.valueOf());let{aliasDuplicateObjects:n,onAnchor:i,onTagObj:s,schema:o,sourceObjects:a}=t,c;if(n&&r&&typeof r=="object"){if(c=a.get(r),c)return(p=c.anchor)!=null||(c.anchor=i(r)),new Sr(c.anchor);c={anchor:null,node:null},a.set(r,c)}e!=null&&e.startsWith("!!")&&(e=MR+e.slice(2));let l=NR(r,e,o.tags);if(!l){if(r&&typeof r.toJSON=="function"&&(r=r.toJSON()),!r||typeof r!="object"){let h=new q(r);return c&&(c.node=h),h}l=r instanceof Map?o[jt]:Symbol.iterator in Object(r)?o[$r]:o[jt]}s&&(s(l),delete t.onTagObj);let d=l!=null&&l.createNode?l.createNode(t.schema,r,t):typeof((y=l==null?void 0:l.nodeClass)==null?void 0:y.from)=="function"?l.nodeClass.from(t.schema,r,t):new q(r);return e?d.tag=e:l.default||(d.tag=l.tag),c&&(c.node=d),d}function Cs(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 Er(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 _i=r=>r==null||typeof r=="object"&&!!r[Symbol.iterator]().next().done,gi=class extends Zr{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=>se(n)||ne(n)?n.clone(e):n),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(_i(e))this.add(t);else{let[n,...i]=e,s=this.get(n,!0);if(le(s))s.addIn(i,t);else if(s===void 0&&this.schema)this.set(n,Cs(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(le(i))return i.deleteIn(n);throw new Error(`Expected YAML collection at ${t}. Remaining path: ${n}`)}getIn(e,t){let[n,...i]=e,s=this.get(n,!0);return i.length===0?!t&&G(s)?s.value:s:le(s)?s.getIn(i,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!ne(t))return!1;let n=t.value;return n==null||e&&G(n)&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn(e){let[t,...n]=e;if(n.length===0)return this.has(t);let i=this.get(t,!0);return le(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(le(s))s.setIn(i,t);else if(s===void 0&&this.schema)this.set(n,Cs(this.schema,i,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${i}`)}}};var Ab=r=>r.replace(/^(?!$)(?: $)?/gm,"#");function It(r,e){return/^\n+$/.test(r)?r.substring(1):e?r.replace(/^(?! *$)/gm,e):r}var lr=(r,e,t)=>r.endsWith(` +`)}};cr.defaultYaml={explicit:!1,version:"1.2"};cr.defaultTags={"!!":"tag:yaml.org,2002:"};function xa(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 nf(r){let e=new Set;return ar(r,{Value(t,n){n.anchor&&e.add(n.anchor)}}),e}function sf(r,e){for(let t=1;;++t){let n=`${r}${t}`;if(!e.has(n))return n}}function Eb(r,e){let t=[],n=new Map,i=null;return{onAnchor:s=>{t.push(s),i!=null||(i=nf(r));let o=sf(e,i);return i.add(o),o},setAnchors:()=>{for(let s of t){let o=n.get(s);if(typeof o=="object"&&o.anchor&&(G(o.node)||le(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 Qr(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||!Aa(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!=null&&t.keep)?Number(r):r}var Zr=class{constructor(e){Object.defineProperty(this,Ze,{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(!sr(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"?Qr(s,{"":a},"",a):a}};var Sr=class extends Zr{constructor(e){super(Sa),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,t){if((t==null?void 0:t.maxAliasCount)===0)throw new ReferenceError("Alias resolution is disabled");let n;t!=null&&t.aliasResolveCache?n=t.aliasResolveCache:(n=[],ar(e,{Node:(s,o)=>{(Dt(o)||Aa(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)}return i}toJSON(e,t){if(!t)return{source:this.source};let{anchors:n,doc:i,maxAliasCount:s}=t,o=this.resolve(i,t);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let a=n.get(o);if(a||(Te(o,null,t),a=n.get(o)),(a==null?void 0:a.res)===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(s>=0&&(a.count+=1,a.aliasCount===0&&(a.aliasCount=Pa(i,o,n)),a.count*a.aliasCount>s)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return a.res}toString(e,t,n){let i=`*${this.source}`;if(e){if(xa(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 Pa(r,e,t){if(Dt(e)){let n=e.resolve(r),i=t&&n&&t.get(n);return i?i.count*i.aliasCount:0}else if(le(e)){let n=0;for(let i of e.items){let s=Pa(r,i,t);s>n&&(n=s)}return n}else if(ne(e)){let n=Pa(r,e.key,t),i=Pa(r,e.value,t);return Math.max(n,i)}return 1}var Ia=r=>!r||typeof r!="function"&&typeof r!="object",F=class extends Zr{constructor(e){super(yt),this.value=e}toJSON(e,t){return t!=null&&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 MR="tag:yaml.org,2002:";function NR(r,e,t){var n;if(e){let i=t.filter(o=>o.tag===e),s=(n=i.find(o=>!o.format))!=null?n:i[0];if(!s)throw new Error(`Tag ${e} not found`);return s}return t.find(i=>{var s;return((s=i.identify)==null?void 0:s.call(i,r))&&!i.format})}function Er(r,e,t){var u,f,p,y;if(sr(r)&&(r=r.contents),se(r))return r;if(ne(r)){let h=(f=(u=t.schema[jt]).createNode)==null?void 0:f.call(u,t.schema,null,t);return h.items.push(r),h}(r instanceof String||r instanceof Number||r instanceof Boolean||typeof BigInt!="undefined"&&r instanceof BigInt)&&(r=r.valueOf());let{aliasDuplicateObjects:n,onAnchor:i,onTagObj:s,schema:o,sourceObjects:a}=t,c;if(n&&r&&typeof r=="object"){if(c=a.get(r),c)return(p=c.anchor)!=null||(c.anchor=i(r)),new Sr(c.anchor);c={anchor:null,node:null},a.set(r,c)}e!=null&&e.startsWith("!!")&&(e=MR+e.slice(2));let l=NR(r,e,o.tags);if(!l){if(r&&typeof r.toJSON=="function"&&(r=r.toJSON()),!r||typeof r!="object"){let h=new F(r);return c&&(c.node=h),h}l=r instanceof Map?o[jt]:Symbol.iterator in Object(r)?o[$r]:o[jt]}s&&(s(l),delete t.onTagObj);let d=l!=null&&l.createNode?l.createNode(t.schema,r,t):typeof((y=l==null?void 0:l.nodeClass)==null?void 0:y.from)=="function"?l.nodeClass.from(t.schema,r,t):new F(r);return e?d.tag=e:l.default||(d.tag=l.tag),c&&(c.node=d),d}function Cs(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 Er(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 _i=r=>r==null||typeof r=="object"&&!!r[Symbol.iterator]().next().done,gi=class extends Zr{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=>se(n)||ne(n)?n.clone(e):n),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(_i(e))this.add(t);else{let[n,...i]=e,s=this.get(n,!0);if(le(s))s.addIn(i,t);else if(s===void 0&&this.schema)this.set(n,Cs(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(le(i))return i.deleteIn(n);throw new Error(`Expected YAML collection at ${t}. Remaining path: ${n}`)}getIn(e,t){let[n,...i]=e,s=this.get(n,!0);return i.length===0?!t&&G(s)?s.value:s:le(s)?s.getIn(i,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!ne(t))return!1;let n=t.value;return n==null||e&&G(n)&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn(e){let[t,...n]=e;if(n.length===0)return this.has(t);let i=this.get(t,!0);return le(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(le(s))s.setIn(i,t);else if(s===void 0&&this.schema)this.set(n,Cs(this.schema,i,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${i}`)}}};var Ab=r=>r.replace(/^(?!$)(?: $)?/gm,"#");function It(r,e){return/^\n+$/.test(r)?r.substring(1):e?r.replace(/^(?! *$)/gm,e):r}var lr=(r,e,t)=>r.endsWith(` `)?It(t,e):t.includes(` `)?` `+It(t,e):(r.endsWith(" ")?"":" ")+t;var of="flow",Oa="block",Ms="quoted";function Ns(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):u=i-n);let f,p,y=!1,h=-1,m=-1,g=-1;t===Oa&&(h=kb(r,h,e.length),h!==-1&&(u=h+c));for(let w;w=r[h+=1];){if(t===Ms&&w==="\\"){switch(m=h,r[h+1]){case"x":h+=3;break;case"u":h+=5;break;case"U":h+=9;break;default:h+=1}g=h}if(w===` @@ -41,41 +41,41 @@ ${e}${r.slice(x+1,v)}`)}return _}function kb(r,e,t){let n=e,i=e+1,s=r[i];for(;s= ${t}`)+"'";return e.implicitKey?n:Ns(n,t,of,Ta(e,!1))}function bi(r,e){let{singleQuote:t}=e.options,n;if(t===!1)n=Ls;else{let i=r.includes('"'),s=r.includes("'");i&&!s?n=af:s&&!i?n=Ls:n=t?af:Ls}return n(r,e)}var cf;try{cf=new RegExp(`(^|(? `;let u,f;for(f=t.length;f>0;--f){let v=t[f-1];if(v!==` `&&v!==" "&&v!==" ")break}let p=t.substring(f),y=p.indexOf(` `);y===-1?u="-":t===p||y!==p.length-1?(u="+",s&&s()):u="",p&&(t=t.slice(0,-p.length),p[p.length-1]===` `&&(p=p.slice(0,-1)),p=p.replace(cf,`$&${l}`));let h=!1,m,g=-1;for(m=0;m{P=!0});let $=Ns(`${_}${v}${p}`,l,Oa,O);if(!P)return`>${x} -${l}${$}`}return t=t.replace(/\n+/g,`$&${l}`),`|${x} +$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),P=!1,O=Ta(n,!0);o!=="folded"&&e!==F.BLOCK_FOLDED&&(O.onOverflow=()=>{P=!0});let A=Ns(`${_}${v}${p}`,l,Oa,O);if(!P)return`>${x} +${l}${A}`}return t=t.replace(/\n+/g,`$&${l}`),`|${x} ${l}${_}${t}${p}`}function jR(r,e,t,n){let{type:i,value:s}=r,{actualString:o,implicitKey:a,indent:c,indentStep:l,inFlow:d}=e;if(a&&s.includes(` `)||d&&/[[\]{},]/.test(s))return bi(s,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(s))return a||d||!s.includes(` -`)?bi(s,e):Ra(r,e,t,n);if(!a&&!d&&i!==q.PLAIN&&s.includes(` +`)?bi(s,e):Ra(r,e,t,n);if(!a&&!d&&i!==F.PLAIN&&s.includes(` `))return Ra(r,e,t,n);if(Ca(s)){if(c==="")return e.forceBlockIndent=!0,Ra(r,e,t,n);if(a&&c===l)return bi(s,e)}let u=s.replace(/\n+/g,`$& -${c}`);if(o){let f=h=>{var m;return h.default&&h.tag!=="tag:yaml.org,2002:str"&&((m=h.test)==null?void 0:m.test(u))},{compat:p,tags:y}=e.doc.schema;if(y.some(f)||p!=null&&p.some(f))return bi(s,e)}return a?u:Ns(u,c,of,Ta(e,!1))}function kn(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!==q.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=q.QUOTE_DOUBLE);let c=d=>{switch(d){case q.BLOCK_FOLDED:case q.BLOCK_LITERAL:return i||s?bi(o.value,e):Ra(o,e,t,n);case q.QUOTE_DOUBLE:return Ls(o.value,e);case q.QUOTE_SINGLE:return af(o.value,e);case q.PLAIN:return jR(o,e,t,n);default:return null}},l=c(a);if(l===null){let{defaultKeyType:d,defaultStringType:u}=e.options,f=i&&d||u;if(l=c(f),l===null)throw new Error(`Unsupported default string type ${f}`)}return l}function Ma(r,e){let t=Object.assign({blockQuote:!0,commentString:Ab,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},r.schema.toStringOptions,e),n;switch(t.collectionStyle){case"block":n=!1;break;case"flow":n=!0;break;default:n=null}return{anchors:new Set,doc:r,flowCollectionPadding:t.flowCollectionPadding?" ":"",indent:"",indentStep:typeof t.indent=="number"?" ".repeat(t.indent):" ",inFlow:n,options:t}}function DR(r,e){var i,s,o,a;if(e.tag){let c=r.filter(l=>l.tag===e.tag);if(c.length>0)return(i=c.find(l=>l.format===e.format))!=null?i:c[0]}let t,n;if(G(e)){n=e.value;let c=r.filter(l=>{var d;return(d=l.identify)==null?void 0:d.call(l,n)});if(c.length>1){let l=c.filter(d=>d.test);l.length>0&&(c=l)}t=(s=c.find(l=>l.format===e.format))!=null?s:c.find(l=>!l.format)}else n=e,t=r.find(c=>c.nodeClass&&n instanceof c.nodeClass);if(!t){let c=(a=(o=n==null?void 0:n.constructor)==null?void 0:o.name)!=null?a:n===null?"null":typeof n;throw new Error(`Tag not resolved for ${c} value`)}return t}function qR(r,e,{anchors:t,doc:n}){var a;if(!n.directives)return"";let i=[],s=(G(r)||le(r))&&r.anchor;s&&xa(s)&&(t.add(s),i.push(`&${s}`));let o=(a=r.tag)!=null?a:e.default?null:e.tag;return o&&i.push(n.directives.tagString(o)),i.join(" ")}function Ar(r,e,t,n){var c,l;if(ne(r))return r.toString(e,t,n);if(Dt(r)){if(e.doc.directives)return r.toString(e);if((c=e.resolvedAliases)!=null&&c.has(r))throw new TypeError("Cannot stringify circular structure without alias nodes");e.resolvedAliases?e.resolvedAliases.add(r):e.resolvedAliases=new Set([r]),r=r.resolve(e.doc)}let i,s=se(r)?r:e.doc.createNode(r,{onTagObj:d=>i=d});i!=null||(i=DR(e.doc.schema.tags,s));let o=qR(s,i,e);o.length>0&&(e.indentAtStart=((l=e.indentAtStart)!=null?l:0)+o.length+1);let a=typeof i.stringify=="function"?i.stringify(s,e,t,n):G(s)?kn(s,e,t,n):s.toString(e,t,n);return o?G(s)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o} -${e.indent}${a}`:a}function xb({key:r,value:e},t,n,i){var O,$;let{allNullValues:s,doc:o,indent:a,indentStep:c,options:{commentString:l,indentSeq:d,simpleKeys:u}}=t,f=se(r)&&r.comment||null;if(u){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(le(r)||!se(r)&&typeof r=="object"){let R="With simple keys, collection cannot be used as a key value";throw new Error(R)}}let p=!u&&(!r||f&&e==null&&!t.inFlow||le(r)||(G(r)?r.type===q.BLOCK_FOLDED||r.type===q.BLOCK_LITERAL:typeof r=="object"));t=Object.assign({},t,{allNullValues:!1,implicitKey:!p&&(u||!s),indent:a+c});let y=!1,h=!1,m=Ar(r,t,()=>y=!0,()=>h=!0);if(!p&&!t.inFlow&&m.length>1024){if(u)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 y&&n&&n(),m===""?"?":p?`? ${m}`:m}else if(s&&!u||e==null&&p)return m=`? ${m}`,f&&!y?m+=lr(m,t.indent,l(f)):h&&i&&i(),m;y&&(f=null),p?(f&&(m+=lr(m,t.indent,l(f))),m=`? ${m} +${c}`);if(o){let f=h=>{var m;return h.default&&h.tag!=="tag:yaml.org,2002:str"&&((m=h.test)==null?void 0:m.test(u))},{compat:p,tags:y}=e.doc.schema;if(y.some(f)||p!=null&&p.some(f))return bi(s,e)}return a?u:Ns(u,c,of,Ta(e,!1))}function kn(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=d=>{switch(d){case F.BLOCK_FOLDED:case F.BLOCK_LITERAL:return i||s?bi(o.value,e):Ra(o,e,t,n);case F.QUOTE_DOUBLE:return Ls(o.value,e);case F.QUOTE_SINGLE:return af(o.value,e);case F.PLAIN:return jR(o,e,t,n);default:return null}},l=c(a);if(l===null){let{defaultKeyType:d,defaultStringType:u}=e.options,f=i&&d||u;if(l=c(f),l===null)throw new Error(`Unsupported default string type ${f}`)}return l}function Ma(r,e){let t=Object.assign({blockQuote:!0,commentString:Ab,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},r.schema.toStringOptions,e),n;switch(t.collectionStyle){case"block":n=!1;break;case"flow":n=!0;break;default:n=null}return{anchors:new Set,doc:r,flowCollectionPadding:t.flowCollectionPadding?" ":"",indent:"",indentStep:typeof t.indent=="number"?" ".repeat(t.indent):" ",inFlow:n,options:t}}function DR(r,e){var i,s,o,a;if(e.tag){let c=r.filter(l=>l.tag===e.tag);if(c.length>0)return(i=c.find(l=>l.format===e.format))!=null?i:c[0]}let t,n;if(G(e)){n=e.value;let c=r.filter(l=>{var d;return(d=l.identify)==null?void 0:d.call(l,n)});if(c.length>1){let l=c.filter(d=>d.test);l.length>0&&(c=l)}t=(s=c.find(l=>l.format===e.format))!=null?s:c.find(l=>!l.format)}else n=e,t=r.find(c=>c.nodeClass&&n instanceof c.nodeClass);if(!t){let c=(a=(o=n==null?void 0:n.constructor)==null?void 0:o.name)!=null?a:n===null?"null":typeof n;throw new Error(`Tag not resolved for ${c} value`)}return t}function qR(r,e,{anchors:t,doc:n}){var a;if(!n.directives)return"";let i=[],s=(G(r)||le(r))&&r.anchor;s&&xa(s)&&(t.add(s),i.push(`&${s}`));let o=(a=r.tag)!=null?a:e.default?null:e.tag;return o&&i.push(n.directives.tagString(o)),i.join(" ")}function Ar(r,e,t,n){var c,l;if(ne(r))return r.toString(e,t,n);if(Dt(r)){if(e.doc.directives)return r.toString(e);if((c=e.resolvedAliases)!=null&&c.has(r))throw new TypeError("Cannot stringify circular structure without alias nodes");e.resolvedAliases?e.resolvedAliases.add(r):e.resolvedAliases=new Set([r]),r=r.resolve(e.doc)}let i,s=se(r)?r:e.doc.createNode(r,{onTagObj:d=>i=d});i!=null||(i=DR(e.doc.schema.tags,s));let o=qR(s,i,e);o.length>0&&(e.indentAtStart=((l=e.indentAtStart)!=null?l:0)+o.length+1);let a=typeof i.stringify=="function"?i.stringify(s,e,t,n):G(s)?kn(s,e,t,n):s.toString(e,t,n);return o?G(s)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o} +${e.indent}${a}`:a}function xb({key:r,value:e},t,n,i){var O,A;let{allNullValues:s,doc:o,indent:a,indentStep:c,options:{commentString:l,indentSeq:d,simpleKeys:u}}=t,f=se(r)&&r.comment||null;if(u){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(le(r)||!se(r)&&typeof r=="object"){let R="With simple keys, collection cannot be used as a key value";throw new Error(R)}}let p=!u&&(!r||f&&e==null&&!t.inFlow||le(r)||(G(r)?r.type===F.BLOCK_FOLDED||r.type===F.BLOCK_LITERAL:typeof r=="object"));t=Object.assign({},t,{allNullValues:!1,implicitKey:!p&&(u||!s),indent:a+c});let y=!1,h=!1,m=Ar(r,t,()=>y=!0,()=>h=!0);if(!p&&!t.inFlow&&m.length>1024){if(u)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 y&&n&&n(),m===""?"?":p?`? ${m}`:m}else if(s&&!u||e==null&&p)return m=`? ${m}`,f&&!y?m+=lr(m,t.indent,l(f)):h&&i&&i(),m;y&&(f=null),p?(f&&(m+=lr(m,t.indent,l(f))),m=`? ${m} ${a}:`):(m=`${m}:`,f&&(m+=lr(m,t.indent,l(f))));let g,_,w;se(e)?(g=!!e.spaceBefore,_=e.commentBefore,w=e.comment):(g=!1,_=null,w=null,e&&typeof e=="object"&&(e=o.createNode(e))),t.implicitKey=!1,!p&&!f&&G(e)&&(t.indentAtStart=m.length+1),h=!1,!d&&c.length>=2&&!t.inFlow&&!p&&Ft(e)&&!e.flow&&!e.tag&&!e.anchor&&(t.indent=t.indent.substring(2));let x=!1,v=Ar(e,t,()=>x=!0,()=>h=!0),P=" ";if(f||g||_){if(P=g?` `:"",_){let R=l(_);P+=` ${It(R,t.indent)}`}v===""&&!t.inFlow?P===` `&&w&&(P=` `):P+=` -${t.indent}`}else if(!p&&le(e)){let R=v[0],S=v.indexOf(` -`),U=S!==-1,B=($=(O=t.inFlow)!=null?O:e.flow)!=null?$:e.items.length===0;if(U||!B){let T=!1;if(U&&(R==="&"||R==="!")){let E=v.indexOf(" ");R==="&"&&E!==-1&&Er===La||typeof r=="symbol"&&r.description===La,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new q(Symbol(La)),{addToJSMap:df}),stringify:()=>La},Pb=(r,e)=>(Vt.identify(e)||G(e)&&(!e.type||e.type===q.PLAIN)&&Vt.identify(e.value))&&(r==null?void 0:r.doc.schema.tags.some(t=>t.tag===Vt.tag&&t.default));function df(r,e,t){let n=Ib(r,t);if(Ft(n))for(let i of n.items)lf(r,e,i);else if(Array.isArray(n))for(let i of n)lf(r,e,i);else lf(r,e,n)}function lf(r,e,t){let n=Ib(r,t);if(!qt(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 Ib(r,e){return r&&Dt(e)?e.resolve(r.doc,r):e}function ja(r,e,{key:t,value:n}){if(se(t)&&t.addToJSMap)t.addToJSMap(r,e,n);else if(Pb(r,t))df(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=FR(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 FR(r,e,t){if(e===null)return"";if(typeof e!="object")return String(e);if(se(r)&&(t!=null&&t.doc)){let n=Ma(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)+'..."'),Na(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 wi(r,e,t){let n=Er(r,void 0,t),i=Er(e,void 0,t);return new Se(n,i)}var Se=class r{constructor(e,t=null){Object.defineProperty(this,Ze,{value:rf}),this.key=e,this.value=t}clone(e){let{key:t,value:n}=this;return se(t)&&(t=t.clone(e)),se(n)&&(n=n.clone(e)),new r(t,n)}toJSON(e,t){let n=t!=null&&t.mapAsMap?new Map:{};return ja(t,n,this)}toString(e,t,n){return e!=null&&e.doc?xb(this,e,t,n):JSON.stringify(this)}};function qa(r,e,t){var s;return(((s=e.inFlow)!=null?s:r.flow)?UR:VR)(r,e,t)}function VR({comment:r,items:e},t,{blockItemPrefix:n,flowChars:i,itemIndent:s,onChompKeep:o,onComment:a}){let{indent:c,options:{commentString:l}}=t,d=Object.assign({},t,{indent:s,type:null}),u=!1,f=[];for(let y=0;ym=null,()=>u=!0);m&&(g+=lr(g,s,l(m))),u&&m&&(u=!1),f.push(n+g)}let p;if(f.length===0)p=i.start+i.end;else{p=f[0];for(let y=1;yr===La||typeof r=="symbol"&&r.description===La,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new F(Symbol(La)),{addToJSMap:df}),stringify:()=>La},Pb=(r,e)=>(Vt.identify(e)||G(e)&&(!e.type||e.type===F.PLAIN)&&Vt.identify(e.value))&&(r==null?void 0:r.doc.schema.tags.some(t=>t.tag===Vt.tag&&t.default));function df(r,e,t){let n=Ib(r,t);if(Ft(n))for(let i of n.items)lf(r,e,i);else if(Array.isArray(n))for(let i of n)lf(r,e,i);else lf(r,e,n)}function lf(r,e,t){let n=Ib(r,t);if(!qt(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 Ib(r,e){return r&&Dt(e)?e.resolve(r.doc,r):e}function ja(r,e,{key:t,value:n}){if(se(t)&&t.addToJSMap)t.addToJSMap(r,e,n);else if(Pb(r,t))df(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=FR(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 FR(r,e,t){if(e===null)return"";if(typeof e!="object")return String(e);if(se(r)&&(t!=null&&t.doc)){let n=Ma(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)+'..."'),Na(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 wi(r,e,t){let n=Er(r,void 0,t),i=Er(e,void 0,t);return new Se(n,i)}var Se=class r{constructor(e,t=null){Object.defineProperty(this,Ze,{value:rf}),this.key=e,this.value=t}clone(e){let{key:t,value:n}=this;return se(t)&&(t=t.clone(e)),se(n)&&(n=n.clone(e)),new r(t,n)}toJSON(e,t){let n=t!=null&&t.mapAsMap?new Map:{};return ja(t,n,this)}toString(e,t,n){return e!=null&&e.doc?xb(this,e,t,n):JSON.stringify(this)}};function qa(r,e,t){var s;return(((s=e.inFlow)!=null?s:r.flow)?UR:VR)(r,e,t)}function VR({comment:r,items:e},t,{blockItemPrefix:n,flowChars:i,itemIndent:s,onChompKeep:o,onComment:a}){let{indent:c,options:{commentString:l}}=t,d=Object.assign({},t,{indent:s,type:null}),u=!1,f=[];for(let y=0;ym=null,()=>u=!0);m&&(g+=lr(g,s,l(m))),u&&m&&(u=!1),f.push(n+g)}let p;if(f.length===0)p=i.start+i.end;else{p=f[0];for(let y=1;ym=null);l||(l=u.length>d||g.includes(` `)),y0&&(l||(l=u.reduce((_,w)=>_+w.length+2,2)+(g.length+2)>e.options.lineWidth)),l&&(g+=",")),m&&(g+=lr(g,n,a(m))),u.push(g),d=u.length}let{start:f,end:p}=t;if(u.length===0)return f+p;if(!l){let y=u.reduce((h,m)=>h+m.length+2,2);l=e.options.lineWidth>0&&y>e.options.lineWidth}if(l){let y=f;for(let h of u)y+=h?` ${s}${i}${h}`:` `;return`${y} -${i}${p}`}else return`${f}${o}${u.join(" ")}${o}${p}`}function Da({indent:r,options:{commentString:e}},t,n,i){if(n&&i&&(n=n.replace(/^\n+/,"")),n){let s=It(e(n),r);t.push(s.trimStart())}}function en(r,e){let t=G(e)?e.value:e;for(let n of r)if(ne(n)&&(n.key===e||n.key===t||G(n.key)&&n.key.value===t))return n}var xe=class extends gi{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(jt,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(wi(c,l,n))};if(t instanceof Map)for(let[c,l]of t)a(c,l);else if(t&&typeof t=="object")for(let c of Object.keys(t))a(c,t[c]);return typeof e.sortMapEntries=="function"&&o.items.sort(e.sortMapEntries),o}add(e,t){var o;let n;ne(e)?n=e:!e||typeof e!="object"||!("key"in e)?n=new Se(e,e==null?void 0:e.value):n=new Se(e.key,e.value);let i=en(this.items,n.key),s=(o=this.schema)==null?void 0:o.sortMapEntries;if(i){if(!t)throw new Error(`Key ${n.key} already set`);G(i.value)&&Ia(n.value)?i.value.value=n.value:i.value=n.value}else if(s){let a=this.items.findIndex(c=>s(n,c)<0);a===-1?this.items.push(n):this.items.splice(a,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){var s;let n=en(this.items,e),i=n==null?void 0:n.value;return(s=!t&&G(i)?i.value:i)!=null?s:void 0}has(e){return!!en(this.items,e)}set(e,t){this.add(new Se(e,t),!0)}toJSON(e,t,n){let i=n?new n:t!=null&&t.mapAsMap?new Map:{};t!=null&&t.onCreate&&t.onCreate(i);for(let s of this.items)ja(t,i,s);return i}toString(e,t,n){if(!e)return JSON.stringify(this);for(let i of this.items)if(!ne(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})),qa(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:n,onComment:t})}};var Ut={collection:"map",default:!0,nodeClass:xe,tag:"tag:yaml.org,2002:map",resolve(r,e){return qt(r)||e("Expected a mapping for this tag"),r},createNode:(r,e,t)=>xe.from(r,e,t)};var He=class extends gi{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super($r,e),this.items=[]}add(e){this.items.push(e)}delete(e){let t=Fa(e);return typeof t!="number"?!1:this.items.splice(t,1).length>0}get(e,t){let n=Fa(e);if(typeof n!="number")return;let i=this.items[n];return!t&&G(i)?i.value:i}has(e){let t=Fa(e);return typeof t=="number"&&t=0?e:null}var Bt={collection:"seq",default:!0,nodeClass:He,tag:"tag:yaml.org,2002:seq",resolve(r,e){return Ft(r)||e("Expected a sequence for this tag"),r},createNode:(r,e,t)=>He.from(r,e,t)};var tn={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),kn(r,e,t,n)}};var xn={identify:r=>r==null,createNode:()=>new q(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new q(null),stringify:({source:r},e)=>typeof r=="string"&&xn.test.test(r)?r:e.options.nullStr};var js={identify:r=>typeof r=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:r=>new q(r[0]==="t"||r[0]==="T"),stringify({source:r,value:e},t){if(r&&js.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 Ke({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 Va={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:Ke},Ua={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():Ke(r)}},Ba={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 q(parseFloat(r)),t=r.indexOf(".");return t!==-1&&r[r.length-1]==="0"&&(e.minFractionDigits=r.length-t-1),e},stringify:Ke};var za=r=>typeof r=="bigint"||Number.isInteger(r),uf=(r,e,t,{intAsBigInt:n})=>n?BigInt(r):parseInt(r.substring(e),t);function Ob(r,e,t){let{value:n}=r;return za(n)&&n>=0?t+n.toString(e):Ke(r)}var Ha={identify:r=>za(r)&&r>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(r,e,t)=>uf(r,2,8,t),stringify:r=>Ob(r,8,"0o")},Ka={identify:za,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(r,e,t)=>uf(r,0,10,t),stringify:Ke},Wa={identify:r=>za(r)&&r>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(r,e,t)=>uf(r,2,16,t),stringify:r=>Ob(r,16,"0x")};var Rb=[Ut,Bt,tn,xn,js,Ha,Ka,Wa,Va,Ua,Ba];function Tb(r){return typeof r=="bigint"||Number.isInteger(r)}var Ga=({value:r})=>JSON.stringify(r),BR=[{identify:r=>typeof r=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:r=>r,stringify:Ga},{identify:r=>r==null,createNode:()=>new q(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Ga},{identify:r=>typeof r=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:r=>r==="true",stringify:Ga},{identify:Tb,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})=>Tb(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:Ga}],zR={default:!0,tag:"",test:/^/,resolve(r,e){return e(`Unresolved plain scalar ${JSON.stringify(r)}`),r}},Cb=[Ut,Bt].concat(BR,zR);var Ds={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 s=i.items[0]||new Se(new q(null));if(i.commentBefore&&(s.key.commentBefore=s.key.commentBefore?`${i.commentBefore} +${i}${p}`}else return`${f}${o}${u.join(" ")}${o}${p}`}function Da({indent:r,options:{commentString:e}},t,n,i){if(n&&i&&(n=n.replace(/^\n+/,"")),n){let s=It(e(n),r);t.push(s.trimStart())}}function en(r,e){let t=G(e)?e.value:e;for(let n of r)if(ne(n)&&(n.key===e||n.key===t||G(n.key)&&n.key.value===t))return n}var xe=class extends gi{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(jt,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(wi(c,l,n))};if(t instanceof Map)for(let[c,l]of t)a(c,l);else if(t&&typeof t=="object")for(let c of Object.keys(t))a(c,t[c]);return typeof e.sortMapEntries=="function"&&o.items.sort(e.sortMapEntries),o}add(e,t){var o;let n;ne(e)?n=e:!e||typeof e!="object"||!("key"in e)?n=new Se(e,e==null?void 0:e.value):n=new Se(e.key,e.value);let i=en(this.items,n.key),s=(o=this.schema)==null?void 0:o.sortMapEntries;if(i){if(!t)throw new Error(`Key ${n.key} already set`);G(i.value)&&Ia(n.value)?i.value.value=n.value:i.value=n.value}else if(s){let a=this.items.findIndex(c=>s(n,c)<0);a===-1?this.items.push(n):this.items.splice(a,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){var s;let n=en(this.items,e),i=n==null?void 0:n.value;return(s=!t&&G(i)?i.value:i)!=null?s:void 0}has(e){return!!en(this.items,e)}set(e,t){this.add(new Se(e,t),!0)}toJSON(e,t,n){let i=n?new n:t!=null&&t.mapAsMap?new Map:{};t!=null&&t.onCreate&&t.onCreate(i);for(let s of this.items)ja(t,i,s);return i}toString(e,t,n){if(!e)return JSON.stringify(this);for(let i of this.items)if(!ne(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})),qa(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:n,onComment:t})}};var Ut={collection:"map",default:!0,nodeClass:xe,tag:"tag:yaml.org,2002:map",resolve(r,e){return qt(r)||e("Expected a mapping for this tag"),r},createNode:(r,e,t)=>xe.from(r,e,t)};var He=class extends gi{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super($r,e),this.items=[]}add(e){this.items.push(e)}delete(e){let t=Fa(e);return typeof t!="number"?!1:this.items.splice(t,1).length>0}get(e,t){let n=Fa(e);if(typeof n!="number")return;let i=this.items[n];return!t&&G(i)?i.value:i}has(e){let t=Fa(e);return typeof t=="number"&&t=0?e:null}var Bt={collection:"seq",default:!0,nodeClass:He,tag:"tag:yaml.org,2002:seq",resolve(r,e){return Ft(r)||e("Expected a sequence for this tag"),r},createNode:(r,e,t)=>He.from(r,e,t)};var tn={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),kn(r,e,t,n)}};var xn={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"&&xn.test.test(r)?r:e.options.nullStr};var js={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&&js.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 Ke({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 Va={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:Ke},Ua={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():Ke(r)}},Ba={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:Ke};var za=r=>typeof r=="bigint"||Number.isInteger(r),uf=(r,e,t,{intAsBigInt:n})=>n?BigInt(r):parseInt(r.substring(e),t);function Ob(r,e,t){let{value:n}=r;return za(n)&&n>=0?t+n.toString(e):Ke(r)}var Ha={identify:r=>za(r)&&r>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(r,e,t)=>uf(r,2,8,t),stringify:r=>Ob(r,8,"0o")},Ka={identify:za,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(r,e,t)=>uf(r,0,10,t),stringify:Ke},Wa={identify:r=>za(r)&&r>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(r,e,t)=>uf(r,2,16,t),stringify:r=>Ob(r,16,"0x")};var Rb=[Ut,Bt,tn,xn,js,Ha,Ka,Wa,Va,Ua,Ba];function Tb(r){return typeof r=="bigint"||Number.isInteger(r)}var Ga=({value:r})=>JSON.stringify(r),BR=[{identify:r=>typeof r=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:r=>r,stringify:Ga},{identify:r=>r==null,createNode:()=>new F(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Ga},{identify:r=>typeof r=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:r=>r==="true",stringify:Ga},{identify:Tb,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})=>Tb(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:Ga}],zR={default:!0,tag:"",test:/^/,resolve(r,e){return e(`Unresolved plain scalar ${JSON.stringify(r)}`),r}},Cb=[Ut,Bt].concat(BR,zR);var Ds={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 s=i.items[0]||new Se(new F(null));if(i.commentBefore&&(s.key.commentBefore=s.key.commentBefore?`${i.commentBefore} ${s.key.commentBefore}`:i.commentBefore),i.comment){let o=(t=s.value)!=null?t:s.key;o.comment=o.comment?`${i.comment} -${o.comment}`:i.comment}i=s}r.items[n]=ne(i)?i:new Se(i)}}else e("Expected a sequence for this tag");return r}function pf(r,e,t){let{replacer:n}=t,i=new He(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(wi(a,c,t))}return i}var qs={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:ff,createNode:pf};var vi=class r extends He{constructor(){super(),this.add=xe.prototype.add.bind(this),this.delete=xe.prototype.delete.bind(this),this.get=xe.prototype.get.bind(this),this.has=xe.prototype.has.bind(this),this.set=xe.prototype.set.bind(this),this.tag=r.tag}toJSON(e,t){if(!t)return super.toJSON(e);let n=new Map;t!=null&&t.onCreate&&t.onCreate(n);for(let i of this.items){let s,o;if(ne(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=pf(e,t,n),s=new this;return s.items=i.items,s}};vi.tag="tag:yaml.org,2002:omap";var Fs={collection:"seq",identify:r=>r instanceof Map,nodeClass:vi,default:!1,tag:"tag:yaml.org,2002:omap",resolve(r,e){let t=ff(r,e),n=[];for(let{key:i}of t.items)G(i)&&(n.includes(i.value)?e(`Ordered maps must not include duplicate keys: ${i.value}`):n.push(i.value));return Object.assign(new vi,t)},createNode:(r,e,t)=>vi.from(r,e,t)};function Mb({value:r,source:e},t){return e&&(r?hf:mf).test.test(e)?e:r?t.options.trueStr:t.options.falseStr}var hf={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 q(!0),stringify:Mb},mf={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 q(!1),stringify:Mb};var Nb={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:Ke},Lb={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:r=>parseFloat(r.replace(/_/g,"")),stringify(r){let e=Number(r.value);return isFinite(e)?e.toExponential():Ke(r)}},jb={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 q(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:Ke};var Vs=r=>typeof r=="bigint"||Number.isInteger(r);function Ja(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 yf(r,e,t){let{value:n}=r;if(Vs(n)){let i=n.toString(e);return n<0?"-"+t+i.substr(1):t+i}return Ke(r)}var Db={identify:Vs,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(r,e,t)=>Ja(r,2,2,t),stringify:r=>yf(r,2,"0b")},qb={identify:Vs,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(r,e,t)=>Ja(r,1,8,t),stringify:r=>yf(r,8,"0")},Fb={identify:Vs,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(r,e,t)=>Ja(r,0,10,t),stringify:Ke},Vb={identify:Vs,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(r,e,t)=>Ja(r,2,16,t),stringify:r=>yf(r,16,"0x")};var $i=class r extends xe{constructor(e){super(e),this.tag=r.tag}add(e){let t;ne(e)?t=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?t=new Se(e.key,null):t=new Se(e,null),en(this.items,t.key)||this.items.push(t)}get(e,t){let n=en(this.items,e);return!t&&ne(n)?G(n.key)?n.key.value:n.key:n}set(e,t){if(typeof t!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof t}`);let n=en(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new Se(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(wi(o,null,n));return s}};$i.tag="tag:yaml.org,2002:set";var Us={collection:"map",identify:r=>r instanceof Set,nodeClass:$i,default:!1,tag:"tag:yaml.org,2002:set",createNode:(r,e,t)=>$i.from(r,e,t),resolve(r,e){if(qt(r)){if(r.hasAllNullValues(!0))return Object.assign(new $i,r);e("Set items must all have null values")}else e("Expected a mapping for this tag");return r}};function gf(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 Ub(r){let{value:e}=r,t=o=>o;if(typeof e=="bigint")t=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return Ke(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 Ya={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})=>gf(r,t),stringify:Ub},Xa={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=>gf(r,!1),stringify:Ub},Si={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(Si.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),d=e[8];if(d&&d!=="Z"){let u=gf(d,!1);Math.abs(u)<30&&(u*=60),l-=6e4*u}return new Date(l)},stringify:({value:r})=>{var e;return(e=r==null?void 0:r.toISOString().replace(/(T00:00:00)?\.000Z$/,""))!=null?e:""}};var _f=[Ut,Bt,tn,xn,hf,mf,Db,qb,Fb,Vb,Nb,Lb,jb,Ds,Vt,Fs,qs,Us,Ya,Xa,Si];var Bb=new Map([["core",Rb],["failsafe",[Ut,Bt,tn]],["json",Cb],["yaml11",_f],["yaml-1.1",_f]]),zb={binary:Ds,bool:js,float:Ba,floatExp:Ua,floatNaN:Va,floatTime:Xa,int:Ka,intHex:Wa,intOct:Ha,intTime:Ya,map:Ut,merge:Vt,null:xn,omap:Fs,pairs:qs,seq:Bt,set:Us,timestamp:Si},Hb={"tag:yaml.org,2002:binary":Ds,"tag:yaml.org,2002:merge":Vt,"tag:yaml.org,2002:omap":Fs,"tag:yaml.org,2002:pairs":qs,"tag:yaml.org,2002:set":Us,"tag:yaml.org,2002:timestamp":Si};function Qa(r,e,t){let n=Bb.get(e);if(n&&!r)return t&&!n.includes(Vt)?n.concat(Vt):n.slice();let i=n;if(!i)if(Array.isArray(r))i=[];else{let s=Array.from(Bb.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(Vt)),i.reduce((s,o)=>{let a=typeof o=="string"?zb[o]:o;if(!a){let c=JSON.stringify(o),l=Object.keys(zb).map(d=>JSON.stringify(d)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return s.includes(a)||s.push(a),s},[])}var HR=(r,e)=>r.keye.key?1:0,Bs=class r{constructor({compat:e,customTags:t,merge:n,resolveKnownTags:i,schema:s,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?Qa(e,"compat"):e?Qa(null,e):null,this.name=typeof s=="string"&&s||"core",this.knownTags=i?Hb:{},this.tags=Qa(t,this.name,n),this.toStringOptions=a!=null?a:null,Object.defineProperty(this,jt,{value:Ut}),Object.defineProperty(this,yt,{value:tn}),Object.defineProperty(this,$r,{value:Bt}),this.sortMapEntries=typeof o=="function"?o:o===!0?HR:null}clone(){let e=Object.create(r.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};function Kb(r,e){var c;let t=[],n=e.directives===!0;if(e.directives!==!1&&r.directives){let l=r.directives.toString(r);l?(t.push(l),n=!0):r.directives.docStart&&(n=!0)}n&&t.push("---");let i=Ma(r,e),{commentString:s}=i.options;if(r.commentBefore){t.length!==1&&t.unshift("");let l=s(r.commentBefore);t.unshift(It(l,""))}let o=!1,a=null;if(r.contents){if(se(r.contents)){if(r.contents.spaceBefore&&n&&t.push(""),r.contents.commentBefore){let u=s(r.contents.commentBefore);t.push(It(u,""))}i.forceBlockIndent=!!r.comment,a=r.contents.comment}let l=a?void 0:()=>o=!0,d=Ar(r.contents,i,()=>a=null,l);a&&(d+=lr(d,"",s(a))),(d[0]==="|"||d[0]===">")&&t[t.length-1]==="---"?t[t.length-1]=`--- ${d}`:t.push(d)}else t.push(Ar(r.contents,i));if((c=r.directives)!=null&&c.docEnd)if(r.comment){let l=s(r.comment);l.includes(` +${o.comment}`:i.comment}i=s}r.items[n]=ne(i)?i:new Se(i)}}else e("Expected a sequence for this tag");return r}function pf(r,e,t){let{replacer:n}=t,i=new He(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(wi(a,c,t))}return i}var qs={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:ff,createNode:pf};var vi=class r extends He{constructor(){super(),this.add=xe.prototype.add.bind(this),this.delete=xe.prototype.delete.bind(this),this.get=xe.prototype.get.bind(this),this.has=xe.prototype.has.bind(this),this.set=xe.prototype.set.bind(this),this.tag=r.tag}toJSON(e,t){if(!t)return super.toJSON(e);let n=new Map;t!=null&&t.onCreate&&t.onCreate(n);for(let i of this.items){let s,o;if(ne(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=pf(e,t,n),s=new this;return s.items=i.items,s}};vi.tag="tag:yaml.org,2002:omap";var Fs={collection:"seq",identify:r=>r instanceof Map,nodeClass:vi,default:!1,tag:"tag:yaml.org,2002:omap",resolve(r,e){let t=ff(r,e),n=[];for(let{key:i}of t.items)G(i)&&(n.includes(i.value)?e(`Ordered maps must not include duplicate keys: ${i.value}`):n.push(i.value));return Object.assign(new vi,t)},createNode:(r,e,t)=>vi.from(r,e,t)};function Mb({value:r,source:e},t){return e&&(r?hf:mf).test.test(e)?e:r?t.options.trueStr:t.options.falseStr}var hf={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:Mb},mf={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:Mb};var Nb={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:Ke},Lb={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:r=>parseFloat(r.replace(/_/g,"")),stringify(r){let e=Number(r.value);return isFinite(e)?e.toExponential():Ke(r)}},jb={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:Ke};var Vs=r=>typeof r=="bigint"||Number.isInteger(r);function Ja(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 yf(r,e,t){let{value:n}=r;if(Vs(n)){let i=n.toString(e);return n<0?"-"+t+i.substr(1):t+i}return Ke(r)}var Db={identify:Vs,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(r,e,t)=>Ja(r,2,2,t),stringify:r=>yf(r,2,"0b")},qb={identify:Vs,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(r,e,t)=>Ja(r,1,8,t),stringify:r=>yf(r,8,"0")},Fb={identify:Vs,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(r,e,t)=>Ja(r,0,10,t),stringify:Ke},Vb={identify:Vs,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(r,e,t)=>Ja(r,2,16,t),stringify:r=>yf(r,16,"0x")};var $i=class r extends xe{constructor(e){super(e),this.tag=r.tag}add(e){let t;ne(e)?t=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?t=new Se(e.key,null):t=new Se(e,null),en(this.items,t.key)||this.items.push(t)}get(e,t){let n=en(this.items,e);return!t&&ne(n)?G(n.key)?n.key.value:n.key:n}set(e,t){if(typeof t!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof t}`);let n=en(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new Se(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(wi(o,null,n));return s}};$i.tag="tag:yaml.org,2002:set";var Us={collection:"map",identify:r=>r instanceof Set,nodeClass:$i,default:!1,tag:"tag:yaml.org,2002:set",createNode:(r,e,t)=>$i.from(r,e,t),resolve(r,e){if(qt(r)){if(r.hasAllNullValues(!0))return Object.assign(new $i,r);e("Set items must all have null values")}else e("Expected a mapping for this tag");return r}};function gf(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 Ub(r){let{value:e}=r,t=o=>o;if(typeof e=="bigint")t=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return Ke(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 Ya={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})=>gf(r,t),stringify:Ub},Xa={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=>gf(r,!1),stringify:Ub},Si={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(Si.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),d=e[8];if(d&&d!=="Z"){let u=gf(d,!1);Math.abs(u)<30&&(u*=60),l-=6e4*u}return new Date(l)},stringify:({value:r})=>{var e;return(e=r==null?void 0:r.toISOString().replace(/(T00:00:00)?\.000Z$/,""))!=null?e:""}};var _f=[Ut,Bt,tn,xn,hf,mf,Db,qb,Fb,Vb,Nb,Lb,jb,Ds,Vt,Fs,qs,Us,Ya,Xa,Si];var Bb=new Map([["core",Rb],["failsafe",[Ut,Bt,tn]],["json",Cb],["yaml11",_f],["yaml-1.1",_f]]),zb={binary:Ds,bool:js,float:Ba,floatExp:Ua,floatNaN:Va,floatTime:Xa,int:Ka,intHex:Wa,intOct:Ha,intTime:Ya,map:Ut,merge:Vt,null:xn,omap:Fs,pairs:qs,seq:Bt,set:Us,timestamp:Si},Hb={"tag:yaml.org,2002:binary":Ds,"tag:yaml.org,2002:merge":Vt,"tag:yaml.org,2002:omap":Fs,"tag:yaml.org,2002:pairs":qs,"tag:yaml.org,2002:set":Us,"tag:yaml.org,2002:timestamp":Si};function Qa(r,e,t){let n=Bb.get(e);if(n&&!r)return t&&!n.includes(Vt)?n.concat(Vt):n.slice();let i=n;if(!i)if(Array.isArray(r))i=[];else{let s=Array.from(Bb.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(Vt)),i.reduce((s,o)=>{let a=typeof o=="string"?zb[o]:o;if(!a){let c=JSON.stringify(o),l=Object.keys(zb).map(d=>JSON.stringify(d)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return s.includes(a)||s.push(a),s},[])}var HR=(r,e)=>r.keye.key?1:0,Bs=class r{constructor({compat:e,customTags:t,merge:n,resolveKnownTags:i,schema:s,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?Qa(e,"compat"):e?Qa(null,e):null,this.name=typeof s=="string"&&s||"core",this.knownTags=i?Hb:{},this.tags=Qa(t,this.name,n),this.toStringOptions=a!=null?a:null,Object.defineProperty(this,jt,{value:Ut}),Object.defineProperty(this,yt,{value:tn}),Object.defineProperty(this,$r,{value:Bt}),this.sortMapEntries=typeof o=="function"?o:o===!0?HR:null}clone(){let e=Object.create(r.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};function Kb(r,e){var c;let t=[],n=e.directives===!0;if(e.directives!==!1&&r.directives){let l=r.directives.toString(r);l?(t.push(l),n=!0):r.directives.docStart&&(n=!0)}n&&t.push("---");let i=Ma(r,e),{commentString:s}=i.options;if(r.commentBefore){t.length!==1&&t.unshift("");let l=s(r.commentBefore);t.unshift(It(l,""))}let o=!1,a=null;if(r.contents){if(se(r.contents)){if(r.contents.spaceBefore&&n&&t.push(""),r.contents.commentBefore){let u=s(r.contents.commentBefore);t.push(It(u,""))}i.forceBlockIndent=!!r.comment,a=r.contents.comment}let l=a?void 0:()=>o=!0,d=Ar(r.contents,i,()=>a=null,l);a&&(d+=lr(d,"",s(a))),(d[0]==="|"||d[0]===">")&&t[t.length-1]==="---"?t[t.length-1]=`--- ${d}`:t.push(d)}else t.push(Ar(r.contents,i));if((c=r.directives)!=null&&c.docEnd)if(r.comment){let l=s(r.comment);l.includes(` `)?(t.push("..."),t.push(It(l,""))):t.push(`... ${l}`)}else t.push("...");else{let l=r.comment;l&&o&&(l=l.replace(/^\n+/,"")),l&&((!o||a)&&t[t.length-1]!==""&&t.push(""),t.push(It(s(l),"")))}return t.join(` `)+` `}var rn=class r{constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,Ze,{value:Ea});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!=null&&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,{[Ze]:{value:Ea}});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=se(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){Ei(this.contents)&&this.contents.add(e)}addIn(e,t){Ei(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){let n=nf(this);e.anchor=!t||n.has(t)?sf(t||"a",n):t}return new Sr(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 m=_=>typeof _=="number"||_ instanceof String||_ instanceof Number,g=t.filter(m).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:d}=n!=null?n:{},{onAnchor:u,setAnchors:f,sourceObjects:p}=Eb(this,o||"a"),y={aliasDuplicateObjects:s!=null?s:!0,keepUndefined:c!=null?c:!1,onAnchor:u,onTagObj:l,replacer:i,schema:this.schema,sourceObjects:p},h=Er(e,d,y);return a&&le(h)&&(h.flow=!0),f(),h}createPair(e,t,n={}){let i=this.createNode(e,null,n),s=this.createNode(t,null,n);return new Se(i,s)}delete(e){return Ei(this.contents)?this.contents.delete(e):!1}deleteIn(e){return _i(e)?this.contents==null?!1:(this.contents=null,!0):Ei(this.contents)?this.contents.deleteIn(e):!1}get(e,t){return le(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return _i(e)?!t&&G(this.contents)?this.contents.value:this.contents:le(this.contents)?this.contents.getIn(e,t):void 0}has(e){return le(this.contents)?this.contents.has(e):!1}hasIn(e){return _i(e)?this.contents!==void 0:le(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=Cs(this.schema,[e],t):Ei(this.contents)&&this.contents.set(e,t)}setIn(e,t){_i(e)?this.contents=t:this.contents==null?this.contents=Cs(this.schema,Array.from(e),t):Ei(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 Bs(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!=null?t:"",a);if(typeof s=="function")for(let{count:l,res:d}of a.anchors.values())s(d,l);return typeof o=="function"?Qr(o,{"":c},"",c):c}toJSON(e,t){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:t})}toString(e={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){let t=JSON.stringify(e.indent);throw new Error(`"indent" option must be a positive integer, not ${t}`)}return Kb(this,e)}};function Ei(r){if(le(r))return!0;throw new Error("Expected a YAML collection as document contents")}var zs=class extends Error{constructor(e,t,n,i){super(),this.name=e,this.code=n,this.message=i,this.pos=t}},zt=class extends zs{constructor(e,t,n){super("YAMLParseError",e,t,n)}},Hs=class extends zs{constructor(e,t,n){super("YAMLWarning",e,t,n)}},bf=(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 @@ -83,16 +83,16 @@ ${o.comment}`:i.comment}i=s}r.items[n]=ne(i)?i:new Se(i)}}else e("Expected a seq ${o} ${l} -`}};function dr(r,{flow:e,indicator:t,next:n,offset:i,onError:s,parentIndent:o,startOnNewline:a}){let c=!1,l=a,d=a,u="",f="",p=!1,y=!1,h=null,m=null,g=null,_=null,w=null,x=null,v=null;for(let $ of r)switch(y&&($.type!=="space"&&$.type!=="newline"&&$.type!=="comma"&&s($.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),y=!1),h&&(l&&$.type!=="comment"&&$.type!=="newline"&&s(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),h=null),$.type){case"space":!e&&(t!=="doc-start"||(n==null?void 0:n.type)!=="flow-collection")&&$.source.includes(" ")&&(h=$),d=!0;break;case"comment":{d||s($,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let R=$.source.substring(1)||" ";u?u+=f+R:u=R,f="",l=!1;break}case"newline":l?u?u+=$.source:(!x||t!=="seq-item-ind")&&(c=!0):f+=$.source,l=!0,p=!0,(m||g)&&(_=$),d=!0;break;case"anchor":m&&s($,"MULTIPLE_ANCHORS","A node can have at most one anchor"),$.source.endsWith(":")&&s($.offset+$.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),m=$,v!=null||(v=$.offset),l=!1,d=!1,y=!0;break;case"tag":{g&&s($,"MULTIPLE_TAGS","A node can have at most one tag"),g=$,v!=null||(v=$.offset),l=!1,d=!1,y=!0;break}case t:(m||g)&&s($,"BAD_PROP_ORDER",`Anchors and tags must be after the ${$.source} indicator`),x&&s($,"UNEXPECTED_TOKEN",`Unexpected ${$.source} in ${e!=null?e:"collection"}`),x=$,l=t==="seq-item-ind"||t==="explicit-key-ind",d=!1;break;case"comma":if(e){w&&s($,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),w=$,l=!1,d=!1;break}default:s($,"UNEXPECTED_TOKEN",`Unexpected ${$.type} token`),l=!1,d=!1}let P=r[r.length-1],O=P?P.offset+P.source.length:i;return y&&n&&n.type!=="space"&&n.type!=="newline"&&n.type!=="comma"&&(n.type!=="scalar"||n.source!=="")&&s(n.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),h&&(l&&h.indent<=o||(n==null?void 0:n.type)==="block-map"||(n==null?void 0:n.type)==="block-seq")&&s(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:w,found:x,spaceBefore:c,comment:u,hasNewline:p,anchor:m,tag:g,newlineAfterProp:_,end:O,start:v!=null?v:O}}function nn(r){if(!r)return null;switch(r.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(r.source.includes(` +`}};function dr(r,{flow:e,indicator:t,next:n,offset:i,onError:s,parentIndent:o,startOnNewline:a}){let c=!1,l=a,d=a,u="",f="",p=!1,y=!1,h=null,m=null,g=null,_=null,w=null,x=null,v=null;for(let A of r)switch(y&&(A.type!=="space"&&A.type!=="newline"&&A.type!=="comma"&&s(A.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),y=!1),h&&(l&&A.type!=="comment"&&A.type!=="newline"&&s(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),h=null),A.type){case"space":!e&&(t!=="doc-start"||(n==null?void 0:n.type)!=="flow-collection")&&A.source.includes(" ")&&(h=A),d=!0;break;case"comment":{d||s(A,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let R=A.source.substring(1)||" ";u?u+=f+R:u=R,f="",l=!1;break}case"newline":l?u?u+=A.source:(!x||t!=="seq-item-ind")&&(c=!0):f+=A.source,l=!0,p=!0,(m||g)&&(_=A),d=!0;break;case"anchor":m&&s(A,"MULTIPLE_ANCHORS","A node can have at most one anchor"),A.source.endsWith(":")&&s(A.offset+A.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),m=A,v!=null||(v=A.offset),l=!1,d=!1,y=!0;break;case"tag":{g&&s(A,"MULTIPLE_TAGS","A node can have at most one tag"),g=A,v!=null||(v=A.offset),l=!1,d=!1,y=!0;break}case t:(m||g)&&s(A,"BAD_PROP_ORDER",`Anchors and tags must be after the ${A.source} indicator`),x&&s(A,"UNEXPECTED_TOKEN",`Unexpected ${A.source} in ${e!=null?e:"collection"}`),x=A,l=t==="seq-item-ind"||t==="explicit-key-ind",d=!1;break;case"comma":if(e){w&&s(A,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),w=A,l=!1,d=!1;break}default:s(A,"UNEXPECTED_TOKEN",`Unexpected ${A.type} token`),l=!1,d=!1}let P=r[r.length-1],O=P?P.offset+P.source.length:i;return y&&n&&n.type!=="space"&&n.type!=="newline"&&n.type!=="comma"&&(n.type!=="scalar"||n.source!=="")&&s(n.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),h&&(l&&h.indent<=o||(n==null?void 0:n.type)==="block-map"||(n==null?void 0:n.type)==="block-seq")&&s(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:w,found:x,spaceBefore:c,comment:u,hasNewline:p,anchor:m,tag:g,newlineAfterProp:_,end:O,start:v!=null?v:O}}function nn(r){if(!r)return null;switch(r.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(r.source.includes(` `))return!0;if(r.end){for(let e of r.end)if(e.type==="newline")return!0}return!1;case"flow-collection":for(let e of r.items){for(let t of e.start)if(t.type==="newline")return!0;if(e.sep){for(let t of e.sep)if(t.type==="newline")return!0}if(nn(e.key)||nn(e.value))return!0}return!1;default:return!0}}function Ks(r,e,t){if((e==null?void 0:e.type)==="flow-collection"){let n=e.end[0];n.indent===r&&(n.source==="]"||n.source==="}")&&nn(e)&&t(n,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}function Za(r,e,t){let{uniqueKeys:n}=r.options;if(n===!1)return!1;let i=typeof n=="function"?n:(s,o)=>s===o||G(s)&&G(o)&&s.value===o.value;return e.some(s=>i(s.key,t))}var Wb="All mapping items must start at the same column";function Gb({composeNode:r,composeEmptyNode:e},t,n,i,s){var d,u;let o=(d=s==null?void 0:s.nodeClass)!=null?d:xe,a=new o(t.schema);t.atRoot&&(t.atRoot=!1);let c=n.offset,l=null;for(let f of n.items){let{start:p,key:y,sep:h,value:m}=f,g=dr(p,{indicator:"explicit-key-ind",next:y!=null?y:h==null?void 0:h[0],offset:c,onError:i,parentIndent:n.indent,startOnNewline:!0}),_=!g.found;if(_){if(y&&(y.type==="block-seq"?i(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in y&&y.indent!==n.indent&&i(c,"BAD_INDENT",Wb)),!g.anchor&&!g.tag&&!h){l=g.end,g.comment&&(a.comment?a.comment+=` `+g.comment:a.comment=g.comment);continue}(g.newlineAfterProp||nn(y))&&i(y!=null?y:p[p.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else((u=g.found)==null?void 0:u.indent)!==n.indent&&i(c,"BAD_INDENT",Wb);t.atKey=!0;let w=g.end,x=y?r(t,y,g,i):e(t,w,p,null,g,i);t.schema.compat&&Ks(n.indent,y,i),t.atKey=!1,Za(t,a.items,x)&&i(w,"DUPLICATE_KEY","Map keys must be unique");let v=dr(h!=null?h:[],{indicator:"map-value-ind",next:m,offset:x.range[2],onError:i,parentIndent:n.indent,startOnNewline:!y||y.type==="block-scalar"});if(c=v.end,v.found){_&&((m==null?void 0:m.type)==="block-map"&&!v.hasNewline&&i(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),t.options.strict&&g.startr&&(r.type==="block-map"||r.type==="block-seq");function Yb({composeNode:r,composeEmptyNode:e},t,n,i,s){var m,g,_;let o=n.start.source==="{",a=o?"flow map":"flow sequence",c=(m=s==null?void 0:s.nodeClass)!=null?m:o?xe:He,l=new c(t.schema);l.flow=!0;let d=t.atRoot;d&&(t.atRoot=!1),t.atKey&&(t.atKey=!1);let u=n.offset+n.start.source.length;for(let w=0;w0){let w=ur(y,h,t.options.strict,i);w.comment&&(l.comment?l.comment+=` -`+w.comment:l.comment=w.comment),l.range=[n.offset,h,w.offset]}else l.range=[n.offset,h,h];return l}function $f(r,e,t,n,i,s){let o=t.type==="block-map"?Gb(r,e,t,n,s):t.type==="block-seq"?Jb(r,e,t,n,s):Yb(r,e,t,n,s),a=o.constructor;return i==="!"||i===a.tagName?(o.tag=a.tagName,o):(i&&(o.tag=i),o)}function Xb(r,e,t,n,i){var f,p,y;let s=n.tag,o=s?e.directives.tagName(s.source,h=>i(s,"TAG_RESOLVE_FAILED",h)):null;if(t.type==="block-seq"){let{anchor:h,newlineAfterProp:m}=n,g=h&&s?h.offset>s.offset?h:s:h!=null?h:s;g&&(!m||m.offseth.tag===o&&h.collection===a);if(!c){let h=e.schema.knownTags[o];if((h==null?void 0:h.collection)===a)e.schema.tags.push(Object.assign({},h,{default:!1})),c=h;else return h?i(s,"BAD_COLLECTION_TYPE",`${h.tag} used for ${a} collection, but expects ${(f=h.collection)!=null?f:"scalar"}`,!0):i(s,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),$f(r,e,t,i,o)}let l=$f(r,e,t,i,o,c),d=(y=(p=c.resolve)==null?void 0:p.call(c,l,h=>i(s,"TAG_RESOLVE_FAILED",h),e.options))!=null?y:l,u=se(d)?d:new q(d);return u.range=l.range,u.tag=o,c!=null&&c.format&&(u.format=c.format),u}function Sf(r,e,t){let n=e.offset,i=KR(e,r.options.strict,t);if(!i)return{value:"",type:null,comment:"",range:[n,n,n]};let s=i.mode===">"?q.BLOCK_FOLDED:q.BLOCK_LITERAL,o=e.source?WR(e.source):[],a=o.length;for(let h=o.length-1;h>=0;--h){let m=o[h][1];if(m===""||m==="\r")a=h;else break}if(a===0){let h=i.chomp==="+"&&o.length>0?` +`+v.comment:x.comment=v.comment);let P=new Se(x);t.options.keepSourceTokens&&(P.srcToken=f),a.items.push(P)}}return l&&lr&&(r.type==="block-map"||r.type==="block-seq");function Yb({composeNode:r,composeEmptyNode:e},t,n,i,s){var m,g,_;let o=n.start.source==="{",a=o?"flow map":"flow sequence",c=(m=s==null?void 0:s.nodeClass)!=null?m:o?xe:He,l=new c(t.schema);l.flow=!0;let d=t.atRoot;d&&(t.atRoot=!1),t.atKey&&(t.atKey=!1);let u=n.offset+n.start.source.length;for(let w=0;w0){let w=ur(y,h,t.options.strict,i);w.comment&&(l.comment?l.comment+=` +`+w.comment:l.comment=w.comment),l.range=[n.offset,h,w.offset]}else l.range=[n.offset,h,h];return l}function $f(r,e,t,n,i,s){let o=t.type==="block-map"?Gb(r,e,t,n,s):t.type==="block-seq"?Jb(r,e,t,n,s):Yb(r,e,t,n,s),a=o.constructor;return i==="!"||i===a.tagName?(o.tag=a.tagName,o):(i&&(o.tag=i),o)}function Xb(r,e,t,n,i){var f,p,y;let s=n.tag,o=s?e.directives.tagName(s.source,h=>i(s,"TAG_RESOLVE_FAILED",h)):null;if(t.type==="block-seq"){let{anchor:h,newlineAfterProp:m}=n,g=h&&s?h.offset>s.offset?h:s:h!=null?h:s;g&&(!m||m.offseth.tag===o&&h.collection===a);if(!c){let h=e.schema.knownTags[o];if((h==null?void 0:h.collection)===a)e.schema.tags.push(Object.assign({},h,{default:!1})),c=h;else return h?i(s,"BAD_COLLECTION_TYPE",`${h.tag} used for ${a} collection, but expects ${(f=h.collection)!=null?f:"scalar"}`,!0):i(s,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),$f(r,e,t,i,o)}let l=$f(r,e,t,i,o,c),d=(y=(p=c.resolve)==null?void 0:p.call(c,l,h=>i(s,"TAG_RESOLVE_FAILED",h),e.options))!=null?y:l,u=se(d)?d:new F(d);return u.range=l.range,u.tag=o,c!=null&&c.format&&(u.format=c.format),u}function Sf(r,e,t){let n=e.offset,i=KR(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?WR(e.source):[],a=o.length;for(let h=o.length-1;h>=0;--h){let m=o[h][1];if(m===""||m==="\r")a=h;else break}if(a===0){let h=i.chomp==="+"&&o.length>0?` `.repeat(Math.max(1,o.length-1)):"",m=n+i.length;return e.source&&(m+=e.source.length),{value:h,type:s,comment:i.comment,range:[n,m,m]}}let c=e.indent+i.indent,l=e.offset+i.length,d=0;for(let h=0;hc&&(c=m.length);else{m.length=a;--h)o[h][0].length>c&&(a=h+1);let u="",f="",p=!1;for(let h=0;hc||g[0]===" "?(f===" "?f=` `:!p&&f===` `&&(f=` @@ -105,7 +105,7 @@ ${l} `+o[h][0].slice(c);u[u.length-1]!==` `&&(u+=` `);break;default:u+=` -`}let y=n+i.length+e.source.length;return{value:u,type:s,comment:i.comment,range:[n,y,y]}}function KR({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,y);switch(i){case"scalar":a=q.PLAIN,c=GR(s,l);break;case"single-quoted-scalar":a=q.QUOTE_SINGLE,c=JR(s,l);break;case"double-quoted-scalar":a=q.QUOTE_DOUBLE,c=YR(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 d=n+s.length,u=ur(o,d,e,t);return{value:c,type:a,comment:u.comment,range:[n,d,u.offset]}}function GR(r,e){let t="";switch(r[0]){case" ":t="a tab character";break;case",":t="flow indicator character ,";break;case"%":t="directive indicator character %";break;case"|":case">":{t=`block scalar indicator ${r[0]}`;break}case"@":case"`":{t=`reserved character ${r[0]}`;break}}return t&&e(0,"BAD_SCALAR_START",`Plain value cannot start with ${t}`),Qb(r)}function JR(r,e){return(r[r.length-1]!=="'"||r.length===1)&&e(r.length,"MISSING_CHAR","Missing closing 'quote"),Qb(r.slice(1,-1)).replace(/''/g,"'")}function Qb(r){var c;let e,t;try{e=new RegExp(`(.*?)(?t(n+f,p,y);switch(i){case"scalar":a=F.PLAIN,c=GR(s,l);break;case"single-quoted-scalar":a=F.QUOTE_SINGLE,c=JR(s,l);break;case"double-quoted-scalar":a=F.QUOTE_DOUBLE,c=YR(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 d=n+s.length,u=ur(o,d,e,t);return{value:c,type:a,comment:u.comment,range:[n,d,u.offset]}}function GR(r,e){let t="";switch(r[0]){case" ":t="a tab character";break;case",":t="flow indicator character ,";break;case"%":t="directive indicator character %";break;case"|":case">":{t=`block scalar indicator ${r[0]}`;break}case"@":case"`":{t=`reserved character ${r[0]}`;break}}return t&&e(0,"BAD_SCALAR_START",`Plain value cannot start with ${t}`),Qb(r)}function JR(r,e){return(r[r.length-1]!=="'"||r.length===1)&&e(r.length,"MISSING_CHAR","Missing closing 'quote"),Qb(r.slice(1,-1)).replace(/''/g,"'")}function Qb(r){var c;let e,t;try{e=new RegExp(`(.*?)(?n(t,"TAG_RESOLVE_FAILED",u)):null,l;r.options.stringKeys&&r.atKey?l=r.schema[yt]:c?l=eT(r.schema,i,c,t,n):e.type==="scalar"?l=tT(r,i,e,n):l=r.schema[yt];let d;try{let u=l.resolve(i,f=>n(t!=null?t:e,"TAG_RESOLVE_FAILED",f),r.options);d=G(u)?u:new q(u)}catch(u){let f=u instanceof Error?u.message:String(u);n(t!=null?t:e,"TAG_RESOLVE_FAILED",f),d=new q(i)}return d.range=a,d.source=i,s&&(d.type=s),c&&(d.tag=c),l.format&&(d.format=l.format),o&&(d.comment=o),d}function eT(r,e,t,n,i){var a;if(t==="!")return r[yt];let s=[];for(let c of r.tags)if(!c.collection&&c.tag===t)if(c.default&&c.test)s.push(c);else return c;for(let c of s)if((a=c.test)!=null&&a.test(e))return c;let o=r.knownTags[t];return o&&!o.collection?(r.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(i(n,"TAG_RESOLVE_FAILED",`Unresolved tag: ${t}`,t!=="tag:yaml.org,2002:str"),r[yt])}function tT({atKey:r,directives:e,schema:t},n,i,s){var a;let o=t.tags.find(c=>{var l;return(c.default===!0||r&&c.default==="key")&&((l=c.test)==null?void 0:l.test(n))})||t[yt];if(t.compat){let c=(a=t.compat.find(l=>{var d;return l.default&&((d=l.test)==null?void 0:d.test(n))}))!=null?a:t[yt];if(o.tag!==c.tag){let l=e.tagString(o.tag),d=e.tagString(c.tag),u=`Value may be parsed as either ${l} or ${d}`;s(i,"TAG_RESOLVE_FAILED",u,!0)}}return o}function Zb(r,e,t){if(e){t!=null||(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==null?void 0:i.type)==="space";)r+=i.source.length,i=e[++n];break}}return r}var rT={composeNode:kf,composeEmptyNode:ec};function kf(r,e,t,n){let i=r.atKey,{spaceBefore:s,comment:o,anchor:a,tag:c}=t,l,d=!0;switch(e.type){case"alias":l=nT(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=Af(r,e,c,n),a&&(l.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=Xb(rT,r,e,t,n),a&&(l.anchor=a.source.substring(1))}catch(u){let f=u instanceof Error?u.message:String(u);n(e,"RESOURCE_EXHAUSTION",f)}break;default:{let u=e.type==="error"?e.message:`Unsupported token (type: ${e.type})`;n(e,"UNEXPECTED_TOKEN",u),d=!1}}return l!=null||(l=ec(r,e.offset,void 0,null,t,n)),a&&l.anchor===""&&n(a,"BAD_ALIAS","Anchor cannot be an empty string"),i&&r.options.stringKeys&&(!G(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&n(c!=null?c:e,"NON_STRING_KEY","With stringKeys, all keys must be strings"),s&&(l.spaceBefore=!0),o&&(e.type==="scalar"&&e.source===""?l.comment=o:l.commentBefore=o),r.options.keepSourceTokens&&d&&(l.srcToken=e),l}function ec(r,e,t,n,{spaceBefore:i,comment:s,anchor:o,tag:a,end:c},l){let d={type:"scalar",offset:Zb(e,t,n),indent:-1,source:""},u=Af(r,d,a,l);return o&&(u.anchor=o.source.substring(1),u.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),i&&(u.spaceBefore=!0),s&&(u.comment=s,u.range[2]=c),u}function nT({options:r},{offset:e,source:t,end:n},i){let s=new Sr(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=ur(n,o,r.strict,i);return s.range=[e,o,a.offset],a.comment&&(s.comment=a.comment),s}function ew(r,e,{offset:t,start:n,value:i,end:s},o){let a=Object.assign({_directives:e},r),c=new rn(void 0,a),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},d=dr(n,{indicator:"doc-start",next:i!=null?i:s==null?void 0:s[0],offset:t,onError:o,parentIndent:0,startOnNewline:!0});d.found&&(c.directives.docStart=!0,i&&(i.type==="block-map"||i.type==="block-seq")&&!d.hasNewline&&o(d.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=i?kf(l,i,d,o):ec(l,d.end,n,null,d,o);let u=c.contents.range[2],f=ur(s,u,!1,o);return f.comment&&(c.comment=f.comment),c.range=[t,u,f.offset],c}function Ws(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 tw(r){var i;let e="",t=!1,n=!1;for(let s=0;sn(t,"TAG_RESOLVE_FAILED",u)):null,l;r.options.stringKeys&&r.atKey?l=r.schema[yt]:c?l=eT(r.schema,i,c,t,n):e.type==="scalar"?l=tT(r,i,e,n):l=r.schema[yt];let d;try{let u=l.resolve(i,f=>n(t!=null?t:e,"TAG_RESOLVE_FAILED",f),r.options);d=G(u)?u:new F(u)}catch(u){let f=u instanceof Error?u.message:String(u);n(t!=null?t:e,"TAG_RESOLVE_FAILED",f),d=new F(i)}return d.range=a,d.source=i,s&&(d.type=s),c&&(d.tag=c),l.format&&(d.format=l.format),o&&(d.comment=o),d}function eT(r,e,t,n,i){var a;if(t==="!")return r[yt];let s=[];for(let c of r.tags)if(!c.collection&&c.tag===t)if(c.default&&c.test)s.push(c);else return c;for(let c of s)if((a=c.test)!=null&&a.test(e))return c;let o=r.knownTags[t];return o&&!o.collection?(r.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(i(n,"TAG_RESOLVE_FAILED",`Unresolved tag: ${t}`,t!=="tag:yaml.org,2002:str"),r[yt])}function tT({atKey:r,directives:e,schema:t},n,i,s){var a;let o=t.tags.find(c=>{var l;return(c.default===!0||r&&c.default==="key")&&((l=c.test)==null?void 0:l.test(n))})||t[yt];if(t.compat){let c=(a=t.compat.find(l=>{var d;return l.default&&((d=l.test)==null?void 0:d.test(n))}))!=null?a:t[yt];if(o.tag!==c.tag){let l=e.tagString(o.tag),d=e.tagString(c.tag),u=`Value may be parsed as either ${l} or ${d}`;s(i,"TAG_RESOLVE_FAILED",u,!0)}}return o}function Zb(r,e,t){if(e){t!=null||(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==null?void 0:i.type)==="space";)r+=i.source.length,i=e[++n];break}}return r}var rT={composeNode:kf,composeEmptyNode:ec};function kf(r,e,t,n){let i=r.atKey,{spaceBefore:s,comment:o,anchor:a,tag:c}=t,l,d=!0;switch(e.type){case"alias":l=nT(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=Af(r,e,c,n),a&&(l.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=Xb(rT,r,e,t,n),a&&(l.anchor=a.source.substring(1))}catch(u){let f=u instanceof Error?u.message:String(u);n(e,"RESOURCE_EXHAUSTION",f)}break;default:{let u=e.type==="error"?e.message:`Unsupported token (type: ${e.type})`;n(e,"UNEXPECTED_TOKEN",u),d=!1}}return l!=null||(l=ec(r,e.offset,void 0,null,t,n)),a&&l.anchor===""&&n(a,"BAD_ALIAS","Anchor cannot be an empty string"),i&&r.options.stringKeys&&(!G(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&n(c!=null?c:e,"NON_STRING_KEY","With stringKeys, all keys must be strings"),s&&(l.spaceBefore=!0),o&&(e.type==="scalar"&&e.source===""?l.comment=o:l.commentBefore=o),r.options.keepSourceTokens&&d&&(l.srcToken=e),l}function ec(r,e,t,n,{spaceBefore:i,comment:s,anchor:o,tag:a,end:c},l){let d={type:"scalar",offset:Zb(e,t,n),indent:-1,source:""},u=Af(r,d,a,l);return o&&(u.anchor=o.source.substring(1),u.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),i&&(u.spaceBefore=!0),s&&(u.comment=s,u.range[2]=c),u}function nT({options:r},{offset:e,source:t,end:n},i){let s=new Sr(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=ur(n,o,r.strict,i);return s.range=[e,o,a.offset],a.comment&&(s.comment=a.comment),s}function ew(r,e,{offset:t,start:n,value:i,end:s},o){let a=Object.assign({_directives:e},r),c=new rn(void 0,a),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},d=dr(n,{indicator:"doc-start",next:i!=null?i:s==null?void 0:s[0],offset:t,onError:o,parentIndent:0,startOnNewline:!0});d.found&&(c.directives.docStart=!0,i&&(i.type==="block-map"||i.type==="block-seq")&&!d.hasNewline&&o(d.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=i?kf(l,i,d,o):ec(l,d.end,n,null,d,o);let u=c.contents.range[2],f=ur(s,u,!1,o);return f.comment&&(c.comment=f.comment),c.range=[t,u,f.offset],c}function Ws(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 tw(r){var i;let e="",t=!1,n=!1;for(let s=0;s{let o=Ws(t);s?this.warnings.push(new Hs(o,n,i)):this.errors.push(new zt(o,n,i))},this.directives=new cr({version:e.version||"1.2"}),this.options=e}decorate(e,t){let{comment:n,afterEmptyLine:i}=tw(this.prelude);if(n){let s=e.contents;if(t)e.comment=e.comment?`${e.comment} @@ -163,11 +163,11 @@ ${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.pus `,t),t>=0&&r.startsWith(i,t)&&t+i.length===r.length}function fc(r,e){var s,o;let t=r.match(/^---[ \t]*\r?\n([\s\S]*?)^---[ \t]*(?:\r?\n|$)([\s\S]*)$/m);if(!t)return{frontmatter:{},body:r};let n;try{n=ki(t[1],{mapAsMap:!0})}catch(a){return{frontmatter:{},body:r}}if(n===null&&t[1].trim()==="")return{frontmatter:{},body:(s=t[2])!=null?s:""};let i=Nf(n,new Set);return i===xr||!gT(i)?{frontmatter:{},body:r}:{frontmatter:i,body:(o=t[2])!=null?o:""}}function Nf(r,e){if(r===null||typeof r=="string"||typeof r=="boolean")return r;if(typeof r=="number")return Number.isFinite(r)?r:xr;if(!r||typeof r!="object"||e.has(r))return xr;e.add(r);try{if(Array.isArray(r)){let n=[];for(let i of r){let s=Nf(i,e);if(s===xr)return xr;n.push(s)}return n}if(!(r instanceof Map))return xr;let t={};for(let[n,i]of r){if(typeof n!="string")return xr;let s=Nf(i,e);if(s===xr)return xr;Object.defineProperty(t,n,{value:s,enumerable:!0,configurable:!0,writable:!0})}return t}finally{e.delete(r)}}function gT(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function fw(r){return typeof r=="boolean"||r===null||typeof r=="number"&&Number.isSafeInteger(r)?String(r):typeof r!="string"||!/^[A-Za-z][A-Za-z0-9 _.-]*$/u.test(r)||r.length<=5&&mT.has(r.toLowerCase())?null:r}function dt(r,e,t){return r.startsWith(e,t)?t+e.length:-1}function pc(r){let e=We.create().update(Pr.encode(`mdbase-authority-manifest-v2 `));for(let t of[...r].sort((n,i)=>n.kind!==i.kind?n.kinde.type==="file_put"||e.type==="file_remove"))throw new b("file_sync_unsupported","This replica cannot materialize collection file changes yet. Upgrade it before continuing sync.")}function mw(r){bT([r])}var J=class extends b{constructor(t,n,i,s){super(t,n);I(this,"status");this.status=i,this.name="AuthorityAdoptionError",(s==null?void 0:s.cause)!==void 0&&(this.cause=s.cause)}},Ir=class extends J{constructor(t,n){super("authority_adoption_outcome_unknown",t,void 0,n);I(this,"sourceMustRemainFenced",!0);this.name="AuthorityAdoptionOutcomeUnknownError"}};var Pi=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function In(r,e){if(!Pi.test(r))throw new J("invalid_authority_adoption",`${e} must be a UUID.`);return r.toLowerCase()}var Qs=Uint32Array.from([1732584193,4023233417,2562383102,271733878,3285377520]),cn=new Uint32Array(80),jf=class extends xi{constructor(){super(64,20,8,!1);I(this,"A",Qs[0]|0);I(this,"B",Qs[1]|0);I(this,"C",Qs[2]|0);I(this,"D",Qs[3]|0);I(this,"E",Qs[4]|0)}get(){let{A:t,B:n,C:i,D:s,E:o}=this;return[t,n,i,s,o]}set(t,n,i,s,o){this.A=t|0,this.B=n|0,this.C=i|0,this.D=s|0,this.E=o|0}process(t,n){for(let l=0;l<16;l++,n+=4)cn[l]=t.getUint32(n,!1);for(let l=16;l<80;l++)cn[l]=ac(cn[l-3]^cn[l-8]^cn[l-14]^cn[l-16],1);let{A:i,B:s,C:o,D:a,E:c}=this;for(let l=0;l<80;l++){let d,u;l<20?(d=lc(s,o,a),u=1518500249):l<40?(d=s^o^a,u=1859775393):l<60?(d=dc(s,o,a),u=2400959708):(d=s^o^a,u=3395469782);let f=ac(i,5)+d+c+u+cn[l]|0;c=a,a=o,o=ac(s,30),s=i,i=f}i=i+this.A|0,s=s+this.B|0,o=o+this.C|0,a=a+this.D|0,c=c+this.E|0,this.set(i,s,o,a,c)}roundClean(){on(cn)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0),on(this.buffer)}},mc=cc(()=>new jf);var wT=1e4,vT=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,$T=new TextEncoder;async function gw(r,e,t,n,i){var h,m,g;let s=ET(n,t.media_type);if(s.size!==t.size||await AT(s,i.signal)!==t.content_digest)throw new J("authority_adoption_file_changed",`File bytes no longer match the fenced snapshot for ${t.path}.`);let o=kT(e.import_id,t),a=await Df(r,`${e.files_url}/uploads`,e.access_token,{protocol_version:1,type:"open_authority_import_file_upload",transfer_id:o,file_id:t.file_id},i.signal);if(PT(a,o,t.size),a.strategy.kind!=="object_put"&&a.strategy.kind!=="object_multipart")throw ut("Connect returned an incompatible authority import file strategy.");let c=a.strategy.kind==="object_put"?Math.max(1,t.size):a.strategy.part_size,l=a.strategy.kind==="object_put"?1:Math.ceil(t.size/c);if(l>wT)throw ut("Authority import returned too many file parts.");let d=new Set(a.received),u=new Map(((h=a.uploaded_parts)!=null?h:[]).map(_=>[_.part_number-1,_]));if(a.received.length===l&&await yw(r,e,t,o,[...u.values()],i.signal))return;let f=Array(l);for(let[_,w]of u)f[_]=w;let p=[...d].reduce((_,w)=>_+Math.min(c,Math.max(0,t.size-w*c)),0);for(let _=0;__!==void 0);if(!await yw(r,e,t,o,y,i.signal))throw new J("authority_adoption_file_upload_incomplete",`Connect could not commit ${t.path}.`)}async function yw(r,e,t,n,i,s){try{let o=await Df(r,`${e.files_url}/uploads/${encodeURIComponent(n)}/commit`,e.access_token,{protocol_version:1,type:"commit_file_upload",transfer_id:n,...i.length>0?{parts:i}:{}},s);if(o.protocol_version!==1||o.type!=="file_upload_committed"||o.transfer_id!==n||!TT(o.file,t))throw ut("Connect returned an invalid authority import file receipt.");return!0}catch(o){if(i.length===0&&o instanceof J&&o.code==="file_upload_incomplete")return!1;throw o}}async function Df(r,e,t,n,i){let s;try{s=await r({url:e,method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/json"},body:n,...i?{signal:i}:{}})}catch(o){throw yc(i),new J("authority_adoption_unreachable","Connect could not be reached for collection adoption.")}if(s.status<200||s.status>=300)throw CT(s);return s.body}async function ST(r,e,t,n){OT(e.url);let i;try{i=await r({url:e.url,method:"PUT",headers:RT(e.headers),body:t,rawBody:!0,...n?{signal:n}:{}})}catch(s){throw yc(n),new J("authority_adoption_unreachable","Connect could not be reached for collection adoption.")}if(i.status<200||i.status>=300)throw new J("authority_adoption_object_upload_failed","Object storage rejected an authority import file part.",i.status);return i}function ET(r,e){if(r instanceof Blob)return r;if(r instanceof ArrayBuffer)return new Blob([r],{type:e});let t=new Uint8Array(r.buffer,r.byteOffset,r.byteLength).slice();return new Blob([t],{type:e})}async function AT(r,e){let t=We.create(),n=r.stream().getReader();try{for(;;){yc(e);let i=await n.read();if(i.done)break;t.update(i.value)}}finally{n.releaseLock()}return`sha256:${Ne(t.digest())}`}function kT(r,e){let t=xT(r),n=$T.encode(`mdbase-authority-import-file-v1\0${e.file_id}\0${e.revision}\0${e.content_digest}`),i=mc(new Uint8Array([...t,...n])).slice(0,16);i[6]=i[6]&15|80,i[8]=i[8]&63|128;let s=Ne(i);return`${s.slice(0,8)}-${s.slice(8,12)}-${s.slice(12,16)}-${s.slice(16,20)}-${s.slice(20)}`}function xT(r){if(!vT.test(r))throw ut("Authority import ID is invalid.");return Uint8Array.from(r.replaceAll("-","").match(/../g).map(e=>Number.parseInt(e,16)))}function PT(r,e,t){var a;let n=r==null?void 0:r.strategy;if((r==null?void 0:r.protocol_version)!==1||r.type!=="file_transfer"||r.transfer_id!==e||r.direction!=="upload"||r.protection!=="transport_tls"||r.total_size!==t||!Array.isArray(r.received)||!n||!["object_put","object_multipart"].includes(n.kind)||n.kind==="object_multipart"&&(!Number.isSafeInteger(n.part_size)||n.part_size<=0))throw ut("Connect returned an invalid authority import file session.");if(n.kind!=="object_put"&&n.kind!=="object_multipart")throw ut("Connect returned an invalid authority import file strategy.");let i=n.kind==="object_put"?Math.max(1,t):n.part_size,s=n.kind==="object_put"?1:Math.ceil(t/i);if(new Set(r.received).size!==r.received.length||r.received.some(c=>!Number.isSafeInteger(c)||c<0||c>=s))throw ut("Connect returned invalid authority import file progress.");let o=(a=r.uploaded_parts)!=null?a:[];if(!Array.isArray(o)||o.some((c,l)=>!Number.isSafeInteger(c==null?void 0:c.part_number)||c.part_number<1||c.part_number>s||typeof c.etag!="string"||c.etag.length===0||c.etag.length>255||l>0&&o[l-1].part_number>=c.part_number)||(n.kind==="object_multipart"?o.length!==r.received.length||o.some((c,l)=>c.part_number-1!==r.received[l]):o.length!==0))throw ut("Connect returned invalid authority import part receipts.")}function IT(r,e,t,n,i){if((r==null?void 0:r.protocol_version)!==1||r.type!=="file_part"||r.transfer_id!==e||r.part_index!==t||r.offset!==n||r.content_length!==i||r.method.toUpperCase()!=="PUT"||!Number.isFinite(Date.parse(r.expires_at))||!qf(r.headers))throw ut("Connect returned an invalid prepared authority import file part.")}function OT(r){let e;try{e=new URL(r)}catch(t){throw ut("Connect returned an invalid object storage URL.")}if(e.protocol!=="https:"&&!(e.protocol==="http:"&&["localhost","127.0.0.1","[::1]","::1"].includes(e.hostname))||e.username||e.password||e.hash)throw ut("Connect returned an unsafe object storage URL.")}function RT(r){let e={};for(let[t,n]of Object.entries(r)){if(["authorization","cookie","host","proxy-authorization"].includes(t.toLowerCase()))throw ut("Connect returned unsafe object storage headers.");if(/\r|\n/.test(t)||/\r|\n/.test(n))throw ut("Connect returned invalid object storage headers.");e[t]=n}return e}function TT(r,e){return r.file_id===e.file_id&&r.path===e.path&&r.revision===e.revision&&r.content_digest===e.content_digest&&r.size===e.size&&r.media_type===e.media_type&&r.media_class===e.media_class&&r.modified_at===e.modified_at}function CT(r){let e=qf(r.body)&&qf(r.body.error)?r.body.error:{};return new J(typeof e.code=="string"?e.code:"authority_adoption_request_failed",typeof e.message=="string"?e.message:`Collection adoption request failed with status ${r.status}.`,r.status)}function ut(r){return new J("invalid_authority_adoption_response",r)}function yc(r){if(r!=null&&r.aborted)throw new J("authority_adoption_cancelled","Collection adoption was cancelled.")}function qf(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}var Ff=1500,MT=250,NT=3e4,Sw=1440*60*1e3,Or=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,gc=class{constructor(e={}){I(this,"request");I(this,"now");I(this,"wait");var t,n,i;this.request=(t=e.request)!=null?t:LT,this.now=(n=e.now)!=null?n:Date.now,this.wait=(i=e.wait)!=null?i:FT}async begin(e,t={}){On(t.signal);let n=Rr(e.controlUrl),i=e.mirrorName.trim();if(!i||i.length>200)throw new Ge("invalid_mirror_name","Mirror name must contain between 1 and 200 characters.");if(!["read_only","read_write"].includes(e.mode))throw new Ge("invalid_mirror_mode","Mirror mode must be read-only or read-write.");if(e.collectionId!==void 0&&!Or.test(e.collectionId))throw new Ge("invalid_collection_id","Collection ID must be a UUID.");let s;try{s=await this.request({url:`${n}/v1/mirror-pairing-requests`,method:"POST",headers:{"content-type":"application/json"},body:{mirror_name:i,mode:e.mode,...e.collectionId?{collection_id:e.collectionId}:{}},...t.signal?{signal:t.signal}:{}})}catch(c){throw On(t.signal),vw()}let o=ww(s,201);if(!Ii(o)||!Or.test(gt(o.pairing_id))||!Zs(o.pairing_secret)||!VT(o.expires_in)||Number(o.expires_in)*1e3>Sw)throw Wt("Connect returned an invalid mirror approval.");let a=Aw(n,gt(o.verification_uri),gt(o.pairing_id));return{controlUrl:n,pairingId:gt(o.pairing_id),refreshCredential:gt(o.pairing_secret),verificationUri:a,expiresAt:new Date(this.now()+Number(o.expires_in)*1e3).toISOString(),requested:{mirrorName:i,mode:e.mode,...e.collectionId?{collectionId:e.collectionId}:{}}}}async enroll(e,t){let n=await this.begin(e,t),{refreshCredential:i,...s}=n;return await t.onVerification(s),this.waitForApproval(n,t)}async waitForApproval(e,t={}){var o,a;jT(e,this.now());let n=$w(t.pollIntervalMs),i=Date.parse(e.expiresAt),s=0;for(;this.now()=500){let l=Vf(c);if(await this.retry(i,(a=c.retryAfterMs)!=null?a:n,t,s,{code:l.code,message:l.message})===null)break;continue}throw Vf(c)}throw new Ge("mirror_enrollment_expired","Mirror approval expired before it was completed.")}async renew(e,t={}){DT(e),On(t.signal);let n;try{n=await this.request({url:bw(e.controlUrl,e.enrollmentId,"renew"),method:"POST",headers:{authorization:`Bearer ${e.refreshCredential}`},...t.signal?{signal:t.signal}:{}})}catch(s){throw On(t.signal),vw()}let i={controlUrl:e.controlUrl,pairingId:e.enrollmentId,refreshCredential:e.refreshCredential,verificationUri:`${e.controlUrl}/mirror/${e.enrollmentId}`,expiresAt:new Date(this.now()+6e4).toISOString(),requested:{mirrorName:e.name,mode:e.mode,collectionId:e.collectionId}};return _w(i,ww(n,200),{replicaId:e.replicaId})}async retry(e,t,n,i,s){var l;let o=e-this.now();if(o<=0)return null;let a=Math.min($w(t),o),c=new Date(this.now()+a).toISOString();return(l=n.onStatus)==null||l.call(n,{state:s?"retrying":"waiting_for_approval",attempt:i,expiresAt:new Date(e).toISOString(),retryAt:c,...s?{error:s}:{}}),await this.wait(a,n.signal),c}},Ge=class extends b{constructor(t,n,i){super(t,n);I(this,"status");this.status=i,this.name="MirrorEnrollmentError"}};function Rr(r){let e;try{e=new URL(r)}catch(n){throw new Ge("invalid_connect_url","Connect URL must be an absolute HTTPS origin.")}if(e.pathname!=="/"||e.search||e.hash||e.username||e.password)throw new Ge("invalid_connect_url","Connect URL must be an origin without credentials, path, query, or fragment.");let t=["localhost","127.0.0.1","[::1]","::1"].includes(e.hostname);if(e.protocol!=="https:"&&!(e.protocol==="http:"&&t))throw new Ge("invalid_connect_url","Connect URL must use HTTPS outside loopback development.");return e.origin}async function LT(r){let e=await fetch(r.url,{method:r.method,headers:r.headers,...r.body===void 0?{}:{body:JSON.stringify(r.body)},...r.signal?{signal:r.signal}:{}}),t=await e.json().catch(()=>null),n=e.headers.get("retry-after");return{status:e.status,body:t,...n===null?{}:{retryAfterMs:qT(n)}}}function _w(r,e,t){if(!Ii(e)||e.status!=="paired"||!Ii(e.replica))throw Wt("Connect returned an invalid mirror enrollment.");let n=e.replica,i=gt(n.id),s=gt(n.collection_id),o=gt(n.name).trim(),a=n.mode,c=gt(e.token),l=gt(e.token_expires_at);if(!Or.test(i)||!Or.test(s)||!o||!["read_only","read_write"].includes(String(a))||!Zs(c)||!xw(l))throw Wt("Connect returned invalid mirror credentials.");if(a!==r.requested.mode)throw Wt("Connect returned a mirror with a different access mode.");if(r.requested.collectionId&&s!==r.requested.collectionId)throw Wt("Connect returned a different collection.");if(t.mirrorName!==void 0&&o!==t.mirrorName)throw Wt("Connect returned a mirror with a different name.");if(t.replicaId!==void 0&&i!==t.replicaId)throw Wt("Connect returned a different mirror replica.");let d;try{d=Ew(gt(e.sync_url),s)}catch(u){throw Wt("Connect returned an invalid authority sync URL.")}return{controlUrl:Rr(r.controlUrl),syncUrl:d,collectionId:s,replicaId:i,mode:a,name:o,enrollmentId:r.pairingId,accessToken:c,refreshCredential:r.refreshCredential,accessTokenExpiresAt:l}}function jT(r,e){Rr(r.controlUrl);let t=Date.parse(r.expiresAt);if(!Or.test(r.pairingId)||!Zs(r.refreshCredential)||!Number.isFinite(t)||t-e>Sw||!r.requested.mirrorName.trim()||r.requested.mirrorName.length>200||!["read_only","read_write"].includes(r.requested.mode)||r.requested.collectionId!==void 0&&!Or.test(r.requested.collectionId))throw new Ge("invalid_mirror_enrollment_session","Mirror enrollment session is invalid.");Aw(r.controlUrl,r.verificationUri,r.pairingId)}function DT(r){if(Rr(r.controlUrl),Ew(r.syncUrl,r.collectionId),!Or.test(r.collectionId)||!Or.test(r.replicaId)||!Or.test(r.enrollmentId)||!Zs(r.accessToken)||!Zs(r.refreshCredential)||!xw(r.accessTokenExpiresAt)||!r.name.trim()||r.name.length>200||!["read_only","read_write"].includes(r.mode))throw new Ge("invalid_mirror_enrollment","Stored mirror enrollment is invalid.")}function Ew(r,e){let t=new URL(r),n=`/v1/authorities/${encodeURIComponent(e)}/sync`;if(!(t.protocol==="https:"||t.protocol==="http:"&&["localhost","127.0.0.1","[::1]","::1"].includes(t.hostname))||t.username||t.password||t.pathname.replace(/\/$/,"")!==n||t.search||t.hash)throw new Error("invalid sync URL");return`${t.origin}${n}`}function Aw(r,e,t){let n;try{n=new URL(e)}catch(s){throw Wt("Connect returned an invalid mirror verification URI.")}let i=new URL(`/mirror/${encodeURIComponent(t)}`,r);if(n.origin!==i.origin||n.pathname!==i.pathname||n.search||n.hash||n.username||n.password)throw Wt("Connect returned an untrusted mirror verification URI.");return n.href}function bw(r,e,t){return`${Rr(r)}/v1/mirror-pairing-requests/${encodeURIComponent(e)}/${t}`}function ww(r,e){if(r.status!==e)throw Vf(r);return r.body}function Vf(r){let e=Ii(r.body)&&Ii(r.body.error)?r.body.error:{};return new Ge(gt(e.code)||"mirror_enrollment_request_failed",gt(e.message)||`Mirror enrollment request failed with status ${r.status}.`,r.status)}function Wt(r){return new Ge("invalid_mirror_enrollment_response",r)}function kw(r){return{code:"mirror_enrollment_unreachable",message:"Connect could not be reached for mirror enrollment."}}function vw(){let r=kw(void 0);return new Ge(r.code,r.message)}function $w(r=Ff){return Number.isFinite(r)?Math.min(NT,Math.max(MT,Math.round(r))):Ff}function qT(r){let e=Number(r);if(Number.isFinite(e)&&e>=0)return e*1e3;let t=Date.parse(r);return Number.isFinite(t)?Math.max(0,t-Date.now()):Ff}function FT(r,e){return On(e),new Promise((t,n)=>{let i=setTimeout(o,r),s=()=>{clearTimeout(i),e==null||e.removeEventListener("abort",s),n(new Ge("mirror_enrollment_cancelled","Mirror enrollment was cancelled."))};function o(){e==null||e.removeEventListener("abort",s),t()}e==null||e.addEventListener("abort",s,{once:!0})})}function On(r){if(r!=null&&r.aborted)throw new Ge("mirror_enrollment_cancelled","Mirror enrollment was cancelled.")}function xw(r){let e=Date.parse(r);return Number.isFinite(e)}function VT(r){return typeof r=="number"&&Number.isSafeInteger(r)&&r>0}function Zs(r){return typeof r=="string"&&r.length>=16}function gt(r){return typeof r=="string"?r:""}function Ii(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}var UT=/(?:^|\/)(?:\.{1,2}|)(?:\/|$)/u,BT=/[\p{Cc}:?<>|*"]/u,zT=/[. ](?:\/|$)/u,HT=/(?:^|\/)(?:CON|PRN|AUX|NUL|COM[1-9¹²³]|LPT[1-9¹²³])(?:\.|\/|$)/iu;function Gt(r){if(!r||r.startsWith("/")||r.includes("\\")||UT.test(r)||BT.test(r)||zT.test(r)||HT.test(r))throw new b("invalid_path",`Mirror received an unsafe path: ${r}.`)}function _t(r){return Gt(r),Oi(r)}function Oi(r){return/^[\x20-\x7e]+$/u.test(r)?/[A-Z]/u.test(r)?r.toLowerCase():r:r.normalize("NFC").toLowerCase().normalize("NFC")}var Iw=new Set(["image","audio","video","pdf","other"]),Pw=["image","audio","video","pdf","other"],KT=new Set([".mdbase",".git","node_modules","_contracts","_schemas","_types","_views"]),WT=/^(?:CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\.|$)/iu,GT=/^sha256:[0-9a-f]{64}$/u,JT=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,YT=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/u;function Rn(r){var s,o;let e={file_classes:[...(s=r==null?void 0:r.file_classes)!=null?s:[]],excluded_folders:[...(o=r==null?void 0:r.excluded_folders)!=null?o:[]]};if(e.excluded_folders.length>100)throw new b("invalid_file_materialization","Selective sync supports at most 100 excluded folders.");let t=new Set;for(let a of e.file_classes){if(!Iw.has(a)||t.has(a))throw new b("invalid_file_materialization","Selected file media classes must be valid and unique.");t.add(a)}let n=new Set,i=new Set;for(let a of e.excluded_folders){Rw(a,!0);let c=_t(a);if(n.has(a)||i.has(c))throw new b("invalid_file_materialization","Excluded folders must be unique on portable filesystems.");n.add(a),i.add(c)}return e.file_classes.sort((a,c)=>Pw.indexOf(a)-Pw.indexOf(c)),e.excluded_folders.sort((a,c)=>_t(a).localeCompare(_t(c))),e}function Tn(r,e){let t=_t(e);return!r.excluded_folders.some(n=>{let i=_t(n);return t===i||t.startsWith(`${i}/`)})}function bc(r,e){return r.file_classes.includes(e.media_class)&&Tn(r,e.path)}function Uf(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 Ow(r,e){return r.file_classes.includes(Uf(e))&&Tn(r,e)}function ft(r){if(Rw(r.path,!1),typeof r.file_id!="string"||!JT.test(r.file_id)||typeof r.revision!="string"||!r.revision||r.revision.length>255||!GT.test(r.content_digest)||!Number.isSafeInteger(r.size)||r.size<0||!Iw.has(r.media_class)||typeof r.modified_at!="string"||!YT.test(r.modified_at)||!Number.isFinite(Date.parse(r.modified_at))||r.media_type!==void 0&&(typeof r.media_type!="string"||!r.media_type||r.media_type.length>255))throw new b("invalid_snapshot",`Collection file ${r.path} has invalid metadata.`)}function Rw(r,e){if(Gt(r),r.length>1024)throw new b("invalid_file_path","Collection file paths cannot exceed 1024 characters.");if(r.split("/").some(i=>i.startsWith(".")||/[<>"|?*]/u.test(i)||WT.test(i)||KT.has(i.toLowerCase()))||!e&&/\.md$/iu.test(r))throw new b("invalid_file_path",`Collection file path ${r} is hidden, reserved, or non-portable.`)}async function Tw(r,e,t){let n,i=new Set;do{let s=await r.fileSnapshot(e.snapshot_id,n);if(s.protocol_version!==1||s.type!=="file_snapshot_page"||s.snapshot_id!==e.snapshot_id||s.scope_epoch!==e.scope_epoch||s.cursor!==e.head)throw new b("invalid_snapshot","Authority file snapshot boundary changed during download.");for(let o of s.files)ft(o);if(await t(s.files),n=s.next_page,n!==void 0&&i.has(n))throw new b("invalid_snapshot","Authority file snapshot repeated a page cursor.");n!==void 0&&i.add(n)}while(n)}function Tr(r,e){return(r==null?void 0:r.size)===e.size&&r.content_digest===e.content_digest}async function*_c(r,e){let t=We.create(),n=0;for await(let i of r){if(!(i instanceof Uint8Array)||i.byteLength===0){if(i instanceof Uint8Array&&i.byteLength===0)continue;throw new b("file_integrity_failed","A file transport returned invalid bytes.")}if(n+=i.byteLength,!Number.isSafeInteger(n)||n>e.size)throw new b("file_integrity_failed",`Downloaded bytes for ${e.path} are oversized.`);t.update(i),yield i}if(n!==e.size||`sha256:${Ne(t.digest())}`!==e.content_digest)throw new b("file_integrity_failed",`Downloaded bytes for ${e.path} failed integrity verification.`)}async function*Cw(r,e,t){let n=We.create(),i=0;for await(let s of r){if(!(s instanceof Uint8Array))throw new b("file_integrity_failed",`Local bytes for ${t} are invalid.`);if(s.byteLength!==0){if(i+=s.byteLength,!Number.isSafeInteger(i)||i>e.size)throw new b("pending_local_changed",`Local file ${t} changed while being staged.`);n.update(s),yield s}}if(i!==e.size||`sha256:${Ne(n.digest())}`!==e.content_digest)throw new b("pending_local_changed",`Local file ${t} changed while being staged.`)}async function wc(r,e,t){if(ft(t),await e.has(t.content_digest))try{for await(let n of _c(e.read(t.content_digest),t));return}catch(n){await e.remove(t.content_digest)}try{await e.write(t.content_digest,_c(r.downloadFile(t),t))}catch(n){throw await e.remove(t.content_digest).catch(()=>{}),n}if(!await e.has(t.content_digest))throw new b("file_integrity_failed","The verified file blob was not persisted.")}var ln=new TextEncoder;function Hf(r){var u,f,p,y,h;let e=In(r.collectionId,"Collection ID"),t=(u=r.sourceHead)!=null?u:0;if(!Number.isSafeInteger(t)||t<0)throw new J("invalid_authority_snapshot","Source head must be a non-negative integer.");let n=new Set,i=r.resources.map(m=>{let g=vc(m.path);if(n.add(g)||Bf(g),!["configuration","lock","contract","schema","type","view"].includes(m.kind))throw new J("invalid_authority_snapshot",`Unsupported collection resource kind for ${g}.`);return{path:g,kind:m.kind,revision:Mw(m.document),document:m.document}}).sort(QT);if(((f=i[0])==null?void 0:f.path)!=="mdbase.yaml"||i[0].kind!=="configuration"||i.filter(({kind:m})=>m==="configuration").length!==1)throw new J("invalid_authority_snapshot","A portable snapshot requires one mdbase.yaml configuration resource.");let s=r.records.map(m=>{let g=vc(m.path);return n.add(g)||Bf(g),{record_id:m.recordId?In(m.recordId,`Record ID for ${g}`):Lw(e,g),path:g,document:m.document}}).sort((m,g)=>zf(m.path,g.path)),o=new Set,a=((p=r.files)!=null?p:[]).map(m=>{let g=vc(m.path);n.add(g)||Bf(g);let _=In(m.file_id,`File ID for ${g}`);if(!o.add(_))throw new J("invalid_authority_snapshot",`Collection snapshot contains file ID more than once: ${_}`);return XT(m,g),{...m,file_id:_,path:g}}).sort((m,g)=>zf(m.path,g.path)),c=Nw(i.flatMap(({path:m,revision:g})=>[m,g])),l=Nw([...i.flatMap(({path:m,revision:g})=>["resource",m,g]),...s.flatMap(m=>["record",m.path,Mw(m.document)]),...a.flatMap(m=>{var g;return["file",m.path,m.file_id,m.revision,m.content_digest,String(m.size),(g=m.media_type)!=null?g:"",m.media_class]})]),d=pc([...i.map(({path:m,document:g})=>({kind:"resource",path:m,identity:"",document_hash:Ne(We(ln.encode(g)))})),...s.map(m=>({kind:"record",path:m.path,identity:m.record_id,document_hash:Ne(We(ln.encode(m.document)))})),...a.map(m=>({kind:"file",path:m.path,identity:m.file_id,document_hash:hc(m)}))]);return{protocol_version:1,collection_id:e,source_head:t,source_revision:l,manifest_digest:d,resources:{revision:c,spec_version:r.specVersion,types:(y=r.types)!=null?y:[],contracts:(h=r.contracts)!=null?h:[],documents:i},records:s,files:a}}function XT(r,e){try{ft({...r,path:e})}catch(t){throw new J("invalid_authority_snapshot",`File descriptor is invalid for ${e}.`)}if(r.media_class!==Uf(e))throw new J("invalid_authority_snapshot",`File media class does not match its path for ${e}.`)}function Lw(r,e){let t=ZT(In(r,"Collection ID")),i=mc(new Uint8Array([...t,...ln.encode(vc(e))])).slice(0,16);i[6]=i[6]&15|80,i[8]=i[8]&63|128;let s=Ne(i);return`${s.slice(0,8)}-${s.slice(8,12)}-${s.slice(12,16)}-${s.slice(16,20)}-${s.slice(20)}`}function Mw(r){return`sha256:${Ne(We(ln.encode(r)))}`}function Nw(r){let e=We.create();for(let t of r){let n=BigInt(ln.encode(t).length),i=new Uint8Array(8);new DataView(i.buffer).setBigUint64(0,n),e.update(i),e.update(ln.encode(t))}return`sha256:${Ne(e.digest())}`}function QT(r,e){return r.kind==="configuration"&&e.kind!=="configuration"?-1:e.kind==="configuration"&&r.kind!=="configuration"?1:zf(r.path,e.path)}function zf(r,e){let t=ln.encode(r),n=ln.encode(e),i=Math.min(t.length,n.length);for(let s=0;s!t||t==="."||t===".."))throw new J("invalid_authority_snapshot",`Collection path is unsafe: ${r}`);return e}function Bf(r){throw new J("invalid_authority_snapshot",`Collection snapshot contains the path more than once: ${r}`)}function ZT(r){return Uint8Array.from(r.replaceAll("-","").match(/../g).map(e=>Number.parseInt(e,16)))}var eC=/^sha256:[a-f0-9]{64}$/,tC=/^[a-f0-9]{64}$/,Wf=1500,Gf=1440*60*1e3,rC=200,jw=8*1024*1024,nC=new TextEncoder,$c=class{constructor(e={}){I(this,"request");I(this,"now");I(this,"wait");var t,n,i;this.request=(t=e.request)!=null?t:aC,this.now=(n=e.now)!=null?n:Date.now,this.wait=(i=e.wait)!=null?i:oC}async begin(e,t={}){var f,p;Mn(t.signal);let n=Rr(e.controlUrl),i=In(e.collectionId,"Collection ID"),s=Kf(e.displayName,"Collection name"),o=Kf(e.sourceName,"Source name"),a=(f=e.retainMirror)!=null?f:!0,c=a?Kf((p=e.mirrorName)!=null?p:o,"Mirror name"):void 0,l;try{l=await this.request({url:`${n}/v1/authority-adoptions`,method:"POST",headers:{"content-type":"application/json"},body:{collection_id:i,display_name:s,source_name:o,retain_mirror:a,...c?{mirror_name:c}:{}},...t.signal?{signal:t.signal}:{}})}catch(y){throw Mn(t.signal),Vw()}let d=sC(l,201);if(!Cr(d)||!Pi.test(et(d.adoption_id))||!Jf(d.adoption_secret)||!uC(d.expires_in)||Number(d.expires_in)*1e3>Gf)throw tt("Connect returned an invalid collection adoption request.");let u=Kw(n,et(d.verification_uri),et(d.adoption_id));return{controlUrl:n,adoptionId:et(d.adoption_id),credential:et(d.adoption_secret),verificationUri:u,expiresAt:new Date(this.now()+Number(d.expires_in)*1e3).toISOString(),requested:{collectionId:i,displayName:s,sourceName:o,retainMirror:a,...c?{mirrorName:c}:{}}}}async start(e,t){let n=await this.begin(e,t),{credential:i,...s}=n;return await t.onVerification(s),{session:n,prepared:await this.waitForApproval(n,t)}}async waitForApproval(e,t={}){var o,a;Ri(e,this.now());let n=Uw(t.pollIntervalMs),i=Date.parse(e.expiresAt),s=0;for(;this.now()=500){let l=Cn(c);if(!await this.retry(i,(a=c.retryAfterMs)!=null?a:n,s,t,{code:l.code,message:l.message}))break;continue}throw Cn(c)}throw new J("authority_adoption_expired","Collection adoption approval expired before upload began.")}async exchange(e,t={}){Ri(e,this.now(),!0);let n=await this.controlRequest(e,"exchange","POST",{},t.signal);if(n.status===202)throw new J("authority_adoption_pending","Collection adoption is still awaiting approval.",202);if(n.status!==200)throw Cn(n);return qw(e,n.body)}async uploadSnapshot(e,t,n,i={}){Ri(e,this.now(),!0),zw(e,t),Dw(e,n);let s={protocol_version:1,collection_id:n.collection_id,source_head:n.source_head,source_revision:n.source_revision,manifest_digest:n.manifest_digest,resources:n.resources,record_count:n.records.length,file_count:n.files.length,files:n.files};await this.importRequest(t.import.manifest_url,"PUT",t.import.access_token,s,i.signal);let o=0,a=[],c=0;for(let l of n.records){let d=nC.encode(JSON.stringify(l)).length;if(d>jw)throw new J("authority_adoption_record_too_large",`Record ${l.path} is too large to adopt.`);a.length>0&&(a.length===rC||c+d>jw)&&(await this.uploadPage(t.import,o,a,i.signal),o+=1,a=[],c=0),a.push(l),c+=d}a.length>0&&await this.uploadPage(t.import,o,a,i.signal);for(let l of n.files){if(!i.fileSource)throw new J("authority_adoption_file_source_required",`File bytes are required to adopt ${l.path}.`);let d=await i.fileSource(l);await gw(this.request,t.import,l,d,i)}await this.importRequest(t.import.finalize_url,"POST",t.import.access_token,void 0,i.signal)}async complete(e,t,n={}){Ri(e,this.now(),!0),Dw(e,t);let i;try{i=await this.controlRequest(e,"complete","POST",{manifest_digest:t.manifest_digest,source_revision:t.source_revision,source_head:t.source_head},n.signal)}catch(a){throw Mn(n.signal),new Ir("Connect could not confirm whether hosted authority activated.",{cause:a})}if(i.status>=500)throw new Ir("Connect could not confirm whether hosted authority activated.");if(i.status!==200)throw Cn(i);let s=i.body;if(!Cr(s)||s.status!=="completed")throw tt("Connect returned an invalid adoption completion.");let o=Hw(e,s.adoption);if(o.state!=="completed"||o.manifest_digest!==t.manifest_digest||o.source_revision!==t.source_revision||o.final_head!==t.source_head)throw tt("Connect completed a different adoption snapshot.");return{status:"completed",adoption:o}}async cancel(e,t={}){Ri(e,this.now(),!0);let n=await this.controlRequest(e,void 0,"DELETE",void 0,t.signal);if(n.status!==200)throw Cn(n)}mirrorEnrollmentSession(e,t){var n;if(Ri(e,this.now(),!0),t.status!=="completed"||t.adoption.collection_id!==e.requested.collectionId)throw tt("Completed adoption does not belong to this session.");return e.requested.retainMirror?{controlUrl:e.controlUrl,pairingId:e.adoptionId,refreshCredential:e.credential,verificationUri:`${e.controlUrl}/mirror/${e.adoptionId}`,expiresAt:new Date(this.now()+Gf).toISOString(),requested:{mirrorName:(n=e.requested.mirrorName)!=null?n:e.requested.sourceName,mode:"read_write",collectionId:e.requested.collectionId}}:null}async uploadPage(e,t,n,i){let s={protocol_version:1,page:t,records:n};await this.importRequest(e.records_url,"PUT",e.access_token,s,i)}async importRequest(e,t,n,i,s){let o;try{o=await this.request({url:e,method:t,headers:{authorization:`Bearer ${n}`,...i===void 0?{}:{"content-type":"application/json"}},...i===void 0?{}:{body:i},...s?{signal:s}:{}})}catch(a){throw Mn(s),Vw()}if(o.status<200||o.status>=300)throw Cn(o)}controlRequest(e,t,n,i,s){return this.request({url:Fw(e,t),method:n,headers:{authorization:`Bearer ${e.credential}`,...i===void 0?{}:{"content-type":"application/json"}},...i===void 0?{}:{body:i},...s?{signal:s}:{}})}async retry(e,t,n,i,s){var l;let o=e-this.now();if(o<=0)return!1;let a=Math.min(Uw(t),o),c=new Date(this.now()+a).toISOString();return(l=i.onStatus)==null||l.call(i,{state:s?"retrying":"waiting_for_approval",attempt:n,expiresAt:new Date(e).toISOString(),retryAt:c,...s?{error:s}:{}}),await this.wait(a,i.signal),!0}};function Ri(r,e,t=!1){Rr(r.controlUrl);let n=Date.parse(r.expiresAt);if(!Pi.test(r.adoptionId)||!Jf(r.credential)||!Number.isFinite(n)||n-e>Gf||!t&&n<=e||!Pi.test(r.requested.collectionId)||!r.requested.displayName.trim()||!r.requested.sourceName.trim())throw new J("invalid_authority_adoption_session","Stored collection adoption state is invalid.");Kw(r.controlUrl,r.verificationUri,r.adoptionId)}function zw(r,e){if(e.status!=="ready"||e.adoption.id!==r.adoptionId||e.adoption.collection_id!==r.requested.collectionId)throw tt("Prepared adoption does not belong to this session.");let t=e.import;if(!Pi.test(t.import_id)||!Jf(t.access_token))throw tt("Connect returned an invalid authority import capability.");let n=[[t.manifest_url,"manifest"],[t.records_url,"records"],[t.files_url,"files"],[t.finalize_url,"finalize"]],i;for(let[s,o]of n){let a=iC(s,t.import_id,o);if(!a||i!==void 0&&a.origin!==i)throw tt("Connect returned an invalid authority import capability.");i=a.origin}}function Dw(r,e){var t;if(e.protocol_version!==1||e.collection_id!==r.requested.collectionId||!Number.isSafeInteger(e.source_head)||e.source_head<0||!eC.test(e.source_revision)||!tC.test(e.manifest_digest)||((t=e.resources.documents)==null?void 0:t.length)===0||!Array.isArray(e.files))throw new J("invalid_authority_snapshot","Authority snapshot does not belong to this adoption.")}function qw(r,e){if(!Cr(e)||!["ready","activating","completed"].includes(et(e.status)))throw tt("Connect returned an invalid adoption exchange.");let t=Hw(r,e.adoption);if(e.status==="completed")return{status:"completed",adoption:t};if(e.status==="activating")return{status:"activating",adoption:t};if(!Cr(e.import)||!Cr(e.staged))throw tt("Connect omitted the authority import capability.");let n=e.import,i=e.staged,s={status:"ready",adoption:t,import:{import_id:et(n.import_id),manifest_url:et(n.manifest_url),records_url:et(n.records_url),files_url:et(n.files_url),finalize_url:et(n.finalize_url),access_token:et(n.access_token)},staged:{state:i.state,manifest_digest:Bw(i.manifest_digest),source_revision:Bw(i.source_revision),source_head:dC(i.source_head)}};if(zw(r,s),!["receiving","uploaded"].includes(s.staged.state))throw tt("Connect returned an invalid staged import state.");return s}function Hw(r,e){if(!Cr(e))throw tt("Connect omitted collection adoption state.");let t=e;if(t.id!==r.adoptionId||t.collection_id!==r.requested.collectionId||!["requested","approved","prepared","activating","completed","cancelled","expired"].includes(t.state)||!Number.isSafeInteger(t.authority_epoch)||t.authority_epoch<2||!lC(t.expires_at))throw tt("Connect returned invalid collection adoption state.");return t}function iC(r,e,t){try{let n=new URL(r);return(n.protocol==="https:"||n.protocol==="http:"&&["localhost","127.0.0.1","[::1]","::1"].includes(n.hostname))&&!n.username&&!n.password&&!n.search&&!n.hash&&n.pathname===`/v1/authority-imports/${e}/${t}`?n:null}catch(n){return null}}function Kw(r,e,t){let n;try{n=new URL(e)}catch(s){throw tt("Connect returned an invalid adoption verification URI.")}let i=new URL(`/adopt/${encodeURIComponent(t)}`,r);if(n.origin!==i.origin||n.pathname!==i.pathname||n.search||n.hash||n.username||n.password)throw tt("Connect returned an untrusted adoption verification URI.");return n.href}function Fw(r,e){let t=e?`/${e}`:"";return`${Rr(r.controlUrl)}/v1/authority-adoptions/${encodeURIComponent(r.adoptionId)}${t}`}function Kf(r,e){let t=r.trim();if(!t||t.length>200)throw new J("invalid_authority_adoption",`${e} must contain between 1 and 200 characters.`);return t}function sC(r,e){if(r.status!==e)throw Cn(r);return r.body}function Cn(r){let e=Cr(r.body)&&Cr(r.body.error)?r.body.error:{};return new J(et(e.code)||"authority_adoption_request_failed",et(e.message)||`Collection adoption request failed with status ${r.status}.`,r.status)}function tt(r){return new J("invalid_authority_adoption_response",r)}function Ww(r){return{code:"authority_adoption_unreachable",message:"Connect could not be reached for collection adoption."}}function Vw(){let r=Ww(void 0);return new J(r.code,r.message)}function Uw(r=Wf){return Number.isFinite(r)?Math.min(3e4,Math.max(250,Math.round(r))):Wf}function oC(r,e){return Mn(e),new Promise((t,n)=>{let i=setTimeout(o,r),s=()=>{clearTimeout(i),e==null||e.removeEventListener("abort",s),n(new J("authority_adoption_cancelled","Collection adoption was cancelled."))};function o(){e==null||e.removeEventListener("abort",s),t()}e==null||e.addEventListener("abort",s,{once:!0})})}function Mn(r){if(r!=null&&r.aborted)throw new J("authority_adoption_cancelled","Collection adoption was cancelled.")}async function aC(r){let e=await fetch(r.url,{method:r.method,headers:r.headers,redirect:"error",...r.body===void 0?{}:{body:r.rawBody?r.body:JSON.stringify(r.body)},...r.signal?{signal:r.signal}:{}}),t=await e.json().catch(()=>({})),n=e.headers.get("retry-after");return{status:e.status,body:t,headers:Object.fromEntries(e.headers.entries()),...n?{retryAfterMs:cC(n)}:{}}}function cC(r){let e=Number(r);if(Number.isFinite(e)&&e>=0)return e*1e3;let t=Date.parse(r);return Number.isFinite(t)?Math.max(0,t-Date.now()):Wf}function lC(r){return Number.isFinite(Date.parse(r))}function Bw(r){return r===null?null:et(r)}function dC(r){return r===null?null:typeof r=="number"&&Number.isSafeInteger(r)&&r>=0?r:Number.NaN}function uC(r){return typeof r=="number"&&Number.isSafeInteger(r)&&r>0}function Jf(r){return typeof r=="string"&&r.length>=16}function et(r){return typeof r=="string"?r:""}function Cr(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}var fC=new TextEncoder,to=Object.freeze({digest:r=>Ne(We(fC.encode(r))),randomId:()=>{var r;if(typeof((r=globalThis.crypto)==null?void 0:r.randomUUID)!="function")throw new b("mirror_random_unavailable","This runtime must provide crypto.randomUUID() or a MirrorRuntime adapter.");return globalThis.crypto.randomUUID()},now:()=>new Date().toISOString()});var eo=class{constructor(){I(this,"held",!1)}async runExclusive(e){if(this.held)throw new b("mirror_folder_in_use","Another mdbase mirror process is already using this folder.");this.held=!0;try{return await e()}finally{this.held=!1}}};function Gw(r,e,t){var i,s,o,a,c,l;if(r.engine_version!==3)throw new b("mirror_state_upgrade_required","Rebuild this prerelease mirror with the plan-only exact-document sync engine.");if(r.protocol_version!==1||r.replica_id!==e)throw new Error;if((i=r.resources)!=null||(r.resources={}),(s=r.generation)!=null||(r.generation=0),(o=r.files)!=null||(r.files={}),r.selective_sync=Rn(r.selective_sync),(a=r.planned_conflicts)!=null||(r.planned_conflicts={}),(c=r.local_bindings)!=null||(r.local_bindings={}),(l=r.mode)!=null||(r.mode="read_only"),r.mode!==t)throw new b("mirror_mode_mismatch",`Mirror metadata belongs to a ${r.mode.replace("_","-")} replica.`);let n=[];for(let[d,u]of Object.entries(r.records))if(n.push(_t(u.path)),u.record&&(u.record.record_id!==d||u.record.path!==u.path))throw new Error;for(let[d,u]of Object.entries(r.resources)){if(Gt(d),d!==u.path)throw new Error;n.push(_t(u.path))}for(let[d,u]of Object.entries(r.files)){if(ft(u.file),u.file.file_id!==d)throw new Error;n.push(_t(u.file.path))}n.sort();for(let d=1;dl.kind==="configuration"&&l.path==="mdbase.yaml");if(n.length!==1)throw new b("invalid_snapshot","Hosted snapshot requires exactly one canonical mdbase.yaml resource.");let i=Xw(n[0].document,e),s=(c=e0(n[0].document).settings)!=null?c:{},o=Ti(s.types_folder,"_types"),a=Ti(s.contracts_folder,"_contracts");for(let l of r){let d=l.path.split(".").at(-1),u=l.path.split("/"),f=u.some(y=>y.startsWith(".")),p=!1;if(l.kind==="configuration")p=l.path==="mdbase.yaml";else if(l.kind==="lock")p=l.path==="mdbase.lock.yaml"&&mC(l.document);else if(l.kind==="type")p=Yf(l.path,o)&&d==="md"&&Jw(l.document,l.path)==="mdbase.type";else if(l.kind==="contract")p=Yf(l.path,a)&&d==="md"&&Jw(l.document,l.path)==="mdbase.contract";else if(l.kind==="schema"){let y=hC(l.document);p=!f&&d==="json"&&u.some(h=>h==="schemas"||h==="_schemas")&&y!==null}else l.kind==="view"&&(p=!f&&d==="base");if(!p)throw new b("invalid_snapshot",`Hosted resource ${l.path} is not valid for kind ${l.kind}.`)}return i}function Yw(r){return{reservedFolders:new Set(["_types","_contracts","_types/_migrations",".mdbase"]),resourcePaths:r}}function Xw(r,e){var s;let t=(s=e0(r).settings)!=null?s:{},n=Ti(t.types_folder,"_types");return{reservedFolders:new Set([n,Ti(t.contracts_folder,"_contracts"),Ti(t.migrations_folder,`${n}/_migrations`),Ti(t.cache_folder,".mdbase",!0)]),resourcePaths:e}}async function Qw(r,e){if(r.length===0)return Yw(new Set);let t=await e();if(t===null)throw new b("invalid_mirror_state","Mirror collection configuration is missing.");return Xw(t,new Set(r))}function dn(r,e){if(Gt(r),/(?:^|\/)\./u.test(r)||e.resourcePaths.has(r)||pC(r,e.reservedFolders)||!r.endsWith(".md"))throw new b("invalid_record_path",`Mirror record path ${r} is outside the configured record namespace.`)}function pC(r,e){for(let t of e)if(Yf(r,t))return!0;return!1}function Zw(r,e){return r.filter(t=>{try{return dn(t,e),!0}catch(n){return!1}})}function e0(r){let e;try{e=ki(r)}catch(n){throw new b("invalid_snapshot","Hosted mdbase.yaml is not valid YAML.")}if(!e||typeof e!="object"||Array.isArray(e))throw new b("invalid_snapshot","Hosted mdbase.yaml requires an object document.");let t=e;if(typeof t.spec_version!="string")throw new b("invalid_snapshot","Hosted mdbase.yaml requires spec_version.");return t}function Ti(r,e,t=!1){let n=typeof r=="string"?r:e;if(Gt(n),!t&&n.split("/").some(i=>i.startsWith(".")))throw new b("invalid_snapshot",`Collection control folder ${n} must not be hidden.`);return n}function Yf(r,e){return r===e||r.startsWith(`${e}/`)}function hC(r){try{let e=JSON.parse(r);return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null}catch(e){return null}}function mC(r){try{let e=ki(r);return e!==null&&typeof e=="object"&&!Array.isArray(e)&&e.kind==="mdbase.type-pack-lock"&&e.lock_version===1&&Array.isArray(e.packs)}catch(e){return!1}}function Jw(r,e){try{return fc(r,e).frontmatter.kind}catch(t){return null}}function bt(r){return Oi(r)}function t0(r,e,t,n,i=[]){let s=bt(r);for(let o of t)if(bt(o)===s)throw new b("invalid_record_path",`Mirror record path ${r} aliases authority resource ${o} on a supported filesystem.`);for(let[o,a]of n)if((o!==e||a.path!==r)&&bt(a.path)===s)throw new b("invalid_record_path",`Mirror record paths ${a.path} and ${r} alias on a supported filesystem.`);for(let[,o]of i)if(bt(o.file.path)===s)throw new b("invalid_record_path",`Mirror record path ${r} aliases collection file ${o.file.path} on a supported filesystem.`)}function r0(r,e,t){var i,s;let n=bt(r);for(let o of Object.values((i=t.resources)!=null?i:{}))if(bt(o.path)===n)throw new b("invalid_file_path",`Collection file ${r} aliases authority resource ${o.path}.`);for(let o of Object.values(t.records))if(bt(o.path)===n)throw new b("invalid_file_path",`Collection file ${r} aliases record ${o.path}.`);for(let[o,a]of Object.entries((s=t.files)!=null?s:{}))if((o!==e||a.file.path!==r)&&bt(a.file.path)===n)throw new b("invalid_file_path",`Collection files ${a.file.path} and ${r} alias on a supported filesystem.`)}function ro(r){let e=new Map;for(let t of r){let n=bt(t),i=e.get(n);if(i!==void 0&&i!==t)throw new b("invalid_record_path",`Mirror paths ${i} and ${t} alias on a supported filesystem.`);e.set(n,t)}}var Ec=class{constructor(e,t,n){I(this,"pathPolicy");I(this,"digest");I(this,"recordIds",new Set);I(this,"physicalPaths",new Set);this.pathPolicy=e,this.digest=n;for(let i of t)this.physicalPaths.add(Oi(i.path))}validate(e){let t=e.document,n=e;if(dn(n.path,this.pathPolicy),this.recordIds.has(n.record_id))throw new b("invalid_snapshot",`Hosted snapshot repeats record identity ${n.record_id}.`);this.recordIds.add(n.record_id);let i=Oi(n.path);if(this.physicalPaths.has(i))throw new b("invalid_snapshot",`Hosted record path ${n.path} aliases another snapshot path on a supported filesystem.`);this.physicalPaths.add(i);let s=this.digest(t);if(n.revision.length!==7+s.length||!n.revision.startsWith("sha256:")||!n.revision.endsWith(s))throw new b("invalid_snapshot",`Hosted record ${n.path} does not match its declared revision.`);if(hw(t,n)!==!0){let a;try{a=fc(t,n.path)}catch(c){throw new b("invalid_snapshot",`Hosted record ${n.path} is not valid Markdown.`)}if(!Xf(a.frontmatter,n.frontmatter)||!yC(a.body,n.body))throw new b("invalid_snapshot",`Hosted record ${n.path} does not match its declared document.`)}return{record:n,document:t,hash:s}}};async function n0(r,e,t){let n,i=new Set;do{let s=await r.snapshot(e.snapshot_id,n);if(s.protocol_version!==1||s.snapshot_id!==e.snapshot_id||s.scope_epoch!==e.scope_epoch||s.cursor!==e.head)throw new b("invalid_snapshot","Authority snapshot boundary changed during download.");if(await t(s.records),n=s.next_page,n!==void 0&&i.has(n))throw new b("invalid_snapshot","Authority snapshot repeated a page cursor.");n!==void 0&&i.add(n)}while(n)}function yC(r,e){return r===e||r.startsWith(` `)&&r.slice(1)===e||e.startsWith(` -`)&&e.slice(1)===r}function Xf(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)=>Xf(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)&&Xf(s,n[i]))}var Ci=class{constructor(e,t,n,i){I(this,"fileSystem");I(this,"runtime");I(this,"mode");I(this,"blobStore");this.fileSystem=e,this.runtime=t,this.mode=n,this.blobStore=i}async recordPathPolicy(e){var t;return Qw(Object.keys((t=e.resources)!=null?t:{}),()=>this.fileSystem.read("mdbase.yaml"))}async put(e,t,n={}){var p,y,h,m;let{managedState:i=e,acceptedHash:s,materialized:o,inspectionPreflighted:a=!1}=n;a||dn(t.path,await this.recordPathPolicy(e)),o===void 0&&!a&&t0(t.path,t.record_id,Object.keys((p=e.resources)!=null?p:{}),Object.entries(e.records),Object.entries((y=e.files)!=null?y:{}));let c=(h=o==null?void 0:o.document)!=null?h:uc(t),l=await this.fileSystem.read(t.path),d=i==null?void 0:i.records[t.record_id];if(l!==null&&l!==c){let g=this.runtime.digest(l);if(!(d!==void 0&&d.path===t.path&&g===d.hash)&&(s===void 0||g!==s))throw new pt(t.record_id,t.path)}d&&d.path!==t.path&&await this.remove(i,t.record_id,d.path);let u=this.runtime.digest(c);typeof s=="string"&&s===u&&l!==null&&this.runtime.digest(l)===u||await this.fileSystem.write(t.path,c),e.records[t.record_id]={path:t.path,revision:t.revision,hash:(m=o==null?void 0:o.hash)!=null?m:u,...this.mode==="read_write"?{record:t}:{}}}async putFile(e,t,n=e,i){var y,h,m,g;if(ft(t),!this.blobStore)throw new b("file_storage_unavailable","Selected collection files require a content-addressed blob store adapter.");r0(t.path,t.file_id,e),(y=e.files)!=null||(e.files={});let s=(h=n.files)==null?void 0:h[t.file_id],o=await this.fileSystem.inspectBinary(t.path),a=bt(t.path),c=Object.values((m=n.files)!=null?m:{}).find(_=>bt(_.file.path)===a),l=[...Object.values((g=n.resources)!=null?g:{}),...Object.values(n.records)].find(_=>bt(_.path)===a),d=l?await this.fileSystem.read(t.path):null,u=(s==null?void 0:s.file.path)===t.path&&Tr(o,s.file),f=c!==void 0&&Tr(o,c.file),p=l!==void 0&&d!==null&&this.runtime.digest(d)===l.hash;if(o!==null&&!Tr(o,t)&&!u&&!f&&!p&&!(i!==void 0&&(o==null?void 0:o.size)===i.size&&o.content_digest===i.content_digest))throw new pt(t.file_id,t.path);if(s&&s.file.path!==t.path){let _=await this.fileSystem.inspectBinary(s.file.path);if(_!==null&&!Tr(_,s.file))throw new pt(t.file_id,s.file.path)}Tr(o,t)||await this.fileSystem.writeBinary(t.path,_c(this.blobStore.read(t.content_digest),t)),s&&s.file.path!==t.path&&await this.fileSystem.remove(s.file.path),e.files[t.file_id]={file:t}}async removeFile(e,t){var s;let n=(s=e.files)==null?void 0:s[t];if(!n)return;let i=await this.fileSystem.inspectBinary(n.file.path);if(i!==null&&!Tr(i,n.file))throw new pt(t,n.file.path);i!==null&&await this.fileSystem.remove(n.file.path),delete e.files[t]}async remove(e,t,n,i={}){var c;let s=e.records[t],o=(c=s==null?void 0:s.path)!=null?c:n;i.inspectionPreflighted||dn(o,await this.recordPathPolicy(e));let a=await this.fileSystem.read(o);if(a!==null&&s&&this.runtime.digest(a)!==s.hash)throw new pt(t,s.path);a!==null&&await this.fileSystem.remove(o),delete e.records[t]}async putResource(e,t,n){var o,a;let i=await this.fileSystem.read(t.path),s=(o=n==null?void 0:n.resources)==null?void 0:o[t.path];if(i!==null&&i!==t.document&&(!s||this.runtime.digest(i)!==s.hash))throw new pt(`resource:${t.path}`,t.path);await this.fileSystem.write(t.path,t.document),(a=e.resources)!=null||(e.resources={}),e.resources[t.path]={path:t.path,revision:t.revision,hash:this.runtime.digest(t.document)}}async removeResource(e,t,n){let i=await this.fileSystem.read(t);if(i!==null&&this.runtime.digest(i)!==n.hash)throw new pt(`resource:${t}`,t);i!==null&&await this.fileSystem.remove(t),e.resources&&delete e.resources[t]}};async function i0(r,e,t,n){var i,s;for(let o in r.records){if(!Object.hasOwn(r.records,o))continue;let a=r.records[o];dn(a.path,e);let c=await t.read(a.path);if(c===null||n(c)!==a.hash)throw new pt(o,a.path)}for(let[o,a]of Object.entries((i=r.resources)!=null?i:{})){let c=await t.read(a.path);if(c===null||n(c)!==a.hash)throw new pt(`resource:${o}`,a.path)}for(let[o,a]of Object.entries((s=r.files)!=null?s:{})){let c=await t.inspectBinary(a.file.path);if(!Tr(c,a.file))throw new pt(o,a.file.path)}}async function s0(r){var u,f,p,y,h;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 b("promotion_incomplete_file_projection","Moving the source of truth requires every collection file class with no excluded folders.");if(Object.keys((u=e.planned_conflicts)!=null?u:{}).length>0||e.batch!==void 0)throw new b("promotion_not_converged","Upload or resolve every local change before moving the source of truth.");await i0(e,i,n,s);let o=new Set(Object.keys((f=e.resources)!=null?f:{})),a=new Set(Object.values(e.records).map(m=>m.path)),c=(await n.listMarkdown(o)).filter(m=>!a.has(m));if(c.length>0)throw new b("promotion_unmanaged_files",`Synchronize unmanaged Markdown before promotion: ${c.join(", ")}.`);if(!n.listBinary)throw new b("promotion_file_scan_unavailable","Moving the source of truth requires binary file enumeration.");let l=new Set(Object.values((p=e.files)!=null?p:{}).map(m=>m.file.path)),d=(await n.listBinary(new Set([...o,...a]))).filter(m=>!l.has(m));if(d.length>0)throw new b("promotion_unmanaged_files",`Synchronize unmanaged files before moving the source of truth: ${d.join(", ")}.`);return{cursor:e.cursor,digest:pc([...Object.entries((y=e.resources)!=null?y:{}).map(([m,g])=>({kind:"resource",path:m,identity:"",document_hash:Lf(g.hash)})),...Object.entries(e.records).map(([m,g])=>({kind:"record",path:g.path,identity:m,document_hash:Lf(g.hash)})),...Object.values((h=e.files)!=null?h:{}).map(({file:m})=>({kind:"file",path:m.path,identity:m.file_id,document_hash:hc(m)}))])}}function Mr(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+t.file_conflicts.length,issues:e.issues,...i?{failure:i}:{}}}function o0(r,e){return["planned","applying","cancelled","stale","blocked","failed"].includes(r.state)?r:r.conflicts.length>0||r.file_conflicts.length>0||r.local_issues.length>0||e.summary.blocking_issues>0||e.summary.conflicts>0?{...r,state:"attention"}:{...r,state:e.actions.some(t=>t.command!=="advance_checkpoint")?"changes_waiting":"up_to_date"}}function fr(r,e){var a,c,l,d,u,f,p,y,h;if(!r)return{state:"not_initialized",mode:e,pending:0,pending_files:0,conflicts:[],file_conflicts:[],local_issues:[],cursor:null,last_synced_at:null};let t=[],n=[];for(let[m,g]of Object.entries((a=r.planned_conflicts)!=null?a:{})){if(g.entity==="file"){let x=g.local.state==="exact"?g.local.object.path:g.remote.state==="exact"?g.remote.object.path:"",v=n.findIndex(({file_id:P})=>P===m);v!==-1&&n.splice(v,1),n.push({file_id:m,path:x,code:"file_conflict",message:"Local and authority changes need a decision."});continue}let _=t.findIndex(({record_id:x})=>x===m);_!==-1&&t.splice(_,1);let w=g.local.state==="exact"?g.local.object.path:g.remote.state==="exact"?g.remote.object.path:null;t.push({record_id:m,path:w,kind:g.conflict_kind==="rejected"?"rejected":"conflicted",message:g.conflict_kind==="rejected"?"The authority rejected this local change.":"Local and authority changes need a decision."})}let i=[],s=r.batch?r.batch.plan.actions.slice(r.batch.next_action).filter(m=>m.command!=="advance_checkpoint").length:0,o=r.batch?r.batch.phase==="prepared"?"planned":r.batch.phase==="applying"||r.batch.phase==="effects_complete"?"applying":r.batch.phase==="cancelled"?"cancelled":((c=r.batch.failure)==null?void 0:c.code)==="sync_plan_stale"?"stale":"blocked":null;return{state:o!=null?o:t.length||n.length?"attention":"up_to_date",mode:e,pending:s,pending_files:r.batch?r.batch.plan.actions.slice(r.batch.next_action).filter(m=>m.command!=="advance_checkpoint"&&("target"in m&&m.target.entity==="file"||"source"in m&&m.source.entity==="file"||"entity"in m&&m.entity==="file")).length:0,conflicts:t,file_conflicts:n,local_issues:i,cursor:(d=(l=r.batch)==null?void 0:l.checkpoint_before.cursor)!=null?d:r.cursor,last_synced_at:(u=r.last_synced_at)!=null?u:null,generation:(f=r.generation)!=null?f:0,pending_checkpoint:(y=(p=r.batch)==null?void 0:p.checkpoint_after.cursor)!=null?y: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,...(h=r.batch)!=null&&h.failure?{failure:r.batch.failure}:{}}}async function gC(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 b("sync_protocol_incompatible",`Filesystem mirror requires exact-document v1 and its own ${t.replace("_","-")} replica.`);return n}async function Ac(r,e,t,n,i){var f;let s=await gC(r,e,t),o=(f=s.resources.documents)!=null?f:[],a=Sc(o),c=new Ec(a,o,i.digest),l=[];await n0(e,s,async p=>{for(let y of p){let h=c.validate(y);Tn(n,h.record.path)&&l.push(h)}});let d=[],u=new Set;return await Tw(e,s,async p=>{for(let y of p)if(bc(n,y)){if(u.has(y.file_id))throw new b("invalid_snapshot",`Hosted snapshot repeats file identity ${y.file_id}.`);u.add(y.file_id),d.push(y)}}),ro([...o.map(p=>p.path),...l.map(({record:p})=>p.path),...d.map(p=>p.path)]),{session:s,resources:o,records:l,files:d}}var kc="exact_document_plan_only_v1",xc="three_way_exact_document_v1",Pc="portable_mirror_projection_v1";function Ic(r){return JSON.stringify(Qf(r))}function no(r,e){return`sha256:${e(Ic(r))}`}function Qf(r){if(r===null||typeof r=="string"||typeof r=="boolean")return r;if(typeof r=="number"){if(!Number.isSafeInteger(r))throw new b("invalid_sync_plan","Sync plans contain only safe integer numeric values.");return r}if(Array.isArray(r))return r.map(Qf);if(typeof r=="object"){let e={};for(let t of Object.keys(r).sort()){let n=r[t];if(n===void 0)throw new b("invalid_sync_plan",`Sync plan field ${t} is undefined rather than an explicit state.`);e[t]=Qf(n)}return e}throw new b("invalid_sync_plan","Sync plans contain only canonical I-JSON values.")}function u0(r,e,t){let n=new Map(r.base.map(d=>[d.identity,d])),i=new Map(r.remote.map(d=>[d.identity,d])),s=new Map,o=new Map(r.local.map(d=>[d.object.path,d]));for(let d of r.local)!d.stable_identity||d.object.identity===""||(s.set(d.object.identity,d.object),o.delete(d.object.path));for(let[d,u]of n){let f=o.get(u.path);f&&(s.set(d,{...f.object,identity:d}),o.delete(u.path))}for(let[d,u]of i){if(s.has(d))continue;let f=o.get(u.path);f&&f.object.entity===u.entity&&(s.set(d,{...f.object,identity:d}),o.delete(u.path))}for(let[d,u]of n){if(s.has(d))continue;let f=[...o.values()].filter(y=>y.object.entity===u.entity&&y.object.payload_revision===u.payload_revision);if(f.length!==1)continue;let p=f[0];s.set(d,{...p.object,identity:d,revision:p.object.payload_revision===u.payload_revision?u.revision:p.object.revision}),o.delete(p.object.path)}for(let d of o.values()){let u=d.stable_identity?d.object.identity:xC(e,d.object,t);s.set(u,{...d.object,identity:u})}let a=new Set([...n.keys(),...s.keys(),...i.keys()]),c=new Map([...s.values()].map(d=>[d.path,d])),l=new Map([...i.values()].map(d=>[d.path,d]));return[...a].sort().map(d=>{var m,g,_,w,x;let u=n.get(d),f=s.get(d),p=i.get(d),y=(g=(m=p==null?void 0:p.path)!=null?m:f==null?void 0:f.path)!=null?g:u.path,h=(w=(_=f==null?void 0:f.path)!=null?_:p==null?void 0:p.path)!=null?w:u.path;return{entity:((x=f!=null?f:p)!=null?x:u).entity,identity:d,base:io(u),local:io(f),remote:io(p),local_target_owner:io(c.get(y)),remote_target_owner:io(l.get(h))}})}function f0(r,e){let t=[];for(let l of[...r.objects].sort(PC))EC(r,l,t);if(t=wC(t,r.objects,e),t=_C(t,r.objects),t.length>0||r.kind!=="incremental"||r.boundary.checkpoint.cursor!==r.boundary.authority_cursor){let l=t.map(d=>d.key);t.push({key:"checkpoint",depends_on_keys:l,command:"advance_checkpoint",reason:r.kind==="incremental"?"remote_change":r.kind,expected:r.boundary.checkpoint,next:{generation:r.boundary.checkpoint.generation+1,cursor:r.boundary.authority_cursor}})}let i=new Map;for(let l of t){let{key:d,depends_on_keys:u,...f}=l;i.set(d,no({action_scope:{replica_id:r.boundary.replica_id,scope_epoch:r.boundary.scope_epoch,generation:r.boundary.checkpoint.generation},key:d,...f},e))}let s=t.map(l=>{let{key:d,depends_on_keys:u,...f}=l,p={...f,action_id:i.get(d),depends_on:u.map(y=>i.get(y))};if((p.command==="put_remote"||p.command==="move_remote"||p.command==="delete_remote")&&(p.idempotency_key=p.action_id),p.command==="move_remote"){let y=u.find(h=>h===`${p.source.identity}:put-remote`);y&&(p.revision_from_dependency=i.get(y))}return p}),o=[...r.issues].sort(IC),a={uploads:s.filter(OC).length,downloads:s.filter(RC).length,conflicts:s.filter(l=>l.command==="record_conflict").length,blocking_issues:o.filter(l=>l.blocking).length},c={plan_version:1,engine_profile:kc,protocol_profile:"exact_document_v1",planner_policy:xc,projection_policy:Pc,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:s,issues:o,summary:a};return{...c,fingerprint:no(c,e)}}function _C(r,e){var c;if(!r.some(l=>l.command==="move_remote"))return r;let t=[...r],n=new Set;for(let l of bC(t))for(let d of l){let u=t.find(f=>f.key===d);(u==null?void 0:u.command)==="move_remote"&&n.add(u.source.identity)}let i=tp(t),s=new Map(t.map(l=>[l.key,l])),o=!0;for(;o;){o=!1;for(let l of t){if(l.command!=="move_remote")continue;let d=l.expected_target_owner;if(d.state!=="exact"||d.object.identity===l.source.identity)continue;let u=s.get((c=i.get(pr(d.object)))!=null?c:""),f=u&&a0(u);(!u||f&&n.has(f))&&!n.has(l.source.identity)&&(n.add(l.source.identity),o=!0)}}if(n.size>0){t=t.filter(d=>{let u=a0(d);return!u||!n.has(u)||d.command!=="put_remote"&&d.command!=="move_remote"});let l=new Map(e.map(d=>[d.identity,d]));for(let d of[...n].sort()){let u=l.get(d);!u||u.entity==="resource"||t.push({key:`${d}:conflict`,depends_on_keys:[],command:"record_conflict",reason:"local_change",identity:d,entity:u.entity,local:u.local,remote:u.remote,conflict_kind:"path_occupied"})}}let a=tp(t);for(let l of t){if(l.command!=="move_remote")continue;let d=l.expected_target_owner;if(d.state!=="exact"||d.object.identity===l.source.identity)continue;let u=a.get(pr(d.object));!u||u===l.key||(l.depends_on_keys.includes(u)||l.depends_on_keys.push(u),l.expected_target_owner={state:"absent"})}return p0(t)}function bC(r){var s;let e=r.filter(o=>o.command==="move_remote"),t=new Map(e.map(o=>[o.key,o])),n=tp(r),i=new Map;for(let o of e){let a=[],c=new Map,l=o;for(;l;){let d=c.get(l.key);if(d!==void 0){let f=a.slice(d);i.set([...f].sort().join("\0"),f);break}c.set(l.key,a.length),a.push(l.key);let u=l.expected_target_owner;l=u.state==="exact"?t.get((s=n.get(pr(u.object)))!=null?s:""):void 0}}return[...i.values()]}function tp(r){let e=new Map;for(let t of r)t.command==="move_remote"?e.set(pr(t.source),t.key):t.command==="delete_remote"&&e.set(pr(t.target),t.key);return e}function a0(r){if(r.command==="move_remote")return r.source.identity;if(r.command==="put_remote"||r.command==="delete_remote")return r.target.identity}function wC(r,e,t){var u;if(!r.some(f=>f.command==="move_local"||f.command==="write_local"))return r;let n=[...r],i=new Set;for(let f of e)f.base.state==="exact"&&i.add(f.base.object.path),f.local.state==="exact"&&i.add(f.local.object.path),f.remote.state==="exact"&&i.add(f.remote.object.path);for(;;){let f=vC(n);if(!f)break;let p=[...f].sort()[0],y=n.findIndex(w=>w.key===p),h=n[y];if(!h||h.command!=="move_local")throw new Error("Planner invariant: local path cycle contains a non-move action.");let m=SC(h.source,h.target_path,i,t);i.add(m);let g={...h.source,path:m},_={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=g,h.expected_source_owner={state:"exact",object:g},h.depends_on_keys=[_.key],n.splice(y,0,_)}let s=rp(n),o=new Map(e.map(f=>[f.identity,f])),a=new Set,c=new Map(n.map(f=>[f.key,f])),l=!0;for(;l;){l=!1;for(let f of n){let p=c0(f),y=Oc(f);if((p==null?void 0:p.state)!=="exact"||p.object.identity===y)continue;let h=c.get((u=s.get(pr(p.object)))!=null?u:""),m=h&&Oc(h);(!h||m&&a.has(m))&&!a.has(y)&&(a.add(y),l=!0)}}if(a.size>0){n=n.filter(f=>!a.has(Oc(f))||f.command!=="move_local"&&f.command!=="write_local");for(let f of[...a].sort()){let p=o.get(f);!p||p.entity==="resource"||n.push({key:`${f}:conflict`,depends_on_keys:[],command:"record_conflict",reason:"remote_change",identity:f,entity:p.entity,local:p.local,remote:p.remote,conflict_kind:"path_occupied"})}}let d=rp(n);for(let f of n){let p=c0(f),y=Oc(f);if((p==null?void 0:p.state)!=="exact"||p.object.identity===y)continue;let h=d.get(pr(p.object));!h||h===f.key||(f.depends_on_keys.includes(h)||f.depends_on_keys.push(h),$C(f,{state:"absent"}))}return p0(n)}function vC(r){var i;let e=r.filter(s=>s.command==="move_local"),t=new Map(e.map(s=>[s.key,s])),n=rp(r);for(let s of e){let o=[],a=new Map,c=s;for(;c;){let l=a.get(c.key);if(l!==void 0)return o.slice(l);a.set(c.key,o.length),o.push(c.key);let d=c.expected_target_owner;c=d.state==="exact"?t.get((i=n.get(pr(d.object)))!=null?i:""):void 0}}}function rp(r){let e=new Map;for(let t of r)t.command==="move_local"?e.set(pr(t.source),t.key):t.command==="delete_local"&&e.set(pr(t.target),t.key);return e}function c0(r){if(r.command==="move_local")return r.expected_target_owner;if(r.command==="write_local")return r.expected_path_owner}function $C(r,e){r.command==="move_local"?r.expected_target_owner=e:r.command==="write_local"&&(r.expected_path_owner=e)}function Oc(r){return r.command==="move_local"?r.source.identity:r.command==="write_local"||r.command==="delete_local"?r.target.identity:""}function pr(r){return`${r.entity}\0${r.identity}\0${r.path}`}function SC(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 d=n(`${r.entity}\0${r.identity}\0${r.path}\0${e}\0${l}`),u=`${s}.mdbase-sync-stage-${d.slice(0,16)}${c}`;if(!t.has(u))return u}}function p0(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 EC(r,e,t){if(e.frozen_conflict){t.push({key:`${e.identity}:conflict`,depends_on_keys:[],command:"record_conflict",reason:"pending",identity:e.identity,entity:e.entity,...e.frozen_conflict});return}let n=!ep(e.local,e.base),i=!ep(e.remote,e.base);if(!(!n&&!i)){if(e.entity==="resource"){if(n)return;Zf(e,t);return}if(r.mode==="read_only"){n||Zf(e,t);return}if(n&&i){if(ep(e.local,e.remote))return;t.push(kC(e));return}n?AC(e,t):Zf(e,t)}}function Zf(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(l0(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(l0(r,t,i?[i]:[]))}function l0(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:Nr(r.local).revision,payload_revision:Nr(r.local).payload_revision,...Nr(r.local).size===void 0?{}:{size:Nr(r.local).size}}}:r.local,expected_path_owner:t.length>0?{state:"exact",object:{...e,revision:Nr(r.local).revision,payload_revision:Nr(r.local).payload_revision,...Nr(r.local).size===void 0?{}:{size:Nr(r.local).size}}}:r.local_target_owner}}function AC(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(d0(r,t,[]));return}let n=r.remote.object,i;if(t.revision!==n.revision){let s=d0(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 d0(r,e,t){return{key:`${r.identity}:put-remote`,depends_on_keys:t,command:"put_remote",reason:"local_change",target:e,payload_revision:Nr(r.local).payload_revision,expected_remote:r.remote,expected_local:r.local,idempotency_key:""}}function kC(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 Nr(r){if(r.state!=="exact")throw new Error("Planner invariant: expected exact object state.");return r.object}function io(r){return r?{state:"exact",object:r}:{state:"absent"}}function xC(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 ep(r,e){return Ic(r)===Ic(e)}function PC(r,e){return`${r.entity}\0${r.identity}`.localeCompare(`${e.entity}\0${e.identity}`)}function IC(r,e){var t,n;return`${(t=r.path)!=null?t:""}\0${r.code}\0${r.message}`.localeCompare(`${(n=e.path)!=null?n:""}\0${e.code}\0${e.message}`)}function OC(r){return r.command==="put_remote"||r.command==="move_remote"||r.command==="delete_remote"}function RC(r){return r.command==="write_local"||r.command==="move_local"||r.command==="delete_local"}var Rc=class{constructor(e,t,n,i,s,o,a,c,l){I(this,"replicaId");I(this,"transport");I(this,"mode");I(this,"fileSystem");I(this,"blobStore");I(this,"selectiveSync");I(this,"runtime");I(this,"readState");I(this,"currentRecordPathPolicy");this.replicaId=e,this.transport=t,this.mode=n,this.fileSystem=i,this.blobStore=s,this.selectiveSync=o,this.runtime=a,this.readState=c,this.currentRecordPathPolicy=l}async inspect(e){let t=e===void 0?await this.readState():e;if(!t)return this.inspectSnapshot("initial",null);if(t.batch)throw new b("mirror_recovery_required","The prepared sync batch must recover before a new inspection can be planned.");return JSON.stringify(t.selective_sync)!==JSON.stringify(this.selectiveSync)?this.inspectSnapshot("rebuild",t):this.inspectIncremental(t)}async inspectSnapshot(e,t){let n=await Ac(this.replicaId,this.transport,this.mode,this.selectiveSync,this.runtime),i=Sc(n.resources),s=await this.inspectLocal(t,n.resources,i),o=new Map(n.records.map(({record:c})=>[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){var l,d;let t=new Map;for(let[u,f]of Object.entries(e.records))f.record&&t.set(u,f.record);let n=new Map(Object.entries((l=e.files)!=null?l:{}).map(([u,f])=>[u,f.file])),i=new Map(h0(e).map(u=>[MC(u),u])),s=e.cursor,o=e.cursor;for(;;){let u=s,f=await this.transport.changes(u,200);if(f.scope_epoch!==e.scope_epoch||f.cursorf.head||f.has_more&&f.cursor===u)throw new b("invalid_change_page","Authority returned an invalid change boundary.");if(f.reset_required)return this.inspectSnapshot("rebuild",e);for(let p of f.events){if(p.sequence<=o||p.sequence>f.cursor)throw new b("invalid_change_page","Authority change events are not strictly ordered.");o=p.sequence,this.applyRemoteObservation(i,t,n,p)}if(s=f.cursor,!f.has_more)break}let a=Object.values((d=e.resources)!=null?d:{}).map(u=>({path:u.path,kind:LC(u.path),revision:u.revision,document:""})),c=await this.inspectLocal(e,a,await this.currentRecordPathPolicy(e));return 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"){mw(i);let s=i.record.record_id;Tn(this.selectiveSync,i.record.path)?(e.set(`record:${s}`,m0(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"){ft(i.file);let s=i.file.file_id;bc(this.selectiveSync,i.file)?(e.set(`file:${s}`,ip(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){var y,h,m,g,_,w,x,v,P,O,$,R,S,U,B;let i=[],s=new Map,o=new Map,a=[],c=new Map(Object.entries((y=e==null?void 0:e.records)!=null?y:{}).map(([T,E])=>[E.path,[T,E]])),l=new Map(Object.entries((h=e==null?void 0:e.planned_conflicts)!=null?h:{}).filter(([,T])=>T.entity==="record"&&T.local.state==="exact").map(([T,E])=>[E.local.state==="exact"?E.local.object.path:"",T])),d=new Map(Object.entries((m=e==null?void 0:e.local_bindings)!=null?m:{}).filter(([,T])=>T.entity==="record").map(([T,E])=>[E.path,T])),u=new Set([...Object.keys((g=e==null?void 0:e.resources)!=null?g:{}),...t.map(T=>T.path)]);for(let T of u){let E=await this.fileSystem.read(T),k=(_=e==null?void 0:e.resources)==null?void 0:_[T];if(E===null)continue;let de=`sha256:${this.runtime.digest(E)}`;i.push({stable_identity:!0,object:Mi("resource",T,T,de)}),s.set(T,E);let Z=t.find(V=>V.path===T);!k&&Z&&Z.revision!==de?a.push({code:"local_collision",message:`${T} differs locally from the exact authority document.`,path:T,blocking:!0}):k&&k.revision!==de&&a.push({code:"mirror_diverged",message:`Authority-owned resource ${T} changed locally.`,path:T,blocking:!0})}let f=new Set(Object.values((w=e==null?void 0:e.records)!=null?w:{}).map(T=>T.path)),p=Zw(await this.fileSystem.listMarkdown(u),n).filter(T=>Tn(this.selectiveSync,T)||f.has(T));for(let T of p){let E=await this.fileSystem.read(T);if(E===null)continue;let k=`sha256:${this.runtime.digest(E)}`,de=l.get(T),Z=d.get(T),V=(x=c.get(T))==null?void 0:x[0],fe=(P=(v=de!=null?de:Z)!=null?v:V)!=null?P:"";i.push({stable_identity:fe!=="",object:Mi("record",fe,T,k)}),s.set(T,E)}if(this.selectiveSync.file_classes.length>0){if(!this.fileSystem.listBinary)throw new b("file_storage_unavailable","Selected files require binary enumeration.");let T=new Set(Object.values((O=e==null?void 0:e.files)!=null?O:{}).map(V=>V.file.path)),E=new Map(Object.entries(($=e==null?void 0:e.files)!=null?$:{}).map(([V,fe])=>[fe.file.path,[V,fe]])),k=new Map(Object.entries((R=e==null?void 0:e.planned_conflicts)!=null?R:{}).filter(([,V])=>V.entity==="file"&&V.local.state==="exact").map(([V,fe])=>[fe.local.state==="exact"?fe.local.object.path:"",V])),de=new Map(Object.entries((S=e==null?void 0:e.local_bindings)!=null?S:{}).filter(([,V])=>V.entity==="file").map(([V,fe])=>[fe.path,V])),Z=(await this.fileSystem.listBinary(u)).filter(V=>Ow(this.selectiveSync,V)||T.has(V));for(let V of Z){let fe=await this.fileSystem.inspectBinary(V);if(!fe)continue;let Ve=k.get(V),Jt=de.get(V),Dr=E.get(V),un=(B=(U=Ve!=null?Ve:Jt)!=null?U:Dr==null?void 0:Dr[0])!=null?B:"";i.push({stable_identity:un!=="",object:{entity:"file",identity:un,path:V,revision:Dr&&Dr[1].file.content_digest===fe.content_digest?Dr[1].file.revision:fe.content_digest,payload_revision:fe.content_digest,size:fe.size}}),o.set(V,fe)}}try{ro([...u,...p,...o.keys()])}catch(T){let E=T instanceof Error?T:new Error(String(T));a.push({code:g0(T),message:E.message,blocking:!0})}return{observations:i,documents:s,binary:o,issues:a}}async finish(e){var u,f,p,y,h;let{prior:t,local:n}=e,i=(u=e.remoteRefs)!=null?u:[...e.remoteResources.map(CC),...[...e.remoteRecords.values()].map(m0),...[...e.remoteFiles.values()].map(ip)],s=u0({base:t?h0(t):[],local:n.observations,remote:i},`${this.replicaId}\0${e.scopeEpoch}\0${(f=t==null?void 0:t.generation)!=null?f:0}`,this.runtime.digest);for(let m of s){let g=(p=t==null?void 0:t.planned_conflicts)==null?void 0:p[m.identity];!g||g.entity!==m.entity||(m.frozen_conflict={local:g.local,remote:g.remote,conflict_kind:g.conflict_kind})}let o=[...n.issues];for(let m of s)(e.kind==="initial"||e.kind==="rebuild")&&m.base.state==="absent"&&m.local.state==="exact"&&m.remote.state==="exact"&&!y0(m.local,m.remote)&&o.push({code:"local_collision",message:`${m.remote.object.path} differs locally from the exact authority object.`,path:m.remote.object.path,blocking:!0}),m.remote.state==="exact"&&m.local_target_owner.state==="exact"&&m.remote.object.identity!==m.local_target_owner.object.identity&&o.push({code:"local_collision",message:`${m.remote.object.path} is owned by different local bytes.`,path:m.remote.object.path,blocking:!0});try{ro([...i.map(m=>m.path),...n.observations.map(({object:m})=>m.path)])}catch(m){let g=m instanceof Error?m:new Error(String(m));o.push({code:g0(m),message:g.message,blocking:!0})}if(this.mode==="read_only"){for(let m of s)if(m.entity!=="resource"&&!y0(m.local,m.base)){let g=NC(m.local,m.base);if(o.some(_=>_.blocking&&_.path===g))continue;o.push({code:"mirror_diverged",message:`${g} changed in a receive-only mirror.`,path:g,blocking:!0})}}let a=no(Rn(this.selectiveSync),this.runtime.digest),c={boundary:{engine_profile:kc,protocol_profile:"exact_document_v1",planner_policy:xc,projection_policy:Pc,replica_id:this.replicaId,scope_epoch:e.scopeEpoch,authority_cursor:e.authorityCursor,checkpoint:{generation:(y=t==null?void 0:t.generation)!=null?y:0,cursor:(h=t==null?void 0:t.cursor)!=null?h:null},selective_sync_fingerprint:a},mode:this.mode,kind:e.kind,selective_sync:Rn(this.selectiveSync),objects:s,issues:TC(o)},l=f0(c,this.runtime.digest),d=await this.bindPayloads(l,n,e.remoteRecords,e.remoteResources,e.remoteFiles);return{summary:c,plan:l,durable_payloads:d,prior:t,snapshot:e.snapshot,remote_records:e.remoteRecords,remote_files:e.remoteFiles}}async bindPayloads(e,t,n,i,s){let o={documents:{},records:{},resources:{},files:{},local_files:{},mutations:{}},a=new Map(i.map(c=>[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 d=t.binary.get(l);if(!d)throw Nn(c.action_id);await this.stageLocalBinary(l,d),o.local_files[c.action_id]={path:l,...d}}else{let d=t.documents.get(l);if(d===void 0||`sha256:${this.runtime.digest(d)}`!==c.payload_revision)throw Nn(c.action_id);o.documents[c.action_id]=d}c.target.entity==="record"&&(o.mutations[c.action_id]={operation:"put",mutation_id:np(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 Nn(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 Nn(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 Nn(c.action_id);await wc(this.transport,this.blobStore,l),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 Nn(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 Nn(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:np(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:np(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 b("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 b("sync_plan_stale",`${e} disappeared during inspection.`);await this.blobStore.write(t.content_digest,Cw(n,t,e))}};function TC(r){var t;let e=new Map;for(let n of r)e.set(`${n.code}\0${(t=n.path)!=null?t:""}\0${n.message}\0${n.blocking}`,n);return[...e.values()]}function h0(r){var e,t;return[...Object.entries((e=r.resources)!=null?e:{}).map(([n,i])=>Mi("resource",n,i.path,i.revision)),...Object.entries(r.records).map(([n,i])=>Mi("record",n,i.path,i.revision)),...Object.entries((t=r.files)!=null?t:{}).map(([n,i])=>ip({...i.file,file_id:n}))]}function m0(r){return Mi("record",r.record_id,r.path,r.revision)}function CC(r){return Mi("resource",r.path,r.path,r.revision)}function Mi(r,e,t,n){return{entity:r,identity:e,path:t,revision:n,payload_revision:n}}function ip(r){return{entity:"file",identity:r.file_id,path:r.path,revision:r.revision,payload_revision:r.content_digest,size:r.size}}function MC(r){return`${r.entity}:${r.identity}`}function y0(r,e){return JSON.stringify(r)===JSON.stringify(e)}function NC(r,e){return r.state==="exact"?r.object.path:e.state==="exact"?e.object.path:"mirror"}function Nn(r){return new b("sync_payload_incomplete",`Inspected action ${r} has no revision-bound payload.`)}function g0(r){return r&&typeof r=="object"&&"code"in r&&typeof r.code=="string"?r.code:"sync_inspection_failed"}function LC(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 np(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 _0(r,e,t,n){if(r!=null&&r.batch){if(r.batch.plan.fingerprint!==e.fingerprint)throw new b("mirror_recovery_required","A different prepared sync batch must recover before this plan can apply.");return r}let i=r?structuredClone(r):DC(e.replica_id,e.scope_epoch,e.mode,e.selective_sync);return i.scope_epoch=e.scope_epoch,i.selective_sync=e.selective_sync,i.batch={phase:"prepared",plan:e,next_action:0,receipts:[],payloads:t,checkpoint_before:{generation:e.checkpoint_generation,cursor:e.base_cursor},checkpoint_after:{generation:e.checkpoint_generation+1,cursor:e.authority_cursor}},await n.write(i),i}async function b0(r,e){let t=rt(r);t.phase!=="effects_complete"&&(t.phase="applying",delete t.failure,await Cc(r,{type:"phase",plan_fingerprint:t.plan.fingerprint,phase:"applying"},e))}async function w0(r,e,t){let n=rt(r),i=n.plan.actions[n.next_action];if(!i||i.action_id!==e.action_id)throw new b("invalid_mirror_state","The durable sync receipt does not match the next prepared action.");let s={type:"receipt",plan_fingerprint:n.plan.fingerprint,receipt:structuredClone(e),delta:jC(r,i)};n.receipts.push(structuredClone(e)),n.next_action+=1,await Cc(r,s,t)}async function v0(r,e){let t=rt(r),n=t.plan.actions[t.next_action];if(!n||n.command!=="advance_checkpoint")throw new b("invalid_mirror_state","Sync effects cannot complete before the checkpoint action is next.");t.phase="effects_complete",await Cc(r,{type:"effects_complete",plan_fingerprint:t.plan.fingerprint},e)}async function Tc(r,e,t,n){let i=rt(r);i.phase=e,i.failure=t,await Cc(r,{type:"phase",plan_fingerprint:i.plan.fingerprint,phase:e,failure:t},n)}async function Cc(r,e,t){t.appendJournal?await t.appendJournal(e):await t.write(r)}function jC(r,e){var s,o,a,c;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]:so((s=r.planned_conflicts)==null?void 0:s[t])},local_bindings:{[t]:so((o=r.local_bindings)==null?void 0:o[t])}};return n==="record"?i.records={[t]:so(r.records[t])}:n==="resource"?i.resources={[t]:so((a=r.resources)==null?void 0:a[t])}:i.files={[t]:so((c=r.files)==null?void 0:c[t])},i}function so(r){return r===void 0?null:structuredClone(r)}function rt(r){if(!r.batch)throw new b("invalid_mirror_state","The mirror has no prepared sync batch.");return r.batch}async function $0(r,e){var n;let t=rt(r);if(t.phase!=="blocked"||((n=t.failure)==null?void 0:n.code)!=="sync_plan_stale")throw new b("mirror_recovery_required","Only a stale batch at a durable action boundary can be abandoned.");delete r.batch,await e.write(r)}function DC(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 Nc=class{constructor(e){I(this,"ports");I(this,"materializer");I(this,"ownersByPath",new Map);I(this,"pathsByOwner",new Map);this.ports=e,this.materializer=new Ci(e.fileSystem,e.runtime,e.mode,e.blobStore)}async execute(e,t){var s,o;let n=rt(e);this.indexPathOwners(e);let i=new Set(n.receipts.map(a=>a.action_id));for(await b0(e,this.ports.store);n.next_action!i.has(l));if(c){let l={code:"invalid_mirror_state",message:`Action ${a.action_id} is missing dependency ${c}.`,action_id:a.action_id};return await Tc(e,"blocked",l,this.ports.store),{status:"blocked",completed:n.next_action,failure:l}}try{let l=await this.dispatch(e,a);await w0(e,l,this.ports.store),i.add(l.action_id),(o=(s=this.ports).onProgress)==null||o.call(s,n.next_action,n.plan.actions.length-1)}catch(l){let d=VC(l,a.action_id);return await Tc(e,"blocked",d,this.ports.store),{status:d.code==="sync_plan_stale"?"stale":"blocked",completed:n.next_action,failure:d}}}throw new b("invalid_mirror_state","Prepared plan has no checkpoint action.")}async dispatch(e,t){var n,i;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":return(n=e.planned_conflicts)!=null||(e.planned_conflicts={}),e.planned_conflicts[t.identity]={entity:t.entity,local:t.local,remote:t.remote,conflict_kind:t.conflict_kind},(i=e.local_bindings)!=null||(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"advance_checkpoint":throw new b("invalid_mirror_state","The executor cannot dispatch checkpoint actions.")}}rebaseConflict(e,t){var s;let n=rt(e).payloads;if(t.entity==="record"){if(t.remote.state==="absent"){delete e.records[t.identity];return}let o=n.records[t.action_id];if(!o||o.revision!==t.remote.object.revision)throw hr(t);Mc(o,this.ports.runtime,o.revision),e.records[t.identity]={path:o.path,revision:o.revision,hash:t.local.state==="exact"?t.local.object.payload_revision.replace(/^sha256:/u,""):this.ports.runtime.digest(o.document),...this.ports.mode==="read_write"?{record:o}:{}};return}if((s=e.files)!=null||(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 hr(t);ft(i),e.files[t.identity]={file:i}}async writeLocal(e,t){let n=await this.ports.fileSystem.exists(t.target.path);(!n||!await this.matchesRef(t.target))&&(await this.assertLocal(t.expected_local),await this.assertPathOwner(t.target.path,t.expected_path_owner,n));let i=rt(e).payloads;if(t.target.entity==="record"){let o=i.records[t.action_id];if(!o||o.revision!==t.payload_revision)throw hr(t);return Mc(o,this.ports.runtime,t.payload_revision),await this.materializer.put(e,o,{inspectionPreflighted:!0}),this.installPathOwner(t.target),{action_id:t.action_id,status:"completed"}}if(t.target.entity==="resource"){let o=i.resources[t.action_id];if(!o||o.revision!==t.payload_revision||`sha256:${this.ports.runtime.digest(o.document)}`!==o.revision)throw hr(t);return await this.materializer.putResource(e,o,e),this.installPathOwner(t.target),{action_id:t.action_id,status:"completed"}}let s=i.files[t.action_id];if(!s||s.content_digest!==t.payload_revision)throw hr(t);return await this.materializer.putFile(e,s,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)),qC(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){var i;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 s=(i=e.resources)==null?void 0:i[t.target.identity];s?await this.materializer.removeResource(e,t.target.path,s):await this.ports.fileSystem.remove(t.target.path)}else await this.materializer.removeFile(e,t.target.identity);else FC(e,t.target);return this.removePathOwner(t.target),{action_id:t.action_id,status:"completed"}}async putRemote(e,t){var a,c;let n=rt(e).payloads;if(t.target.entity==="record"){let l=n.mutations[t.action_id],d=n.documents[t.action_id];if(!l||l.operation!=="put"||d===void 0)throw hr(t);if(`sha256:${this.ports.runtime.digest(d)}`!==t.payload_revision)throw new b("sync_plan_stale","Prepared local document payload no longer matches its revision.");let u=await this.ports.transport.mutate(l);return this.acceptRecordReceipt(e,t,u,d),sp(t.action_id,u)}if(t.target.entity==="resource")throw new b("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 hr(t);let s={protocol_version:1,type:"open_file_upload",transfer_id:ap(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(ft(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 op(t);return(a=e.files)!=null||(e.files={}),e.files[o.file.file_id]={file:o.file},(c=e.local_bindings)==null||delete c[t.target.identity],{action_id:t.action_id,status:"completed",file:o.file}}async moveRemote(e,t){var s,o,a;if(t.source.entity==="record"){let c=rt(e).payloads.mutations[t.action_id];if(!c||c.operation!=="move")throw hr(t);let l=await this.ports.transport.mutate(c);return this.acceptRecordReceipt(e,t,l),sp(t.action_id,l)}if(t.source.entity==="resource"||!this.ports.transport.moveFile)throw new b("invalid_sync_plan","This remote move command is unsupported.");let n={protocol_version:1,type:"move_file",mutation_id:ap(t.action_id),file_id:t.source.identity,if_revision:(s=this.dependencyFileRevision(e,t))!=null?s: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(ft(i.file),i.mutation_id!==n.mutation_id||i.file.file_id!==t.source.identity||i.file.path!==t.target_path)throw op(t);return(o=e.files)!=null||(e.files={}),e.files[t.source.identity]={file:i.file},(a=e.local_bindings)==null||delete a[t.source.identity],{action_id:t.action_id,status:"completed",file:i.file}}dependencyFileRevision(e,t){if(!t.revision_from_dependency)return;let n=rt(e).receipts.find(({action_id:i})=>i===t.revision_from_dependency);if(!(n!=null&&n.file)||n.file.file_id!==t.source.identity)throw new b("invalid_mirror_state",`Move ${t.action_id} is missing its dependency file receipt.`);return n.file.revision}async deleteRemote(e,t){var s,o;if(t.target.entity==="record"){let a=rt(e).payloads.mutations[t.action_id];if(!a||a.operation!=="delete")throw hr(t);let c=await this.ports.transport.mutate(a);return this.acceptRecordReceipt(e,t,c),sp(t.action_id,c)}if(t.target.entity==="resource"||!this.ports.transport.deleteFile)throw new b("invalid_sync_plan","This remote delete command is unsupported.");let n={protocol_version:1,type:"delete_file",mutation_id:ap(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 op(t);return(s=e.files)==null||delete s[t.target.identity],(o=e.local_bindings)==null||delete o[t.target.identity],{action_id:t.action_id,status:"completed"}}acceptRecordReceipt(e,t,n,i){var l,d,u,f;let o=("target"in t?t.target:t.source).identity;if(n.status==="applied"||n.status==="previously_applied"){if(n.record){Mc(n.record,this.ports.runtime,n.record.revision);let p=e.records[o];e.records[o]={path:n.record.path,revision:n.record.revision,hash:i===void 0?(l=p==null?void 0:p.hash)!=null?l: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];(d=e.local_bindings)==null||delete d[o];return}let a=n.status==="conflicted"?n.conflict.current:void 0;a&&Mc(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;(u=e.planned_conflicts)!=null||(e.planned_conflicts={}),e.planned_conflicts[o]={entity:"record",local:t.expected_local,remote:c,conflict_kind:n.status==="rejected"?"rejected":"both_changed"},(f=e.local_bindings)!=null||(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 new b("sync_plan_stale",`${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!=null?n:await this.pathExists(e)))throw new b("sync_plan_stale",`${e} is no longer vacant.`);return}if(!i||i.entity!==t.object.entity||i.identity!==t.object.identity)throw new b("sync_plan_stale",`${e} has a different path owner.`)}async matchesRef(e){if(e.entity==="file"){let n=await this.ports.fileSystem.inspectBinary(e.path);return n!==null&&n.content_digest===e.payload_revision&&(e.size===void 0||n.size===e.size)}let t=await this.ports.fileSystem.read(e.path);return t!==null&&`sha256:${this.ports.runtime.digest(t)}`===e.payload_revision}async pathExists(e){return this.ports.fileSystem.exists(e)}indexPathOwners(e){var t,n;this.ownersByPath.clear(),this.pathsByOwner.clear();for(let[i,s]of Object.entries(e.records))this.installPathOwner({entity:"record",identity:i,path:s.path,revision:s.revision,payload_revision:`sha256:${s.hash}`});for(let[i,s]of Object.entries((t=e.resources)!=null?t:{}))this.installPathOwner({entity:"resource",identity:i,path:s.path,revision:s.revision,payload_revision:`sha256:${s.hash}`});for(let[i,s]of Object.entries((n=e.files)!=null?n:{}))this.installPathOwner({entity:"file",identity:i,path:s.file.path,revision:s.file.revision,payload_revision:s.file.content_digest,size:s.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){var i;let t=`${e.entity}:${e.identity}`,n=(i=this.pathsByOwner.get(t))!=null?i:e.path;this.ownersByPath.delete(n),this.pathsByOwner.delete(t)}};function qC(r,e,t){var n,i;if(e.entity==="record"){let s=r.records[e.identity];s&&(s.path=t)}else if(e.entity==="resource"){let s=(n=r.resources)==null?void 0:n[e.identity];s&&(s.path=t)}else{let s=(i=r.files)==null?void 0:i[e.identity];s&&(s.file.path=t)}}function FC(r,e){var t,n;e.entity==="record"?delete r.records[e.identity]:e.entity==="resource"?(t=r.resources)==null||delete t[e.identity]:(n=r.files)==null||delete n[e.identity]}function Mc(r,e,t){let n=uc(r);if(r.revision!==t||`sha256:${e.digest(n)}`!==t)throw new b("invalid_sync_response","Record receipt does not match its exact document revision.")}function sp(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 hr(r){return new b("sync_payload_incomplete",`Prepared action ${r.action_id} has no exact payload capability.`)}function op(r){return new b("invalid_sync_response",`Authority receipt does not match prepared action ${r.action_id}.`)}function VC(r,e){let t=r instanceof Error?r:new Error(String(r));return{code:r&&typeof r=="object"&&"code"in r&&typeof r.code=="string"?r.code:"sync_action_failed",message:t.message,action_id:e}}function ap(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 jc=class{constructor(e,t){I(this,"fileSystem");I(this,"runtime");this.fileSystem=e,this.runtime=t}async validate(e,t){var n,i,s;if(((n=t==null?void 0:t.generation)!=null?n:0)!==e.checkpoint_generation||((i=t==null?void 0:t.cursor)!=null?i:null)!==e.base_cursor||((s=t==null?void 0:t.scope_epoch)!=null?s:e.scope_epoch)!==e.scope_epoch)throw Lc("The durable checkpoint changed after inspection.");for(let o of e.actions)o.depends_on.length===0&&await this.validateAction(o)}async validateAction(e){switch(e.command){case"write_local":await this.expected(e.expected_local),await this.expectedAt(e.target.path,e.expected_path_owner);return;case"delete_local":await this.expected(e.expected_local),await this.expectedAt(e.target.path,e.expected_path_owner);return;case"move_local":await this.expectedAt(e.source.path,e.expected_source_owner),await this.expectedAt(e.target_path,e.expected_target_owner);return;case"put_remote":case"move_remote":await this.expected(e.expected_local);return;case"delete_remote":await this.expectedAt(e.target.path,e.expected_local);return;case"record_conflict":await this.expected(e.local);return;case"advance_checkpoint":return}}async expectedAt(e,t){if(t.state==="absent"){if(await this.pathExists(e))throw Lc(`${e} is no longer vacant.`);return}if(t.object.path!==e||!await this.matches(t.object))throw Lc(`${e} no longer has the inspected owner and bytes.`)}async expected(e){if(e.state!=="absent"&&!await this.matches(e.object))throw Lc(`${e.object.path} no longer matches the inspected bytes.`)}async matches(e){if(e.entity==="file"){let n=await this.fileSystem.inspectBinary(e.path);return n!==null&&n.content_digest===e.payload_revision&&(e.size===void 0||n.size===e.size)}let t=await this.fileSystem.read(e.path);return t!==null&&`sha256:${this.runtime.digest(t)}`===e.payload_revision}async pathExists(e){return this.fileSystem.exists(e)}};function Lc(r){return new b("sync_plan_stale",r)}async function S0(r,e,t){var o;let n=rt(r);if(n.phase!=="effects_complete")throw new b("invalid_mirror_state","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 new b("invalid_mirror_state","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 new b("invalid_mirror_state","Prepared checkpoint boundary is inconsistent.");let s=n.plan.fingerprint;return r.generation=i.next.generation,r.cursor=(o=i.next.cursor)!=null?o:0,r.last_completed_plan=s,r.last_synced_at=e.now(),delete r.batch,await t.write(r),s}async function E0(r,e,t,n){var s,o,a;let[i]=e.actions;if(e.actions.length!==1||!i||i.command!=="advance_checkpoint"||i.expected.generation!==((s=r.generation)!=null?s:0)||i.expected.cursor!==r.cursor||i.next.generation!==((o=r.generation)!=null?o:0)+1||i.next.cursor!==e.authority_cursor||r.batch!==void 0)throw new b("invalid_mirror_state","Empty checkpoint plan is inconsistent.");return r.generation=i.next.generation,r.cursor=(a=i.next.cursor)!=null?a:0,r.last_completed_plan=e.fingerprint,r.last_synced_at=t.now(),await n.write(r),e.fingerprint}var Ln=class{constructor(e,t,n,i="read_only"){I(this,"replicaId");I(this,"transport");I(this,"mode");I(this,"stateStore");I(this,"fileSystem");I(this,"blobStore");I(this,"selectiveSync");I(this,"lease");I(this,"runtime");I(this,"materializer");I(this,"onProgress");var s,o;this.replicaId=e,this.transport=t,this.mode=i,this.stateStore=n.stateStore,this.fileSystem=n.fileSystem,this.blobStore=n.blobStore,this.selectiveSync=Rn(n.selectiveSync),this.lease=(s=n.lease)!=null?s:new eo,this.runtime=(o=n.runtime)!=null?o:to,this.materializer=new Ci(this.fileSystem,this.runtime,this.mode,this.blobStore),this.onProgress=n.onProgress}async sync(e={}){return this.lease.runExclusive(async()=>{var i,s;let t=await this.readState();if(((i=t==null?void 0:t.batch)==null?void 0:i.phase)==="blocked"&&((s=t.batch.failure)==null?void 0:s.code)==="sync_plan_stale"&&(await $0(t,this.journalStore()),t=await this.readState()),t!=null&&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()=>{var t,n;let e=await this.readState();return(n=(t=e==null?void 0:e.batch)==null?void 0:t.plan)!=null?n:(await this.inspectDetailed(e)).plan})}async apply(e,t={}){return this.lease.runExclusive(async()=>{let n=await this.readState();if(n!=null&&n.batch){if(n.batch.plan.fingerprint!==e.fingerprint)throw new b("mirror_recovery_required","A different prepared plan must recover before this plan can apply.");return this.executePrepared(n,t.signal)}let i=await this.inspectDetailed(n);return i.plan.fingerprint!==e.fingerprint?Mr("stale",e,fr(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){var s;let n=e.plan;if(n.issues.some(o=>o.blocking))return Mr("attention",n,fr(e.prior,this.mode),0);if(t!=null&&t.aborted)return Mr("cancelled",n,fr(e.prior,this.mode),0,{code:"sync_cancelled",message:"Sync cancelled before preparation."});try{await new jc(this.fileSystem,this.runtime).validate(n,e.prior)}catch(o){let a=o instanceof Error?o:new Error(String(o)),c=o&&typeof o=="object"&&"code"in o&&typeof o.code=="string"?o.code:"sync_revalidation_failed";return Mr(c==="sync_plan_stale"?"stale":"failed",n,fr(e.prior,this.mode),0,{code:c,message:a.message})}if(n.actions.length===0)return Mr("applied",n,fr(e.prior,this.mode),0);if(e.prior&&n.actions.length===1&&((s=n.actions[0])==null?void 0:s.command)==="advance_checkpoint")return await E0(e.prior,n,this.runtime,this.journalStore()),Mr("applied",n,fr(e.prior,this.mode),0);let i=await _0(e.prior,n,e.durable_payloads,this.journalStore());return this.executePrepared(i,t)}async executePrepared(e,t){let n=e.batch,i=await new Nc({transport:this.transport,fileSystem:this.fileSystem,blobStore:this.blobStore,runtime:this.runtime,mode:this.mode,store:this.journalStore(),onProgress:(c,l)=>{var d;return(d=this.onProgress)==null?void 0:d.call(this,{phase:"applying",completed:c,total:l,done:c===l})}}).execute(e,t);if(i.status!=="effects_complete"){let c=fr(e,this.mode);return Mr(i.status==="blocked"?"failed":i.status,n.plan,c,i.completed,i.failure)}let s=n.plan;await S0(e,this.runtime,this.journalStore()),await this.pruneFileBlobs();let o=fr(e,this.mode),a=o.conflicts.length>0||o.file_conflicts.length>0||o.local_issues.length>0||s.summary.conflicts>0;return Mr(a?"attention":"applied",s,o,i.completed)}inspectDetailed(e){return new Rc(this.replicaId,this.transport,this.mode,this.fileSystem,this.blobStore,this.selectiveSync,this.runtime,()=>this.readState(),t=>this.currentRecordPathPolicy(t)).inspect(e)}async status(){let e=await this.checkpointStatus();return e.state==="not_initialized"?e:o0(e,await this.inspect())}async checkpointStatus(){return this.lease.runExclusive(()=>this.checkpointStatusUnlocked())}async checkpointStatusUnlocked(){return fr(await this.readState(),this.mode)}async authorityPromotionManifest(){return this.lease.runExclusive(async()=>{var i;if(this.mode!=="read_write")throw new b("promotion_requires_writable_mirror","Only a read-write mirror can prove an authority promotion source.");let e=await this.readState();if(!e)throw new b("mirror_not_initialized","Synchronize this mirror first.");if(e.batch||Object.keys((i=e.planned_conflicts)!=null?i:{}).length>0)throw new b("promotion_mirror_not_clean","Finish the prepared batch and resolve conflicts before promotion.");let t=await s0({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(s=>s.command!=="advance_checkpoint"))throw new b("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){await this.lease.runExclusive(()=>this.resolveConflictUnlocked(e,"record",t))}async resolveFileConflict(e,t){await this.lease.runExclusive(()=>this.resolveConflictUnlocked(e,"file",t))}async resolveConflictUnlocked(e,t,n){var o,a,c,l;if(this.mode!=="read_write")throw new b("mirror_read_only","Receive-only mirrors have no writable conflicts.");let i=await this.readState();if(!i||i.batch)throw new b("mirror_recovery_required","Finish sync recovery before resolving conflicts.");if(!((o=i.planned_conflicts)==null?void 0:o[e]))throw new b("mirror_conflict_not_found","Writable mirror conflict was not found.");if(n==="remote"){let d=await Ac(this.replicaId,this.transport,this.mode,this.selectiveSync,this.runtime);if(t==="record"){let u=(a=d.records.find(({record:f})=>f.record_id===e))==null?void 0:a.record;await this.installRemoteRecord(i,e,u)}else{let u=d.files.find(f=>f.file_id===e);await this.installRemoteFile(i,e,u)}}(c=i.planned_conflicts)==null||delete c[e],n==="remote"&&((l=i.local_bindings)==null||delete l[e]),await this.writeState(i)}async installRemoteRecord(e,t,n){var o,a,c,l;if(n){let d=(o=e.planned_conflicts)==null?void 0:o[t],u=await this.fileSystem.read(n.path),f=((a=e.records[t])==null?void 0:a.path)===n.path||(d==null?void 0:d.local.state)==="exact"&&d.local.object.path===n.path;await this.materializer.put(e,n,{inspectionPreflighted:!1,...f&&u!==null?{acceptedHash:this.runtime.digest(u)}:{}});return}let i=(c=e.planned_conflicts)==null?void 0:c[t],s=(i==null?void 0:i.local.state)==="exact"?i.local.object.path:(l=e.records[t])==null?void 0:l.path;s&&await this.fileSystem.read(s)!==null&&await this.fileSystem.remove(s),delete e.records[t]}async installRemoteFile(e,t,n){var o,a,c,l,d,u,f,p;if(n){if(!this.blobStore)throw new b("file_storage_unavailable","File resolution needs a blob store.");await wc(this.transport,this.blobStore,n);let y=(o=e.planned_conflicts)==null?void 0:o[t],h=(y==null?void 0:y.local.state)==="exact"?{content_digest:y.local.object.payload_revision,size:(a=y.local.object.size)!=null?a:0}:void 0,m=(l=(c=e.local_bindings)==null?void 0:c[t])==null?void 0:l.path;await this.materializer.putFile(e,n,e,h),m&&m!==n.path&&await this.fileSystem.remove(m);return}let i=(d=e.planned_conflicts)==null?void 0:d[t],s=(i==null?void 0:i.local.state)==="exact"?i.local.object.path:(f=(u=e.files)==null?void 0:u[t])==null?void 0:f.file.path;s&&await this.fileSystem.inspectBinary(s)!==null&&await this.fileSystem.remove(s),(p=e.files)==null||delete p[t]}async readState(){let e=await this.stateStore.read();if(e===null)return null;try{return Gw(e,this.replicaId,this.mode)}catch(t){throw t instanceof b?t:new b("invalid_mirror_state","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(){var n,i,s,o,a;if(!this.blobStore)return;let e=await this.readState();if(!e)return;let t=new Set;for(let c of Object.values((n=e.files)!=null?n:{}))t.add(c.file.content_digest);for(let c of Object.values((s=(i=e.batch)==null?void 0:i.payloads.files)!=null?s:{}))t.add(c.content_digest);for(let c of Object.values((a=(o=e.batch)==null?void 0:o.payloads.local_files)!=null?a:{}))t.add(c.content_digest);await this.blobStore.prune(t)}currentRecordPathPolicy(e){return this.materializer.recordPathPolicy(e)}};var oo=class extends Ln{constructor(e,t,n){super(e,t,n,"read_write")}};function A0(r){let e=[...r.actions.flatMap(t=>t.command==="advance_checkpoint"?[]:[UC(t)]),...r.issues.map(t=>{var n;return{kind:"document",path:(n=t.path)!=null?n:"Sync engine",direction:"attention",action:"fix",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).map(t=>t.path),local_issues:r.issues.filter(t=>t.code==="invalid_frontmatter"&&t.path!==void 0).map(t=>({code:"invalid_frontmatter",message:t.message,path:t.path}))}}function UC(r){var c;if(r.command==="advance_checkpoint")throw new Error("Checkpoint actions are not preview entries.");if(r.command==="record_conflict"){let l=r.local.state==="exact"?r.local.object:r.remote.state==="exact"?r.remote.object:void 0;return{kind:r.entity==="file"?"file":"document",path:(c=l==null?void 0:l.path)!=null?c:r.identity,direction:"attention",action:"fix",detail:`Local and hosted ${r.entity} changes conflict (${r.conflict_kind.replace(/_/g," ")}).`,...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=r.command.split("_")[0],a=r.command.startsWith("move_")?` from ${t.path}`:"";return{kind:t.entity==="file"?"file":"document",path:n,direction:e?"download":"upload",action:s,detail:`${e?"Hosted":"Local"} ${t.entity} will ${o}${a}.`,...t.entity==="record"?{recordId:t.identity}:{},...t.entity==="file"?{fileId:t.identity}:{}}}var ao=".mdbase/connect-role.json",co=".mdbase/authority-adoption.json",lo=".mdbase/authority-adoption-snapshot.json",BC="mdbase-obsidian-connect-exact-v1",Ni="mirrors",zC="mdbase-connect-access-",HC="mdbase-connect-refresh-",KC="mdbase-connect-adoption-",WC=300*1e3,lp=[".git/",".obsidian/",".trash/",".mdbase/"],uo=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Fe(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function Dc(r,e){if(e!=null)return e;if(!r.trim())return{};try{return JSON.parse(r)}catch(t){return{}}}function x0(r){var i;let e=(i=r["retry-after"])!=null?i:r["Retry-After"];if(!e)return;let t=Number(e);if(Number.isFinite(t)&&t>=0)return t*1e3;let n=Date.parse(e);if(Number.isFinite(n))return Math.max(0,n-Date.now())}function GC(){return async r=>{var t,n;if((t=r.signal)!=null&&t.aborted)throw new DOMException("Enrollment cancelled.","AbortError");let e=await(0,oe.requestUrl)({url:r.url,method:r.method,headers:r.headers,body:r.body===void 0?void 0:JSON.stringify(r.body),contentType:r.body===void 0?void 0:"application/json",throw:!1});if((n=r.signal)!=null&&n.aborted)throw new DOMException("Enrollment cancelled.","AbortError");return{status:e.status,body:Dc(e.text,e.json),retryAfterMs:x0(e.headers)}}}function JC(){return async r=>{var t,n;if((t=r.signal)!=null&&t.aborted)throw new DOMException("Collection adoption cancelled.","AbortError");let e=await(0,oe.requestUrl)({url:r.url,method:r.method,headers:r.headers,body:r.body===void 0?void 0:JSON.stringify(r.body),contentType:r.body===void 0?void 0:"application/json",throw:!1});if((n=r.signal)!=null&&n.aborted)throw new DOMException("Collection adoption cancelled.","AbortError");return{status:e.status,body:Dc(e.text,e.json),retryAfterMs:x0(e.headers)}}}var dp=class{constructor(e,t){this.accessToken=t;let n;try{n=new URL(e)}catch(i){throw new b("invalid_sync_url","Sync URL must be an absolute authority endpoint.")}if(!(n.protocol==="https:"||n.protocol==="http:"&&["localhost","127.0.0.1","[::1]","::1"].includes(n.hostname))||n.username||n.password||n.search||n.hash||!/^\/v1\/authorities\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\/sync\/?$/i.test(n.pathname))throw new b("invalid_sync_url","Sync URL must identify one authority sync endpoint.");this.syncUrl=n.href.replace(/\/$/,""),this.filesUrl=this.syncUrl.replace(/\/sync$/,"/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){let t=crypto.randomUUID();try{let n=await this.fileRequest("POST","downloads",{protocol_version:1,type:"open_file_download",transfer_id:t,file_id:e.file_id,revision:e.revision}),i=Fe(n.strategy)?n.strategy:{},s=i.part_size;if(n.protocol_version!==1||n.type!=="file_transfer"||n.transfer_id!==t||n.direction!=="download"||n.protection!=="transport_tls"||n.total_size!==e.size||i.kind!=="object_ranges"||!Number.isSafeInteger(s)||s<=0)throw new b("invalid_sync_response","The authority returned an incompatible file download session.");let o=Math.ceil(e.size/s);for(let a=0;a=300){let d=Dc(l.text,l.json),u=Fe(d)&&Fe(d.error)?d.error:{};throw new b(typeof u.code=="string"?u.code:"file_download_failed",typeof u.message=="string"?u.message:`File download failed (${l.status}).`)}if(l.arrayBuffer.byteLength!==c)throw new b("file_integrity_failed","The authority returned a file part with the wrong length.");yield new Uint8Array(l.arrayBuffer)}}finally{await this.fileRequest("DELETE",`transfers/${encodeURIComponent(t)}`).catch(()=>{})}}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)}request(e,t,n){return this.requestAt(this.syncUrl,e,t,n)}fileRequest(e,t,n){return this.requestAt(this.filesUrl,e,t,n)}async requestAt(e,t,n,i){let s=await(0,oe.requestUrl)({url:`${e}/${n}`,method:t,headers:{authorization:`Bearer ${this.accessToken}`},body:i===void 0?void 0:JSON.stringify(i),contentType:i===void 0?void 0:"application/json",throw:!1}),o=Dc(s.text,s.json);if(s.status<200||s.status>=300){let a=Fe(o)&&Fe(o.error)?o.error:{};throw new b(typeof a.code=="string"?a.code:"sync_failed",typeof a.message=="string"?a.message:`Sync request failed (${s.status}).`)}return o}};function Lr(r){let e=Rs(r);if(e===".mdbase"||lp.some(t=>e.startsWith(t)))throw new b("unsafe_mirror_path",`The collection authority attempted to write a reserved path: ${e}`);return e}async function ji(r,e){let t=(0,oe.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 oe.TFolder)){if(s)throw new b("mirror_path_collision",`A file blocks the mirror folder ${n}.`);await r.adapter.exists(n)||await r.createFolder(n)}}}var up=class{constructor(e){this.vault=e}async exists(e){let t=Lr(e);return this.vault.getAbstractFileByPath(t)!==null||await this.vault.adapter.exists(t)}async read(e){let t=Lr(e),n=this.vault.getAbstractFileByPath(t);if(n==null)return null;if(!(n instanceof oe.TFile))throw new b("mirror_path_collision",`Expected a file at ${t}.`);return this.vault.cachedRead(n)}async write(e,t){let n=Lr(e),i=n.lastIndexOf("/");i>=0&&await ji(this.vault,n.slice(0,i));let s=this.vault.getAbstractFileByPath(n);if(s instanceof oe.TFolder)throw new b("mirror_path_collision",`A folder blocks the mirror file ${n}.`);s instanceof oe.TFile?await this.vault.modify(s,t):await this.vault.create(n,t)}async move(e,t){let n=Lr(e),i=Lr(t),s=i.lastIndexOf("/");s>=0&&await ji(this.vault,i.slice(0,s));let o=this.vault.getAbstractFileByPath(n);if(!(o instanceof oe.TFile))throw new b("mirror_path_collision",`Expected a file at ${n}.`);if(this.vault.getAbstractFileByPath(i)!==null||await this.vault.adapter.exists(i))throw new b("mirror_path_collision",`A file or folder blocks ${i}.`);await this.vault.rename(o,i)}async remove(e){let t=Lr(e),n=this.vault.getAbstractFileByPath(t);if(n!=null){if(!(n instanceof oe.TFile))throw new b("mirror_path_collision",`Expected a file at ${t}.`);await this.vault.delete(n,!0)}}async listMarkdown(e){return this.vault.getMarkdownFiles().map(t=>(0,oe.normalizePath)(t.path)).filter(t=>!e.has(t)).filter(t=>!lp.some(n=>t.startsWith(n))).sort()}async inspectBinary(e){let t=Lr(e),n=this.vault.getAbstractFileByPath(t);if(n==null)return null;if(!(n instanceof oe.TFile))throw new b("mirror_path_collision",`Expected a file at ${t}.`);let i=await this.vault.readBinary(n),s=await crypto.subtle.digest("SHA-256",i),o=Array.from(new Uint8Array(s),a=>a.toString(16).padStart(2,"0")).join("");return{size:i.byteLength,content_digest:`sha256:${o}`}}async writeBinary(e,t){let n=Lr(e),i=[],s=0;for await(let d of t){if(!(d instanceof Uint8Array)||!Number.isSafeInteger(s+d.byteLength))throw new b("invalid_file_materialization","The binary file stream is invalid or too large.");i.push(d),s+=d.byteLength}let o=new Uint8Array(s),a=0;for(let d of i)o.set(d,a),a+=d.byteLength;let c=n.lastIndexOf("/");c>=0&&await ji(this.vault,n.slice(0,c));let l=this.vault.getAbstractFileByPath(n);if(l instanceof oe.TFolder)throw new b("mirror_path_collision",`A folder blocks the mirror file ${n}.`);l instanceof oe.TFile?await this.vault.modifyBinary(l,o.buffer):await this.vault.createBinary(n,o.buffer)}async listBinary(e){return this.vault.getFiles().map(t=>(0,oe.normalizePath)(t.path)).filter(t=>!t.toLowerCase().endsWith(".md")).filter(t=>!e.has(t)).filter(t=>!lp.some(n=>t.startsWith(n))).sort()}async readBinary(e){let t=Lr(e),n=this.vault.getAbstractFileByPath(t);if(n==null)return null;if(!(n instanceof oe.TFile))throw new b("mirror_path_collision",`Expected a file at ${t}.`);let i=new Uint8Array(await this.vault.readBinary(n));return(async function*(){yield i})()}},fp=class{constructor(e){this.key=e;this.database=null}async read(){let e=await this.open();return new Promise((t,n)=>{let i=e.transaction(Ni,"readonly").objectStore(Ni).get(this.key);i.onsuccess=()=>{var s;return t((s=i.result)!=null?s:null)},i.onerror=()=>n(i.error)})}async write(e){let t=await this.open();await new Promise((n,i)=>{let s=t.transaction(Ni,"readwrite");s.objectStore(Ni).put(e,this.key),s.oncomplete=()=>n(),s.onerror=()=>i(s.error),s.onabort=()=>i(s.error)})}open(){var e;if(typeof indexedDB=="undefined")throw new b("storage_unavailable","IndexedDB is required for persistent mirror state.");return(e=this.database)!=null||(this.database=new Promise((t,n)=>{let i=indexedDB.open(BC,1);i.onupgradeneeded=()=>{i.result.objectStoreNames.contains(Ni)||i.result.createObjectStore(Ni)},i.onerror=()=>n(i.error),i.onsuccess=()=>t(i.result)})),this.database}},Li=class Li{constructor(e){this.key=e}async runExclusive(e){if(Li.active.has(this.key))throw new b("mirror_busy","A mirror operation is already running for this vault.");Li.active.add(this.key);try{return await e()}finally{Li.active.delete(this.key)}}};Li.active=new Set;var pp=Li,qc=class{constructor(e,t,n={}){this.app=e;this.settingsHost=t;this.options=n;this.progress=null;this.syncAbort=null;this.adoptionMarker=null;var i,s,o;this.fileSystem=(i=n.fileSystem)!=null?i:new up(e.vault),this.enrollmentClient=(s=n.enrollmentClient)!=null?s:new gc({request:GC()}),this.adoptionClient=(o=n.adoptionClient)!=null?o:new $c({request:JC()})}async initialize(){if(this.adoptionMarker=await this.readAdoptionMarker(),this.adoptionMarker&&this.settingsHost.getMirrorProfile())throw new b("authority_adoption_state_conflict","This vault contains both an authority-adoption checkpoint and a mirror profile.")}getProgress(){return this.progress?{...this.progress}:null}cancelSync(){var e;(e=this.syncAbort)==null||e.abort()}getAdoptionMarker(){return this.adoptionMarker?JSON.parse(JSON.stringify(this.adoptionMarker)):null}assertLocalAuthorityWritable(){if(this.adoptionMarker&&["fenced","activating","adopted"].includes(this.adoptionMarker.phase))throw new b("local_authority_fenced",this.adoptionMarker.phase==="adopted"?"Hosted mdbase is now authoritative. Finish reconnecting this vault as its mirror before editing.":"This local authority is frozen while its exact snapshot is adopted by hosted mdbase.")}async adoptLocalCollection(e,t){if(this.settingsHost.getMirrorProfile())throw new b("mirror_already_configured","This vault already mirrors a collection authority.");if(this.adoptionMarker)return this.resumeAdoption(t);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);return await this.storeAdoptionSecret(i),await this.writeAdoptionMarker({version:1,phase:"waiting_for_approval",session:cp(i),manifest_digest:null,source_revision:null,source_head:null}),await t.onVerification(cp(i)),this.runAdoptionWithRecovery(i,t)}async resumeAdoption(e={}){var s,o,a;let t=(s=this.adoptionMarker)!=null?s:await this.readAdoptionMarker();if(!t)throw new b("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 b("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((o=e.onVerification)==null?void 0:o.call(e,cp(i))),this.runAdoptionWithRecovery(i,{...e,onVerification:(a=e.onVerification)!=null?a:(()=>{})})}async cancelAdoption(e){var i;let t=(i=this.adoptionMarker)!=null?i:await this.readAdoptionMarker();if(!t)return;if(["activating","adopted"].includes(t.phase))throw new b("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 b("authority_adoption_credentials_missing","The collection-adoption credential is missing from Obsidian's secret store.");await this.adoptionClient.cancel({...t.session,credential:n},{signal:e}),await this.clearAdoptionCheckpoint(t.session.adoptionId)}async enroll(e,t){let n=await this.assertCanBecomeMirror(e.collectionId),i=await this.enrollmentClient.enroll({...e,...n?{collectionId:n}:{}},t),s=await this.markMirror(i.collectionId);try{await this.persistEnrollment(i)}catch(o){if(s)try{await this.app.vault.adapter.remove(ao)}catch(a){throw new b("enrollment_recovery_required",`Enrollment settings could not be saved and the temporary role marker could not be removed: ${o instanceof Error?o.message:String(o)}`)}throw o}return this.requireProfile()}async preview(){let e=await this.createMirror();return A0(await e.inspect())}async status(){let e=this.settingsHost.getMirrorProfile();return e?(await this.assertMirror(e.collectionId),(await this.createMirror()).status()):null}async sync(e,t){if(this.syncAbort)throw new b("mirror_busy","Synchronization is already running for this vault.");let n=new AbortController;this.syncAbort=n;let i=await this.createMirror(s=>{this.progress=s,t==null||t({...s})});try{return await i.apply(e.plan,{signal:n.signal})}finally{this.progress=null,this.syncAbort=null}}async resolveConflict(e,t){let n=await this.createMirror();return await n.resolveConflict(e,t),n.status()}async runAdoption(e,t){let n=this.requireAdoptionMarker(e.adoptionId),i=null;if(n.phase==="adopted"){let s=await this.adoptionClient.exchange(e,t);if(s.status!=="completed")throw new b("authority_adoption_state_conflict","The local checkpoint says adoption completed, but Connect does not.");i=s}else if(n.phase==="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"&&await this.adoptionClient.uploadSnapshot(e,o,s,t),await this.updateAdoptionPhase("activating",s),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),o=await this.captureAuthoritySnapshot(e.requested.collectionId);await this.updateAdoptionPhase("uploading"),await this.adoptionClient.uploadSnapshot(e,s,o,t);let a=await this.captureAuthoritySnapshot(e.requested.collectionId);await this.writeAdoptionSnapshot(a),await this.updateAdoptionPhase("fenced",a);let c=await this.requirePreparedAdoption(e,t);await this.adoptionClient.uploadSnapshot(e,c,a,t),await this.updateAdoptionPhase("activating",a),i=await this.adoptionClient.complete(e,a,t)}return await this.updateAdoptionPhase("adopted"),this.finishRetainedMirror(e,i,t)}async runAdoptionWithRecovery(e,t){try{return await this.runAdoption(e,t)}catch(n){throw YC(n)?(await this.adoptionClient.cancel(e,{signal:t.signal}).catch(()=>{}),await this.clearAdoptionCheckpoint(e.adoptionId),new b(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 Ir("Hosted authority activation has already started. Resume using the saved fenced snapshot."):new b("authority_adoption_already_completed","Hosted authority has already adopted this collection.")}async finishRetainedMirror(e,t,n){var a,c;let i,s=this.adoptionClient.mirrorEnrollmentSession(e,t);if(!s)throw new b("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:l=>{var d;return(d=n.onStatus)==null?void 0:d.call(n,{...l,state:l.state})}})}catch(l){if((a=n.signal)!=null&&a.aborted)throw l;i=await this.enrollmentClient.enroll({controlUrl:e.controlUrl,collectionId:e.requested.collectionId,mirrorName:(c=e.requested.mirrorName)!=null?c:e.requested.sourceName,mode:"read_write"},{signal:n.signal,onVerification:n.onVerification})}let o=await this.markMirror(i.collectionId);try{await this.persistEnrollment(i)}catch(l){throw o&&await this.app.vault.adapter.remove(ao),l}return await this.clearAdoptionCheckpoint(e.adoptionId),this.requireProfile()}async captureAuthoritySnapshot(e){let t=await pi(this.app.vault);if(!t)throw new b("invalid_collection_configuration","A valid mdbase.yaml is required.");let n=await this.app.vault.adapter.read("mdbase.yaml"),i=(0,oe.parseYaml)(n),s=[{path:"mdbase.yaml",kind:"configuration",document:n}],o=`${(0,oe.normalizePath)(t.settings.types_folder)}/`,a=this.app.vault.getMarkdownFiles().filter(d=>(0,oe.normalizePath)(d.path).startsWith(o)).sort((d,u)=>d.path.localeCompare(u.path));for(let d of a)s.push({path:(0,oe.normalizePath)(d.path),kind:"type",document:await this.app.vault.cachedRead(d)});let c=XC(i);if(c.length){let d=c.map(f=>(0,k0.default)(f,{dot:!0})),u=QC(this.app.vault).filter(f=>f.extension==="base").filter(f=>d.some(p=>p((0,oe.normalizePath)(f.path)))).sort((f,p)=>f.path.localeCompare(p.path));for(let f of u)s.push({path:(0,oe.normalizePath)(f.path),kind:"view",document:await this.app.vault.cachedRead(f)})}let l=[];for(let d of this.app.vault.getMarkdownFiles().sort((u,f)=>u.path.localeCompare(f.path))){let u=(0,oe.normalizePath)(d.path);if(Ts(u,t))continue;let f=await this.app.vault.cachedRead(d);l.push({path:u,document:f})}return Hf({collectionId:e,sourceHead:0,specVersion:t.spec_version,resources:s,records:l})}async ensurePortableCollectionIdentity(){if(!await this.app.vault.adapter.exists("mdbase.yaml"))throw new b("collection_not_initialized","Initialize an mdbase collection before hosting it.");let e=await this.app.vault.adapter.read("mdbase.yaml"),t;try{t=(0,oe.parseYaml)(e)}catch(o){throw new b("invalid_collection_configuration","mdbase.yaml must contain valid YAML.")}if(!Fe(t))throw new b("invalid_collection_configuration","mdbase.yaml must contain a YAML mapping.");let n=Fe(t["x-mdbase-connect"])?t["x-mdbase-connect"].collection_id:void 0,i;if(n===void 0){i=crypto.randomUUID();let o=Fe(t["x-mdbase-connect"])?t["x-mdbase-connect"]:{};t["x-mdbase-connect"]={...o,collection_id:i},await this.app.vault.adapter.write("mdbase.yaml",(0,oe.stringifyYaml)(t))}else if(typeof n=="string"&&uo.test(n))i=n;else throw new b("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}}async createMirror(e){var o,a,c,l,d,u,f,p,y;let t=this.requireProfile();await this.assertMirror(t.collectionId);let n=await this.freshAccessToken(t),i=(c=(a=(o=this.options).transportFactory)==null?void 0:a.call(o,t,n))!=null?c:new dp(t.syncUrl,n),s={stateStore:(u=(d=(l=this.options).stateStoreFactory)==null?void 0:d.call(l,t))!=null?u:new fp(`${t.collectionId}:${t.replicaId}`),fileSystem:this.fileSystem,lease:(y=(p=(f=this.options).leaseFactory)==null?void 0:p.call(f,t))!=null?y:new pp(`${t.collectionId}:${t.replicaId}`),onProgress:e};return t.mode==="read_write"?new oo(t.replicaId,i,s):new Ln(t.replicaId,i,s)}requireProfile(){let e=this.settingsHost.getMirrorProfile();if(!e)throw new b("mirror_not_configured","This vault is not connected to a collection authority.");return e}accessSecretId(e){return`${zC}${e.toLowerCase()}`}refreshSecretId(e){return`${HC}${e.toLowerCase()}`}adoptionSecretId(e){return`${KC}${e.toLowerCase()}`}async storeAdoptionSecret(e){this.app.secretStorage.setSecret(this.adoptionSecretId(e.adoptionId),e.credential)}async persistEnrollment(e){this.app.secretStorage.setSecret(this.accessSecretId(e.collectionId),e.accessToken),this.app.secretStorage.setSecret(this.refreshSecretId(e.collectionId),e.refreshCredential),await this.settingsHost.saveMirrorProfile({version:1,syncUrl:e.syncUrl,controlUrl:e.controlUrl,collectionId:e.collectionId,replicaId:e.replicaId,mode:e.mode,name:e.name,enrollmentId:e.enrollmentId,accessTokenExpiresAt:e.accessTokenExpiresAt})}async freshAccessToken(e){let t=this.accessSecretId(e.collectionId),n=this.app.secretStorage.getSecret(t),i=Date.parse(e.accessTokenExpiresAt);if(n&&Number.isFinite(i)&&i-Date.now()>WC)return n;let s=this.app.secretStorage.getSecret(this.refreshSecretId(e.collectionId));if(!s)throw new b("mirror_credentials_missing","The mirror refresh credential is missing. Re-enroll this vault.");let o=await this.enrollmentClient.renew({controlUrl:e.controlUrl,syncUrl:e.syncUrl,collectionId:e.collectionId,replicaId:e.replicaId,mode:e.mode,name:e.name,enrollmentId:e.enrollmentId,accessToken:n!=null?n:"",refreshCredential:s,accessTokenExpiresAt:e.accessTokenExpiresAt});return await this.persistEnrollment(o),o.accessToken}async assertCanBecomeMirror(e){var o;let t=await this.readMarker(),n=await this.readPortableCollectionId();if(n&&!t)throw new b("local_authority_requires_transfer","This vault has a local Connect identity. Transfer authority explicitly before using it as a mirror.");if(n&&(t==null?void 0:t.collection_id)!==n)throw new b("mirror_identity_conflict","The vault identity and mirror role marker identify different collections.");let i=this.settingsHost.getMirrorProfile(),s=(o=i==null?void 0:i.collectionId)!=null?o:e;if(t&&s&&t.collection_id!==s)throw new b("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 b("existing_collection_requires_transfer","This vault already contains an mdbase collection. Connect an empty vault, or transfer collection authority explicitly.");return s!=null?s:t==null?void 0:t.collection_id}async readPortableCollectionId(){if(!await this.app.vault.adapter.exists("mdbase.yaml"))return null;let e;try{e=(0,oe.parseYaml)(await this.app.vault.adapter.read("mdbase.yaml"))}catch(i){throw new b("invalid_collection_configuration","mdbase.yaml must contain valid YAML.")}if(!Fe(e))throw new b("invalid_collection_configuration","mdbase.yaml must contain a YAML mapping.");let t=e["x-mdbase-connect"];if(t===void 0)return null;if(!Fe(t))throw new b("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"||!uo.test(n))throw new b("invalid_collection_configuration","x-mdbase-connect.collection_id must be a UUID string.");return n}async markMirror(e){let t=await this.readMarker();if(t){if(t.collection_id!==e)throw new b("mirror_identity_conflict","This vault already mirrors a different collection authority.");return!1}return await ji(this.app.vault,".mdbase"),await this.app.vault.adapter.write(ao,`${JSON.stringify({version:1,role:"mirror",collection_id:e},null,2)} +`)&&e.slice(1)===r}function Xf(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)=>Xf(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)&&Xf(s,n[i]))}var Ci=class{constructor(e,t,n,i){I(this,"fileSystem");I(this,"runtime");I(this,"mode");I(this,"blobStore");this.fileSystem=e,this.runtime=t,this.mode=n,this.blobStore=i}async recordPathPolicy(e){var t;return Qw(Object.keys((t=e.resources)!=null?t:{}),()=>this.fileSystem.read("mdbase.yaml"))}async put(e,t,n={}){var p,y,h,m;let{managedState:i=e,acceptedHash:s,materialized:o,inspectionPreflighted:a=!1}=n;a||dn(t.path,await this.recordPathPolicy(e)),o===void 0&&!a&&t0(t.path,t.record_id,Object.keys((p=e.resources)!=null?p:{}),Object.entries(e.records),Object.entries((y=e.files)!=null?y:{}));let c=(h=o==null?void 0:o.document)!=null?h:uc(t),l=await this.fileSystem.read(t.path),d=i==null?void 0:i.records[t.record_id];if(l!==null&&l!==c){let g=this.runtime.digest(l);if(!(d!==void 0&&d.path===t.path&&g===d.hash)&&(s===void 0||g!==s))throw new pt(t.record_id,t.path)}d&&d.path!==t.path&&await this.remove(i,t.record_id,d.path);let u=this.runtime.digest(c);typeof s=="string"&&s===u&&l!==null&&this.runtime.digest(l)===u||await this.fileSystem.write(t.path,c),e.records[t.record_id]={path:t.path,revision:t.revision,hash:(m=o==null?void 0:o.hash)!=null?m:u,...this.mode==="read_write"?{record:t}:{}}}async putFile(e,t,n=e,i){var y,h,m,g;if(ft(t),!this.blobStore)throw new b("file_storage_unavailable","Selected collection files require a content-addressed blob store adapter.");r0(t.path,t.file_id,e),(y=e.files)!=null||(e.files={});let s=(h=n.files)==null?void 0:h[t.file_id],o=await this.fileSystem.inspectBinary(t.path),a=bt(t.path),c=Object.values((m=n.files)!=null?m:{}).find(_=>bt(_.file.path)===a),l=[...Object.values((g=n.resources)!=null?g:{}),...Object.values(n.records)].find(_=>bt(_.path)===a),d=l?await this.fileSystem.read(t.path):null,u=(s==null?void 0:s.file.path)===t.path&&Tr(o,s.file),f=c!==void 0&&Tr(o,c.file),p=l!==void 0&&d!==null&&this.runtime.digest(d)===l.hash;if(o!==null&&!Tr(o,t)&&!u&&!f&&!p&&!(i!==void 0&&(o==null?void 0:o.size)===i.size&&o.content_digest===i.content_digest))throw new pt(t.file_id,t.path);if(s&&s.file.path!==t.path){let _=await this.fileSystem.inspectBinary(s.file.path);if(_!==null&&!Tr(_,s.file))throw new pt(t.file_id,s.file.path)}Tr(o,t)||await this.fileSystem.writeBinary(t.path,_c(this.blobStore.read(t.content_digest),t)),s&&s.file.path!==t.path&&await this.fileSystem.remove(s.file.path),e.files[t.file_id]={file:t}}async removeFile(e,t){var s;let n=(s=e.files)==null?void 0:s[t];if(!n)return;let i=await this.fileSystem.inspectBinary(n.file.path);if(i!==null&&!Tr(i,n.file))throw new pt(t,n.file.path);i!==null&&await this.fileSystem.remove(n.file.path),delete e.files[t]}async remove(e,t,n,i={}){var c;let s=e.records[t],o=(c=s==null?void 0:s.path)!=null?c:n;i.inspectionPreflighted||dn(o,await this.recordPathPolicy(e));let a=await this.fileSystem.read(o);if(a!==null&&s&&this.runtime.digest(a)!==s.hash)throw new pt(t,s.path);a!==null&&await this.fileSystem.remove(o),delete e.records[t]}async putResource(e,t,n){var o,a;let i=await this.fileSystem.read(t.path),s=(o=n==null?void 0:n.resources)==null?void 0:o[t.path];if(i!==null&&i!==t.document&&(!s||this.runtime.digest(i)!==s.hash))throw new pt(`resource:${t.path}`,t.path);await this.fileSystem.write(t.path,t.document),(a=e.resources)!=null||(e.resources={}),e.resources[t.path]={path:t.path,revision:t.revision,hash:this.runtime.digest(t.document)}}async removeResource(e,t,n){let i=await this.fileSystem.read(t);if(i!==null&&this.runtime.digest(i)!==n.hash)throw new pt(`resource:${t}`,t);i!==null&&await this.fileSystem.remove(t),e.resources&&delete e.resources[t]}};async function i0(r,e,t,n){var i,s;for(let o in r.records){if(!Object.hasOwn(r.records,o))continue;let a=r.records[o];dn(a.path,e);let c=await t.read(a.path);if(c===null||n(c)!==a.hash)throw new pt(o,a.path)}for(let[o,a]of Object.entries((i=r.resources)!=null?i:{})){let c=await t.read(a.path);if(c===null||n(c)!==a.hash)throw new pt(`resource:${o}`,a.path)}for(let[o,a]of Object.entries((s=r.files)!=null?s:{})){let c=await t.inspectBinary(a.file.path);if(!Tr(c,a.file))throw new pt(o,a.file.path)}}async function s0(r){var u,f,p,y,h;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 b("promotion_incomplete_file_projection","Moving the source of truth requires every collection file class with no excluded folders.");if(Object.keys((u=e.planned_conflicts)!=null?u:{}).length>0||e.batch!==void 0)throw new b("promotion_not_converged","Upload or resolve every local change before moving the source of truth.");await i0(e,i,n,s);let o=new Set(Object.keys((f=e.resources)!=null?f:{})),a=new Set(Object.values(e.records).map(m=>m.path)),c=(await n.listMarkdown(o)).filter(m=>!a.has(m));if(c.length>0)throw new b("promotion_unmanaged_files",`Synchronize unmanaged Markdown before promotion: ${c.join(", ")}.`);if(!n.listBinary)throw new b("promotion_file_scan_unavailable","Moving the source of truth requires binary file enumeration.");let l=new Set(Object.values((p=e.files)!=null?p:{}).map(m=>m.file.path)),d=(await n.listBinary(new Set([...o,...a]))).filter(m=>!l.has(m));if(d.length>0)throw new b("promotion_unmanaged_files",`Synchronize unmanaged files before moving the source of truth: ${d.join(", ")}.`);return{cursor:e.cursor,digest:pc([...Object.entries((y=e.resources)!=null?y:{}).map(([m,g])=>({kind:"resource",path:m,identity:"",document_hash:Lf(g.hash)})),...Object.entries(e.records).map(([m,g])=>({kind:"record",path:g.path,identity:m,document_hash:Lf(g.hash)})),...Object.values((h=e.files)!=null?h:{}).map(({file:m})=>({kind:"file",path:m.path,identity:m.file_id,document_hash:hc(m)}))])}}function Mr(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+t.file_conflicts.length,issues:e.issues,...i?{failure:i}:{}}}function o0(r,e){return["planned","applying","cancelled","stale","blocked","failed"].includes(r.state)?r:r.conflicts.length>0||r.file_conflicts.length>0||r.local_issues.length>0||e.summary.blocking_issues>0||e.summary.conflicts>0?{...r,state:"attention"}:{...r,state:e.actions.some(t=>t.command!=="advance_checkpoint")?"changes_waiting":"up_to_date"}}function fr(r,e){var a,c,l,d,u,f,p,y,h;if(!r)return{state:"not_initialized",mode:e,pending:0,pending_files:0,conflicts:[],file_conflicts:[],local_issues:[],cursor:null,last_synced_at:null};let t=[],n=[];for(let[m,g]of Object.entries((a=r.planned_conflicts)!=null?a:{})){if(g.entity==="file"){let x=g.local.state==="exact"?g.local.object.path:g.remote.state==="exact"?g.remote.object.path:"",v=n.findIndex(({file_id:P})=>P===m);v!==-1&&n.splice(v,1),n.push({file_id:m,path:x,code:"file_conflict",message:"Local and authority changes need a decision."});continue}let _=t.findIndex(({record_id:x})=>x===m);_!==-1&&t.splice(_,1);let w=g.local.state==="exact"?g.local.object.path:g.remote.state==="exact"?g.remote.object.path:null;t.push({record_id:m,path:w,kind:g.conflict_kind==="rejected"?"rejected":"conflicted",message:g.conflict_kind==="rejected"?"The authority rejected this local change.":"Local and authority changes need a decision."})}let i=[],s=r.batch?r.batch.plan.actions.slice(r.batch.next_action).filter(m=>m.command!=="advance_checkpoint").length:0,o=r.batch?r.batch.phase==="prepared"?"planned":r.batch.phase==="applying"||r.batch.phase==="effects_complete"?"applying":r.batch.phase==="cancelled"?"cancelled":((c=r.batch.failure)==null?void 0:c.code)==="sync_plan_stale"?"stale":"blocked":null;return{state:o!=null?o:t.length||n.length?"attention":"up_to_date",mode:e,pending:s,pending_files:r.batch?r.batch.plan.actions.slice(r.batch.next_action).filter(m=>m.command!=="advance_checkpoint"&&("target"in m&&m.target.entity==="file"||"source"in m&&m.source.entity==="file"||"entity"in m&&m.entity==="file")).length:0,conflicts:t,file_conflicts:n,local_issues:i,cursor:(d=(l=r.batch)==null?void 0:l.checkpoint_before.cursor)!=null?d:r.cursor,last_synced_at:(u=r.last_synced_at)!=null?u:null,generation:(f=r.generation)!=null?f:0,pending_checkpoint:(y=(p=r.batch)==null?void 0:p.checkpoint_after.cursor)!=null?y: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,...(h=r.batch)!=null&&h.failure?{failure:r.batch.failure}:{}}}async function gC(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 b("sync_protocol_incompatible",`Filesystem mirror requires exact-document v1 and its own ${t.replace("_","-")} replica.`);return n}async function Ac(r,e,t,n,i){var f;let s=await gC(r,e,t),o=(f=s.resources.documents)!=null?f:[],a=Sc(o),c=new Ec(a,o,i.digest),l=[];await n0(e,s,async p=>{for(let y of p){let h=c.validate(y);Tn(n,h.record.path)&&l.push(h)}});let d=[],u=new Set;return await Tw(e,s,async p=>{for(let y of p)if(bc(n,y)){if(u.has(y.file_id))throw new b("invalid_snapshot",`Hosted snapshot repeats file identity ${y.file_id}.`);u.add(y.file_id),d.push(y)}}),ro([...o.map(p=>p.path),...l.map(({record:p})=>p.path),...d.map(p=>p.path)]),{session:s,resources:o,records:l,files:d}}var kc="exact_document_plan_only_v1",xc="three_way_exact_document_v1",Pc="portable_mirror_projection_v1";function Ic(r){return JSON.stringify(Qf(r))}function no(r,e){return`sha256:${e(Ic(r))}`}function Qf(r){if(r===null||typeof r=="string"||typeof r=="boolean")return r;if(typeof r=="number"){if(!Number.isSafeInteger(r))throw new b("invalid_sync_plan","Sync plans contain only safe integer numeric values.");return r}if(Array.isArray(r))return r.map(Qf);if(typeof r=="object"){let e={};for(let t of Object.keys(r).sort()){let n=r[t];if(n===void 0)throw new b("invalid_sync_plan",`Sync plan field ${t} is undefined rather than an explicit state.`);e[t]=Qf(n)}return e}throw new b("invalid_sync_plan","Sync plans contain only canonical I-JSON values.")}function u0(r,e,t){let n=new Map(r.base.map(d=>[d.identity,d])),i=new Map(r.remote.map(d=>[d.identity,d])),s=new Map,o=new Map(r.local.map(d=>[d.object.path,d]));for(let d of r.local)!d.stable_identity||d.object.identity===""||(s.set(d.object.identity,d.object),o.delete(d.object.path));for(let[d,u]of n){let f=o.get(u.path);f&&(s.set(d,{...f.object,identity:d}),o.delete(u.path))}for(let[d,u]of i){if(s.has(d))continue;let f=o.get(u.path);f&&f.object.entity===u.entity&&(s.set(d,{...f.object,identity:d}),o.delete(u.path))}for(let[d,u]of n){if(s.has(d))continue;let f=[...o.values()].filter(y=>y.object.entity===u.entity&&y.object.payload_revision===u.payload_revision);if(f.length!==1)continue;let p=f[0];s.set(d,{...p.object,identity:d,revision:p.object.payload_revision===u.payload_revision?u.revision:p.object.revision}),o.delete(p.object.path)}for(let d of o.values()){let u=d.stable_identity?d.object.identity:xC(e,d.object,t);s.set(u,{...d.object,identity:u})}let a=new Set([...n.keys(),...s.keys(),...i.keys()]),c=new Map([...s.values()].map(d=>[d.path,d])),l=new Map([...i.values()].map(d=>[d.path,d]));return[...a].sort().map(d=>{var m,g,_,w,x;let u=n.get(d),f=s.get(d),p=i.get(d),y=(g=(m=p==null?void 0:p.path)!=null?m:f==null?void 0:f.path)!=null?g:u.path,h=(w=(_=f==null?void 0:f.path)!=null?_:p==null?void 0:p.path)!=null?w:u.path;return{entity:((x=f!=null?f:p)!=null?x:u).entity,identity:d,base:io(u),local:io(f),remote:io(p),local_target_owner:io(c.get(y)),remote_target_owner:io(l.get(h))}})}function f0(r,e){let t=[];for(let l of[...r.objects].sort(PC))EC(r,l,t);if(t=wC(t,r.objects,e),t=_C(t,r.objects),t.length>0||r.kind!=="incremental"||r.boundary.checkpoint.cursor!==r.boundary.authority_cursor){let l=t.map(d=>d.key);t.push({key:"checkpoint",depends_on_keys:l,command:"advance_checkpoint",reason:r.kind==="incremental"?"remote_change":r.kind,expected:r.boundary.checkpoint,next:{generation:r.boundary.checkpoint.generation+1,cursor:r.boundary.authority_cursor}})}let i=new Map;for(let l of t){let{key:d,depends_on_keys:u,...f}=l;i.set(d,no({action_scope:{replica_id:r.boundary.replica_id,scope_epoch:r.boundary.scope_epoch,generation:r.boundary.checkpoint.generation},key:d,...f},e))}let s=t.map(l=>{let{key:d,depends_on_keys:u,...f}=l,p={...f,action_id:i.get(d),depends_on:u.map(y=>i.get(y))};if((p.command==="put_remote"||p.command==="move_remote"||p.command==="delete_remote")&&(p.idempotency_key=p.action_id),p.command==="move_remote"){let y=u.find(h=>h===`${p.source.identity}:put-remote`);y&&(p.revision_from_dependency=i.get(y))}return p}),o=[...r.issues].sort(IC),a={uploads:s.filter(OC).length,downloads:s.filter(RC).length,conflicts:s.filter(l=>l.command==="record_conflict").length,blocking_issues:o.filter(l=>l.blocking).length},c={plan_version:1,engine_profile:kc,protocol_profile:"exact_document_v1",planner_policy:xc,projection_policy:Pc,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:s,issues:o,summary:a};return{...c,fingerprint:no(c,e)}}function _C(r,e){var c;if(!r.some(l=>l.command==="move_remote"))return r;let t=[...r],n=new Set;for(let l of bC(t))for(let d of l){let u=t.find(f=>f.key===d);(u==null?void 0:u.command)==="move_remote"&&n.add(u.source.identity)}let i=tp(t),s=new Map(t.map(l=>[l.key,l])),o=!0;for(;o;){o=!1;for(let l of t){if(l.command!=="move_remote")continue;let d=l.expected_target_owner;if(d.state!=="exact"||d.object.identity===l.source.identity)continue;let u=s.get((c=i.get(pr(d.object)))!=null?c:""),f=u&&a0(u);(!u||f&&n.has(f))&&!n.has(l.source.identity)&&(n.add(l.source.identity),o=!0)}}if(n.size>0){t=t.filter(d=>{let u=a0(d);return!u||!n.has(u)||d.command!=="put_remote"&&d.command!=="move_remote"});let l=new Map(e.map(d=>[d.identity,d]));for(let d of[...n].sort()){let u=l.get(d);!u||u.entity==="resource"||t.push({key:`${d}:conflict`,depends_on_keys:[],command:"record_conflict",reason:"local_change",identity:d,entity:u.entity,local:u.local,remote:u.remote,conflict_kind:"path_occupied"})}}let a=tp(t);for(let l of t){if(l.command!=="move_remote")continue;let d=l.expected_target_owner;if(d.state!=="exact"||d.object.identity===l.source.identity)continue;let u=a.get(pr(d.object));!u||u===l.key||(l.depends_on_keys.includes(u)||l.depends_on_keys.push(u),l.expected_target_owner={state:"absent"})}return p0(t)}function bC(r){var s;let e=r.filter(o=>o.command==="move_remote"),t=new Map(e.map(o=>[o.key,o])),n=tp(r),i=new Map;for(let o of e){let a=[],c=new Map,l=o;for(;l;){let d=c.get(l.key);if(d!==void 0){let f=a.slice(d);i.set([...f].sort().join("\0"),f);break}c.set(l.key,a.length),a.push(l.key);let u=l.expected_target_owner;l=u.state==="exact"?t.get((s=n.get(pr(u.object)))!=null?s:""):void 0}}return[...i.values()]}function tp(r){let e=new Map;for(let t of r)t.command==="move_remote"?e.set(pr(t.source),t.key):t.command==="delete_remote"&&e.set(pr(t.target),t.key);return e}function a0(r){if(r.command==="move_remote")return r.source.identity;if(r.command==="put_remote"||r.command==="delete_remote")return r.target.identity}function wC(r,e,t){var u;if(!r.some(f=>f.command==="move_local"||f.command==="write_local"))return r;let n=[...r],i=new Set;for(let f of e)f.base.state==="exact"&&i.add(f.base.object.path),f.local.state==="exact"&&i.add(f.local.object.path),f.remote.state==="exact"&&i.add(f.remote.object.path);for(;;){let f=vC(n);if(!f)break;let p=[...f].sort()[0],y=n.findIndex(w=>w.key===p),h=n[y];if(!h||h.command!=="move_local")throw new Error("Planner invariant: local path cycle contains a non-move action.");let m=SC(h.source,h.target_path,i,t);i.add(m);let g={...h.source,path:m},_={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=g,h.expected_source_owner={state:"exact",object:g},h.depends_on_keys=[_.key],n.splice(y,0,_)}let s=rp(n),o=new Map(e.map(f=>[f.identity,f])),a=new Set,c=new Map(n.map(f=>[f.key,f])),l=!0;for(;l;){l=!1;for(let f of n){let p=c0(f),y=Oc(f);if((p==null?void 0:p.state)!=="exact"||p.object.identity===y)continue;let h=c.get((u=s.get(pr(p.object)))!=null?u:""),m=h&&Oc(h);(!h||m&&a.has(m))&&!a.has(y)&&(a.add(y),l=!0)}}if(a.size>0){n=n.filter(f=>!a.has(Oc(f))||f.command!=="move_local"&&f.command!=="write_local");for(let f of[...a].sort()){let p=o.get(f);!p||p.entity==="resource"||n.push({key:`${f}:conflict`,depends_on_keys:[],command:"record_conflict",reason:"remote_change",identity:f,entity:p.entity,local:p.local,remote:p.remote,conflict_kind:"path_occupied"})}}let d=rp(n);for(let f of n){let p=c0(f),y=Oc(f);if((p==null?void 0:p.state)!=="exact"||p.object.identity===y)continue;let h=d.get(pr(p.object));!h||h===f.key||(f.depends_on_keys.includes(h)||f.depends_on_keys.push(h),$C(f,{state:"absent"}))}return p0(n)}function vC(r){var i;let e=r.filter(s=>s.command==="move_local"),t=new Map(e.map(s=>[s.key,s])),n=rp(r);for(let s of e){let o=[],a=new Map,c=s;for(;c;){let l=a.get(c.key);if(l!==void 0)return o.slice(l);a.set(c.key,o.length),o.push(c.key);let d=c.expected_target_owner;c=d.state==="exact"?t.get((i=n.get(pr(d.object)))!=null?i:""):void 0}}}function rp(r){let e=new Map;for(let t of r)t.command==="move_local"?e.set(pr(t.source),t.key):t.command==="delete_local"&&e.set(pr(t.target),t.key);return e}function c0(r){if(r.command==="move_local")return r.expected_target_owner;if(r.command==="write_local")return r.expected_path_owner}function $C(r,e){r.command==="move_local"?r.expected_target_owner=e:r.command==="write_local"&&(r.expected_path_owner=e)}function Oc(r){return r.command==="move_local"?r.source.identity:r.command==="write_local"||r.command==="delete_local"?r.target.identity:""}function pr(r){return`${r.entity}\0${r.identity}\0${r.path}`}function SC(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 d=n(`${r.entity}\0${r.identity}\0${r.path}\0${e}\0${l}`),u=`${s}.mdbase-sync-stage-${d.slice(0,16)}${c}`;if(!t.has(u))return u}}function p0(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 EC(r,e,t){if(e.frozen_conflict){t.push({key:`${e.identity}:conflict`,depends_on_keys:[],command:"record_conflict",reason:"pending",identity:e.identity,entity:e.entity,...e.frozen_conflict});return}let n=!ep(e.local,e.base),i=!ep(e.remote,e.base);if(!(!n&&!i)){if(e.entity==="resource"){if(n)return;Zf(e,t);return}if(r.mode==="read_only"){n||Zf(e,t);return}if(n&&i){if(ep(e.local,e.remote))return;t.push(kC(e));return}n?AC(e,t):Zf(e,t)}}function Zf(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(l0(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(l0(r,t,i?[i]:[]))}function l0(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:Nr(r.local).revision,payload_revision:Nr(r.local).payload_revision,...Nr(r.local).size===void 0?{}:{size:Nr(r.local).size}}}:r.local,expected_path_owner:t.length>0?{state:"exact",object:{...e,revision:Nr(r.local).revision,payload_revision:Nr(r.local).payload_revision,...Nr(r.local).size===void 0?{}:{size:Nr(r.local).size}}}:r.local_target_owner}}function AC(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(d0(r,t,[]));return}let n=r.remote.object,i;if(t.revision!==n.revision){let s=d0(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 d0(r,e,t){return{key:`${r.identity}:put-remote`,depends_on_keys:t,command:"put_remote",reason:"local_change",target:e,payload_revision:Nr(r.local).payload_revision,expected_remote:r.remote,expected_local:r.local,idempotency_key:""}}function kC(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 Nr(r){if(r.state!=="exact")throw new Error("Planner invariant: expected exact object state.");return r.object}function io(r){return r?{state:"exact",object:r}:{state:"absent"}}function xC(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 ep(r,e){return Ic(r)===Ic(e)}function PC(r,e){return`${r.entity}\0${r.identity}`.localeCompare(`${e.entity}\0${e.identity}`)}function IC(r,e){var t,n;return`${(t=r.path)!=null?t:""}\0${r.code}\0${r.message}`.localeCompare(`${(n=e.path)!=null?n:""}\0${e.code}\0${e.message}`)}function OC(r){return r.command==="put_remote"||r.command==="move_remote"||r.command==="delete_remote"}function RC(r){return r.command==="write_local"||r.command==="move_local"||r.command==="delete_local"}var Rc=class{constructor(e,t,n,i,s,o,a,c,l){I(this,"replicaId");I(this,"transport");I(this,"mode");I(this,"fileSystem");I(this,"blobStore");I(this,"selectiveSync");I(this,"runtime");I(this,"readState");I(this,"currentRecordPathPolicy");this.replicaId=e,this.transport=t,this.mode=n,this.fileSystem=i,this.blobStore=s,this.selectiveSync=o,this.runtime=a,this.readState=c,this.currentRecordPathPolicy=l}async inspect(e){let t=e===void 0?await this.readState():e;if(!t)return this.inspectSnapshot("initial",null);if(t.batch)throw new b("mirror_recovery_required","The prepared sync batch must recover before a new inspection can be planned.");return JSON.stringify(t.selective_sync)!==JSON.stringify(this.selectiveSync)?this.inspectSnapshot("rebuild",t):this.inspectIncremental(t)}async inspectSnapshot(e,t){let n=await Ac(this.replicaId,this.transport,this.mode,this.selectiveSync,this.runtime),i=Sc(n.resources),s=await this.inspectLocal(t,n.resources,i),o=new Map(n.records.map(({record:c})=>[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){var l,d;let t=new Map;for(let[u,f]of Object.entries(e.records))f.record&&t.set(u,f.record);let n=new Map(Object.entries((l=e.files)!=null?l:{}).map(([u,f])=>[u,f.file])),i=new Map(h0(e).map(u=>[MC(u),u])),s=e.cursor,o=e.cursor;for(;;){let u=s,f=await this.transport.changes(u,200);if(f.scope_epoch!==e.scope_epoch||f.cursorf.head||f.has_more&&f.cursor===u)throw new b("invalid_change_page","Authority returned an invalid change boundary.");if(f.reset_required)return this.inspectSnapshot("rebuild",e);for(let p of f.events){if(p.sequence<=o||p.sequence>f.cursor)throw new b("invalid_change_page","Authority change events are not strictly ordered.");o=p.sequence,this.applyRemoteObservation(i,t,n,p)}if(s=f.cursor,!f.has_more)break}let a=Object.values((d=e.resources)!=null?d:{}).map(u=>({path:u.path,kind:LC(u.path),revision:u.revision,document:""})),c=await this.inspectLocal(e,a,await this.currentRecordPathPolicy(e));return 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"){mw(i);let s=i.record.record_id;Tn(this.selectiveSync,i.record.path)?(e.set(`record:${s}`,m0(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"){ft(i.file);let s=i.file.file_id;bc(this.selectiveSync,i.file)?(e.set(`file:${s}`,ip(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){var y,h,m,g,_,w,x,v,P,O,A,R,$,M,V;let i=[],s=new Map,o=new Map,a=[],c=new Map(Object.entries((y=e==null?void 0:e.records)!=null?y:{}).map(([T,S])=>[S.path,[T,S]])),l=new Map(Object.entries((h=e==null?void 0:e.planned_conflicts)!=null?h:{}).filter(([,T])=>T.entity==="record"&&T.local.state==="exact").map(([T,S])=>[S.local.state==="exact"?S.local.object.path:"",T])),d=new Map(Object.entries((m=e==null?void 0:e.local_bindings)!=null?m:{}).filter(([,T])=>T.entity==="record").map(([T,S])=>[S.path,T])),u=new Set([...Object.keys((g=e==null?void 0:e.resources)!=null?g:{}),...t.map(T=>T.path)]);for(let T of u){let S=await this.fileSystem.read(T),k=(_=e==null?void 0:e.resources)==null?void 0:_[T];if(S===null)continue;let de=`sha256:${this.runtime.digest(S)}`;i.push({stable_identity:!0,object:Mi("resource",T,T,de)}),s.set(T,S);let Z=t.find(B=>B.path===T);!k&&Z&&Z.revision!==de?a.push({code:"local_collision",message:`${T} differs locally from the exact authority document.`,path:T,blocking:!0}):k&&k.revision!==de&&a.push({code:"mirror_diverged",message:`Authority-owned resource ${T} changed locally.`,path:T,blocking:!0})}let f=new Set(Object.values((w=e==null?void 0:e.records)!=null?w:{}).map(T=>T.path)),p=Zw(await this.fileSystem.listMarkdown(u),n).filter(T=>Tn(this.selectiveSync,T)||f.has(T));for(let T of p){let S=await this.fileSystem.read(T);if(S===null)continue;let k=`sha256:${this.runtime.digest(S)}`,de=l.get(T),Z=d.get(T),B=(x=c.get(T))==null?void 0:x[0],fe=(P=(v=de!=null?de:Z)!=null?v:B)!=null?P:"";i.push({stable_identity:fe!=="",object:Mi("record",fe,T,k)}),s.set(T,S)}if(this.selectiveSync.file_classes.length>0){if(!this.fileSystem.listBinary)throw new b("file_storage_unavailable","Selected files require binary enumeration.");let T=new Set(Object.values((O=e==null?void 0:e.files)!=null?O:{}).map(B=>B.file.path)),S=new Map(Object.entries((A=e==null?void 0:e.files)!=null?A:{}).map(([B,fe])=>[fe.file.path,[B,fe]])),k=new Map(Object.entries((R=e==null?void 0:e.planned_conflicts)!=null?R:{}).filter(([,B])=>B.entity==="file"&&B.local.state==="exact").map(([B,fe])=>[fe.local.state==="exact"?fe.local.object.path:"",B])),de=new Map(Object.entries(($=e==null?void 0:e.local_bindings)!=null?$:{}).filter(([,B])=>B.entity==="file").map(([B,fe])=>[fe.path,B])),Z=(await this.fileSystem.listBinary(u)).filter(B=>Ow(this.selectiveSync,B)||T.has(B));for(let B of Z){let fe=await this.fileSystem.inspectBinary(B);if(!fe)continue;let Ve=k.get(B),Jt=de.get(B),Dr=S.get(B),un=(V=(M=Ve!=null?Ve:Jt)!=null?M:Dr==null?void 0:Dr[0])!=null?V:"";i.push({stable_identity:un!=="",object:{entity:"file",identity:un,path:B,revision:Dr&&Dr[1].file.content_digest===fe.content_digest?Dr[1].file.revision:fe.content_digest,payload_revision:fe.content_digest,size:fe.size}}),o.set(B,fe)}}try{ro([...u,...p,...o.keys()])}catch(T){let S=T instanceof Error?T:new Error(String(T));a.push({code:g0(T),message:S.message,blocking:!0})}return{observations:i,documents:s,binary:o,issues:a}}async finish(e){var u,f,p,y,h;let{prior:t,local:n}=e,i=(u=e.remoteRefs)!=null?u:[...e.remoteResources.map(CC),...[...e.remoteRecords.values()].map(m0),...[...e.remoteFiles.values()].map(ip)],s=u0({base:t?h0(t):[],local:n.observations,remote:i},`${this.replicaId}\0${e.scopeEpoch}\0${(f=t==null?void 0:t.generation)!=null?f:0}`,this.runtime.digest);for(let m of s){let g=(p=t==null?void 0:t.planned_conflicts)==null?void 0:p[m.identity];!g||g.entity!==m.entity||(m.frozen_conflict={local:g.local,remote:g.remote,conflict_kind:g.conflict_kind})}let o=[...n.issues];for(let m of s)(e.kind==="initial"||e.kind==="rebuild")&&m.base.state==="absent"&&m.local.state==="exact"&&m.remote.state==="exact"&&!y0(m.local,m.remote)&&o.push({code:"local_collision",message:`${m.remote.object.path} differs locally from the exact authority object.`,path:m.remote.object.path,blocking:!0}),m.remote.state==="exact"&&m.local_target_owner.state==="exact"&&m.remote.object.identity!==m.local_target_owner.object.identity&&o.push({code:"local_collision",message:`${m.remote.object.path} is owned by different local bytes.`,path:m.remote.object.path,blocking:!0});try{ro([...i.map(m=>m.path),...n.observations.map(({object:m})=>m.path)])}catch(m){let g=m instanceof Error?m:new Error(String(m));o.push({code:g0(m),message:g.message,blocking:!0})}if(this.mode==="read_only"){for(let m of s)if(m.entity!=="resource"&&!y0(m.local,m.base)){let g=NC(m.local,m.base);if(o.some(_=>_.blocking&&_.path===g))continue;o.push({code:"mirror_diverged",message:`${g} changed in a receive-only mirror.`,path:g,blocking:!0})}}let a=no(Rn(this.selectiveSync),this.runtime.digest),c={boundary:{engine_profile:kc,protocol_profile:"exact_document_v1",planner_policy:xc,projection_policy:Pc,replica_id:this.replicaId,scope_epoch:e.scopeEpoch,authority_cursor:e.authorityCursor,checkpoint:{generation:(y=t==null?void 0:t.generation)!=null?y:0,cursor:(h=t==null?void 0:t.cursor)!=null?h:null},selective_sync_fingerprint:a},mode:this.mode,kind:e.kind,selective_sync:Rn(this.selectiveSync),objects:s,issues:TC(o)},l=f0(c,this.runtime.digest),d=await this.bindPayloads(l,n,e.remoteRecords,e.remoteResources,e.remoteFiles);return{summary:c,plan:l,durable_payloads:d,prior:t,snapshot:e.snapshot,remote_records:e.remoteRecords,remote_files:e.remoteFiles}}async bindPayloads(e,t,n,i,s){let o={documents:{},records:{},resources:{},files:{},local_files:{},mutations:{}},a=new Map(i.map(c=>[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 d=t.binary.get(l);if(!d)throw Nn(c.action_id);await this.stageLocalBinary(l,d),o.local_files[c.action_id]={path:l,...d}}else{let d=t.documents.get(l);if(d===void 0||`sha256:${this.runtime.digest(d)}`!==c.payload_revision)throw Nn(c.action_id);o.documents[c.action_id]=d}c.target.entity==="record"&&(o.mutations[c.action_id]={operation:"put",mutation_id:np(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 Nn(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 Nn(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 Nn(c.action_id);await wc(this.transport,this.blobStore,l),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 Nn(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 Nn(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:np(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:np(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 b("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 b("sync_plan_stale",`${e} disappeared during inspection.`);await this.blobStore.write(t.content_digest,Cw(n,t,e))}};function TC(r){var t;let e=new Map;for(let n of r)e.set(`${n.code}\0${(t=n.path)!=null?t:""}\0${n.message}\0${n.blocking}`,n);return[...e.values()]}function h0(r){var e,t;return[...Object.entries((e=r.resources)!=null?e:{}).map(([n,i])=>Mi("resource",n,i.path,i.revision)),...Object.entries(r.records).map(([n,i])=>Mi("record",n,i.path,i.revision)),...Object.entries((t=r.files)!=null?t:{}).map(([n,i])=>ip({...i.file,file_id:n}))]}function m0(r){return Mi("record",r.record_id,r.path,r.revision)}function CC(r){return Mi("resource",r.path,r.path,r.revision)}function Mi(r,e,t,n){return{entity:r,identity:e,path:t,revision:n,payload_revision:n}}function ip(r){return{entity:"file",identity:r.file_id,path:r.path,revision:r.revision,payload_revision:r.content_digest,size:r.size}}function MC(r){return`${r.entity}:${r.identity}`}function y0(r,e){return JSON.stringify(r)===JSON.stringify(e)}function NC(r,e){return r.state==="exact"?r.object.path:e.state==="exact"?e.object.path:"mirror"}function Nn(r){return new b("sync_payload_incomplete",`Inspected action ${r} has no revision-bound payload.`)}function g0(r){return r&&typeof r=="object"&&"code"in r&&typeof r.code=="string"?r.code:"sync_inspection_failed"}function LC(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 np(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 _0(r,e,t,n){if(r!=null&&r.batch){if(r.batch.plan.fingerprint!==e.fingerprint)throw new b("mirror_recovery_required","A different prepared sync batch must recover before this plan can apply.");return r}let i=r?structuredClone(r):DC(e.replica_id,e.scope_epoch,e.mode,e.selective_sync);return i.scope_epoch=e.scope_epoch,i.selective_sync=e.selective_sync,i.batch={phase:"prepared",plan:e,next_action:0,receipts:[],payloads:t,checkpoint_before:{generation:e.checkpoint_generation,cursor:e.base_cursor},checkpoint_after:{generation:e.checkpoint_generation+1,cursor:e.authority_cursor}},await n.write(i),i}async function b0(r,e){let t=rt(r);t.phase!=="effects_complete"&&(t.phase="applying",delete t.failure,await Cc(r,{type:"phase",plan_fingerprint:t.plan.fingerprint,phase:"applying"},e))}async function w0(r,e,t){let n=rt(r),i=n.plan.actions[n.next_action];if(!i||i.action_id!==e.action_id)throw new b("invalid_mirror_state","The durable sync receipt does not match the next prepared action.");let s={type:"receipt",plan_fingerprint:n.plan.fingerprint,receipt:structuredClone(e),delta:jC(r,i)};n.receipts.push(structuredClone(e)),n.next_action+=1,await Cc(r,s,t)}async function v0(r,e){let t=rt(r),n=t.plan.actions[t.next_action];if(!n||n.command!=="advance_checkpoint")throw new b("invalid_mirror_state","Sync effects cannot complete before the checkpoint action is next.");t.phase="effects_complete",await Cc(r,{type:"effects_complete",plan_fingerprint:t.plan.fingerprint},e)}async function Tc(r,e,t,n){let i=rt(r);i.phase=e,i.failure=t,await Cc(r,{type:"phase",plan_fingerprint:i.plan.fingerprint,phase:e,failure:t},n)}async function Cc(r,e,t){t.appendJournal?await t.appendJournal(e):await t.write(r)}function jC(r,e){var s,o,a,c;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]:so((s=r.planned_conflicts)==null?void 0:s[t])},local_bindings:{[t]:so((o=r.local_bindings)==null?void 0:o[t])}};return n==="record"?i.records={[t]:so(r.records[t])}:n==="resource"?i.resources={[t]:so((a=r.resources)==null?void 0:a[t])}:i.files={[t]:so((c=r.files)==null?void 0:c[t])},i}function so(r){return r===void 0?null:structuredClone(r)}function rt(r){if(!r.batch)throw new b("invalid_mirror_state","The mirror has no prepared sync batch.");return r.batch}async function $0(r,e){var n;let t=rt(r);if(t.phase!=="blocked"||((n=t.failure)==null?void 0:n.code)!=="sync_plan_stale")throw new b("mirror_recovery_required","Only a stale batch at a durable action boundary can be abandoned.");delete r.batch,await e.write(r)}function DC(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 Nc=class{constructor(e){I(this,"ports");I(this,"materializer");I(this,"ownersByPath",new Map);I(this,"pathsByOwner",new Map);this.ports=e,this.materializer=new Ci(e.fileSystem,e.runtime,e.mode,e.blobStore)}async execute(e,t){var s,o;let n=rt(e);this.indexPathOwners(e);let i=new Set(n.receipts.map(a=>a.action_id));for(await b0(e,this.ports.store);n.next_action!i.has(l));if(c){let l={code:"invalid_mirror_state",message:`Action ${a.action_id} is missing dependency ${c}.`,action_id:a.action_id};return await Tc(e,"blocked",l,this.ports.store),{status:"blocked",completed:n.next_action,failure:l}}try{let l=await this.dispatch(e,a);await w0(e,l,this.ports.store),i.add(l.action_id),(o=(s=this.ports).onProgress)==null||o.call(s,n.next_action,n.plan.actions.length-1)}catch(l){let d=VC(l,a.action_id);return await Tc(e,"blocked",d,this.ports.store),{status:d.code==="sync_plan_stale"?"stale":"blocked",completed:n.next_action,failure:d}}}throw new b("invalid_mirror_state","Prepared plan has no checkpoint action.")}async dispatch(e,t){var n,i;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":return(n=e.planned_conflicts)!=null||(e.planned_conflicts={}),e.planned_conflicts[t.identity]={entity:t.entity,local:t.local,remote:t.remote,conflict_kind:t.conflict_kind},(i=e.local_bindings)!=null||(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"advance_checkpoint":throw new b("invalid_mirror_state","The executor cannot dispatch checkpoint actions.")}}rebaseConflict(e,t){var s;let n=rt(e).payloads;if(t.entity==="record"){if(t.remote.state==="absent"){delete e.records[t.identity];return}let o=n.records[t.action_id];if(!o||o.revision!==t.remote.object.revision)throw hr(t);Mc(o,this.ports.runtime,o.revision),e.records[t.identity]={path:o.path,revision:o.revision,hash:t.local.state==="exact"?t.local.object.payload_revision.replace(/^sha256:/u,""):this.ports.runtime.digest(o.document),...this.ports.mode==="read_write"?{record:o}:{}};return}if((s=e.files)!=null||(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 hr(t);ft(i),e.files[t.identity]={file:i}}async writeLocal(e,t){let n=await this.ports.fileSystem.exists(t.target.path);(!n||!await this.matchesRef(t.target))&&(await this.assertLocal(t.expected_local),await this.assertPathOwner(t.target.path,t.expected_path_owner,n));let i=rt(e).payloads;if(t.target.entity==="record"){let o=i.records[t.action_id];if(!o||o.revision!==t.payload_revision)throw hr(t);return Mc(o,this.ports.runtime,t.payload_revision),await this.materializer.put(e,o,{inspectionPreflighted:!0}),this.installPathOwner(t.target),{action_id:t.action_id,status:"completed"}}if(t.target.entity==="resource"){let o=i.resources[t.action_id];if(!o||o.revision!==t.payload_revision||`sha256:${this.ports.runtime.digest(o.document)}`!==o.revision)throw hr(t);return await this.materializer.putResource(e,o,e),this.installPathOwner(t.target),{action_id:t.action_id,status:"completed"}}let s=i.files[t.action_id];if(!s||s.content_digest!==t.payload_revision)throw hr(t);return await this.materializer.putFile(e,s,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)),qC(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){var i;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 s=(i=e.resources)==null?void 0:i[t.target.identity];s?await this.materializer.removeResource(e,t.target.path,s):await this.ports.fileSystem.remove(t.target.path)}else await this.materializer.removeFile(e,t.target.identity);else FC(e,t.target);return this.removePathOwner(t.target),{action_id:t.action_id,status:"completed"}}async putRemote(e,t){var a,c;let n=rt(e).payloads;if(t.target.entity==="record"){let l=n.mutations[t.action_id],d=n.documents[t.action_id];if(!l||l.operation!=="put"||d===void 0)throw hr(t);if(`sha256:${this.ports.runtime.digest(d)}`!==t.payload_revision)throw new b("sync_plan_stale","Prepared local document payload no longer matches its revision.");let u=await this.ports.transport.mutate(l);return this.acceptRecordReceipt(e,t,u,d),sp(t.action_id,u)}if(t.target.entity==="resource")throw new b("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 hr(t);let s={protocol_version:1,type:"open_file_upload",transfer_id:ap(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(ft(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 op(t);return(a=e.files)!=null||(e.files={}),e.files[o.file.file_id]={file:o.file},(c=e.local_bindings)==null||delete c[t.target.identity],{action_id:t.action_id,status:"completed",file:o.file}}async moveRemote(e,t){var s,o,a;if(t.source.entity==="record"){let c=rt(e).payloads.mutations[t.action_id];if(!c||c.operation!=="move")throw hr(t);let l=await this.ports.transport.mutate(c);return this.acceptRecordReceipt(e,t,l),sp(t.action_id,l)}if(t.source.entity==="resource"||!this.ports.transport.moveFile)throw new b("invalid_sync_plan","This remote move command is unsupported.");let n={protocol_version:1,type:"move_file",mutation_id:ap(t.action_id),file_id:t.source.identity,if_revision:(s=this.dependencyFileRevision(e,t))!=null?s: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(ft(i.file),i.mutation_id!==n.mutation_id||i.file.file_id!==t.source.identity||i.file.path!==t.target_path)throw op(t);return(o=e.files)!=null||(e.files={}),e.files[t.source.identity]={file:i.file},(a=e.local_bindings)==null||delete a[t.source.identity],{action_id:t.action_id,status:"completed",file:i.file}}dependencyFileRevision(e,t){if(!t.revision_from_dependency)return;let n=rt(e).receipts.find(({action_id:i})=>i===t.revision_from_dependency);if(!(n!=null&&n.file)||n.file.file_id!==t.source.identity)throw new b("invalid_mirror_state",`Move ${t.action_id} is missing its dependency file receipt.`);return n.file.revision}async deleteRemote(e,t){var s,o;if(t.target.entity==="record"){let a=rt(e).payloads.mutations[t.action_id];if(!a||a.operation!=="delete")throw hr(t);let c=await this.ports.transport.mutate(a);return this.acceptRecordReceipt(e,t,c),sp(t.action_id,c)}if(t.target.entity==="resource"||!this.ports.transport.deleteFile)throw new b("invalid_sync_plan","This remote delete command is unsupported.");let n={protocol_version:1,type:"delete_file",mutation_id:ap(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 op(t);return(s=e.files)==null||delete s[t.target.identity],(o=e.local_bindings)==null||delete o[t.target.identity],{action_id:t.action_id,status:"completed"}}acceptRecordReceipt(e,t,n,i){var l,d,u,f;let o=("target"in t?t.target:t.source).identity;if(n.status==="applied"||n.status==="previously_applied"){if(n.record){Mc(n.record,this.ports.runtime,n.record.revision);let p=e.records[o];e.records[o]={path:n.record.path,revision:n.record.revision,hash:i===void 0?(l=p==null?void 0:p.hash)!=null?l: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];(d=e.local_bindings)==null||delete d[o];return}let a=n.status==="conflicted"?n.conflict.current:void 0;a&&Mc(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;(u=e.planned_conflicts)!=null||(e.planned_conflicts={}),e.planned_conflicts[o]={entity:"record",local:t.expected_local,remote:c,conflict_kind:n.status==="rejected"?"rejected":"both_changed"},(f=e.local_bindings)!=null||(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 new b("sync_plan_stale",`${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!=null?n:await this.pathExists(e)))throw new b("sync_plan_stale",`${e} is no longer vacant.`);return}if(!i||i.entity!==t.object.entity||i.identity!==t.object.identity)throw new b("sync_plan_stale",`${e} has a different path owner.`)}async matchesRef(e){if(e.entity==="file"){let n=await this.ports.fileSystem.inspectBinary(e.path);return n!==null&&n.content_digest===e.payload_revision&&(e.size===void 0||n.size===e.size)}let t=await this.ports.fileSystem.read(e.path);return t!==null&&`sha256:${this.ports.runtime.digest(t)}`===e.payload_revision}async pathExists(e){return this.ports.fileSystem.exists(e)}indexPathOwners(e){var t,n;this.ownersByPath.clear(),this.pathsByOwner.clear();for(let[i,s]of Object.entries(e.records))this.installPathOwner({entity:"record",identity:i,path:s.path,revision:s.revision,payload_revision:`sha256:${s.hash}`});for(let[i,s]of Object.entries((t=e.resources)!=null?t:{}))this.installPathOwner({entity:"resource",identity:i,path:s.path,revision:s.revision,payload_revision:`sha256:${s.hash}`});for(let[i,s]of Object.entries((n=e.files)!=null?n:{}))this.installPathOwner({entity:"file",identity:i,path:s.file.path,revision:s.file.revision,payload_revision:s.file.content_digest,size:s.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){var i;let t=`${e.entity}:${e.identity}`,n=(i=this.pathsByOwner.get(t))!=null?i:e.path;this.ownersByPath.delete(n),this.pathsByOwner.delete(t)}};function qC(r,e,t){var n,i;if(e.entity==="record"){let s=r.records[e.identity];s&&(s.path=t)}else if(e.entity==="resource"){let s=(n=r.resources)==null?void 0:n[e.identity];s&&(s.path=t)}else{let s=(i=r.files)==null?void 0:i[e.identity];s&&(s.file.path=t)}}function FC(r,e){var t,n;e.entity==="record"?delete r.records[e.identity]:e.entity==="resource"?(t=r.resources)==null||delete t[e.identity]:(n=r.files)==null||delete n[e.identity]}function Mc(r,e,t){let n=uc(r);if(r.revision!==t||`sha256:${e.digest(n)}`!==t)throw new b("invalid_sync_response","Record receipt does not match its exact document revision.")}function sp(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 hr(r){return new b("sync_payload_incomplete",`Prepared action ${r.action_id} has no exact payload capability.`)}function op(r){return new b("invalid_sync_response",`Authority receipt does not match prepared action ${r.action_id}.`)}function VC(r,e){let t=r instanceof Error?r:new Error(String(r));return{code:r&&typeof r=="object"&&"code"in r&&typeof r.code=="string"?r.code:"sync_action_failed",message:t.message,action_id:e}}function ap(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 jc=class{constructor(e,t){I(this,"fileSystem");I(this,"runtime");this.fileSystem=e,this.runtime=t}async validate(e,t){var n,i,s;if(((n=t==null?void 0:t.generation)!=null?n:0)!==e.checkpoint_generation||((i=t==null?void 0:t.cursor)!=null?i:null)!==e.base_cursor||((s=t==null?void 0:t.scope_epoch)!=null?s:e.scope_epoch)!==e.scope_epoch)throw Lc("The durable checkpoint changed after inspection.");for(let o of e.actions)o.depends_on.length===0&&await this.validateAction(o)}async validateAction(e){switch(e.command){case"write_local":await this.expected(e.expected_local),await this.expectedAt(e.target.path,e.expected_path_owner);return;case"delete_local":await this.expected(e.expected_local),await this.expectedAt(e.target.path,e.expected_path_owner);return;case"move_local":await this.expectedAt(e.source.path,e.expected_source_owner),await this.expectedAt(e.target_path,e.expected_target_owner);return;case"put_remote":case"move_remote":await this.expected(e.expected_local);return;case"delete_remote":await this.expectedAt(e.target.path,e.expected_local);return;case"record_conflict":await this.expected(e.local);return;case"advance_checkpoint":return}}async expectedAt(e,t){if(t.state==="absent"){if(await this.pathExists(e))throw Lc(`${e} is no longer vacant.`);return}if(t.object.path!==e||!await this.matches(t.object))throw Lc(`${e} no longer has the inspected owner and bytes.`)}async expected(e){if(e.state!=="absent"&&!await this.matches(e.object))throw Lc(`${e.object.path} no longer matches the inspected bytes.`)}async matches(e){if(e.entity==="file"){let n=await this.fileSystem.inspectBinary(e.path);return n!==null&&n.content_digest===e.payload_revision&&(e.size===void 0||n.size===e.size)}let t=await this.fileSystem.read(e.path);return t!==null&&`sha256:${this.runtime.digest(t)}`===e.payload_revision}async pathExists(e){return this.fileSystem.exists(e)}};function Lc(r){return new b("sync_plan_stale",r)}async function S0(r,e,t){var o;let n=rt(r);if(n.phase!=="effects_complete")throw new b("invalid_mirror_state","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 new b("invalid_mirror_state","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 new b("invalid_mirror_state","Prepared checkpoint boundary is inconsistent.");let s=n.plan.fingerprint;return r.generation=i.next.generation,r.cursor=(o=i.next.cursor)!=null?o:0,r.last_completed_plan=s,r.last_synced_at=e.now(),delete r.batch,await t.write(r),s}async function E0(r,e,t,n){var s,o,a;let[i]=e.actions;if(e.actions.length!==1||!i||i.command!=="advance_checkpoint"||i.expected.generation!==((s=r.generation)!=null?s:0)||i.expected.cursor!==r.cursor||i.next.generation!==((o=r.generation)!=null?o:0)+1||i.next.cursor!==e.authority_cursor||r.batch!==void 0)throw new b("invalid_mirror_state","Empty checkpoint plan is inconsistent.");return r.generation=i.next.generation,r.cursor=(a=i.next.cursor)!=null?a:0,r.last_completed_plan=e.fingerprint,r.last_synced_at=t.now(),await n.write(r),e.fingerprint}var Ln=class{constructor(e,t,n,i="read_only"){I(this,"replicaId");I(this,"transport");I(this,"mode");I(this,"stateStore");I(this,"fileSystem");I(this,"blobStore");I(this,"selectiveSync");I(this,"lease");I(this,"runtime");I(this,"materializer");I(this,"onProgress");var s,o;this.replicaId=e,this.transport=t,this.mode=i,this.stateStore=n.stateStore,this.fileSystem=n.fileSystem,this.blobStore=n.blobStore,this.selectiveSync=Rn(n.selectiveSync),this.lease=(s=n.lease)!=null?s:new eo,this.runtime=(o=n.runtime)!=null?o:to,this.materializer=new Ci(this.fileSystem,this.runtime,this.mode,this.blobStore),this.onProgress=n.onProgress}async sync(e={}){return this.lease.runExclusive(async()=>{var i,s;let t=await this.readState();if(((i=t==null?void 0:t.batch)==null?void 0:i.phase)==="blocked"&&((s=t.batch.failure)==null?void 0:s.code)==="sync_plan_stale"&&(await $0(t,this.journalStore()),t=await this.readState()),t!=null&&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()=>{var t,n;let e=await this.readState();return(n=(t=e==null?void 0:e.batch)==null?void 0:t.plan)!=null?n:(await this.inspectDetailed(e)).plan})}async apply(e,t={}){return this.lease.runExclusive(async()=>{let n=await this.readState();if(n!=null&&n.batch){if(n.batch.plan.fingerprint!==e.fingerprint)throw new b("mirror_recovery_required","A different prepared plan must recover before this plan can apply.");return this.executePrepared(n,t.signal)}let i=await this.inspectDetailed(n);return i.plan.fingerprint!==e.fingerprint?Mr("stale",e,fr(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){var s;let n=e.plan;if(n.issues.some(o=>o.blocking))return Mr("attention",n,fr(e.prior,this.mode),0);if(t!=null&&t.aborted)return Mr("cancelled",n,fr(e.prior,this.mode),0,{code:"sync_cancelled",message:"Sync cancelled before preparation."});try{await new jc(this.fileSystem,this.runtime).validate(n,e.prior)}catch(o){let a=o instanceof Error?o:new Error(String(o)),c=o&&typeof o=="object"&&"code"in o&&typeof o.code=="string"?o.code:"sync_revalidation_failed";return Mr(c==="sync_plan_stale"?"stale":"failed",n,fr(e.prior,this.mode),0,{code:c,message:a.message})}if(n.actions.length===0)return Mr("applied",n,fr(e.prior,this.mode),0);if(e.prior&&n.actions.length===1&&((s=n.actions[0])==null?void 0:s.command)==="advance_checkpoint")return await E0(e.prior,n,this.runtime,this.journalStore()),Mr("applied",n,fr(e.prior,this.mode),0);let i=await _0(e.prior,n,e.durable_payloads,this.journalStore());return this.executePrepared(i,t)}async executePrepared(e,t){let n=e.batch,i=await new Nc({transport:this.transport,fileSystem:this.fileSystem,blobStore:this.blobStore,runtime:this.runtime,mode:this.mode,store:this.journalStore(),onProgress:(c,l)=>{var d;return(d=this.onProgress)==null?void 0:d.call(this,{phase:"applying",completed:c,total:l,done:c===l})}}).execute(e,t);if(i.status!=="effects_complete"){let c=fr(e,this.mode);return Mr(i.status==="blocked"?"failed":i.status,n.plan,c,i.completed,i.failure)}let s=n.plan;await S0(e,this.runtime,this.journalStore()),await this.pruneFileBlobs();let o=fr(e,this.mode),a=o.conflicts.length>0||o.file_conflicts.length>0||o.local_issues.length>0||s.summary.conflicts>0;return Mr(a?"attention":"applied",s,o,i.completed)}inspectDetailed(e){return new Rc(this.replicaId,this.transport,this.mode,this.fileSystem,this.blobStore,this.selectiveSync,this.runtime,()=>this.readState(),t=>this.currentRecordPathPolicy(t)).inspect(e)}async status(){let e=await this.checkpointStatus();return e.state==="not_initialized"?e:o0(e,await this.inspect())}async checkpointStatus(){return this.lease.runExclusive(()=>this.checkpointStatusUnlocked())}async checkpointStatusUnlocked(){return fr(await this.readState(),this.mode)}async authorityPromotionManifest(){return this.lease.runExclusive(async()=>{var i;if(this.mode!=="read_write")throw new b("promotion_requires_writable_mirror","Only a read-write mirror can prove an authority promotion source.");let e=await this.readState();if(!e)throw new b("mirror_not_initialized","Synchronize this mirror first.");if(e.batch||Object.keys((i=e.planned_conflicts)!=null?i:{}).length>0)throw new b("promotion_mirror_not_clean","Finish the prepared batch and resolve conflicts before promotion.");let t=await s0({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(s=>s.command!=="advance_checkpoint"))throw new b("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){await this.lease.runExclusive(()=>this.resolveConflictUnlocked(e,"record",t))}async resolveFileConflict(e,t){await this.lease.runExclusive(()=>this.resolveConflictUnlocked(e,"file",t))}async resolveConflictUnlocked(e,t,n){var o,a,c,l;if(this.mode!=="read_write")throw new b("mirror_read_only","Receive-only mirrors have no writable conflicts.");let i=await this.readState();if(!i||i.batch)throw new b("mirror_recovery_required","Finish sync recovery before resolving conflicts.");if(!((o=i.planned_conflicts)==null?void 0:o[e]))throw new b("mirror_conflict_not_found","Writable mirror conflict was not found.");if(n==="remote"){let d=await Ac(this.replicaId,this.transport,this.mode,this.selectiveSync,this.runtime);if(t==="record"){let u=(a=d.records.find(({record:f})=>f.record_id===e))==null?void 0:a.record;await this.installRemoteRecord(i,e,u)}else{let u=d.files.find(f=>f.file_id===e);await this.installRemoteFile(i,e,u)}}(c=i.planned_conflicts)==null||delete c[e],n==="remote"&&((l=i.local_bindings)==null||delete l[e]),await this.writeState(i)}async installRemoteRecord(e,t,n){var o,a,c,l;if(n){let d=(o=e.planned_conflicts)==null?void 0:o[t],u=await this.fileSystem.read(n.path),f=((a=e.records[t])==null?void 0:a.path)===n.path||(d==null?void 0:d.local.state)==="exact"&&d.local.object.path===n.path;await this.materializer.put(e,n,{inspectionPreflighted:!1,...f&&u!==null?{acceptedHash:this.runtime.digest(u)}:{}});return}let i=(c=e.planned_conflicts)==null?void 0:c[t],s=(i==null?void 0:i.local.state)==="exact"?i.local.object.path:(l=e.records[t])==null?void 0:l.path;s&&await this.fileSystem.read(s)!==null&&await this.fileSystem.remove(s),delete e.records[t]}async installRemoteFile(e,t,n){var o,a,c,l,d,u,f,p;if(n){if(!this.blobStore)throw new b("file_storage_unavailable","File resolution needs a blob store.");await wc(this.transport,this.blobStore,n);let y=(o=e.planned_conflicts)==null?void 0:o[t],h=(y==null?void 0:y.local.state)==="exact"?{content_digest:y.local.object.payload_revision,size:(a=y.local.object.size)!=null?a:0}:void 0,m=(l=(c=e.local_bindings)==null?void 0:c[t])==null?void 0:l.path;await this.materializer.putFile(e,n,e,h),m&&m!==n.path&&await this.fileSystem.remove(m);return}let i=(d=e.planned_conflicts)==null?void 0:d[t],s=(i==null?void 0:i.local.state)==="exact"?i.local.object.path:(f=(u=e.files)==null?void 0:u[t])==null?void 0:f.file.path;s&&await this.fileSystem.inspectBinary(s)!==null&&await this.fileSystem.remove(s),(p=e.files)==null||delete p[t]}async readState(){let e=await this.stateStore.read();if(e===null)return null;try{return Gw(e,this.replicaId,this.mode)}catch(t){throw t instanceof b?t:new b("invalid_mirror_state","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(){var n,i,s,o,a;if(!this.blobStore)return;let e=await this.readState();if(!e)return;let t=new Set;for(let c of Object.values((n=e.files)!=null?n:{}))t.add(c.file.content_digest);for(let c of Object.values((s=(i=e.batch)==null?void 0:i.payloads.files)!=null?s:{}))t.add(c.content_digest);for(let c of Object.values((a=(o=e.batch)==null?void 0:o.payloads.local_files)!=null?a:{}))t.add(c.content_digest);await this.blobStore.prune(t)}currentRecordPathPolicy(e){return this.materializer.recordPathPolicy(e)}};var oo=class extends Ln{constructor(e,t,n){super(e,t,n,"read_write")}};function A0(r){let e=[...r.actions.flatMap(t=>t.command==="advance_checkpoint"?[]:[UC(t)]),...r.issues.map(t=>{var n;return{kind:"document",path:(n=t.path)!=null?n:"Sync engine",direction:"attention",action:"fix",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).map(t=>t.path),local_issues:r.issues.filter(t=>t.code==="invalid_frontmatter"&&t.path!==void 0).map(t=>({code:"invalid_frontmatter",message:t.message,path:t.path}))}}function UC(r){var c;if(r.command==="advance_checkpoint")throw new Error("Checkpoint actions are not preview entries.");if(r.command==="record_conflict"){let l=r.local.state==="exact"?r.local.object:r.remote.state==="exact"?r.remote.object:void 0;return{kind:r.entity==="file"?"file":"document",path:(c=l==null?void 0:l.path)!=null?c:r.identity,direction:"attention",action:"fix",detail:`Local and hosted ${r.entity} changes conflict (${r.conflict_kind.replace(/_/g," ")}).`,...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=r.command.split("_")[0],a=r.command.startsWith("move_")?` from ${t.path}`:"";return{kind:t.entity==="file"?"file":"document",path:n,direction:e?"download":"upload",action:s,detail:`${e?"Hosted":"Local"} ${t.entity} will ${o}${a}.`,...t.entity==="record"?{recordId:t.identity}:{},...t.entity==="file"?{fileId:t.identity}:{}}}var ao=".mdbase/connect-role.json",co=".mdbase/authority-adoption.json",lo=".mdbase/authority-adoption-snapshot.json",BC="mdbase-obsidian-connect-exact-v1",Ni="mirrors",zC="mdbase-connect-access-",HC="mdbase-connect-refresh-",KC="mdbase-connect-adoption-",WC=300*1e3,lp=[".git/",".obsidian/",".trash/",".mdbase/"],uo=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Fe(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function Dc(r,e){if(e!=null)return e;if(!r.trim())return{};try{return JSON.parse(r)}catch(t){return{}}}function x0(r){var i;let e=(i=r["retry-after"])!=null?i:r["Retry-After"];if(!e)return;let t=Number(e);if(Number.isFinite(t)&&t>=0)return t*1e3;let n=Date.parse(e);if(Number.isFinite(n))return Math.max(0,n-Date.now())}function GC(){return async r=>{var t,n;if((t=r.signal)!=null&&t.aborted)throw new DOMException("Enrollment cancelled.","AbortError");let e=await(0,oe.requestUrl)({url:r.url,method:r.method,headers:r.headers,body:r.body===void 0?void 0:JSON.stringify(r.body),contentType:r.body===void 0?void 0:"application/json",throw:!1});if((n=r.signal)!=null&&n.aborted)throw new DOMException("Enrollment cancelled.","AbortError");return{status:e.status,body:Dc(e.text,e.json),retryAfterMs:x0(e.headers)}}}function JC(){return async r=>{var t,n;if((t=r.signal)!=null&&t.aborted)throw new DOMException("Collection adoption cancelled.","AbortError");let e=await(0,oe.requestUrl)({url:r.url,method:r.method,headers:r.headers,body:r.body===void 0?void 0:JSON.stringify(r.body),contentType:r.body===void 0?void 0:"application/json",throw:!1});if((n=r.signal)!=null&&n.aborted)throw new DOMException("Collection adoption cancelled.","AbortError");return{status:e.status,body:Dc(e.text,e.json),retryAfterMs:x0(e.headers)}}}var dp=class{constructor(e,t){this.accessToken=t;let n;try{n=new URL(e)}catch(i){throw new b("invalid_sync_url","Sync URL must be an absolute authority endpoint.")}if(!(n.protocol==="https:"||n.protocol==="http:"&&["localhost","127.0.0.1","[::1]","::1"].includes(n.hostname))||n.username||n.password||n.search||n.hash||!/^\/v1\/authorities\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\/sync\/?$/i.test(n.pathname))throw new b("invalid_sync_url","Sync URL must identify one authority sync endpoint.");this.syncUrl=n.href.replace(/\/$/,""),this.filesUrl=this.syncUrl.replace(/\/sync$/,"/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){let t=crypto.randomUUID();try{let n=await this.fileRequest("POST","downloads",{protocol_version:1,type:"open_file_download",transfer_id:t,file_id:e.file_id,revision:e.revision}),i=Fe(n.strategy)?n.strategy:{},s=i.part_size;if(n.protocol_version!==1||n.type!=="file_transfer"||n.transfer_id!==t||n.direction!=="download"||n.protection!=="transport_tls"||n.total_size!==e.size||i.kind!=="object_ranges"||!Number.isSafeInteger(s)||s<=0)throw new b("invalid_sync_response","The authority returned an incompatible file download session.");let o=Math.ceil(e.size/s);for(let a=0;a=300){let d=Dc(l.text,l.json),u=Fe(d)&&Fe(d.error)?d.error:{};throw new b(typeof u.code=="string"?u.code:"file_download_failed",typeof u.message=="string"?u.message:`File download failed (${l.status}).`)}if(l.arrayBuffer.byteLength!==c)throw new b("file_integrity_failed","The authority returned a file part with the wrong length.");yield new Uint8Array(l.arrayBuffer)}}finally{await this.fileRequest("DELETE",`transfers/${encodeURIComponent(t)}`).catch(()=>{})}}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)}request(e,t,n){return this.requestAt(this.syncUrl,e,t,n)}fileRequest(e,t,n){return this.requestAt(this.filesUrl,e,t,n)}async requestAt(e,t,n,i){let s=await(0,oe.requestUrl)({url:`${e}/${n}`,method:t,headers:{authorization:`Bearer ${this.accessToken}`},body:i===void 0?void 0:JSON.stringify(i),contentType:i===void 0?void 0:"application/json",throw:!1}),o=Dc(s.text,s.json);if(s.status<200||s.status>=300){let a=Fe(o)&&Fe(o.error)?o.error:{};throw new b(typeof a.code=="string"?a.code:"sync_failed",typeof a.message=="string"?a.message:`Sync request failed (${s.status}).`)}return o}};function Lr(r){let e=Rs(r);if(e===".mdbase"||lp.some(t=>e.startsWith(t)))throw new b("unsafe_mirror_path",`The collection authority attempted to write a reserved path: ${e}`);return e}async function ji(r,e){let t=(0,oe.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 oe.TFolder)){if(s)throw new b("mirror_path_collision",`A file blocks the mirror folder ${n}.`);await r.adapter.exists(n)||await r.createFolder(n)}}}var up=class{constructor(e){this.vault=e}async exists(e){let t=Lr(e);return this.vault.getAbstractFileByPath(t)!==null||await this.vault.adapter.exists(t)}async read(e){let t=Lr(e),n=this.vault.getAbstractFileByPath(t);if(n==null)return null;if(!(n instanceof oe.TFile))throw new b("mirror_path_collision",`Expected a file at ${t}.`);return this.vault.cachedRead(n)}async write(e,t){let n=Lr(e),i=n.lastIndexOf("/");i>=0&&await ji(this.vault,n.slice(0,i));let s=this.vault.getAbstractFileByPath(n);if(s instanceof oe.TFolder)throw new b("mirror_path_collision",`A folder blocks the mirror file ${n}.`);s instanceof oe.TFile?await this.vault.modify(s,t):await this.vault.create(n,t)}async move(e,t){let n=Lr(e),i=Lr(t),s=i.lastIndexOf("/");s>=0&&await ji(this.vault,i.slice(0,s));let o=this.vault.getAbstractFileByPath(n);if(!(o instanceof oe.TFile))throw new b("mirror_path_collision",`Expected a file at ${n}.`);if(this.vault.getAbstractFileByPath(i)!==null||await this.vault.adapter.exists(i))throw new b("mirror_path_collision",`A file or folder blocks ${i}.`);await this.vault.rename(o,i)}async remove(e){let t=Lr(e),n=this.vault.getAbstractFileByPath(t);if(n!=null){if(!(n instanceof oe.TFile))throw new b("mirror_path_collision",`Expected a file at ${t}.`);await this.vault.delete(n,!0)}}async listMarkdown(e){return this.vault.getMarkdownFiles().map(t=>(0,oe.normalizePath)(t.path)).filter(t=>!e.has(t)).filter(t=>!lp.some(n=>t.startsWith(n))).sort()}async inspectBinary(e){let t=Lr(e),n=this.vault.getAbstractFileByPath(t);if(n==null)return null;if(!(n instanceof oe.TFile))throw new b("mirror_path_collision",`Expected a file at ${t}.`);let i=await this.vault.readBinary(n),s=await crypto.subtle.digest("SHA-256",i),o=Array.from(new Uint8Array(s),a=>a.toString(16).padStart(2,"0")).join("");return{size:i.byteLength,content_digest:`sha256:${o}`}}async writeBinary(e,t){let n=Lr(e),i=[],s=0;for await(let d of t){if(!(d instanceof Uint8Array)||!Number.isSafeInteger(s+d.byteLength))throw new b("invalid_file_materialization","The binary file stream is invalid or too large.");i.push(d),s+=d.byteLength}let o=new Uint8Array(s),a=0;for(let d of i)o.set(d,a),a+=d.byteLength;let c=n.lastIndexOf("/");c>=0&&await ji(this.vault,n.slice(0,c));let l=this.vault.getAbstractFileByPath(n);if(l instanceof oe.TFolder)throw new b("mirror_path_collision",`A folder blocks the mirror file ${n}.`);l instanceof oe.TFile?await this.vault.modifyBinary(l,o.buffer):await this.vault.createBinary(n,o.buffer)}async listBinary(e){return this.vault.getFiles().map(t=>(0,oe.normalizePath)(t.path)).filter(t=>!t.toLowerCase().endsWith(".md")).filter(t=>!e.has(t)).filter(t=>!lp.some(n=>t.startsWith(n))).sort()}async readBinary(e){let t=Lr(e),n=this.vault.getAbstractFileByPath(t);if(n==null)return null;if(!(n instanceof oe.TFile))throw new b("mirror_path_collision",`Expected a file at ${t}.`);let i=new Uint8Array(await this.vault.readBinary(n));return(async function*(){yield i})()}},fp=class{constructor(e){this.key=e;this.database=null}async read(){let e=await this.open();return new Promise((t,n)=>{let i=e.transaction(Ni,"readonly").objectStore(Ni).get(this.key);i.onsuccess=()=>{var s;return t((s=i.result)!=null?s:null)},i.onerror=()=>n(i.error)})}async write(e){let t=await this.open();await new Promise((n,i)=>{let s=t.transaction(Ni,"readwrite");s.objectStore(Ni).put(e,this.key),s.oncomplete=()=>n(),s.onerror=()=>i(s.error),s.onabort=()=>i(s.error)})}open(){var e;if(typeof indexedDB=="undefined")throw new b("storage_unavailable","IndexedDB is required for persistent mirror state.");return(e=this.database)!=null||(this.database=new Promise((t,n)=>{let i=indexedDB.open(BC,1);i.onupgradeneeded=()=>{i.result.objectStoreNames.contains(Ni)||i.result.createObjectStore(Ni)},i.onerror=()=>n(i.error),i.onsuccess=()=>t(i.result)})),this.database}},Li=class Li{constructor(e){this.key=e}async runExclusive(e){if(Li.active.has(this.key))throw new b("mirror_busy","A mirror operation is already running for this vault.");Li.active.add(this.key);try{return await e()}finally{Li.active.delete(this.key)}}};Li.active=new Set;var pp=Li,qc=class{constructor(e,t,n={}){this.app=e;this.settingsHost=t;this.options=n;this.progress=null;this.syncAbort=null;this.adoptionMarker=null;var i,s,o;this.fileSystem=(i=n.fileSystem)!=null?i:new up(e.vault),this.enrollmentClient=(s=n.enrollmentClient)!=null?s:new gc({request:GC()}),this.adoptionClient=(o=n.adoptionClient)!=null?o:new $c({request:JC()})}async initialize(){if(this.adoptionMarker=await this.readAdoptionMarker(),this.adoptionMarker&&this.settingsHost.getMirrorProfile())throw new b("authority_adoption_state_conflict","This vault contains both an authority-adoption checkpoint and a mirror profile.")}getProgress(){return this.progress?{...this.progress}:null}cancelSync(){var e;(e=this.syncAbort)==null||e.abort()}getAdoptionMarker(){return this.adoptionMarker?JSON.parse(JSON.stringify(this.adoptionMarker)):null}assertLocalAuthorityWritable(){if(this.adoptionMarker&&["fenced","activating","adopted"].includes(this.adoptionMarker.phase))throw new b("local_authority_fenced",this.adoptionMarker.phase==="adopted"?"Hosted mdbase is now authoritative. Finish reconnecting this vault as its mirror before editing.":"This local authority is frozen while its exact snapshot is adopted by hosted mdbase.")}async adoptLocalCollection(e,t){if(this.settingsHost.getMirrorProfile())throw new b("mirror_already_configured","This vault already mirrors a collection authority.");if(this.adoptionMarker)return this.resumeAdoption(t);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);return await this.storeAdoptionSecret(i),await this.writeAdoptionMarker({version:1,phase:"waiting_for_approval",session:cp(i),manifest_digest:null,source_revision:null,source_head:null}),await t.onVerification(cp(i)),this.runAdoptionWithRecovery(i,t)}async resumeAdoption(e={}){var s,o,a;let t=(s=this.adoptionMarker)!=null?s:await this.readAdoptionMarker();if(!t)throw new b("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 b("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((o=e.onVerification)==null?void 0:o.call(e,cp(i))),this.runAdoptionWithRecovery(i,{...e,onVerification:(a=e.onVerification)!=null?a:(()=>{})})}async cancelAdoption(e){var i;let t=(i=this.adoptionMarker)!=null?i:await this.readAdoptionMarker();if(!t)return;if(["activating","adopted"].includes(t.phase))throw new b("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 b("authority_adoption_credentials_missing","The collection-adoption credential is missing from Obsidian's secret store.");await this.adoptionClient.cancel({...t.session,credential:n},{signal:e}),await this.clearAdoptionCheckpoint(t.session.adoptionId)}async enroll(e,t){let n=await this.assertCanBecomeMirror(e.collectionId),i=await this.enrollmentClient.enroll({...e,...n?{collectionId:n}:{}},t),s=await this.markMirror(i.collectionId);try{await this.persistEnrollment(i)}catch(o){if(s)try{await this.app.vault.adapter.remove(ao)}catch(a){throw new b("enrollment_recovery_required",`Enrollment settings could not be saved and the temporary role marker could not be removed: ${o instanceof Error?o.message:String(o)}`)}throw o}return this.requireProfile()}async preview(){let e=await this.createMirror();return A0(await e.inspect())}async status(){let e=this.settingsHost.getMirrorProfile();return e?(await this.assertMirror(e.collectionId),(await this.createMirror()).status()):null}async sync(e,t){if(this.syncAbort)throw new b("mirror_busy","Synchronization is already running for this vault.");let n=new AbortController;this.syncAbort=n;let i=await this.createMirror(s=>{this.progress=s,t==null||t({...s})});try{return await i.apply(e.plan,{signal:n.signal})}finally{this.progress=null,this.syncAbort=null}}async resolveConflict(e,t){let n=await this.createMirror();return await n.resolveConflict(e,t),n.status()}async runAdoption(e,t){let n=this.requireAdoptionMarker(e.adoptionId),i=null;if(n.phase==="adopted"){let s=await this.adoptionClient.exchange(e,t);if(s.status!=="completed")throw new b("authority_adoption_state_conflict","The local checkpoint says adoption completed, but Connect does not.");i=s}else if(n.phase==="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"&&await this.adoptionClient.uploadSnapshot(e,o,s,t),await this.updateAdoptionPhase("activating",s),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),o=await this.captureAuthoritySnapshot(e.requested.collectionId);await this.updateAdoptionPhase("uploading"),await this.adoptionClient.uploadSnapshot(e,s,o,t);let a=await this.captureAuthoritySnapshot(e.requested.collectionId);await this.writeAdoptionSnapshot(a),await this.updateAdoptionPhase("fenced",a);let c=await this.requirePreparedAdoption(e,t);await this.adoptionClient.uploadSnapshot(e,c,a,t),await this.updateAdoptionPhase("activating",a),i=await this.adoptionClient.complete(e,a,t)}return await this.updateAdoptionPhase("adopted"),this.finishRetainedMirror(e,i,t)}async runAdoptionWithRecovery(e,t){try{return await this.runAdoption(e,t)}catch(n){throw YC(n)?(await this.adoptionClient.cancel(e,{signal:t.signal}).catch(()=>{}),await this.clearAdoptionCheckpoint(e.adoptionId),new b(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 Ir("Hosted authority activation has already started. Resume using the saved fenced snapshot."):new b("authority_adoption_already_completed","Hosted authority has already adopted this collection.")}async finishRetainedMirror(e,t,n){var a,c;let i,s=this.adoptionClient.mirrorEnrollmentSession(e,t);if(!s)throw new b("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:l=>{var d;return(d=n.onStatus)==null?void 0:d.call(n,{...l,state:l.state})}})}catch(l){if((a=n.signal)!=null&&a.aborted)throw l;i=await this.enrollmentClient.enroll({controlUrl:e.controlUrl,collectionId:e.requested.collectionId,mirrorName:(c=e.requested.mirrorName)!=null?c:e.requested.sourceName,mode:"read_write"},{signal:n.signal,onVerification:n.onVerification})}let o=await this.markMirror(i.collectionId);try{await this.persistEnrollment(i)}catch(l){throw o&&await this.app.vault.adapter.remove(ao),l}return await this.clearAdoptionCheckpoint(e.adoptionId),this.requireProfile()}async captureAuthoritySnapshot(e){let t=await pi(this.app.vault);if(!t)throw new b("invalid_collection_configuration","A valid mdbase.yaml is required.");let n=await this.app.vault.adapter.read("mdbase.yaml"),i=(0,oe.parseYaml)(n),s=[{path:"mdbase.yaml",kind:"configuration",document:n}],o=`${(0,oe.normalizePath)(t.settings.types_folder)}/`,a=this.app.vault.getMarkdownFiles().filter(d=>(0,oe.normalizePath)(d.path).startsWith(o)).sort((d,u)=>d.path.localeCompare(u.path));for(let d of a)s.push({path:(0,oe.normalizePath)(d.path),kind:"type",document:await this.app.vault.cachedRead(d)});let c=XC(i);if(c.length){let d=c.map(f=>(0,k0.default)(f,{dot:!0})),u=QC(this.app.vault).filter(f=>f.extension==="base").filter(f=>d.some(p=>p((0,oe.normalizePath)(f.path)))).sort((f,p)=>f.path.localeCompare(p.path));for(let f of u)s.push({path:(0,oe.normalizePath)(f.path),kind:"view",document:await this.app.vault.cachedRead(f)})}let l=[];for(let d of this.app.vault.getMarkdownFiles().sort((u,f)=>u.path.localeCompare(f.path))){let u=(0,oe.normalizePath)(d.path);if(Ts(u,t))continue;let f=await this.app.vault.cachedRead(d);l.push({path:u,document:f})}return Hf({collectionId:e,sourceHead:0,specVersion:t.spec_version,resources:s,records:l})}async ensurePortableCollectionIdentity(){if(!await this.app.vault.adapter.exists("mdbase.yaml"))throw new b("collection_not_initialized","Initialize an mdbase collection before hosting it.");let e=await this.app.vault.adapter.read("mdbase.yaml"),t;try{t=(0,oe.parseYaml)(e)}catch(o){throw new b("invalid_collection_configuration","mdbase.yaml must contain valid YAML.")}if(!Fe(t))throw new b("invalid_collection_configuration","mdbase.yaml must contain a YAML mapping.");let n=Fe(t["x-mdbase-connect"])?t["x-mdbase-connect"].collection_id:void 0,i;if(n===void 0){i=crypto.randomUUID();let o=Fe(t["x-mdbase-connect"])?t["x-mdbase-connect"]:{};t["x-mdbase-connect"]={...o,collection_id:i},await this.app.vault.adapter.write("mdbase.yaml",(0,oe.stringifyYaml)(t))}else if(typeof n=="string"&&uo.test(n))i=n;else throw new b("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}}async createMirror(e){var o,a,c,l,d,u,f,p,y;let t=this.requireProfile();await this.assertMirror(t.collectionId);let n=await this.freshAccessToken(t),i=(c=(a=(o=this.options).transportFactory)==null?void 0:a.call(o,t,n))!=null?c:new dp(t.syncUrl,n),s={stateStore:(u=(d=(l=this.options).stateStoreFactory)==null?void 0:d.call(l,t))!=null?u:new fp(`${t.collectionId}:${t.replicaId}`),fileSystem:this.fileSystem,lease:(y=(p=(f=this.options).leaseFactory)==null?void 0:p.call(f,t))!=null?y:new pp(`${t.collectionId}:${t.replicaId}`),onProgress:e};return t.mode==="read_write"?new oo(t.replicaId,i,s):new Ln(t.replicaId,i,s)}requireProfile(){let e=this.settingsHost.getMirrorProfile();if(!e)throw new b("mirror_not_configured","This vault is not connected to a collection authority.");return e}accessSecretId(e){return`${zC}${e.toLowerCase()}`}refreshSecretId(e){return`${HC}${e.toLowerCase()}`}adoptionSecretId(e){return`${KC}${e.toLowerCase()}`}async storeAdoptionSecret(e){this.app.secretStorage.setSecret(this.adoptionSecretId(e.adoptionId),e.credential)}async persistEnrollment(e){this.app.secretStorage.setSecret(this.accessSecretId(e.collectionId),e.accessToken),this.app.secretStorage.setSecret(this.refreshSecretId(e.collectionId),e.refreshCredential),await this.settingsHost.saveMirrorProfile({version:1,syncUrl:e.syncUrl,controlUrl:e.controlUrl,collectionId:e.collectionId,replicaId:e.replicaId,mode:e.mode,name:e.name,enrollmentId:e.enrollmentId,accessTokenExpiresAt:e.accessTokenExpiresAt})}async freshAccessToken(e){let t=this.accessSecretId(e.collectionId),n=this.app.secretStorage.getSecret(t),i=Date.parse(e.accessTokenExpiresAt);if(n&&Number.isFinite(i)&&i-Date.now()>WC)return n;let s=this.app.secretStorage.getSecret(this.refreshSecretId(e.collectionId));if(!s)throw new b("mirror_credentials_missing","The mirror refresh credential is missing. Re-enroll this vault.");let o=await this.enrollmentClient.renew({controlUrl:e.controlUrl,syncUrl:e.syncUrl,collectionId:e.collectionId,replicaId:e.replicaId,mode:e.mode,name:e.name,enrollmentId:e.enrollmentId,accessToken:n!=null?n:"",refreshCredential:s,accessTokenExpiresAt:e.accessTokenExpiresAt});return await this.persistEnrollment(o),o.accessToken}async assertCanBecomeMirror(e){var o;let t=await this.readMarker(),n=await this.readPortableCollectionId();if(n&&!t)throw new b("local_authority_requires_transfer","This vault has a local Connect identity. Transfer authority explicitly before using it as a mirror.");if(n&&(t==null?void 0:t.collection_id)!==n)throw new b("mirror_identity_conflict","The vault identity and mirror role marker identify different collections.");let i=this.settingsHost.getMirrorProfile(),s=(o=i==null?void 0:i.collectionId)!=null?o:e;if(t&&s&&t.collection_id!==s)throw new b("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 b("existing_collection_requires_transfer","This vault already contains an mdbase collection. Connect an empty vault, or transfer collection authority explicitly.");return s!=null?s:t==null?void 0:t.collection_id}async readPortableCollectionId(){if(!await this.app.vault.adapter.exists("mdbase.yaml"))return null;let e;try{e=(0,oe.parseYaml)(await this.app.vault.adapter.read("mdbase.yaml"))}catch(i){throw new b("invalid_collection_configuration","mdbase.yaml must contain valid YAML.")}if(!Fe(e))throw new b("invalid_collection_configuration","mdbase.yaml must contain a YAML mapping.");let t=e["x-mdbase-connect"];if(t===void 0)return null;if(!Fe(t))throw new b("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"||!uo.test(n))throw new b("invalid_collection_configuration","x-mdbase-connect.collection_id must be a UUID string.");return n}async markMirror(e){let t=await this.readMarker();if(t){if(t.collection_id!==e)throw new b("mirror_identity_conflict","This vault already mirrors a different collection authority.");return!1}return await ji(this.app.vault,".mdbase"),await this.app.vault.adapter.write(ao,`${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 b("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(ao))return null;let e;try{e=JSON.parse(await this.app.vault.adapter.read(ao))}catch(t){throw new b("invalid_mirror_marker","The mirror role marker is corrupt.")}if(!Fe(e)||e.version!==1||e.role!=="mirror"||typeof e.collection_id!="string"||!uo.test(e.collection_id))throw new b("invalid_mirror_marker","The mirror role marker is invalid.");return e}requireAdoptionMarker(e){if(!this.adoptionMarker||this.adoptionMarker.session.adoptionId!==e)throw new b("authority_adoption_state_conflict","The collection-adoption checkpoint does not match this approval.");return this.adoptionMarker}async updateAdoptionPhase(e,t){if(!this.adoptionMarker)throw new b("authority_adoption_not_found","Collection-adoption checkpoint is missing.");await this.writeAdoptionMarker({...this.adoptionMarker,phase:e,...t?{manifest_digest:t.manifest_digest,source_revision:t.source_revision,source_head:t.source_head}:{}})}async writeAdoptionMarker(e){await ji(this.app.vault,".mdbase"),await this.app.vault.adapter.write(co,`${JSON.stringify(e,null,2)} -`),this.adoptionMarker=e}async readAdoptionMarker(){if(!await this.app.vault.adapter.exists(co))return null;let e;try{e=JSON.parse(await this.app.vault.adapter.read(co))}catch(t){throw new b("invalid_authority_adoption_checkpoint","The collection-adoption checkpoint is corrupt.")}if(!ZC(e))throw new b("invalid_authority_adoption_checkpoint","The collection-adoption checkpoint is invalid.");return e}async writeAdoptionSnapshot(e){await ji(this.app.vault,".mdbase"),await this.app.vault.adapter.write(lo,JSON.stringify(e))}async readAdoptionSnapshot(e){if(!await this.app.vault.adapter.exists(lo))throw new b("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(lo))}catch(n){throw new b("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 b("authority_adoption_snapshot_mismatch","The fenced authority snapshot does not match its durable checkpoint.");return t}async clearAdoptionCheckpoint(e){await this.app.vault.adapter.exists(co)&&await this.app.vault.adapter.remove(co),await this.app.vault.adapter.exists(lo)&&await this.app.vault.adapter.remove(lo),this.app.secretStorage.setSecret(this.adoptionSecretId(e),""),this.adoptionMarker=null}};function cp(r){let{credential:e,...t}=r;return t}function YC(r){return r instanceof J&&["authority_adoption_expired","authority_adoption_cancelled"].includes(r.code)}function XC(r){if(!Fe(r))return[];let e=r["x-obsidian"];return!Fe(e)||!Fe(e.bases)||!Array.isArray(e.bases.include)?[]:e.bases.include.filter(t=>typeof t=="string")}function QC(r){var i;let e=(i=r.getFiles)==null?void 0:i.call(r);if(e)return e;let t=[],n=s=>{for(let o of s.children)o instanceof oe.TFile?t.push(o):o instanceof oe.TFolder&&n(o)};return n(r.getRoot()),t}function ZC(r){if(!Fe(r)||r.version!==1||!["waiting_for_approval","uploading","fenced","activating","adopted"].includes(String(r.phase))||!Fe(r.session))return!1;let e=r.session;return typeof e.controlUrl=="string"&&typeof e.adoptionId=="string"&&uo.test(e.adoptionId)&&typeof e.verificationUri=="string"&&typeof e.expiresAt=="string"&&Fe(e.requested)&&typeof e.requested.collectionId=="string"&&uo.test(e.requested.collectionId)&&typeof e.requested.displayName=="string"&&typeof e.requested.sourceName=="string"&&e.requested.retainMirror===!0&&(r.manifest_digest===null||typeof r.manifest_digest=="string")&&(r.source_revision===null||typeof r.source_revision=="string")&&(r.source_head===null||Number.isSafeInteger(r.source_head))}var nt=require("obsidian");var mo="0.3.0",eM=new Set(["name","description","display_name_key","strict","path_pattern","filename_pattern","match","fields","extends"]),tM=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 ve(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function Ce(r){return r===void 0?r:JSON.parse(JSON.stringify(r))}function jr(r){return to.digest(r)}function jn(r){return Array.isArray(r)?`[${r.map(jn).join(",")}]`:ve(r)?`{${Object.keys(r).sort().map(e=>`${JSON.stringify(e)}:${jn(r[e])}`).join(",")}}`:JSON.stringify(r)}function hp(r){if(Array.isArray(r))return r.map(hp);if(!ve(r))return r;let e={};for(let[t,n]of Object.entries(r)){let i=hp(n);i!=null&&(Array.isArray(i)&&i.length===0||ve(i)&&Object.keys(i).length===0||(e[t]=i))}return e}function Di(r){return[...new Set(r)]}function rM(r){return ve(r.fields)?Object.values(r.fields).some(e=>ve(e)&&(typeof e.tn_role=="string"||Array.isArray(e.tn_completed_values))):!1}function mp(r,e,t){let n=ve(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)?Ce(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=mp(`${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[d,u]of Object.entries(ve(n.fields)?n.fields:{})){let f=mp(`${r}.${d}`,u,t);c[d]=f.schema,Object.assign(i,f.links),Object.assign(s,f.legacy),o.push(...f.unsupported),ve(u)&&u.required===!0&&l.push(d)}t&&r==="blockedBy[]"&&l.push("uid"),a={type:"object",additionalProperties:Object.keys(c).length===0,properties:c,...l.length?{required:Di(l)}:{}};break}default:a={},o.push(`${r}.type`);break}t&&r==="title"&&(a.minLength=1,a.description="Short summary of the task."),typeof n.description=="string"&&(a.description=n.description),typeof n.min=="number"&&(n.type==="string"?a.minLength=n.min:n.type==="list"?a.minItems=n.min:a.minimum=n.min),typeof n.max=="number"&&(n.type==="string"?a.maxLength=n.max:n.type==="list"?a.maxItems=n.max:a.maximum=n.max),typeof n.min_length=="number"&&(a.minLength=n.min_length),typeof n.max_length=="number"&&(a.maxLength=n.max_length),typeof n.pattern=="string"&&(a.pattern=n.pattern),n.deprecated===!0&&(a.deprecated=!0),n.default!==void 0&&(a.default=Ce(n.default)),n.computed!==void 0&&o.push(`${r}.computed`);for(let[c,l]of Object.entries(n)){let d=t&&(c==="tn_role"||c==="tn_completed_values");(!tM.has(c)||(c==="tn_role"||c==="tn_completed_values")&&!d)&&(s[`${r}.${c}`]=Ce(l))}return{schema:a,links:i,legacy:s,unsupported:o}}function fo(r,e,t,n){let i=ve(r[e])?r[e]:{},s=ve(i.set)?i.set:{};s[t]=n,i.set=s,r[e]=i}function nM(r,e,t){if(t==="now")fo(r,"on_create",e,{now:!0});else if(t==="now_on_write")fo(r,"on_update",e,{now:!0});else if(t==="uuid")fo(r,"on_create",e,{uuid:!0});else if(t==="ulid")fo(r,"on_create",e,{ulid:!0});else if(ve(t)&&t.transform==="slugify"&&typeof t.from=="string")fo(r,"on_create",e,{slugify:t.from});else return!1;return!0}function iM(r){var t;let e=r.match(/^(.*\/)?\{title\}\.md$/);return e?{runtime:"tasknotes",template:"{{title}}",folder:((t=e[1])!=null?t:"").replace(/\/$/,""),generated_by:"tasknotes.filename.create"}:{runtime:"tasknotes",template:r,generated_by:"tasknotes.filename.create"}}function sM(r,e,t){var P;if(t.kind==="mdbase.type"||t.schema!==void 0)throw new Error(`${r} already looks like a v0.3 type.`);if(typeof t.name!="string"||!ve(t.fields))throw new Error(`${r} is not a v0.2 type with a name and fields.`);let n=rM(t),i=t.name.trim().toLowerCase(),s={type:{const:i}},o=[],a={},c={},l=[],d={},u={},f=[],p=[],y={},h={},m={};for(let[O,$]of Object.entries(t.fields)){let R=ve($)?$:{},S=mp(O,R,n);s[O]=S.schema,Object.assign(c,S.links),Object.assign(u,S.legacy),f.push(...S.unsupported),R.required===!0&&o.push(O),R.default!==void 0&&(a[O]=Ce(R.default)),R.unique===!0&&l.push({field:O,scope:"collection"}),R.generated!==void 0&&nM(d,O,R.generated)&&p.push(O),typeof R.tn_role=="string"&&(y[R.tn_role]=O),Array.isArray(R.tn_completed_values)&&(h.completed_values=Ce(R.tn_completed_values))}a.status!==void 0&&(h.default=Ce(a.status)),a.priority!==void 0&&(m.default=Ce(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,_={...g?{display:{name_field:g}}:{},read_defaults:a,links:c,unique:l};typeof t.path_pattern=="string"&&(_.path=n?iM(t.path_pattern):{pattern:t.path_pattern});let w={};for(let[O,$]of Object.entries(t))eM.has(O)||(w[O]=Ce($));Object.keys(u).length&&(w.fields=u);let x=hp({kind:"mdbase.type",name:i,version:1,description:typeof t.description=="string"?t.description:void 0,match:ve(t.match)?Ce(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:Di(o)}:{}}},collection:_,lifecycle:d,...n?{"x-tasknotes":{contract:"tasknotes.task",version:1,field_roles:y,status:h,priority:m,archive:{tags_field:(P=y.tags)!=null?P:"tags",archived_tag:"archived"}}}:{},...Object.keys(w).length?{"x-legacy-v0.2":w}:{}}),v=[];t.extends!==void 0&&f.push("extends");for(let O of Di(f).sort())v.push({path:r,code:"migration_lossy",message:`${O} cannot be expressed as canonical v0.3 write behavior and was retained as legacy metadata where possible.`,severity:"lossy"});return n&&v.push({path:r,code:"path_policy_runtime_owned",message:"TaskNotes filename behavior is recorded as TaskNotes runtime metadata.",severity:"warning"}),t.strict!==!0&&v.push({path:r,code:"additional_properties_true",message:"The migrated schema allows additional properties because the source type was not strict.",severity:"warning"}),typeof t.display_name_key=="string"&&!g&&v.push({path:r,code:"display_field_missing",message:`The display field '${t.display_name_key}' is not declared, so collection.display was omitted.`,severity:"warning"}),{target:x,summary:{path:r,name:i,fieldsConverted:Object.keys(t.fields).length,requiredFields:Di(o),defaultsMoved:Object.keys(a),generatedFieldsMoved:Di(p),linksMoved:Object.keys(c),taskNotes:n},diagnostics:v}}function oM(r){let e=Ce(r);e.spec_version=mo;let t=ve(e.settings)?e.settings:{};if(e.settings=t,!Array.isArray(t.record_extensions)){let n=Array.isArray(t.extensions)?t.extensions.map(String).map(i=>i.replace(/^\./,"")):[];t.record_extensions=Di(["md",...n])}return Array.isArray(t.explicit_type_keys)||(t.explicit_type_keys=["type","types"]),typeof t.include_subfolders!="boolean"&&(t.include_subfolders=!0),t.validation===void 0&&typeof t.default_validation=="string"&&(t.validation=t.default_validation),t.validation===void 0&&typeof e.default_validation=="string"&&(t.validation=e.default_validation),delete t.default_validation,delete t.extensions,delete e.default_validation,e}function P0(r,e){let t=ve(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 aM(r,e){var n,i;let t={};for(let[s,o]of Object.entries(ve(e.fields)?e.fields:{}))ve(o)&&(t[s]=Ce(o));return{name:typeof e.name=="string"?e.name:(i=(n=r.split("/").pop())==null?void 0:n.replace(/\.md$/,""))!=null?i:"type",fields:t,match:ve(e.match)?Ce(e.match):void 0,filePath:r,specProfile:"v0.2"}}function cM(r,e){var i,s;let t=ve(e.schema)?e.schema:{},n=ve(t.value)?t.value:{};return{name:typeof e.name=="string"?e.name:(s=(i=r.split("/").pop())==null?void 0:i.replace(/\.md$/,""))!=null?s:"type",fields:An(n),match:ve(e.match)?Ce(e.match):void 0,collection:ve(e.collection)?Ce(e.collection):void 0,schema:Ce(n),filePath:r,specProfile:"v0.3"}}function lM(r,e,t){let n=Ce(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]=Ce(a.default))}return n}function dM(r,e,t){var i,s;let n=Ce(r);for(let o of e){let a=t.get(o);if(a)for(let[c,l]of Object.entries((s=(i=a.collection)==null?void 0:i.read_defaults)!=null?s:{}))c in n||(n[c]=Ce(l))}return n}async function uM(r,e){let t=(0,nt.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 nt.TFolder)){if(s)throw new Error(`A file blocks folder ${n}.`);await r.adapter.exists(n)||await r.createFolder(n)}}}async function Fc(r,e,t){let n=(0,nt.normalizePath)(e),i=n.lastIndexOf("/");if(i>=0&&await uM(r,n.slice(0,i)),n.startsWith(".mdbase/")){await r.adapter.write(n,t);return}let s=r.getAbstractFileByPath(n);if(s instanceof nt.TFolder)throw new Error(`A folder blocks file ${n}.`);s instanceof nt.TFile?await r.modify(s,t):await r.create(n,t)}async function ho(r,e){let t=(0,nt.normalizePath)(e),n=r.getAbstractFileByPath(t);if(n instanceof nt.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 I0(r){var x;let e=await ho(r,"mdbase.yaml"),t=(0,nt.parseYaml)(e);if(!ve(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===mo?"This collection is already mdbase v0.3.":`Expected an mdbase v0.2.x collection, found ${JSON.stringify(n)}.`);let i=ve(t.settings)?t.settings:{},s=typeof i.types_folder=="string"?(0,nt.normalizePath)(i.types_folder):"_types",o=`${s}/`,a=[],c=[],l=[],d=oM(t),u=`${(0,nt.stringifyYaml)(d).trimEnd()} -`;a.push({path:"mdbase.yaml",sourceDigest:jr(e),targetDigest:jr(u),source:e,target:u});let f=new Map,p=new Map;for(let v of r.getMarkdownFiles().filter(P=>P.path.startsWith(o)).sort((P,O)=>P.path.localeCompare(O.path))){let P=await r.cachedRead(v),O=Pt(P);if(!O.hasFrontmatter||O.error)throw new Error(`Cannot migrate ${v.path}: ${(x=O.error)!=null?x:"frontmatter is missing"}.`);let $=sM(v.path,n,O.frontmatter),R=aM(v.path,O.frontmatter),S=cM(v.path,$.target);f.set(R.name,R),p.set(S.name,S);let U=`${mt($.target,O.body)} -`;a.push({path:v.path,sourceDigest:jr(P),targetDigest:jr(U),source:P,target:U}),c.push($.summary),l.push(...$.diagnostics)}if(!c.length)throw new Error(`No v0.2 type files were found in ${s}.`);let y=0,h=0,m=P0(t,n),g=P0(d,mo),_=r.getMarkdownFiles().filter(v=>!v.path.startsWith(o)).filter(v=>!v.path.startsWith(".mdbase/")).sort((v,P)=>v.path.localeCompare(P.path));for(let[v,P]of _.entries()){let O=Pt(await r.cachedRead(P));if(O.error){h+=1;continue}let $=hi(P.path,O.frontmatter,m,f),R=hi(P.path,O.frontmatter,g,p),S=lM(O.frontmatter,$,f),U=dM(O.frontmatter,R,p);(jn($.slice().sort())!==jn(R.slice().sort())||jn(S)!==jn(U))&&l.push({path:P.path,code:"effective_read_changed",message:"The proposed v0.3 types would change this record's resolved types or effective default values.",severity:"lossy"}),y+=1,v>0&&v%250===0&&await new Promise(B=>setTimeout(B,0))}let w=jr(jn({sourceVersion:n,operations:a.map(({path:v,sourceDigest:P,targetDigest:O})=>({path:v,sourceDigest:P,targetDigest:O})),diagnostics:l}));return{planVersion:1,analysisId:w,sourceVersion:n,targetVersion:mo,createdAt:new Date().toISOString(),backupLocation:`.mdbase/migrations/v02-to-v03-${w.slice(0,12)}`,operations:a,typeSummaries:c,diagnostics:l,applicable:!l.some(v=>v.severity==="lossy"),recordFilesRewritten:0,recordsVerified:y,recordsSkipped:h}}async function po(r,e,t){await Fc(r,e,`${JSON.stringify(t,null,2)} +`),this.adoptionMarker=e}async readAdoptionMarker(){if(!await this.app.vault.adapter.exists(co))return null;let e;try{e=JSON.parse(await this.app.vault.adapter.read(co))}catch(t){throw new b("invalid_authority_adoption_checkpoint","The collection-adoption checkpoint is corrupt.")}if(!ZC(e))throw new b("invalid_authority_adoption_checkpoint","The collection-adoption checkpoint is invalid.");return e}async writeAdoptionSnapshot(e){await ji(this.app.vault,".mdbase"),await this.app.vault.adapter.write(lo,JSON.stringify(e))}async readAdoptionSnapshot(e){if(!await this.app.vault.adapter.exists(lo))throw new b("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(lo))}catch(n){throw new b("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 b("authority_adoption_snapshot_mismatch","The fenced authority snapshot does not match its durable checkpoint.");return t}async clearAdoptionCheckpoint(e){await this.app.vault.adapter.exists(co)&&await this.app.vault.adapter.remove(co),await this.app.vault.adapter.exists(lo)&&await this.app.vault.adapter.remove(lo),this.app.secretStorage.setSecret(this.adoptionSecretId(e),""),this.adoptionMarker=null}};function cp(r){let{credential:e,...t}=r;return t}function YC(r){return r instanceof J&&["authority_adoption_expired","authority_adoption_cancelled"].includes(r.code)}function XC(r){if(!Fe(r))return[];let e=r["x-obsidian"];return!Fe(e)||!Fe(e.bases)||!Array.isArray(e.bases.include)?[]:e.bases.include.filter(t=>typeof t=="string")}function QC(r){var i;let e=(i=r.getFiles)==null?void 0:i.call(r);if(e)return e;let t=[],n=s=>{for(let o of s.children)o instanceof oe.TFile?t.push(o):o instanceof oe.TFolder&&n(o)};return n(r.getRoot()),t}function ZC(r){if(!Fe(r)||r.version!==1||!["waiting_for_approval","uploading","fenced","activating","adopted"].includes(String(r.phase))||!Fe(r.session))return!1;let e=r.session;return typeof e.controlUrl=="string"&&typeof e.adoptionId=="string"&&uo.test(e.adoptionId)&&typeof e.verificationUri=="string"&&typeof e.expiresAt=="string"&&Fe(e.requested)&&typeof e.requested.collectionId=="string"&&uo.test(e.requested.collectionId)&&typeof e.requested.displayName=="string"&&typeof e.requested.sourceName=="string"&&e.requested.retainMirror===!0&&(r.manifest_digest===null||typeof r.manifest_digest=="string")&&(r.source_revision===null||typeof r.source_revision=="string")&&(r.source_head===null||Number.isSafeInteger(r.source_head))}var nt=require("obsidian");var mo="0.3.0",eM=new Set(["name","description","display_name_key","strict","path_pattern","filename_pattern","match","fields","extends"]),tM=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 ve(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function Ce(r){return r===void 0?r:JSON.parse(JSON.stringify(r))}function jr(r){return to.digest(r)}function jn(r){return Array.isArray(r)?`[${r.map(jn).join(",")}]`:ve(r)?`{${Object.keys(r).sort().map(e=>`${JSON.stringify(e)}:${jn(r[e])}`).join(",")}}`:JSON.stringify(r)}function hp(r){if(Array.isArray(r))return r.map(hp);if(!ve(r))return r;let e={};for(let[t,n]of Object.entries(r)){let i=hp(n);i!=null&&(Array.isArray(i)&&i.length===0||ve(i)&&Object.keys(i).length===0||(e[t]=i))}return e}function Di(r){return[...new Set(r)]}function rM(r){return ve(r.fields)?Object.values(r.fields).some(e=>ve(e)&&(typeof e.tn_role=="string"||Array.isArray(e.tn_completed_values))):!1}function mp(r,e,t){let n=ve(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)?Ce(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=mp(`${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[d,u]of Object.entries(ve(n.fields)?n.fields:{})){let f=mp(`${r}.${d}`,u,t);c[d]=f.schema,Object.assign(i,f.links),Object.assign(s,f.legacy),o.push(...f.unsupported),ve(u)&&u.required===!0&&l.push(d)}t&&r==="blockedBy[]"&&l.push("uid"),a={type:"object",additionalProperties:Object.keys(c).length===0,properties:c,...l.length?{required:Di(l)}:{}};break}default:a={},o.push(`${r}.type`);break}t&&r==="title"&&(a.minLength=1,a.description="Short summary of the task."),typeof n.description=="string"&&(a.description=n.description),typeof n.min=="number"&&(n.type==="string"?a.minLength=n.min:n.type==="list"?a.minItems=n.min:a.minimum=n.min),typeof n.max=="number"&&(n.type==="string"?a.maxLength=n.max:n.type==="list"?a.maxItems=n.max:a.maximum=n.max),typeof n.min_length=="number"&&(a.minLength=n.min_length),typeof n.max_length=="number"&&(a.maxLength=n.max_length),typeof n.pattern=="string"&&(a.pattern=n.pattern),n.deprecated===!0&&(a.deprecated=!0),n.default!==void 0&&(a.default=Ce(n.default)),n.computed!==void 0&&o.push(`${r}.computed`);for(let[c,l]of Object.entries(n)){let d=t&&(c==="tn_role"||c==="tn_completed_values");(!tM.has(c)||(c==="tn_role"||c==="tn_completed_values")&&!d)&&(s[`${r}.${c}`]=Ce(l))}return{schema:a,links:i,legacy:s,unsupported:o}}function fo(r,e,t,n){let i=ve(r[e])?r[e]:{},s=ve(i.set)?i.set:{};s[t]=n,i.set=s,r[e]=i}function nM(r,e,t){if(t==="now")fo(r,"on_create",e,{now:!0});else if(t==="now_on_write")fo(r,"on_update",e,{now:!0});else if(t==="uuid")fo(r,"on_create",e,{uuid:!0});else if(t==="ulid")fo(r,"on_create",e,{ulid:!0});else if(ve(t)&&t.transform==="slugify"&&typeof t.from=="string")fo(r,"on_create",e,{slugify:t.from});else return!1;return!0}function iM(r){var t;let e=r.match(/^(.*\/)?\{title\}\.md$/);return e?{runtime:"tasknotes",template:"{{title}}",folder:((t=e[1])!=null?t:"").replace(/\/$/,""),generated_by:"tasknotes.filename.create"}:{runtime:"tasknotes",template:r,generated_by:"tasknotes.filename.create"}}function sM(r,e,t){var P;if(t.kind==="mdbase.type"||t.schema!==void 0)throw new Error(`${r} already looks like a v0.3 type.`);if(typeof t.name!="string"||!ve(t.fields))throw new Error(`${r} is not a v0.2 type with a name and fields.`);let n=rM(t),i=t.name.trim().toLowerCase(),s={type:{const:i}},o=[],a={},c={},l=[],d={},u={},f=[],p=[],y={},h={},m={};for(let[O,A]of Object.entries(t.fields)){let R=ve(A)?A:{},$=mp(O,R,n);s[O]=$.schema,Object.assign(c,$.links),Object.assign(u,$.legacy),f.push(...$.unsupported),R.required===!0&&o.push(O),R.default!==void 0&&(a[O]=Ce(R.default)),R.unique===!0&&l.push({field:O,scope:"collection"}),R.generated!==void 0&&nM(d,O,R.generated)&&p.push(O),typeof R.tn_role=="string"&&(y[R.tn_role]=O),Array.isArray(R.tn_completed_values)&&(h.completed_values=Ce(R.tn_completed_values))}a.status!==void 0&&(h.default=Ce(a.status)),a.priority!==void 0&&(m.default=Ce(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,_={...g?{display:{name_field:g}}:{},read_defaults:a,links:c,unique:l};typeof t.path_pattern=="string"&&(_.path=n?iM(t.path_pattern):{pattern:t.path_pattern});let w={};for(let[O,A]of Object.entries(t))eM.has(O)||(w[O]=Ce(A));Object.keys(u).length&&(w.fields=u);let x=hp({kind:"mdbase.type",name:i,version:1,description:typeof t.description=="string"?t.description:void 0,match:ve(t.match)?Ce(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:Di(o)}:{}}},collection:_,lifecycle:d,...n?{"x-tasknotes":{contract:"tasknotes.task",version:1,field_roles:y,status:h,priority:m,archive:{tags_field:(P=y.tags)!=null?P:"tags",archived_tag:"archived"}}}:{},...Object.keys(w).length?{"x-legacy-v0.2":w}:{}}),v=[];t.extends!==void 0&&f.push("extends");for(let O of Di(f).sort())v.push({path:r,code:"migration_lossy",message:`${O} cannot be expressed as canonical v0.3 write behavior and was retained as legacy metadata where possible.`,severity:"lossy"});return n&&v.push({path:r,code:"path_policy_runtime_owned",message:"TaskNotes filename behavior is recorded as TaskNotes runtime metadata.",severity:"warning"}),t.strict!==!0&&v.push({path:r,code:"additional_properties_true",message:"The migrated schema allows additional properties because the source type was not strict.",severity:"warning"}),typeof t.display_name_key=="string"&&!g&&v.push({path:r,code:"display_field_missing",message:`The display field '${t.display_name_key}' is not declared, so collection.display was omitted.`,severity:"warning"}),{target:x,summary:{path:r,name:i,fieldsConverted:Object.keys(t.fields).length,requiredFields:Di(o),defaultsMoved:Object.keys(a),generatedFieldsMoved:Di(p),linksMoved:Object.keys(c),taskNotes:n},diagnostics:v}}function oM(r){let e=Ce(r);e.spec_version=mo;let t=ve(e.settings)?e.settings:{};if(e.settings=t,!Array.isArray(t.record_extensions)){let n=Array.isArray(t.extensions)?t.extensions.map(String).map(i=>i.replace(/^\./,"")):[];t.record_extensions=Di(["md",...n])}return Array.isArray(t.explicit_type_keys)||(t.explicit_type_keys=["type","types"]),typeof t.include_subfolders!="boolean"&&(t.include_subfolders=!0),t.validation===void 0&&typeof t.default_validation=="string"&&(t.validation=t.default_validation),t.validation===void 0&&typeof e.default_validation=="string"&&(t.validation=e.default_validation),delete t.default_validation,delete t.extensions,delete e.default_validation,e}function P0(r,e){let t=ve(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 aM(r,e){var n,i;let t={};for(let[s,o]of Object.entries(ve(e.fields)?e.fields:{}))ve(o)&&(t[s]=Ce(o));return{name:typeof e.name=="string"?e.name:(i=(n=r.split("/").pop())==null?void 0:n.replace(/\.md$/,""))!=null?i:"type",fields:t,match:ve(e.match)?Ce(e.match):void 0,filePath:r,specProfile:"v0.2"}}function cM(r,e){var i,s;let t=ve(e.schema)?e.schema:{},n=ve(t.value)?t.value:{};return{name:typeof e.name=="string"?e.name:(s=(i=r.split("/").pop())==null?void 0:i.replace(/\.md$/,""))!=null?s:"type",fields:An(n),match:ve(e.match)?Ce(e.match):void 0,collection:ve(e.collection)?Ce(e.collection):void 0,schema:Ce(n),filePath:r,specProfile:"v0.3"}}function lM(r,e,t){let n=Ce(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]=Ce(a.default))}return n}function dM(r,e,t){var i,s;let n=Ce(r);for(let o of e){let a=t.get(o);if(a)for(let[c,l]of Object.entries((s=(i=a.collection)==null?void 0:i.read_defaults)!=null?s:{}))c in n||(n[c]=Ce(l))}return n}async function uM(r,e){let t=(0,nt.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 nt.TFolder)){if(s)throw new Error(`A file blocks folder ${n}.`);await r.adapter.exists(n)||await r.createFolder(n)}}}async function Fc(r,e,t){let n=(0,nt.normalizePath)(e),i=n.lastIndexOf("/");if(i>=0&&await uM(r,n.slice(0,i)),n.startsWith(".mdbase/")){await r.adapter.write(n,t);return}let s=r.getAbstractFileByPath(n);if(s instanceof nt.TFolder)throw new Error(`A folder blocks file ${n}.`);s instanceof nt.TFile?await r.modify(s,t):await r.create(n,t)}async function ho(r,e){let t=(0,nt.normalizePath)(e),n=r.getAbstractFileByPath(t);if(n instanceof nt.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 I0(r){var x;let e=await ho(r,"mdbase.yaml"),t=(0,nt.parseYaml)(e);if(!ve(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===mo?"This collection is already mdbase v0.3.":`Expected an mdbase v0.2.x collection, found ${JSON.stringify(n)}.`);let i=ve(t.settings)?t.settings:{},s=typeof i.types_folder=="string"?(0,nt.normalizePath)(i.types_folder):"_types",o=`${s}/`,a=[],c=[],l=[],d=oM(t),u=`${(0,nt.stringifyYaml)(d).trimEnd()} +`;a.push({path:"mdbase.yaml",sourceDigest:jr(e),targetDigest:jr(u),source:e,target:u});let f=new Map,p=new Map;for(let v of r.getMarkdownFiles().filter(P=>P.path.startsWith(o)).sort((P,O)=>P.path.localeCompare(O.path))){let P=await r.cachedRead(v),O=Pt(P);if(!O.hasFrontmatter||O.error)throw new Error(`Cannot migrate ${v.path}: ${(x=O.error)!=null?x:"frontmatter is missing"}.`);let A=sM(v.path,n,O.frontmatter),R=aM(v.path,O.frontmatter),$=cM(v.path,A.target);f.set(R.name,R),p.set($.name,$);let M=`${mt(A.target,O.body)} +`;a.push({path:v.path,sourceDigest:jr(P),targetDigest:jr(M),source:P,target:M}),c.push(A.summary),l.push(...A.diagnostics)}if(!c.length)throw new Error(`No v0.2 type files were found in ${s}.`);let y=0,h=0,m=P0(t,n),g=P0(d,mo),_=r.getMarkdownFiles().filter(v=>!v.path.startsWith(o)).filter(v=>!v.path.startsWith(".mdbase/")).sort((v,P)=>v.path.localeCompare(P.path));for(let[v,P]of _.entries()){let O=Pt(await r.cachedRead(P));if(O.error){h+=1;continue}let A=hi(P.path,O.frontmatter,m,f),R=hi(P.path,O.frontmatter,g,p),$=lM(O.frontmatter,A,f),M=dM(O.frontmatter,R,p);(jn(A.slice().sort())!==jn(R.slice().sort())||jn($)!==jn(M))&&l.push({path:P.path,code:"effective_read_changed",message:"The proposed v0.3 types would change this record's resolved types or effective default values.",severity:"lossy"}),y+=1,v>0&&v%250===0&&await new Promise(V=>setTimeout(V,0))}let w=jr(jn({sourceVersion:n,operations:a.map(({path:v,sourceDigest:P,targetDigest:O})=>({path:v,sourceDigest:P,targetDigest:O})),diagnostics:l}));return{planVersion:1,analysisId:w,sourceVersion:n,targetVersion:mo,createdAt:new Date().toISOString(),backupLocation:`.mdbase/migrations/v02-to-v03-${w.slice(0,12)}`,operations:a,typeSummaries:c,diagnostics:l,applicable:!l.some(v=>v.severity==="lossy"),recordFilesRewritten:0,recordsVerified:y,recordsSkipped:h}}async function po(r,e,t){await Fc(r,e,`${JSON.stringify(t,null,2)} `)}async function O0(r,e,t={}){if(e.planVersion!==1||e.targetVersion!==mo)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 ho(r,s.path);if(jr(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 Fc(r,`${e.backupLocation}/files/${s.path}`,s.source);await po(r,n,i),i.status="applying",await po(r,n,i);try{for(let s of e.operations){let o=await ho(r,s.path);if(jr(o)!==s.sourceDigest)throw new Error(`${s.path} changed during migration.`);i.written.push(s.path),await po(r,n,i),await Fc(r,s.path,s.target);let a=await ho(r,s.path);if(jr(a)!==s.targetDigest)throw new Error(`${s.path} did not verify after write.`)}return i.status="applied",i.completed_at=new Date().toISOString(),await po(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 Fc(r,a,c.source),jr(await ho(r,a))!==c.sourceDigest&&o.push(a)}catch(l){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 po(r,n,i)}catch(a){}return{applied:!1,restored:o.length===0,manifestPath:n,written:[...i.written],error:i.error}}}var Vc=require("obsidian");function Pe(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function mr(r){return JSON.parse(JSON.stringify(r))}var fM=new Set(["file","formula","this"]);function pM(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(fM.has(e.toLowerCase()))throw new Error(`Type name '${e}' is reserved.`);return e}function yp(){return{specProfile:"v0.3",originalFrontmatter:{},name:"",description:"",extendsType:"",displayNameKey:"",strictMode:!1,pathPattern:"",filenamePattern:"",matchPathGlob:"",matchFieldsPresent:"",matchWhere:"",fields:[{name:"title",definition:{type:"string",required:!0}}],body:`# Type Describe the type and intended usage.`,extraFrontmatter:{}}}function hM(r){return Pe(r)?Object.entries(r).filter(e=>Pe(e[1])).map(([e,t])=>({name:e,definition:mr(t)})):[]}function mM(r){return Object.fromEntries(r.map(e=>[e.name,e.definition]))}function yM(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 Uc(r,e,t){let n=r.kind==="mdbase.type",i=n&&Pe(r.schema)?r.schema:{},s=Pe(i.value)?i.value:{},o=typeof i.ref=="string"?i.ref:"",a=n&&Pe(r.collection)?r.collection:{},c=Pe(a.display)?a.display:{},l=Pe(a.path)?a.path:{},d=hM(n?An(s):r.fields);n&&gM(d,a.links);let u=Pe(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"]),y={};for(let[m,g]of Object.entries(r))p.has(m)||(y[m]=mr(g));let h="";if(u.where!==void 0)try{h=(0,Vc.stringifyYaml)(u.where).trim()}catch(m){h=""}return{specProfile:n?"v0.3":"v0.2",originalFrontmatter:mr(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 u.path_glob=="string"?u.path_glob:"",matchFieldsPresent:Array.isArray(u.fields_present)?u.fields_present.map(String).join(", "):"",matchWhere:h,fields:d.length||o?d:yp().fields,body:e.trim()||`# ${t} @@ -186,12 +186,12 @@ Type definition for ${t}.`,extraFrontmatter:y,...o?{readOnlyReason:`This type us `;var qn="mdbase-workspace-view",_M=["string","integer","number","boolean","date","datetime","time","enum","link","list","object","any"];function Dn(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function gp(r){return JSON.parse(JSON.stringify(r))}function C0(r){return typeof r.type=="string"?r.type:"any"}function bM(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 M0(r,e,t){Object.defineProperty(r,e,{configurable:!0,enumerable:!0,writable:!0,value:t})}function wM(r,e){if(!r)return["A new type definition will be created."];let t=[];r.name!==e.name&&t.push(`Rename type from ${r.name} to ${e.name}.`),(r.matchPathGlob!==e.matchPathGlob||r.matchFieldsPresent!==e.matchFieldsPresent||r.matchWhere!==e.matchWhere)&&t.push("Membership rules changed; different records may match this type.");let n=new Map(r.fields.map(c=>[c.name,c])),i=new Map(e.fields.map(c=>[c.name,c])),s=[...n.keys()].filter(c=>!i.has(c)),o=[...i.keys()].filter(c=>!n.has(c));o.length&&t.push(`Add ${o.length} field${o.length===1?"":"s"}: ${o.join(", ")}.`),s.length&&t.push(`Remove ${s.length} field${s.length===1?"":"s"}: ${s.join(", ")}.`);let a=[...i.entries()].filter(([c,l])=>{var d;return l.definition.required===!0&&((d=n.get(c))==null?void 0:d.definition.required)!==!0}).map(([c])=>c);return a.length&&t.push(`New required fields may invalidate records: ${a.join(", ")}.`),t.length||t.push("Metadata, schema details, or documentation changed."),t}function Ot(r,e,t,n,i={}){var l;let s=r.createDiv({cls:"mdbase-form-row"}),o=s.createEl("label",{text:e}),a=`mdbase-${Math.random().toString(36).slice(2)}`;o.htmlFor=a,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.value=t,c.placeholder=(l=i.placeholder)!=null?l:"",c.addEventListener("input",()=>n(c.value)),c}function Me(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 vM(r){if(r<1e3)return String(r);let e=r<1e4?1:0;return`${(r/1e3).toFixed(e)}k`}var Bc=class extends Ee.ItemView{constructor(t,n){super(t);this.host=n;this.destination="types";this.editorMode="design";this.schema=null;this.query="";this.selectedPath=null;this.model=null;this.originalModel=null;this.yamlDraft="";this.dirty=!1;this.busy=!1;this.migrationPlan=null;this.allowLossy=!1;this.mirrorStatus=null;this.mirrorPreview=null;this.mirrorProgress=null;this.transientMessage="";this.issueQuery="";this.issueSeverity="all";this.issueLimit=250;this.enrollmentVerification="";this.enrollmentAbort=null}getViewType(){return qn}getDisplayText(){return"mdbase"}getIcon(){return qi}async onOpen(){this.containerEl.addClass("mdbase-workspace"),await this.refresh(!0)}async onClose(){var t;(t=this.enrollmentAbort)==null||t.abort(),this.enrollmentAbort=null}async refresh(t=!1){try{this.schema=await this.host.loadWorkspaceSchema(t),this.selectedPath&&!this.typeEntries().some(n=>n.filePath===this.selectedPath)&&(this.selectedPath=null,this.model=null,this.originalModel=null),!this.selectedPath&&this.typeEntries().length&&!Ee.Platform.isMobile&&(this.selectedPath=this.typeEntries()[0].filePath),this.selectedPath&&(!this.model||t)&&await this.selectType(this.selectedPath,!1),this.destination==="sync"&&await this.refreshMirrorStatus(),this.render()}catch(n){this.transientMessage=n instanceof Error?n.message:String(n),this.render()}}showDestination(t){this.destination=t,t==="sync"?this.refreshMirrorStatus().then(()=>this.render()):this.render()}typeEntries(){return this.schema?[...this.schema.types.values()].sort((t,n)=>t.name.localeCompare(n.name)):[]}render(){let t=this.containerEl;t.empty(),t.addClass("mdbase-workspace");let n=t.createDiv({cls:"mdbase-shell"});this.renderTopbar(n),this.transientMessage&&n.createDiv({cls:"mdbase-inline-message",text:this.transientMessage}).setAttr("role","status");let i=n.createDiv({cls:"mdbase-workspace-content"});this.destination==="types"?this.renderTypes(i):this.destination==="sync"?this.renderSync(i):this.renderIssues(i)}renderTopbar(t){let n=t.createDiv({cls:"mdbase-topbar"}),i=n.createDiv({cls:"mdbase-identity"}),s=i.createSpan({cls:"mdbase-mark"});s.setAttr("aria-hidden","true"),(0,Ee.setIcon)(s,qi),i.createSpan({cls:"mdbase-title",text:"mdbase"});let o=n.createDiv({cls:"mdbase-nav"});o.setAttr("role","tablist");for(let[a,c]of[["types","Types"],["sync","Sync"],["issues","Issues"]]){let l=o.createEl("button",{text:c});if(l.addClass("mdbase-nav-button"),l.setAttr("role","tab"),l.setAttr("aria-selected",String(this.destination===a)),this.destination===a&&l.addClass("is-active"),a==="issues"&&this.host.getIssues().length){let d=this.host.getIssues().length;l.createSpan({cls:"mdbase-count",text:vM(d)}).setAttr("title",`${d} issues`)}l.onclick=()=>this.showDestination(a)}}renderTypes(t){if(!this.schema){let i=t.createDiv({cls:"mdbase-empty-state"});i.createEl("h2",{text:"Start an mdbase collection"}),i.createEl("p",{text:"Initialize this vault as a local v0.3 collection, or use Sync to connect an empty vault to a collection authority."});let s=i.createDiv({cls:"mdbase-actions"}),o=s.createEl("button",{text:"Initialize local collection"});o.addClass("mod-cta"),o.disabled=this.busy||this.host.getMirrorProfile()!==null,o.onclick=()=>void this.perform(async()=>{await this.host.initializeCollection(),await this.refresh(!0)});let a=s.createEl("button",{text:"Connect collection authority"});a.onclick=()=>this.showDestination("sync");return}this.schema.config.spec_version.startsWith("0.2.")&&this.renderLegacyBanner(t);let n=t.createDiv({cls:"mdbase-types-layout"});this.model&&n.addClass("has-selection"),this.renderTypeList(n),this.renderTypeEditor(n)}renderLegacyBanner(t){var o;let n=t.createDiv({cls:"mdbase-legacy-banner"}),i=n.createDiv();i.createEl("strong",{text:`mdbase ${(o=this.schema)==null?void 0:o.config.spec_version} compatibility mode`}),i.createEl("p",{text:"Types are readable and validation remains available, but authoring is disabled until a reviewed v0.3 migration."});let s=n.createEl("button",{text:this.migrationPlan?"Review migration":"Analyze migration"});s.disabled=this.busy||this.host.getMirrorProfile()!==null,s.onclick=()=>void this.perform(async()=>{this.migrationPlan=await this.host.analyzeMigration(),this.render()}),this.host.getMirrorProfile()&&n.createDiv({cls:"mdbase-form-description",text:"Hosted resources must be migrated at the collection authority."}),this.migrationPlan&&this.renderMigrationReview(t,this.migrationPlan)}renderMigrationReview(t,n){let i=t.createDiv({cls:"mdbase-migration-review"}),s=i.createDiv({cls:"mdbase-section-header"});s.createEl("h3",{text:"Migration review"}),s.createSpan({cls:"mdbase-spec-badge",text:`${n.sourceVersion} \u2192 ${n.targetVersion}`});let o=i.createDiv({cls:"mdbase-status-list"});Me(o,"Files replaced",String(n.operations.length)),Me(o,"Type definitions",String(n.typeSummaries.length)),Me(o,"Record reads verified",String(n.recordsVerified)),n.recordsSkipped&&Me(o,"Records skipped",String(n.recordsSkipped)),Me(o,"Record files rewritten","0"),Me(o,"Recovery backup",n.backupLocation);let a=i.createDiv({cls:"mdbase-review-list"});n.diagnostics.length||a.createDiv({cls:"mdbase-review-ok",text:"No migration diagnostics."});for(let u of n.diagnostics.slice(0,250)){let f=a.createDiv({cls:"mdbase-review-item"});f.setAttr("data-severity",u.severity),f.createDiv({cls:"mdbase-review-code",text:`${u.severity} \xB7 ${u.path}`}),f.createDiv({text:u.message})}if(n.diagnostics.length>250&&a.createDiv({cls:"mdbase-form-description",text:`Showing 250 of ${n.diagnostics.length} diagnostics.`}),!n.applicable){let u=i.createEl("label",{cls:"mdbase-consent"}),f=u.createEl("input",{type:"checkbox"});f.checked=this.allowLossy,f.onchange=()=>{this.allowLossy=f.checked,this.render()},u.createSpan({text:"I reviewed the lossy diagnostics and want to apply this migration."})}let c=i.createDiv({cls:"mdbase-actions"}),l=c.createEl("button",{text:"Apply migration"});l.addClass("mod-warning"),l.disabled=this.busy||!n.applicable&&!this.allowLossy,l.onclick=()=>void this.perform(async()=>{await this.host.applyMigration(n,this.allowLossy),this.migrationPlan=null,this.allowLossy=!1,this.model=null,this.originalModel=null,await this.refresh(!0)});let d=c.createEl("button",{text:"Close review"});d.onclick=()=>{this.migrationPlan=null,this.render()}}renderTypeList(t){var d,u,f,p;let n=t.createDiv({cls:"mdbase-type-list-pane"}),i=n.createDiv({cls:"mdbase-pane-header"});i.createEl("h2",{text:"Types"});let s=i.createEl("button");s.setAttr("aria-label","Create type"),(0,Ee.setIcon)(s,"plus"),s.disabled=((u=(d=this.schema)==null?void 0:d.config.spec_version.startsWith("0.2."))!=null?u:!0)||((f=this.host.getMirrorProfile())==null?void 0:f.mode)==="read_only",s.onclick=()=>this.createType();let o=n.createEl("input",{type:"search"});o.addClass("mdbase-type-search"),o.placeholder="Search types",o.setAttr("aria-label","Search types"),o.value=this.query,o.oninput=()=>{this.query=o.value,this.render();let y=this.containerEl.querySelector(".mdbase-type-search");y==null||y.focus(),y==null||y.setSelectionRange(y.value.length,y.value.length)};let a=n.createDiv({cls:"mdbase-type-list"}),c=this.query.trim().toLowerCase(),l=this.typeEntries().filter(y=>{var h;return`${y.name} ${(h=y.description)!=null?h:""} ${y.filePath}`.toLowerCase().includes(c)});if(!l.length){a.createDiv({cls:"mdbase-empty-list",text:c?"No matching types.":"No type definitions."});return}for(let y of l){let h=a.createEl("button",{cls:"mdbase-type-row"});y.filePath===this.selectedPath&&h.addClass("is-active"),h.setAttr("aria-current",y.filePath===this.selectedPath?"true":"false"),h.createSpan({cls:"mdbase-type-name",text:y.name}),h.createSpan({cls:"mdbase-type-meta",text:`${Object.keys(y.fields).length} fields \xB7 ${(p=y.specProfile)!=null?p:"v0.2"}`}),h.onclick=()=>void this.selectType(y.filePath)}}renderTypeEditor(t){var h,m,g,_;let n=t.createDiv({cls:"mdbase-type-editor-pane"});if(!this.model){let w=n.createDiv({cls:"mdbase-empty-state"});w.createEl("h2",{text:"Choose a type"}),w.createEl("p",{text:"Select a type definition from the list to inspect or edit it."});return}let i=((h=this.host.getMirrorProfile())==null?void 0:h.mode)==="read_only",s=this.model.specProfile==="v0.2"||i||!!this.model.readOnlyReason,o=(m=this.model.readOnlyReason)!=null?m:i?"This mirror has read-only access. Re-enroll it with write access before editing types.":"This v0.2 type is read-only. Review and apply a collection migration before editing.",a=n.createDiv({cls:"mdbase-editor-header"}),c=a.createEl("button",{cls:"mdbase-mobile-back"});c.setAttr("aria-label","Back to type list"),(0,Ee.setIcon)(c,"arrow-left"),c.onclick=()=>{if(this.dirty){new Ee.Notice("Save or discard the current type changes before going back.");return}this.selectedPath=null,this.model=null,this.originalModel=null,this.render()};let l=a.createDiv(),d=l.createDiv({cls:"mdbase-editor-title-line"});d.createEl("h2",{text:this.model.name||"Untitled type"}),d.createSpan({cls:"mdbase-spec-badge",text:(g=this.model.specProfile)!=null?g:"v0.2"}),this.dirty&&d.createSpan({cls:"mdbase-dirty",text:"Unsaved"}),l.createDiv({cls:"mdbase-editor-path",text:(_=this.selectedPath)!=null?_:"New type"});let u=a.createDiv({cls:"mdbase-editor-actions"});if(this.selectedPath){let w=u.createEl("button",{text:"Open source"});w.onclick=()=>void this.host.openFileByPath(this.selectedPath)}let f=u.createEl("button",{text:"Save"});f.addClass("mod-cta"),f.disabled=s||!this.dirty||this.busy,f.onclick=()=>void this.saveCurrentType(),s&&n.createDiv({cls:"mdbase-readonly-note",text:o});let p=n.createDiv({cls:"mdbase-mode-switch"});p.setAttr("role","tablist");for(let[w,x]of[["design","Design"],["yaml","YAML"]]){let v=p.createEl("button",{text:x});v.setAttr("role","tab"),v.setAttr("aria-selected",String(this.editorMode===w)),this.editorMode===w&&v.addClass("is-active"),v.onclick=()=>this.switchEditorMode(w)}let y=n.createDiv({cls:"mdbase-editor-document"});this.editorMode==="design"?this.renderDesignEditor(y,this.model,s):this.renderYamlEditor(y,s)}renderDesignEditor(t,n,i){let s=t.createEl("section",{cls:"mdbase-editor-section"});s.createEl("h3",{text:"Identity"});let o=Ot(s,"Name",n.name,P=>{n.name=P,this.markDirty()},{description:"Stable type name used by collection records."});o.disabled=i;let a=Ot(s,"Description",n.description,P=>{n.description=P,this.markDirty()},{multiline:!0});a.disabled=i;let c=Ot(s,"Display field",n.displayNameKey,P=>{n.displayNameKey=P,this.markDirty()},{placeholder:"title"});c.disabled=i;let l=s.createEl("label",{cls:"mdbase-checkbox-row"}),d=l.createEl("input",{type:"checkbox"});d.checked=n.strictMode===!0,d.disabled=i,d.onchange=()=>{n.strictMode=d.checked,this.markDirty()},l.createSpan({text:"Reject undeclared fields"});let u=t.createEl("section",{cls:"mdbase-editor-section"});u.createEl("h3",{text:"Membership"});let f=Ot(u,"Path glob",n.matchPathGlob,P=>{n.matchPathGlob=P,this.markDirty()},{placeholder:"Projects/**/*.md"});f.disabled=i;let p=Ot(u,"Fields present",n.matchFieldsPresent,P=>{n.matchFieldsPresent=P,this.markDirty()},{description:"Comma-separated frontmatter keys."});p.disabled=i;let y=Ot(u,"Where",n.matchWhere,P=>{n.matchWhere=P,this.markDirty()},{multiline:!0,description:"YAML predicate, including contains and nested equality conditions.",placeholder:`tags: - contains: task`});y.disabled=i;let h=t.createEl("section",{cls:"mdbase-editor-section"}),m=h.createDiv({cls:"mdbase-section-header"});m.createEl("h3",{text:"Fields"});let g=m.createEl("button",{text:"Add field"});g.disabled=i,g.onclick=()=>{n.fields.push({name:"",definition:{type:"string"}}),this.markDirty(!0)};let _=h.createDiv({cls:"mdbase-fields"});for(let[P,O]of n.fields.entries())this.renderFieldRow(_,O,P,i);n.fields.length||_.createDiv({cls:"mdbase-empty-list",text:"No fields declared."});let w=t.createEl("section",{cls:"mdbase-editor-section"});w.createEl("h3",{text:"Placement"});let x=Ot(w,"Path pattern",n.pathPattern,P=>{n.pathPattern=P,this.markDirty()},{placeholder:"Notes/{title}.md"});x.disabled=i;let v=t.createEl("section",{cls:"mdbase-editor-section mdbase-change-review"});if(v.createEl("h3",{text:"Change review"}),!this.dirty)v.createEl("p",{text:"No pending changes."});else{let P=v.createEl("ul");for(let O of wM(this.originalModel,n))P.createEl("li",{text:O})}}renderFieldRow(t,n,i,s){this.renderFieldDefinition(t,n.definition,{name:n.name,nameLabel:`Field ${i+1} name`,onNameInput:o=>{n.name=o,this.markDirty()},required:n.definition.required===!0,onRequiredChange:o=>{n.definition.required=o,this.markDirty()},onRemove:()=>{var o;(o=this.model)==null||o.fields.splice(i,1),this.markDirty(!0)},readOnly:s,depth:0})}renderFieldDefinition(t,n,i){var d;let s=t.createDiv({cls:"mdbase-field-node"});s.setAttr("data-depth",String(i.depth));let o=s.createDiv({cls:"mdbase-field-row"});if(i.staticLabel)o.createDiv({cls:"mdbase-field-role",text:i.staticLabel});else{let u=o.createEl("input",{type:"text",cls:"mdbase-field-name-control"});u.setAttr("aria-label",i.nameLabel),u.placeholder="fieldName",u.value=(d=i.name)!=null?d:"",u.disabled=i.readOnly,i.onNameInput&&(u.oninput=()=>{var f;return(f=i.onNameInput)==null?void 0:f.call(i,u.value)}),i.onNameCommit&&(u.onchange=()=>{var f;return(f=i.onNameCommit)==null?void 0:f.call(i,u.value,u)})}let a=o.createEl("select",{cls:"mdbase-field-type-control"});a.setAttr("aria-label",`${i.name||i.staticLabel||"Field"} type`);for(let u of _M){let f=u==="any"?"Any value":u[0].toUpperCase()+u.slice(1);a.createEl("option",{value:u,text:f})}a.value=C0(n),a.disabled=i.readOnly,a.onchange=()=>{n.type=a.value,a.value==="list"&&!Dn(n.items)&&(n.items={type:"string"}),a.value==="object"&&!Dn(n.fields)&&(n.fields={}),a.value==="enum"&&!Array.isArray(n.values)&&(n.values=[]),this.markDirty(!0)};let c=o.createEl("input",{type:"text",cls:"mdbase-field-description-control"});if(c.setAttr("aria-label",`${i.name||i.staticLabel||"Field"} description`),c.placeholder="Description",c.value=typeof n.description=="string"?n.description:"",c.disabled=i.readOnly,c.oninput=()=>{c.value?n.description=c.value:delete n.description,this.markDirty()},i.onRequiredChange){let u=o.createEl("label",{cls:"mdbase-field-required"}),f=u.createEl("input",{type:"checkbox"});f.checked=i.required===!0,f.disabled=i.readOnly,f.onchange=()=>{var p;return(p=i.onRequiredChange)==null?void 0:p.call(i,f.checked)},u.createSpan({text:"Required"})}if(i.onRemove){let u=o.createEl("button",{cls:"mdbase-field-remove"});u.setAttr("aria-label",`Remove ${i.name||i.staticLabel||"field"}`),(0,Ee.setIcon)(u,"trash-2"),u.disabled=i.readOnly,u.onclick=i.onRemove}let l=C0(n);l==="enum"&&this.renderEnumFieldDetails(s,n,i),l==="link"&&this.renderLinkFieldDetails(s,n,i),l==="list"&&this.renderListFieldDetails(s,n,i),l==="object"&&this.renderObjectFieldDetails(s,n,i)}renderEnumFieldDetails(t,n,i){let s=t.createDiv({cls:"mdbase-field-details mdbase-field-options"}),o=s.createEl("label",{text:"Allowed values"}),a=s.createEl("input",{type:"text"});a.setAttr("aria-label",`${i.name||i.staticLabel||"Enum"} allowed values`),a.placeholder="draft, published, archived",a.value=Array.isArray(n.values)?n.values.map(String).join(", "):"",a.disabled=i.readOnly,a.oninput=()=>{n.values=a.value.split(",").map(c=>c.trim()).filter(Boolean),this.markDirty()},o.htmlFor=a.id=`mdbase-${Math.random().toString(36).slice(2)}`}renderLinkFieldDetails(t,n,i){let s=t.createDiv({cls:"mdbase-field-details mdbase-field-options"}),o=s.createEl("label",{text:"Target type"}),a=s.createEl("input",{type:"text"});a.setAttr("aria-label",`${i.name||i.staticLabel||"Link"} target type`),a.placeholder="Any type",a.value=typeof n.target=="string"?n.target:"",a.disabled=i.readOnly,a.oninput=()=>{a.value.trim()?n.target=a.value.trim():delete n.target,this.markDirty()},o.htmlFor=a.id=`mdbase-${Math.random().toString(36).slice(2)}`;let c=s.createEl("label",{cls:"mdbase-field-required"}),l=c.createEl("input",{type:"checkbox"});l.checked=n.validate_exists===!0,l.disabled=i.readOnly,l.onchange=()=>{n.validate_exists=l.checked,this.markDirty()},c.createSpan({text:"Validate target exists"})}renderListFieldDetails(t,n,i){let s=t.createDiv({cls:"mdbase-field-children"});s.createDiv({cls:"mdbase-field-children-label",text:"List items"});let o=Dn(n.items)?n.items:{type:"any"};!Dn(n.items)&&!i.readOnly&&(n.items=o),this.renderFieldDefinition(s,o,{staticLabel:"Item",nameLabel:"List item",readOnly:i.readOnly,depth:i.depth+1})}renderObjectFieldDetails(t,n,i){let s=t.createDiv({cls:"mdbase-field-children"}),o=s.createDiv({cls:"mdbase-field-children-header"});o.createDiv({cls:"mdbase-field-children-label",text:"Object fields"});let a=o.createEl("button",{text:"Add nested field"});a.disabled=i.readOnly;let c=Dn(n.fields)?n.fields:{};!Dn(n.fields)&&!i.readOnly&&(n.fields=c),a.onclick=()=>{let u=bM(c);M0(c,u,{type:"string"}),this.markDirty(!0)};let l=s.createDiv({cls:"mdbase-nested-fields"}),d=Object.entries(c).filter(u=>Dn(u[1]));if(!d.length){l.createDiv({cls:"mdbase-empty-list",text:"No nested fields."});return}for(let[u,f]of d){let p=u;this.renderFieldDefinition(l,f,{name:p,nameLabel:`${p} nested field name`,onNameCommit:(y,h)=>{let m=y.trim();if(!m){new Ee.Notice("Nested field name is required."),h.value=p;return}if(m!==p&&Object.prototype.hasOwnProperty.call(c,m)){new Ee.Notice(`Nested field already exists: ${m}`),h.value=p;return}m!==p&&(delete c[p],M0(c,m,f),p=m,this.markDirty())},required:f.required===!0,onRequiredChange:y=>{f.required=y,this.markDirty()},onRemove:()=>{delete c[p],this.markDirty(!0)},readOnly:i.readOnly,depth:i.depth+1})}}renderYamlEditor(t,n){let i=t.createEl("section",{cls:"mdbase-editor-section mdbase-yaml-section"});i.createEl("h3",{text:"Canonical type document"}),i.createEl("p",{cls:"mdbase-form-description",text:"Unknown v0.3 extensions are preserved. Invalid YAML is never normalized or saved."});let s=i.createEl("textarea",{cls:"mdbase-yaml-editor"});s.setAttr("aria-label","Type definition YAML"),s.value=this.yamlDraft,s.disabled=n,s.spellcheck=!1,s.oninput=()=>{this.yamlDraft=s.value,this.markDirty(!1)}}renderSync(t){var y,h,m,g,_,w,x,v,P,O;let n=t.createDiv({cls:"mdbase-sync-document"}),i=n.createDiv({cls:"mdbase-document-header"});i.createEl("h2",{text:"Sync"}),i.createEl("p",{text:"Connect this vault to a collection authority and keep ordinary Markdown mirrored locally."});let s=this.host.getMirrorProfile();if(!s){this.renderEnrollment(n);return}let o=n.createEl("section",{cls:"mdbase-editor-section"});o.createEl("h3",{text:"Collection authority"});let a=o.createDiv({cls:"mdbase-status-list"});if(Me(a,"Name",s.name),Me(a,"Collection",s.collectionId),Me(a,"Access",s.mode==="read_write"?"Read and write":"Read only"),Me(a,"Provider",s.syncUrl),Me(a,"State",(h=(y=this.mirrorStatus)==null?void 0:y.state.replace(/_/g," "))!=null?h:"Checking"),Me(a,"Last synced",(g=(m=this.mirrorStatus)==null?void 0:m.last_synced_at)!=null?g:"Never"),this.mirrorProgress){let $=this.mirrorProgress.total,R=o.createEl("progress");R.max=$!=null?$:1,R.value=$==null?0:this.mirrorProgress.completed,$==null&&R.removeAttribute("value"),o.createDiv({cls:"mdbase-progress-label",text:`${this.mirrorProgress.phase}: ${this.mirrorProgress.completed}${$==null?"":` of ${$}`}`});let S=o.createEl("button",{text:"Stop safely"});S.onclick=()=>{this.host.connectSync.cancelSync(),this.transientMessage="Stopping after the current action boundary\u2026",this.render()}}let c=o.createDiv({cls:"mdbase-actions"}),l=c.createEl("button",{text:"Preview"});l.disabled=this.busy,l.onclick=()=>void this.perform(async()=>{this.mirrorPreview=await this.host.connectSync.preview(),this.transientMessage=this.mirrorPreview.entries.length?"Review the engine plan below, then sync when ready.":"No content effects are needed; confirm the sync checkpoint when ready.",this.render()});let d=(w=(_=this.mirrorPreview)==null?void 0:_.plan.actions.filter($=>$.command!=="advance_checkpoint").length)!=null?w:0,u=((v=(x=this.mirrorPreview)==null?void 0:x.plan.summary.blocking_issues)!=null?v:0)>0,f=c.createEl("button",{text:this.mirrorPreview?d?`Sync ${d} ${d===1?"outcome":"outcomes"}`:"Confirm sync checkpoint":"Review before syncing"});f.addClass("mod-cta"),f.disabled=this.busy||!this.mirrorPreview||u,f.onclick=()=>void this.perform(async()=>{var R,S;let $=await this.host.connectSync.sync(this.mirrorPreview,U=>{this.mirrorProgress=U,this.render()});this.mirrorStatus=await this.host.connectSync.status(),this.mirrorPreview=await this.host.connectSync.preview(),this.mirrorProgress=null,this.transientMessage=$.status==="applied"?"Sync completed and the local checkpoint was verified.":$.status==="attention"?"Sync checkpointed completed actions and recorded the items that need attention.":$.status==="cancelled"?`Sync stopped safely after ${$.applied} actions; ${$.pending} remain pending.`:$.status==="stale"?"The reviewed plan became stale. Review the new engine plan before syncing again.":`Sync stopped at a durable action boundary: ${(S=(R=$.failure)==null?void 0:R.message)!=null?S:$.status}.`,await this.refresh(!0)}),this.mirrorPreview&&this.renderMirrorPreview(n,this.mirrorPreview),(P=this.mirrorStatus)!=null&&P.conflicts.length&&this.renderConflicts(n,this.mirrorStatus),(O=this.mirrorStatus)!=null&&O.local_issues.length&&this.renderLocalMirrorIssues(n,this.mirrorStatus);let p=n.createEl("section",{cls:"mdbase-editor-section"});p.createEl("h3",{text:"Mirror ownership"}),p.createEl("p",{text:"Use this plugin as the only sync owner for this vault. Obsidian protects concurrent operations inside the app; a separate desktop mirror process cannot share that mobile-safe lease."})}renderEnrollment(t){if(this.schema||this.host.connectSync.getAdoptionMarker()){this.renderLocalAdoption(t);return}let n=t.createEl("section",{cls:"mdbase-editor-section mdbase-enrollment"});if(n.createEl("h3",{text:"Connect collection authority"}),n.createEl("p",{text:"Connect will open an approval page. Credentials are stored in Obsidian's secret store and never written into this vault."}),this.enrollmentVerification){let u=n.createDiv({cls:"mdbase-approval-link"});u.createSpan({text:"Approval page: "});let f=u.createEl("a",{text:"Open Connect",href:this.enrollmentVerification});f.setAttr("target","_blank"),f.setAttr("rel","noopener noreferrer")}let i="https://connect.mdbase.dev",s="Obsidian",o="",a="read_write";Ot(n,"Connect URL",i,u=>{i=u},{placeholder:"https://connect.mdbase.dev"}),Ot(n,"Mirror name",s,u=>{s=u}),Ot(n,"Collection ID",o,u=>{o=u},{description:"Optional. Leave blank to choose during approval."});let c=n.createDiv({cls:"mdbase-form-row"});c.createEl("label",{text:"Access"});let l=c.createEl("select");l.createEl("option",{value:"read_write",text:"Read and write"}),l.createEl("option",{value:"read_only",text:"Read only"}),l.value=a,l.onchange=()=>{a=l.value==="read_only"?"read_only":"read_write"};let d=n.createEl("button",{text:"Open Connect approval"});d.addClass("mod-cta"),d.disabled=this.busy,d.onclick=()=>void this.perform(async()=>{var f;(f=this.enrollmentAbort)==null||f.abort();let u=new AbortController;this.enrollmentAbort=u;try{await this.host.connectSync.enroll({controlUrl:i,mirrorName:s,mode:a,...o.trim()?{collectionId:o.trim()}:{}},{signal:u.signal,onVerification:p=>{this.enrollmentVerification=p.verificationUri,this.transientMessage="Approve the mirror in the Connect page. This view will keep waiting securely.",window.open(p.verificationUri,"_blank","noopener,noreferrer"),this.render()},onStatus:p=>{this.transientMessage=p.state==="waiting_for_approval"?"Waiting for approval in Connect\u2026":`Connect is retrying enrollment (attempt ${p.attempt}).`,this.render()}}),this.enrollmentVerification="",this.transientMessage="Mirror enrolled. Preview before the first sync.",await this.refreshMirrorStatus(),this.render()}finally{this.enrollmentAbort===u&&(this.enrollmentAbort=null)}})}renderLocalAdoption(t){var d,u;let n=this.host.connectSync.getAdoptionMarker(),i=t.createEl("section",{cls:"mdbase-editor-section mdbase-enrollment"});i.createEl("h3",{text:"Host this local collection"}),i.createEl("p",{text:n?"This vault has a durable adoption checkpoint. Resume it without creating another hosted collection.":"Hosted mdbase will adopt an exact snapshot and become the collection authority. This vault will then continue as a read-write mirror."});let s=this.enrollmentVerification||(n==null?void 0:n.session.verificationUri);if(s){let f=i.createDiv({cls:"mdbase-approval-link"});f.createSpan({text:"Approval page: "});let p=f.createEl("a",{text:"Open Connect",href:s});p.setAttr("target","_blank"),p.setAttr("rel","noopener noreferrer")}let o=(d=n==null?void 0:n.session.controlUrl)!=null?d:"https://connect.mdbase.dev",a=(u=n==null?void 0:n.session.requested.mirrorName)!=null?u:"Obsidian";if(!n)Ot(i,"Connect URL",o,f=>{o=f},{placeholder:"https://connect.mdbase.dev"}),Ot(i,"Mirror name",a,f=>{a=f});else{let f=i.createDiv({cls:"mdbase-status-list"});Me(f,"Collection",n.session.requested.collectionId),Me(f,"Phase",n.phase.replace(/_/g," ")),Me(f,"Connect",n.session.controlUrl)}let c=i.createDiv({cls:"mdbase-inline-message"});c.createEl("strong",{text:"Authority cut-over: "}),c.appendText("once final staging begins, plugin-managed local edits pause until hosted activation is confirmed. The checkpoint survives app restarts and uncertain network responses.");let l=i.createEl("button",{text:n?"Resume adoption":"Approve and host collection"});if(l.addClass("mod-cta"),l.disabled=this.busy,l.onclick=()=>void this.perform(async()=>{var h;(h=this.enrollmentAbort)==null||h.abort();let f=new AbortController;this.enrollmentAbort=f;let p=m=>{this.enrollmentVerification=m.verificationUri,this.transientMessage="Approve the authority move in Connect, then return here. This checkpoint is safe to resume.",this.render()},y=m=>{this.transientMessage=m.state==="waiting_for_approval"?"Waiting for authority-move approval in Connect\u2026":`Connect is retrying (attempt ${m.attempt}).`,this.render()};try{n?await this.host.connectSync.resumeAdoption({signal:f.signal,onVerification:p,onStatus:y}):await this.host.connectSync.adoptLocalCollection({controlUrl:o,mirrorName:a},{signal:f.signal,onVerification:p,onStatus:y}),this.enrollmentVerification="",this.transientMessage="Hosted mdbase is authoritative and this vault is now its read-write mirror.",await this.refresh(!0)}finally{this.enrollmentAbort===f&&(this.enrollmentAbort=null)}}),n&&!["activating","adopted"].includes(n.phase)){let f=i.createEl("button",{text:"Cancel adoption"});f.disabled=this.busy,f.onclick=()=>void this.perform(async()=>{await this.host.connectSync.cancelAdoption(),this.enrollmentVerification="",this.transientMessage="Collection adoption cancelled. This vault remains the local authority.",await this.refresh(!0)})}}renderMirrorPreview(t,n){let i=t.createEl("section",{cls:"mdbase-editor-section"});i.createEl("h3",{text:"Sync preview"});let s=i.createDiv({cls:"mdbase-status-list"});if(Me(s,"Download documents",String(n.download_documents)),Me(s,"Upload documents",String(n.upload_documents)),Me(s,"Unchanged documents",String(n.unchanged_documents)),Me(s,"Plan",n.plan.fingerprint),n.entries.length){let o=i.createEl("ul");for(let a of n.entries.slice(0,200))o.createEl("li",{text:`${a.direction==="attention"?"Attention":a.direction}: ${a.path} \u2014 ${a.detail}`})}if(n.collisions.length){i.createDiv({cls:"mdbase-inline-error",text:`${n.collisions.length} path collision${n.collisions.length===1?"":"s"} must be resolved before sync.`});let o=i.createEl("ul");for(let a of n.collisions.slice(0,100))o.createEl("li",{text:a})}if(n.local_issues.length){i.createDiv({cls:"mdbase-inline-error",text:`${n.local_issues.length} local file${n.local_issues.length===1?"":"s"} cannot be uploaded until its frontmatter is fixed.`});let o=i.createEl("ul");for(let a of n.local_issues.slice(0,100))o.createEl("li",{text:`${a.path}: ${a.message}`})}}renderConflicts(t,n){var s;let i=t.createEl("section",{cls:"mdbase-editor-section"});i.createEl("h3",{text:"Conflicts"});for(let o of n.conflicts){let a=i.createDiv({cls:"mdbase-conflict-row"}),c=a.createDiv();c.createEl("strong",{text:(s=o.path)!=null?s:o.record_id}),c.createDiv({text:o.message});let l=a.createDiv({cls:"mdbase-actions"});for(let d of["local","remote"]){let u=l.createEl("button",{text:d==="local"?"Keep local":"Use remote"});u.disabled=this.busy,u.onclick=()=>void this.perform(async()=>{this.mirrorStatus=await this.host.connectSync.resolveConflict(o.record_id,d),this.render()})}}}renderLocalMirrorIssues(t,n){let i=t.createEl("section",{cls:"mdbase-editor-section"});i.createEl("h3",{text:"Local files needing attention"}),i.createEl("p",{text:"These files remain untouched and unsynced. Other valid Markdown continues to synchronize."});for(let s of n.local_issues){let o=i.createDiv({cls:"mdbase-conflict-row"}),a=o.createDiv();a.createEl("strong",{text:s.path}),a.createDiv({text:s.message});let l=o.createDiv({cls:"mdbase-actions"}).createEl("button",{text:"Open file"});l.disabled=this.busy,l.onclick=()=>void this.host.openFileByPath(s.path)}}renderIssues(t){var g;let n=t.createDiv({cls:"mdbase-issues-document"}),i=this.host.getIssues(),s=new Set(i.map(_=>_.path)).size,o=n.createDiv({cls:"mdbase-document-header"}),a=o.createDiv();a.createEl("h2",{text:"Issues"}),a.createEl("p",{text:i.length?`${i.length.toLocaleString()} validation issues in ${s.toLocaleString()} files.`:"The collection has no current validation issues."});let c=o.createEl("button",{text:"Validate collection"});c.disabled=this.busy,c.onclick=()=>void this.perform(async()=>{await this.host.validateCollection(),this.render()});let l=n.createDiv({cls:"mdbase-issue-controls"}),d=l.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.render()};let u=l.createEl("input",{type:"search"});u.setAttr("aria-label","Filter issues"),u.placeholder="Filter by path, code, field, or message",u.value=this.issueQuery,u.oninput=()=>{this.issueQuery=u.value,this.issueLimit=250,this.render();let _=this.containerEl.querySelector(".mdbase-issue-controls input[type='search']");_==null||_.focus(),_==null||_.setSelectionRange(_.value.length,_.value.length)};let f=this.issueQuery.trim().toLowerCase(),p=i.filter(_=>{var w;return this.issueSeverity!=="all"&&_.severity!==this.issueSeverity?!1:f?`${_.path} ${_.code} ${(w=_.field)!=null?w:""} ${_.message}`.toLowerCase().includes(f):!0}),y=new Set(p.map(_=>_.path)).size;if(n.createDiv({cls:"mdbase-issues-summary",text:p.length===i.length?`Showing ${Math.min(p.length,this.issueLimit).toLocaleString()} of ${p.length.toLocaleString()} issues`:`${p.length.toLocaleString()} matching issues in ${y.toLocaleString()} files`}),!p.length){n.createDiv({cls:"mdbase-empty-state",text:"No validation issues."});return}let h=p.slice(0,this.issueLimit),m=new Map;for(let _ of h)m.set(_.path,[...(g=m.get(_.path))!=null?g:[],_]);for(let[_,w]of m){let x=n.createEl("section",{cls:"mdbase-issue-group"}),v=x.createDiv({cls:"mdbase-issue-group-header"}),P=v.createEl("button",{cls:"mdbase-issue-file-button"});(0,Ee.setIcon)(P.createSpan({cls:"mdbase-issue-file-icon"}),"file-text"),P.createSpan({cls:"mdbase-issue-file-path",text:_}),P.onclick=()=>void this.host.openFileByPath(_),v.createSpan({cls:"mdbase-issue-file-count",text:`${w.length} ${w.length===1?"issue":"issues"}`});for(let O of w){let $=x.createEl("button",{cls:"mdbase-issue-row"});$.setAttr("data-severity",O.severity),$.setAttr("aria-label",`${O.severity==="warn"?"Warning":"Error"}: ${O.message}`),$.createSpan({cls:"mdbase-issue-indicator"}).setAttr("aria-hidden","true");let R=$.createDiv({cls:"mdbase-issue-metadata"});R.createEl("code",{text:O.code}),R.createDiv({cls:"mdbase-issue-context",text:`${O.severity==="warn"?"Warning":"Error"}${O.field?` \xB7 ${O.field}`:""}`}),$.createDiv({cls:"mdbase-issue-row-message",text:O.message}),$.onclick=()=>void this.host.openFileByPath(O.path,O.field)}}if(p.length>h.length){let _=n.createEl("button",{cls:"mdbase-load-more",text:`Load ${Math.min(250,p.length-h.length)} more`});_.onclick=()=>{this.issueLimit+=250,this.render()}}}async selectType(t,n=!0){if(n&&this.dirty&&t!==this.selectedPath){new Ee.Notice("Save or discard the current type changes before switching.");return}let i=await this.host.loadTypeModel(t);this.selectedPath=t,this.model=i,this.originalModel=gp(i),this.yamlDraft=`${mt(N0(i),i.body)} + contains: task`});y.disabled=i;let h=t.createEl("section",{cls:"mdbase-editor-section"}),m=h.createDiv({cls:"mdbase-section-header"});m.createEl("h3",{text:"Fields"});let g=m.createEl("button",{text:"Add field"});g.disabled=i,g.onclick=()=>{n.fields.push({name:"",definition:{type:"string"}}),this.markDirty(!0)};let _=h.createDiv({cls:"mdbase-fields"});for(let[P,O]of n.fields.entries())this.renderFieldRow(_,O,P,i);n.fields.length||_.createDiv({cls:"mdbase-empty-list",text:"No fields declared."});let w=t.createEl("section",{cls:"mdbase-editor-section"});w.createEl("h3",{text:"Placement"});let x=Ot(w,"Path pattern",n.pathPattern,P=>{n.pathPattern=P,this.markDirty()},{placeholder:"Notes/{title}.md"});x.disabled=i;let v=t.createEl("section",{cls:"mdbase-editor-section mdbase-change-review"});if(v.createEl("h3",{text:"Change review"}),!this.dirty)v.createEl("p",{text:"No pending changes."});else{let P=v.createEl("ul");for(let O of wM(this.originalModel,n))P.createEl("li",{text:O})}}renderFieldRow(t,n,i,s){this.renderFieldDefinition(t,n.definition,{name:n.name,nameLabel:`Field ${i+1} name`,onNameInput:o=>{n.name=o,this.markDirty()},required:n.definition.required===!0,onRequiredChange:o=>{n.definition.required=o,this.markDirty()},onRemove:()=>{var o;(o=this.model)==null||o.fields.splice(i,1),this.markDirty(!0)},readOnly:s,depth:0})}renderFieldDefinition(t,n,i){var d;let s=t.createDiv({cls:"mdbase-field-node"});s.setAttr("data-depth",String(i.depth));let o=s.createDiv({cls:"mdbase-field-row"});if(i.staticLabel)o.createDiv({cls:"mdbase-field-role",text:i.staticLabel});else{let u=o.createEl("input",{type:"text",cls:"mdbase-field-name-control"});u.setAttr("aria-label",i.nameLabel),u.placeholder="fieldName",u.value=(d=i.name)!=null?d:"",u.disabled=i.readOnly,i.onNameInput&&(u.oninput=()=>{var f;return(f=i.onNameInput)==null?void 0:f.call(i,u.value)}),i.onNameCommit&&(u.onchange=()=>{var f;return(f=i.onNameCommit)==null?void 0:f.call(i,u.value,u)})}let a=o.createEl("select",{cls:"mdbase-field-type-control"});a.setAttr("aria-label",`${i.name||i.staticLabel||"Field"} type`);for(let u of _M){let f=u==="any"?"Any value":u[0].toUpperCase()+u.slice(1);a.createEl("option",{value:u,text:f})}a.value=C0(n),a.disabled=i.readOnly,a.onchange=()=>{n.type=a.value,a.value==="list"&&!Dn(n.items)&&(n.items={type:"string"}),a.value==="object"&&!Dn(n.fields)&&(n.fields={}),a.value==="enum"&&!Array.isArray(n.values)&&(n.values=[]),this.markDirty(!0)};let c=o.createEl("input",{type:"text",cls:"mdbase-field-description-control"});if(c.setAttr("aria-label",`${i.name||i.staticLabel||"Field"} description`),c.placeholder="Description",c.value=typeof n.description=="string"?n.description:"",c.disabled=i.readOnly,c.oninput=()=>{c.value?n.description=c.value:delete n.description,this.markDirty()},i.onRequiredChange){let u=o.createEl("label",{cls:"mdbase-field-required"}),f=u.createEl("input",{type:"checkbox"});f.checked=i.required===!0,f.disabled=i.readOnly,f.onchange=()=>{var p;return(p=i.onRequiredChange)==null?void 0:p.call(i,f.checked)},u.createSpan({text:"Required"})}if(i.onRemove){let u=o.createEl("button",{cls:"mdbase-field-remove"});u.setAttr("aria-label",`Remove ${i.name||i.staticLabel||"field"}`),(0,Ee.setIcon)(u,"trash-2"),u.disabled=i.readOnly,u.onclick=i.onRemove}let l=C0(n);l==="enum"&&this.renderEnumFieldDetails(s,n,i),l==="link"&&this.renderLinkFieldDetails(s,n,i),l==="list"&&this.renderListFieldDetails(s,n,i),l==="object"&&this.renderObjectFieldDetails(s,n,i)}renderEnumFieldDetails(t,n,i){let s=t.createDiv({cls:"mdbase-field-details mdbase-field-options"}),o=s.createEl("label",{text:"Allowed values"}),a=s.createEl("input",{type:"text"});a.setAttr("aria-label",`${i.name||i.staticLabel||"Enum"} allowed values`),a.placeholder="draft, published, archived",a.value=Array.isArray(n.values)?n.values.map(String).join(", "):"",a.disabled=i.readOnly,a.oninput=()=>{n.values=a.value.split(",").map(c=>c.trim()).filter(Boolean),this.markDirty()},o.htmlFor=a.id=`mdbase-${Math.random().toString(36).slice(2)}`}renderLinkFieldDetails(t,n,i){let s=t.createDiv({cls:"mdbase-field-details mdbase-field-options"}),o=s.createEl("label",{text:"Target type"}),a=s.createEl("input",{type:"text"});a.setAttr("aria-label",`${i.name||i.staticLabel||"Link"} target type`),a.placeholder="Any type",a.value=typeof n.target=="string"?n.target:"",a.disabled=i.readOnly,a.oninput=()=>{a.value.trim()?n.target=a.value.trim():delete n.target,this.markDirty()},o.htmlFor=a.id=`mdbase-${Math.random().toString(36).slice(2)}`;let c=s.createEl("label",{cls:"mdbase-field-required"}),l=c.createEl("input",{type:"checkbox"});l.checked=n.validate_exists===!0,l.disabled=i.readOnly,l.onchange=()=>{n.validate_exists=l.checked,this.markDirty()},c.createSpan({text:"Validate target exists"})}renderListFieldDetails(t,n,i){let s=t.createDiv({cls:"mdbase-field-children"});s.createDiv({cls:"mdbase-field-children-label",text:"List items"});let o=Dn(n.items)?n.items:{type:"any"};!Dn(n.items)&&!i.readOnly&&(n.items=o),this.renderFieldDefinition(s,o,{staticLabel:"Item",nameLabel:"List item",readOnly:i.readOnly,depth:i.depth+1})}renderObjectFieldDetails(t,n,i){let s=t.createDiv({cls:"mdbase-field-children"}),o=s.createDiv({cls:"mdbase-field-children-header"});o.createDiv({cls:"mdbase-field-children-label",text:"Object fields"});let a=o.createEl("button",{text:"Add nested field"});a.disabled=i.readOnly;let c=Dn(n.fields)?n.fields:{};!Dn(n.fields)&&!i.readOnly&&(n.fields=c),a.onclick=()=>{let u=bM(c);M0(c,u,{type:"string"}),this.markDirty(!0)};let l=s.createDiv({cls:"mdbase-nested-fields"}),d=Object.entries(c).filter(u=>Dn(u[1]));if(!d.length){l.createDiv({cls:"mdbase-empty-list",text:"No nested fields."});return}for(let[u,f]of d){let p=u;this.renderFieldDefinition(l,f,{name:p,nameLabel:`${p} nested field name`,onNameCommit:(y,h)=>{let m=y.trim();if(!m){new Ee.Notice("Nested field name is required."),h.value=p;return}if(m!==p&&Object.prototype.hasOwnProperty.call(c,m)){new Ee.Notice(`Nested field already exists: ${m}`),h.value=p;return}m!==p&&(delete c[p],M0(c,m,f),p=m,this.markDirty())},required:f.required===!0,onRequiredChange:y=>{f.required=y,this.markDirty()},onRemove:()=>{delete c[p],this.markDirty(!0)},readOnly:i.readOnly,depth:i.depth+1})}}renderYamlEditor(t,n){let i=t.createEl("section",{cls:"mdbase-editor-section mdbase-yaml-section"});i.createEl("h3",{text:"Canonical type document"}),i.createEl("p",{cls:"mdbase-form-description",text:"Unknown v0.3 extensions are preserved. Invalid YAML is never normalized or saved."});let s=i.createEl("textarea",{cls:"mdbase-yaml-editor"});s.setAttr("aria-label","Type definition YAML"),s.value=this.yamlDraft,s.disabled=n,s.spellcheck=!1,s.oninput=()=>{this.yamlDraft=s.value,this.markDirty(!1)}}renderSync(t){var h,m,g,_,w,x,v,P,O,A,R,$;let n=t.createDiv({cls:"mdbase-sync-document"}),i=n.createDiv({cls:"mdbase-document-header"});i.createEl("h2",{text:"Sync"}),i.createEl("p",{text:"Connect this vault to a collection authority and keep ordinary Markdown mirrored locally."});let s=this.host.getMirrorProfile();if(!s){this.renderEnrollment(n);return}let o=n.createEl("section",{cls:"mdbase-editor-section"});o.createEl("h3",{text:"Collection authority"});let a=o.createDiv({cls:"mdbase-status-list"});if(Me(a,"Name",s.name),Me(a,"Collection",s.collectionId),Me(a,"Access",s.mode==="read_write"?"Read and write":"Read only"),Me(a,"Provider",s.syncUrl),Me(a,"State",(m=(h=this.mirrorStatus)==null?void 0:h.state.replace(/_/g," "))!=null?m:"Checking"),Me(a,"Last synced",(_=(g=this.mirrorStatus)==null?void 0:g.last_synced_at)!=null?_:"Never"),this.mirrorProgress){let M=this.mirrorProgress.total,V=o.createEl("progress");V.max=M!=null?M:1,V.value=M==null?0:this.mirrorProgress.completed,M==null&&V.removeAttribute("value"),o.createDiv({cls:"mdbase-progress-label",text:`${this.mirrorProgress.phase}: ${this.mirrorProgress.completed}${M==null?"":` of ${M}`}`});let T=o.createEl("button",{text:"Stop safely"});T.onclick=()=>{this.host.connectSync.cancelSync(),this.transientMessage="Stopping after the current action boundary\u2026",this.render()}}let c=o.createDiv({cls:"mdbase-actions"}),l=c.createEl("button",{text:"Preview"});l.disabled=this.busy,l.onclick=()=>void this.perform(async()=>{this.mirrorPreview=await this.host.connectSync.preview(),this.transientMessage=this.mirrorPreview.entries.length?"Review the engine plan below, then sync when ready.":this.mirrorPreview.plan.actions.some(M=>M.command==="advance_checkpoint")?"No content effects are needed; confirm the sync checkpoint when ready.":"This mirror is already up to date.",this.render()});let d=(x=(w=this.mirrorPreview)==null?void 0:w.plan.actions.filter(M=>M.command!=="advance_checkpoint").length)!=null?x:0,u=(P=(v=this.mirrorPreview)==null?void 0:v.plan.actions.some(M=>M.command==="advance_checkpoint"))!=null?P:!1,f=((A=(O=this.mirrorPreview)==null?void 0:O.plan.summary.blocking_issues)!=null?A:0)>0,p=c.createEl("button",{text:this.mirrorPreview?d?`Sync ${d} ${d===1?"outcome":"outcomes"}`:u?"Confirm sync checkpoint":"Already up to date":"Review before syncing"});p.addClass("mod-cta"),p.disabled=this.busy||!this.mirrorPreview||f||this.mirrorPreview.plan.actions.length===0,p.onclick=()=>void this.perform(async()=>{var V,T;let M=await this.host.connectSync.sync(this.mirrorPreview,S=>{this.mirrorProgress=S,this.render()});this.mirrorStatus=await this.host.connectSync.status(),this.mirrorPreview=await this.host.connectSync.preview(),this.mirrorProgress=null,this.transientMessage=M.status==="applied"?"Sync completed and the local checkpoint was verified.":M.status==="attention"?"Sync checkpointed completed actions and recorded the items that need attention.":M.status==="cancelled"?`Sync stopped safely after ${M.applied} actions; ${M.pending} remain pending.`:M.status==="stale"?"The reviewed plan became stale. Review the new engine plan before syncing again.":`Sync stopped at a durable action boundary: ${(T=(V=M.failure)==null?void 0:V.message)!=null?T:M.status}.`,await this.refresh(!0)}),this.mirrorPreview&&this.renderMirrorPreview(n,this.mirrorPreview),(R=this.mirrorStatus)!=null&&R.conflicts.length&&this.renderConflicts(n,this.mirrorStatus),($=this.mirrorStatus)!=null&&$.local_issues.length&&this.renderLocalMirrorIssues(n,this.mirrorStatus);let y=n.createEl("section",{cls:"mdbase-editor-section"});y.createEl("h3",{text:"Mirror ownership"}),y.createEl("p",{text:"Use this plugin as the only sync owner for this vault. Obsidian protects concurrent operations inside the app; a separate desktop mirror process cannot share that mobile-safe lease."})}renderEnrollment(t){if(this.schema||this.host.connectSync.getAdoptionMarker()){this.renderLocalAdoption(t);return}let n=t.createEl("section",{cls:"mdbase-editor-section mdbase-enrollment"});if(n.createEl("h3",{text:"Connect collection authority"}),n.createEl("p",{text:"Connect will open an approval page. Credentials are stored in Obsidian's secret store and never written into this vault."}),this.enrollmentVerification){let u=n.createDiv({cls:"mdbase-approval-link"});u.createSpan({text:"Approval page: "});let f=u.createEl("a",{text:"Open Connect",href:this.enrollmentVerification});f.setAttr("target","_blank"),f.setAttr("rel","noopener noreferrer")}let i="https://connect.mdbase.dev",s="Obsidian",o="",a="read_write";Ot(n,"Connect URL",i,u=>{i=u},{placeholder:"https://connect.mdbase.dev"}),Ot(n,"Mirror name",s,u=>{s=u}),Ot(n,"Collection ID",o,u=>{o=u},{description:"Optional. Leave blank to choose during approval."});let c=n.createDiv({cls:"mdbase-form-row"});c.createEl("label",{text:"Access"});let l=c.createEl("select");l.createEl("option",{value:"read_write",text:"Read and write"}),l.createEl("option",{value:"read_only",text:"Read only"}),l.value=a,l.onchange=()=>{a=l.value==="read_only"?"read_only":"read_write"};let d=n.createEl("button",{text:"Open Connect approval"});d.addClass("mod-cta"),d.disabled=this.busy,d.onclick=()=>void this.perform(async()=>{var f;(f=this.enrollmentAbort)==null||f.abort();let u=new AbortController;this.enrollmentAbort=u;try{await this.host.connectSync.enroll({controlUrl:i,mirrorName:s,mode:a,...o.trim()?{collectionId:o.trim()}:{}},{signal:u.signal,onVerification:p=>{this.enrollmentVerification=p.verificationUri,this.transientMessage="Approve the mirror in the Connect page. This view will keep waiting securely.",window.open(p.verificationUri,"_blank","noopener,noreferrer"),this.render()},onStatus:p=>{this.transientMessage=p.state==="waiting_for_approval"?"Waiting for approval in Connect\u2026":`Connect is retrying enrollment (attempt ${p.attempt}).`,this.render()}}),this.enrollmentVerification="",this.transientMessage="Mirror enrolled. Preview before the first sync.",await this.refreshMirrorStatus(),this.render()}finally{this.enrollmentAbort===u&&(this.enrollmentAbort=null)}})}renderLocalAdoption(t){var d,u;let n=this.host.connectSync.getAdoptionMarker(),i=t.createEl("section",{cls:"mdbase-editor-section mdbase-enrollment"});i.createEl("h3",{text:"Host this local collection"}),i.createEl("p",{text:n?"This vault has a durable adoption checkpoint. Resume it without creating another hosted collection.":"Hosted mdbase will adopt an exact snapshot and become the collection authority. This vault will then continue as a read-write mirror."});let s=this.enrollmentVerification||(n==null?void 0:n.session.verificationUri);if(s){let f=i.createDiv({cls:"mdbase-approval-link"});f.createSpan({text:"Approval page: "});let p=f.createEl("a",{text:"Open Connect",href:s});p.setAttr("target","_blank"),p.setAttr("rel","noopener noreferrer")}let o=(d=n==null?void 0:n.session.controlUrl)!=null?d:"https://connect.mdbase.dev",a=(u=n==null?void 0:n.session.requested.mirrorName)!=null?u:"Obsidian";if(!n)Ot(i,"Connect URL",o,f=>{o=f},{placeholder:"https://connect.mdbase.dev"}),Ot(i,"Mirror name",a,f=>{a=f});else{let f=i.createDiv({cls:"mdbase-status-list"});Me(f,"Collection",n.session.requested.collectionId),Me(f,"Phase",n.phase.replace(/_/g," ")),Me(f,"Connect",n.session.controlUrl)}let c=i.createDiv({cls:"mdbase-inline-message"});c.createEl("strong",{text:"Authority cut-over: "}),c.appendText("once final staging begins, plugin-managed local edits pause until hosted activation is confirmed. The checkpoint survives app restarts and uncertain network responses.");let l=i.createEl("button",{text:n?"Resume adoption":"Approve and host collection"});if(l.addClass("mod-cta"),l.disabled=this.busy,l.onclick=()=>void this.perform(async()=>{var h;(h=this.enrollmentAbort)==null||h.abort();let f=new AbortController;this.enrollmentAbort=f;let p=m=>{this.enrollmentVerification=m.verificationUri,this.transientMessage="Approve the authority move in Connect, then return here. This checkpoint is safe to resume.",this.render()},y=m=>{this.transientMessage=m.state==="waiting_for_approval"?"Waiting for authority-move approval in Connect\u2026":`Connect is retrying (attempt ${m.attempt}).`,this.render()};try{n?await this.host.connectSync.resumeAdoption({signal:f.signal,onVerification:p,onStatus:y}):await this.host.connectSync.adoptLocalCollection({controlUrl:o,mirrorName:a},{signal:f.signal,onVerification:p,onStatus:y}),this.enrollmentVerification="",this.transientMessage="Hosted mdbase is authoritative and this vault is now its read-write mirror.",await this.refresh(!0)}finally{this.enrollmentAbort===f&&(this.enrollmentAbort=null)}}),n&&!["activating","adopted"].includes(n.phase)){let f=i.createEl("button",{text:"Cancel adoption"});f.disabled=this.busy,f.onclick=()=>void this.perform(async()=>{await this.host.connectSync.cancelAdoption(),this.enrollmentVerification="",this.transientMessage="Collection adoption cancelled. This vault remains the local authority.",await this.refresh(!0)})}}renderMirrorPreview(t,n){let i=t.createEl("section",{cls:"mdbase-editor-section"});i.createEl("h3",{text:"Sync preview"});let s=i.createDiv({cls:"mdbase-status-list"});if(Me(s,"Download documents",String(n.download_documents)),Me(s,"Upload documents",String(n.upload_documents)),Me(s,"Unchanged documents",String(n.unchanged_documents)),Me(s,"Plan",n.plan.fingerprint),n.entries.length){let o=i.createEl("ul");for(let a of n.entries.slice(0,200))o.createEl("li",{text:`${a.direction==="attention"?"Attention":a.direction}: ${a.path} \u2014 ${a.detail}`})}if(n.collisions.length){i.createDiv({cls:"mdbase-inline-error",text:`${n.collisions.length} path collision${n.collisions.length===1?"":"s"} must be resolved before sync.`});let o=i.createEl("ul");for(let a of n.collisions.slice(0,100))o.createEl("li",{text:a})}if(n.local_issues.length){i.createDiv({cls:"mdbase-inline-error",text:`${n.local_issues.length} local file${n.local_issues.length===1?"":"s"} cannot be uploaded until its frontmatter is fixed.`});let o=i.createEl("ul");for(let a of n.local_issues.slice(0,100))o.createEl("li",{text:`${a.path}: ${a.message}`})}}renderConflicts(t,n){var s;let i=t.createEl("section",{cls:"mdbase-editor-section"});i.createEl("h3",{text:"Conflicts"});for(let o of n.conflicts){let a=i.createDiv({cls:"mdbase-conflict-row"}),c=a.createDiv();c.createEl("strong",{text:(s=o.path)!=null?s:o.record_id}),c.createDiv({text:o.message});let l=a.createDiv({cls:"mdbase-actions"});for(let d of["local","remote"]){let u=l.createEl("button",{text:d==="local"?"Keep local":"Use remote"});u.disabled=this.busy,u.onclick=()=>void this.perform(async()=>{this.mirrorStatus=await this.host.connectSync.resolveConflict(o.record_id,d),this.render()})}}}renderLocalMirrorIssues(t,n){let i=t.createEl("section",{cls:"mdbase-editor-section"});i.createEl("h3",{text:"Local files needing attention"}),i.createEl("p",{text:"These files remain untouched and unsynced. Other valid Markdown continues to synchronize."});for(let s of n.local_issues){let o=i.createDiv({cls:"mdbase-conflict-row"}),a=o.createDiv();a.createEl("strong",{text:s.path}),a.createDiv({text:s.message});let l=o.createDiv({cls:"mdbase-actions"}).createEl("button",{text:"Open file"});l.disabled=this.busy,l.onclick=()=>void this.host.openFileByPath(s.path)}}renderIssues(t){var g;let n=t.createDiv({cls:"mdbase-issues-document"}),i=this.host.getIssues(),s=new Set(i.map(_=>_.path)).size,o=n.createDiv({cls:"mdbase-document-header"}),a=o.createDiv();a.createEl("h2",{text:"Issues"}),a.createEl("p",{text:i.length?`${i.length.toLocaleString()} validation issues in ${s.toLocaleString()} files.`:"The collection has no current validation issues."});let c=o.createEl("button",{text:"Validate collection"});c.disabled=this.busy,c.onclick=()=>void this.perform(async()=>{await this.host.validateCollection(),this.render()});let l=n.createDiv({cls:"mdbase-issue-controls"}),d=l.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.render()};let u=l.createEl("input",{type:"search"});u.setAttr("aria-label","Filter issues"),u.placeholder="Filter by path, code, field, or message",u.value=this.issueQuery,u.oninput=()=>{this.issueQuery=u.value,this.issueLimit=250,this.render();let _=this.containerEl.querySelector(".mdbase-issue-controls input[type='search']");_==null||_.focus(),_==null||_.setSelectionRange(_.value.length,_.value.length)};let f=this.issueQuery.trim().toLowerCase(),p=i.filter(_=>{var w;return this.issueSeverity!=="all"&&_.severity!==this.issueSeverity?!1:f?`${_.path} ${_.code} ${(w=_.field)!=null?w:""} ${_.message}`.toLowerCase().includes(f):!0}),y=new Set(p.map(_=>_.path)).size;if(n.createDiv({cls:"mdbase-issues-summary",text:p.length===i.length?`Showing ${Math.min(p.length,this.issueLimit).toLocaleString()} of ${p.length.toLocaleString()} issues`:`${p.length.toLocaleString()} matching issues in ${y.toLocaleString()} files`}),!p.length){n.createDiv({cls:"mdbase-empty-state",text:"No validation issues."});return}let h=p.slice(0,this.issueLimit),m=new Map;for(let _ of h)m.set(_.path,[...(g=m.get(_.path))!=null?g:[],_]);for(let[_,w]of m){let x=n.createEl("section",{cls:"mdbase-issue-group"}),v=x.createDiv({cls:"mdbase-issue-group-header"}),P=v.createEl("button",{cls:"mdbase-issue-file-button"});(0,Ee.setIcon)(P.createSpan({cls:"mdbase-issue-file-icon"}),"file-text"),P.createSpan({cls:"mdbase-issue-file-path",text:_}),P.onclick=()=>void this.host.openFileByPath(_),v.createSpan({cls:"mdbase-issue-file-count",text:`${w.length} ${w.length===1?"issue":"issues"}`});for(let O of w){let A=x.createEl("button",{cls:"mdbase-issue-row"});A.setAttr("data-severity",O.severity),A.setAttr("aria-label",`${O.severity==="warn"?"Warning":"Error"}: ${O.message}`),A.createSpan({cls:"mdbase-issue-indicator"}).setAttr("aria-hidden","true");let R=A.createDiv({cls:"mdbase-issue-metadata"});R.createEl("code",{text:O.code}),R.createDiv({cls:"mdbase-issue-context",text:`${O.severity==="warn"?"Warning":"Error"}${O.field?` \xB7 ${O.field}`:""}`}),A.createDiv({cls:"mdbase-issue-row-message",text:O.message}),A.onclick=()=>void this.host.openFileByPath(O.path,O.field)}}if(p.length>h.length){let _=n.createEl("button",{cls:"mdbase-load-more",text:`Load ${Math.min(250,p.length-h.length)} more`});_.onclick=()=>{this.issueLimit+=250,this.render()}}}async selectType(t,n=!0){if(n&&this.dirty&&t!==this.selectedPath){new Ee.Notice("Save or discard the current type changes before switching.");return}let i=await this.host.loadTypeModel(t);this.selectedPath=t,this.model=i,this.originalModel=gp(i),this.yamlDraft=`${mt(N0(i),i.body)} `,this.dirty=!1,this.editorMode="design",this.render()}createType(){if(this.dirty){new Ee.Notice("Save or discard the current type changes before creating another type.");return}let t=yp();this.selectedPath=null,this.model=t,this.originalModel=null,this.yamlDraft=`${mt(yo(t),t.body)} `,this.dirty=!0,this.editorMode="design",this.render()}switchEditorMode(t){if(!(!this.model||t===this.editorMode)){if(t==="yaml")try{this.yamlDraft=`${mt(N0(this.model),this.model.body)} -`}catch(n){new Ee.Notice(n instanceof Error?n.message:String(n));return}else if(!this.readYamlDraftIntoModel())return;this.editorMode=t,this.render()}}readYamlDraftIntoModel(){var n,i;let t=Pt(this.yamlDraft);if(!t.hasFrontmatter||t.error)return new Ee.Notice(`Invalid type YAML: ${(n=t.error)!=null?n:"frontmatter is missing"}`),!1;if(t.frontmatter.kind!=="mdbase.type")return new Ee.Notice("Canonical v0.3 type YAML requires kind: mdbase.type."),!1;try{return this.model=Uc(t.frontmatter,t.body,((i=this.model)==null?void 0:i.name)||"type"),!0}catch(s){return new Ee.Notice(s instanceof Error?s.message:String(s)),!1}}async saveCurrentType(){if(!(!this.model||this.model.specProfile!=="v0.3"||this.model.readOnlyReason)&&!(this.editorMode==="yaml"&&!this.readYamlDraftIntoModel())){if(!this.model.name.trim()){new Ee.Notice("Type name is required.");return}await this.perform(async()=>{let t=await this.host.saveTypeModel(this.model,this.selectedPath);this.selectedPath=t.path,this.originalModel=gp(this.model),this.dirty=!1,this.transientMessage=`Saved ${t.path}.`,await this.refresh(!0)})}}markDirty(t=!1){var o,a;if(this.dirty=!0,t){this.render();return}let n=this.containerEl.querySelector(".mdbase-editor-title-line");n&&!n.querySelector(".mdbase-dirty")&&n.createSpan({cls:"mdbase-dirty",text:"Unsaved"});let i=this.containerEl.querySelector(".mdbase-editor-actions .mod-cta");i&&((o=this.model)==null?void 0:o.specProfile)==="v0.3"&&!this.model.readOnlyReason&&((a=this.host.getMirrorProfile())==null?void 0:a.mode)!=="read_only"&&(i.disabled=!1);let s=this.containerEl.querySelector(".mdbase-change-review");if(s){let c=s.querySelector("p");c&&c.setText("Pending changes. Review details after leaving the current field.")}}async refreshMirrorStatus(){try{this.mirrorStatus=await this.host.connectSync.status()}catch(t){this.mirrorStatus=null,this.transientMessage=t instanceof Error?t.message:String(t)}}async perform(t){if(!this.busy){this.busy=!0,this.transientMessage="",this.render();try{await t()}catch(n){let i=n instanceof Error?n.message:String(n);this.transientMessage=i,new Ee.Notice(i)}finally{this.busy=!1,this.render()}}}};function N0(r){var e;return r.specProfile==="v0.3"&&!r.readOnlyReason?yo(r):gp((e=r.originalFrontmatter)!=null?e:{name:r.name,fields:Object.fromEntries(r.fields.map(t=>[t.name,t.definition]))})}var Fi="mdbase-issues-view",$M={validateOnSave:!0,validateOnOpen:!0,showNoticeOnSave:!1,interopEnabled:!1,mirrorProfile:null};function SM(r){if(!r||typeof r!="object"||Array.isArray(r))return!1;let e=r;return e.version===1&&typeof e.syncUrl=="string"&&typeof e.controlUrl=="string"&&typeof e.collectionId=="string"&&typeof e.replicaId=="string"&&(e.mode==="read_only"||e.mode==="read_write")&&typeof e.name=="string"&&typeof e.enrollmentId=="string"&&typeof e.accessTokenExpiresAt=="string"}function EM(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var go=class extends L.Modal{constructor(t,n,i="",s=""){super(t);this.resolvePromise=null;this.settled=!1;this.title=n,this.placeholder=i,this.defaultValue=s}openAndGetValue(){return new Promise(t=>{this.settled=!1,this.resolvePromise=t,this.open()})}onOpen(){let{contentEl:t}=this;t.empty(),t.createEl("h3",{text:this.title});let n=t.createEl("input",{type:"text"});n.placeholder=this.placeholder,n.value=this.defaultValue,n.addClass("prompt-input");let i=t.createDiv({cls:"modal-button-container"}),s=i.createEl("button",{text:"Cancel"}),o=i.createEl("button",{text:"OK"});o.addClass("mod-cta"),s.onclick=()=>{this.finish(null),this.close()},o.onclick=()=>{this.finish(n.value.trim()),this.close()},n.addEventListener("keydown",a=>{a.key==="Enter"&&(a.preventDefault(),this.finish(n.value.trim()),this.close()),a.key==="Escape"&&(a.preventDefault(),this.finish(null),this.close())}),window.setTimeout(()=>n.focus(),0)}onClose(){this.settled||this.finish(null),this.contentEl.empty()}finish(t){var n;this.settled||(this.settled=!0,(n=this.resolvePromise)==null||n.call(this,t),this.resolvePromise=null)}},_p=class extends L.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=>{var a,c,l;let s=(c=(a=i.match)==null?void 0:a.path_glob)!=null?c:"";return`${i.name} ${(l=i.display_name_key)!=null?l:""} ${i.filePath} ${s}`.toLowerCase().includes(n)}).slice(0,100):this.typeDefs.slice(0,100)}renderSuggestion(t,n){var o,a;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((o=t.fields)!=null?o:{}).length} fields`}),(a=t.match)!=null&&a.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 AM(r,e){return new Promise(t=>{new _p(r,e,i=>{if(i.type==="selected"){t(i.typeDef);return}t(null)}).open()})}var bp=class extends L.ItemView{constructor(t,n){super(t);this.severityFilter="all";this.query="";this.plugin=n}getViewType(){return Fi}getDisplayText(){return"mdbase issues"}getIcon(){return"shield-alert"}async onOpen(){this.containerEl.empty(),this.containerEl.addClass("mdbase-issues-view"),this.render()}render(){var y;let t=this.containerEl;t.empty(),t.addClass("mdbase-issues-view");let n=t.createDiv({cls:"mdbase-issues-header"});n.createEl("h3",{text:"mdbase Issues"});let s=n.createDiv({cls:"mdbase-issues-header-actions"}).createEl("button",{text:"Refresh"});s.addClass("mod-cta"),s.onclick=()=>{this.plugin.runCollectionValidation(!1)};let o=t.createDiv({cls:"mdbase-issues-controls"}),a=o.createEl("select");a.addClass("mdbase-issues-severity"),a.createEl("option",{value:"all",text:"All severities"}),a.createEl("option",{value:"error",text:"Errors only"}),a.createEl("option",{value:"warn",text:"Warnings only"}),a.value=this.severityFilter,a.onchange=()=>{let h=a.value;(h==="error"||h==="warn"||h==="all")&&(this.severityFilter=h),this.render()};let c=o.createEl("input",{type:"search"});c.addClass("mdbase-issues-query"),c.placeholder="Filter by path, code, message, field",c.value=this.query,c.oninput=()=>{this.query=c.value,this.render()};let l=this.plugin.getIssues(),d=this.query.trim().toLowerCase(),u=l.filter(h=>{var g;return this.severityFilter!=="all"&&h.severity!==this.severityFilter?!1:d?`${h.path} ${h.code} ${h.message} ${(g=h.field)!=null?g:""}`.toLowerCase().includes(d):!0}),f=u.slice(0,500);if(t.createDiv({cls:"mdbase-issues-count",text:u.length>f.length?`Showing ${f.length} of ${u.length} matching issues`:u.length===l.length?`${u.length} issue${u.length===1?"":"s"}`:`${u.length} of ${l.length} issue${l.length===1?"":"s"}`}),u.length===0){t.createDiv({cls:"mdbase-empty",text:l.length===0?"No validation issues.":"No issues match current filters."});return}let p=new Map;for(let h of f){let m=(y=p.get(h.path))!=null?y:[];m.push(h),p.set(h.path,m)}for(let[h,m]of p.entries()){t.createDiv({cls:"mdbase-issue-file",text:h});for(let g of m){let _=t.createDiv({cls:"mdbase-issue-item"});_.setAttr("data-severity",g.severity),_.createDiv({cls:"mdbase-issue-code",text:`${g.severity.toUpperCase()} \xB7 ${g.code}${g.field?` \xB7 ${g.field}`:""}`}),_.createDiv({cls:"mdbase-issue-message",text:g.message});let w=_.createDiv({cls:"mdbase-issue-actions"}),x=w.createEl("button",{text:g.field?"Open field":"Open file"});x.onclick=P=>{P.stopPropagation(),this.plugin.openIssue(g)};let v=this.plugin.getQuickFixLabel(g);if(v){let P=w.createEl("button",{text:v});P.onclick=O=>{O.stopPropagation(),this.plugin.applyQuickFix(g)}}_.onclick=()=>{this.plugin.openIssue(g)}}}}},wp=class extends L.PluginSettingTab{constructor(e,t){super(e,t),this.plugin=t}display(){let{containerEl:e}=this;e.empty(),e.createEl("h2",{text:"mdbase settings"}),new L.Setting(e).setName("Validate on save").setDesc("Run mdbase validation when a markdown file is modified.").addToggle(t=>t.setValue(this.plugin.settings.validateOnSave).onChange(async n=>{this.plugin.settings.validateOnSave=n,await this.plugin.saveSettings()})),new L.Setting(e).setName("Validate on file open").setDesc("Validate the active note when opened.").addToggle(t=>t.setValue(this.plugin.settings.validateOnOpen).onChange(async n=>{this.plugin.settings.validateOnOpen=n,await this.plugin.saveSettings()})),new L.Setting(e).setName("Show notices on save").setDesc("Display a notice when save-time validation finds issues.").addToggle(t=>t.setValue(this.plugin.settings.showNoticeOnSave).onChange(async n=>{this.plugin.settings.showNoticeOnSave=n,await this.plugin.saveSettings()})),new L.Setting(e).setName("Allow local application interoperability").setDesc("Allow installed Obsidian plugins to exchange validated mdbase events and actions in this vault. Contracts establish compatibility; this switch is the separate user grant.").addToggle(t=>t.setValue(this.plugin.settings.interopEnabled).onChange(async n=>{this.plugin.settings.interopEnabled=n,await this.plugin.saveSettings()}))}},zc=class extends L.Plugin{constructor(t,n){super(t,n);this.issueMap=new Map;this.sortedIssuesCache=null;this.schemaCache=null;this.schemaLoadPromise=null;this.pendingSaveValidations=new Map;this.saveValidationDebounceMs=250;this.connectSync=new qc(t,{getMirrorProfile:()=>this.getMirrorProfile(),saveMirrorProfile:async i=>{this.settings.mirrorProfile=i,await this.saveSettings()}}),this.interopBridge=new ga(t,()=>{var i;return((i=this.settings)==null?void 0:i.interopEnabled)===!0}),this.api={apiVersion:1,interop:this.interopBridge,getInteropStatus:()=>{var i;return{enabled:((i=this.settings)==null?void 0:i.interopEnabled)===!0,profileVersion:"0.1"}}}}async onload(){await this.loadSettings(),await this.connectSync.initialize(),(0,L.addIcon)(qi,T0),this.statusBarEl=this.addStatusBarItem(),this.updateStatusBar(),this.registerView(qn,n=>new Bc(n,this)),this.registerView(Fi,n=>new bp(n,this)),this.addSettingTab(new wp(this.app,this)),this.addRibbonIcon(qi,"Open mdbase",()=>void this.openWorkspace()),this.addCommand({id:"mdbase-open",name:"mdbase: Open workspace",callback:()=>void this.openWorkspace()}),this.addCommand({id:"mdbase-initialize-collection",name:"mdbase: Initialize collection",callback:()=>void this.initializeCollectionCommand()}),this.addCommand({id:"mdbase-create-type",name:"mdbase: Create type definition",callback:()=>void this.openWorkspace("types")}),this.addCommand({id:"mdbase-edit-type",name:"mdbase: Edit type definition",callback:()=>void this.openWorkspace("types")}),this.addCommand({id:"mdbase-edit-current-type",name:"mdbase: Edit current type definition",callback:()=>void this.openWorkspace("types")}),this.addCommand({id:"mdbase-create-note-from-type",name:"mdbase: Create note from type",callback:()=>void this.createNoteFromTypeCommand()}),this.addCommand({id:"mdbase-validate-current-note",name:"mdbase: Validate current note",callback:()=>void this.validateCurrentNoteCommand()}),this.addCommand({id:"mdbase-validate-collection",name:"mdbase: Validate collection",callback:()=>void this.runCollectionValidation(!0)}),this.addCommand({id:"mdbase-open-issues-view",name:"mdbase: Open issues view",callback:()=>void this.openWorkspace("issues")}),this.addCommand({id:"mdbase-sync",name:"mdbase: Sync collection authority",callback:()=>void this.syncHostedCollectionCommand()}),this.addCommand({id:"mdbase-open-sync",name:"mdbase: Open sync",callback:()=>void this.openWorkspace("sync")}),this.registerEvent(this.app.vault.on("modify",n=>{n instanceof L.TFile&&this.onVaultModify(n)})),this.registerEvent(this.app.vault.on("rename",(n,i)=>{n instanceof L.TFile&&this.onVaultRename(n,i)})),this.registerEvent(this.app.vault.on("delete",n=>{n instanceof L.TFile&&this.onVaultDelete(n)})),this.registerEvent(this.app.vault.on("create",n=>{n instanceof L.TFile&&this.onVaultCreate(n)})),this.registerEvent(this.app.workspace.on("file-open",n=>{this.settings.validateOnOpen&&(!(n instanceof L.TFile)||n.extension!=="md"||this.validateFileAndStore(n,"open"))}));let t=this.app.workspace.getActiveFile();t&&this.settings.validateOnOpen&&this.validateFileAndStore(t,"open")}async onunload(){await this.interopBridge.dispose(),this.app.workspace.getLeavesOfType(qn).forEach(t=>t.detach()),this.app.workspace.getLeavesOfType(Fi).forEach(t=>t.detach()),this.clearAllPendingSaveValidations()}async loadSettings(){this.settings=Object.assign({},$M,await this.loadData()),SM(this.settings.mirrorProfile)||(this.settings.mirrorProfile=null)}async saveSettings(){await this.saveData(this.settings)}getIssues(){var t;return(t=this.sortedIssuesCache)!=null||(this.sortedIssuesCache=Array.from(this.issueMap.values()).flat().sort((n,i)=>n.path.localeCompare(i.path)||n.severity.localeCompare(i.severity)||n.code.localeCompare(i.code))),this.sortedIssuesCache}getMirrorProfile(){return this.settings.mirrorProfile?{...this.settings.mirrorProfile}:null}async loadWorkspaceSchema(t=!1){return this.getConfigAndTypes(t)}async loadTypeModel(t){var s;let n=this.app.vault.getAbstractFileByPath((0,L.normalizePath)(t));if(!(n instanceof L.TFile))throw new Error(`Type file not found: ${t}`);let i=Pt(await this.app.vault.cachedRead(n));if(!i.hasFrontmatter||i.error)throw new Error(`Invalid type frontmatter: ${(s=i.error)!=null?s:"frontmatter is missing"}`);return Uc(i.frontmatter,i.body,n.basename)}async saveTypeModel(t,n){var a;if(this.connectSync.assertLocalAuthorityWritable(),((a=this.getMirrorProfile())==null?void 0:a.mode)==="read_only")throw new Error("This mirror has read-only access. Re-enroll it with write access before editing types.");let i=await pi(this.app.vault);if(!i)throw new Error("No mdbase.yaml found.");if(!i.spec_version.startsWith("0.3."))throw new Error("mdbase v0.2 type definitions are read-only. Migrate the collection first.");let s=n?this.app.vault.getAbstractFileByPath((0,L.normalizePath)(n)):null;if(s!=null&&!(s instanceof L.TFile))throw new Error(`Type file not found: ${n}`);let o=await this.writeTypeDefinition(i,t,s);return this.refreshWorkspaceViews(!0),o}async initializeCollection(){this.connectSync.assertLocalAuthorityWritable(),await this.initializeCollectionCommand(),this.refreshWorkspaceViews(!0)}async validateCollection(){await this.runCollectionValidation(!1)}analyzeMigration(){if(this.getMirrorProfile())throw new Error("Collection authority resources must be migrated at the collection authority.");return I0(this.app.vault)}async applyMigration(t,n){var s,o;if(this.connectSync.assertLocalAuthorityWritable(),this.getMirrorProfile())throw new Error("Collection authority resources must be migrated at the collection authority.");let i=await O0(this.app.vault,t,{allowLossy:n});if(!i.applied)throw new Error(i.restored?`Migration failed and all writes were rolled back. ${(s=i.error)!=null?s:""}`.trim():`Migration needs manual recovery. See ${i.manifestPath}. ${(o=i.error)!=null?o:""}`.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["unknown_field","schema_additional_properties"].includes(t.code)&&t.field?"Remove field":["missing_required","schema_required"].includes(t.code)&&t.field?"Add placeholder":null}async applyQuickFix(t){this.connectSync.assertLocalAuthorityWritable();let n=this.app.vault.getAbstractFileByPath(t.path);if(!(n instanceof L.TFile)){new L.Notice(`File not found: ${t.path}`);return}let i=await this.app.vault.cachedRead(n),s=Pt(i);if(s.error){new L.Notice(`Cannot apply quick fix: invalid frontmatter (${s.error})`);return}if(["unknown_field","schema_additional_properties"].includes(t.code)&&t.field){let o=$a(t.field);if(!(o in s.frontmatter)){new L.Notice(`Field '${o}' not found in frontmatter.`);return}delete s.frontmatter[o],await this.app.vault.modify(n,`${mt(s.frontmatter,s.body)} -`),new L.Notice(`Removed '${o}' from ${n.basename}`),await this.validateFileAndStore(n,"manual");return}if(["missing_required","schema_required"].includes(t.code)&&t.field){let o=$a(t.field);s.frontmatter[o]===void 0&&(s.frontmatter[o]="TODO");let a=s.hasFrontmatter?s.body:i;await this.app.vault.modify(n,`${mt(s.frontmatter,a)} -`),new L.Notice(`Added placeholder '${o}' to ${n.basename}`),await this.validateFileAndStore(n,"manual");return}new L.Notice("No quick fix available for this issue.")}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=$a(n),l=new RegExp(`^\\s*${EM(c)}\\s*:`);if(o.getLine(0).trim()==="---")for(let d=1;ds.severity==="error").length,i=t.length-n;if(t.length===0){this.statusBarEl.setText("mdbase: no issues");return}this.statusBarEl.setText(`mdbase: ${n} error${n===1?"":"s"}, ${i} warning${i===1?"":"s"}`)}async openIssuesView(){var i;let t=this.app.workspace.getLeavesOfType(Fi)[0];if(t){this.app.workspace.revealLeaf(t),t.view.render();return}let n=(i=this.app.workspace.getRightLeaf(!1))!=null?i:this.app.workspace.getLeaf(!0);await n.setViewState({type:Fi,active:!0}),this.app.workspace.revealLeaf(n)}async openWorkspace(t="types"){let n=this.app.workspace.getLeavesOfType(qn)[0];if(n){this.app.workspace.revealLeaf(n);let o=n.view;o.showDestination(t),await o.refresh();return}let i=this.app.workspace.getLeaf(!0);await i.setViewState({type:qn,active:!0}),this.app.workspace.revealLeaf(i),i.view.showDestination(t)}refreshWorkspaceViews(t=!1){for(let n of this.app.workspace.getLeavesOfType(qn))n.view.refresh(t)}refreshIssueViews(){this.updateStatusBar();for(let t of this.app.workspace.getLeavesOfType(Fi))t.view.render();this.refreshWorkspaceViews()}setFileIssues(t,n){n.length===0?this.issueMap.delete(t):this.issueMap.set(t,n),this.sortedIssuesCache=null,this.refreshIssueViews()}clearFileIssues(t){this.issueMap.has(t)&&(this.issueMap.delete(t),this.sortedIssuesCache=null,this.refreshIssueViews())}moveFileIssues(t,n){let 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())}clearAllPendingSaveValidations(){for(let t of this.pendingSaveValidations.values())window.clearTimeout(t);this.pendingSaveValidations.clear()}clearPendingSaveValidation(t){let n=this.pendingSaveValidations.get(t);n!=null&&(window.clearTimeout(n),this.pendingSaveValidations.delete(t))}scheduleSaveValidation(t){this.clearPendingSaveValidation(t.path);let n=window.setTimeout(()=>{this.pendingSaveValidations.delete(t.path),this.validateFileAndStore(t,"save")},this.saveValidationDebounceMs);this.pendingSaveValidations.set(t.path,n)}isSchemaRelevantPath(t){let n=(0,L.normalizePath)(t);if(n==="mdbase.yaml")return!0;let i=new Set(["_types"]);this.schemaCache&&i.add((0,L.normalizePath)(this.schemaCache.config.settings.types_folder));for(let s of i)if(n===s||n.startsWith(`${s}/`))return!0;return!1}invalidateSchemaCache(){this.schemaCache=null,this.schemaLoadPromise=null}async getConfigAndTypes(t=!1){if(t&&this.invalidateSchemaCache(),this.schemaCache)return this.schemaCache;if(this.schemaLoadPromise)return this.schemaLoadPromise;this.schemaLoadPromise=(async()=>{let n=await pi(this.app.vault);if(!n)return null;let i=await fb(this.app.vault,n);return{config:n,types:i}})();try{let n=await this.schemaLoadPromise;return n&&(this.schemaCache=n),n}finally{this.schemaLoadPromise=null}}async requireConfigAndTypes(t={}){var s,o;let n=(s=t.background)!=null?s:!1,i=await this.getConfigAndTypes((o=t.forceReload)!=null?o:!1);return i?(i.types.size===0&&!n&&new L.Notice(`No types found in ${i.config.settings.types_folder}`),i):(n||new L.Notice("No mdbase.yaml found. Run 'mdbase: Initialize collection' first."),null)}onVaultModify(t){this.isSchemaRelevantPath(t.path)&&(this.invalidateSchemaCache(),this.refreshWorkspaceViews()),this.settings.validateOnSave&&t.extension==="md"&&this.scheduleSaveValidation(t)}onVaultRename(t,n){(this.isSchemaRelevantPath(n)||this.isSchemaRelevantPath(t.path))&&(this.invalidateSchemaCache(),this.refreshWorkspaceViews()),t.extension==="md"&&(this.clearPendingSaveValidation(n),this.moveFileIssues(n,t.path),this.settings.validateOnSave&&this.scheduleSaveValidation(t))}onVaultDelete(t){this.isSchemaRelevantPath(t.path)&&(this.invalidateSchemaCache(),this.refreshWorkspaceViews()),t.extension==="md"&&(this.clearPendingSaveValidation(t.path),this.clearFileIssues(t.path))}onVaultCreate(t){this.isSchemaRelevantPath(t.path)&&(this.invalidateSchemaCache(),this.refreshWorkspaceViews())}async validateFileAndStore(t,n){let i=await this.requireConfigAndTypes({background:n!=="manual"});if(!i)return n!=="manual"&&this.clearFileIssues(t.path),[];let s=await ef(this.app.vault,t,i.config,i.types);return this.setFileIssues(t.path,s),n==="save"&&this.settings.showNoticeOnSave&&s.length>0&&new L.Notice(`mdbase: ${s.length} issue${s.length===1?"":"s"} in ${t.basename}`),s}async initializeCollectionCommand(){if(this.connectSync.assertLocalAuthorityWritable(),this.getMirrorProfile()){new L.Notice("This vault is configured as a mirror. Sync it instead of initializing a local collection.");return}let{created:t}=await lb(this.app.vault);if(this.invalidateSchemaCache(),t.length===0){new L.Notice("mdbase collection already initialized.");return}new L.Notice(`Initialized mdbase collection: ${t.join(", ")}`)}async syncHostedCollectionCommand(){var t,n,i,s;if(!this.getMirrorProfile()){await this.openWorkspace("sync");return}try{let o=await this.connectSync.preview(),a=await this.connectSync.sync(o),c=await this.connectSync.status();this.invalidateSchemaCache(),this.refreshWorkspaceViews(!0);let l=((t=c==null?void 0:c.conflicts.length)!=null?t:0)+((n=c==null?void 0:c.local_issues.length)!=null?n:0);new L.Notice(a.status==="stale"?"The sync plan changed before it could apply. Review the new plan in the mdbase workspace.":a.status==="failed"||a.status==="blocked"?`mdbase sync stopped safely: ${(s=(i=a.failure)==null?void 0:i.message)!=null?s:a.status}.`:l?`Sync completed with ${l} item${l===1?"":"s"} needing attention.`:"mdbase sync completed.")}catch(o){new L.Notice(`mdbase sync failed: ${o instanceof Error?o.message:String(o)}`),await this.openWorkspace("sync")}}async createNoteFromTypeCommand(){var d,u;this.connectSync.assertLocalAuthorityWritable();let t=await this.requireConfigAndTypes();if(!t)return;if(t.types.size===0){new L.Notice("No type definitions found.");return}let n=await AM(this.app,Array.from(t.types.values()));if(!n)return;let i=mb(n,t.config),s=yb(n,i);for(let[f,p]of s){let y=`Required field: ${f}`,h=await new go(this.app,y,(d=p.type)!=null?d:"string").openAndGetValue();if(h==null)return;if(h.trim().length===0){new L.Notice(`Field '${f}' is required.`);return}try{i[f]=tf(h,p)}catch(m){new L.Notice(`Invalid value for ${f}: ${m instanceof Error?m.message:String(m)}`);return}}let o=(u=n.display_name_key)!=null?u:"title";if(i[o]==null){let f=await new go(this.app,`Optional ${o} (used for filename)`,"").openAndGetValue();f&&f.trim().length>0&&(i[o]=f.trim())}let a=await _b(this.app.vault,n,i),c=await new go(this.app,"Note path","Relative path in vault",a).openAndGetValue();if(c==null)return;let l=(0,L.normalizePath)(c.trim().length>0?c.trim():a);l.endsWith(".md")||(l=`${l}.md`);try{let f=await bb(this.app.vault,l,i);await this.app.workspace.getLeaf(!0).openFile(f),new L.Notice(`Created note: ${f.path}`),await this.validateFileAndStore(f,"manual")}catch(f){new L.Notice(f instanceof Error?f.message:String(f))}}async validateCurrentNoteCommand(){let t=this.app.workspace.getActiveFile();if(!(t instanceof L.TFile)||t.extension!=="md"){new L.Notice("Open a markdown note first.");return}let n=await this.validateFileAndStore(t,"manual");n.length===0?new L.Notice("No issues in current note."):(new L.Notice(`Found ${n.length} issue${n.length===1?"":"s"} in current note.`),await this.openIssuesView())}async runCollectionValidation(t){var o;let n=await this.requireConfigAndTypes({background:!1});if(!n)return;let i=await hb(this.app.vault,n.config,n.types),s=new Map;for(let a of i){let c=(o=s.get(a.path))!=null?o:[];c.push(a),s.set(a.path,c)}if(this.issueMap=s,this.sortedIssuesCache=null,this.refreshIssueViews(),t)if(i.length===0)new L.Notice("Collection validation passed with no issues.");else{let a=i.filter(l=>l.severity==="error").length,c=i.length-a;new L.Notice(`Collection validation: ${a} error(s), ${c} warning(s)`),await this.openIssuesView()}}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){let s=n.name.trim();if(!s)throw new Error("Type name is required.");if(!t.spec_version.startsWith("0.3.")||n.specProfile!=="v0.3")throw new Error("mdbase v0.2 type definitions are read-only. Migrate the collection first.");let o=yo(n),a=n.body.trim()||`# ${s} +`}catch(n){new Ee.Notice(n instanceof Error?n.message:String(n));return}else if(!this.readYamlDraftIntoModel())return;this.editorMode=t,this.render()}}readYamlDraftIntoModel(){var n,i;let t=Pt(this.yamlDraft);if(!t.hasFrontmatter||t.error)return new Ee.Notice(`Invalid type YAML: ${(n=t.error)!=null?n:"frontmatter is missing"}`),!1;if(t.frontmatter.kind!=="mdbase.type")return new Ee.Notice("Canonical v0.3 type YAML requires kind: mdbase.type."),!1;try{return this.model=Uc(t.frontmatter,t.body,((i=this.model)==null?void 0:i.name)||"type"),!0}catch(s){return new Ee.Notice(s instanceof Error?s.message:String(s)),!1}}async saveCurrentType(){if(!(!this.model||this.model.specProfile!=="v0.3"||this.model.readOnlyReason)&&!(this.editorMode==="yaml"&&!this.readYamlDraftIntoModel())){if(!this.model.name.trim()){new Ee.Notice("Type name is required.");return}await this.perform(async()=>{let t=await this.host.saveTypeModel(this.model,this.selectedPath);this.selectedPath=t.path,this.originalModel=gp(this.model),this.dirty=!1,this.transientMessage=`Saved ${t.path}.`,await this.refresh(!0)})}}markDirty(t=!1){var o,a;if(this.dirty=!0,t){this.render();return}let n=this.containerEl.querySelector(".mdbase-editor-title-line");n&&!n.querySelector(".mdbase-dirty")&&n.createSpan({cls:"mdbase-dirty",text:"Unsaved"});let i=this.containerEl.querySelector(".mdbase-editor-actions .mod-cta");i&&((o=this.model)==null?void 0:o.specProfile)==="v0.3"&&!this.model.readOnlyReason&&((a=this.host.getMirrorProfile())==null?void 0:a.mode)!=="read_only"&&(i.disabled=!1);let s=this.containerEl.querySelector(".mdbase-change-review");if(s){let c=s.querySelector("p");c&&c.setText("Pending changes. Review details after leaving the current field.")}}async refreshMirrorStatus(){try{this.mirrorStatus=await this.host.connectSync.status()}catch(t){this.mirrorStatus=null,this.transientMessage=t instanceof Error?t.message:String(t)}}async perform(t){if(!this.busy){this.busy=!0,this.transientMessage="",this.render();try{await t()}catch(n){let i=n instanceof Error?n.message:String(n);this.transientMessage=i,new Ee.Notice(i)}finally{this.busy=!1,this.render()}}}};function N0(r){var e;return r.specProfile==="v0.3"&&!r.readOnlyReason?yo(r):gp((e=r.originalFrontmatter)!=null?e:{name:r.name,fields:Object.fromEntries(r.fields.map(t=>[t.name,t.definition]))})}var Fi="mdbase-issues-view",$M={validateOnSave:!0,validateOnOpen:!0,showNoticeOnSave:!1,interopEnabled:!1,mirrorProfile:null};function SM(r){if(!r||typeof r!="object"||Array.isArray(r))return!1;let e=r;return e.version===1&&typeof e.syncUrl=="string"&&typeof e.controlUrl=="string"&&typeof e.collectionId=="string"&&typeof e.replicaId=="string"&&(e.mode==="read_only"||e.mode==="read_write")&&typeof e.name=="string"&&typeof e.enrollmentId=="string"&&typeof e.accessTokenExpiresAt=="string"}function EM(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var go=class extends j.Modal{constructor(t,n,i="",s=""){super(t);this.resolvePromise=null;this.settled=!1;this.title=n,this.placeholder=i,this.defaultValue=s}openAndGetValue(){return new Promise(t=>{this.settled=!1,this.resolvePromise=t,this.open()})}onOpen(){let{contentEl:t}=this;t.empty(),t.createEl("h3",{text:this.title});let n=t.createEl("input",{type:"text"});n.placeholder=this.placeholder,n.value=this.defaultValue,n.addClass("prompt-input");let i=t.createDiv({cls:"modal-button-container"}),s=i.createEl("button",{text:"Cancel"}),o=i.createEl("button",{text:"OK"});o.addClass("mod-cta"),s.onclick=()=>{this.finish(null),this.close()},o.onclick=()=>{this.finish(n.value.trim()),this.close()},n.addEventListener("keydown",a=>{a.key==="Enter"&&(a.preventDefault(),this.finish(n.value.trim()),this.close()),a.key==="Escape"&&(a.preventDefault(),this.finish(null),this.close())}),window.setTimeout(()=>n.focus(),0)}onClose(){this.settled||this.finish(null),this.contentEl.empty()}finish(t){var n;this.settled||(this.settled=!0,(n=this.resolvePromise)==null||n.call(this,t),this.resolvePromise=null)}},_p=class extends j.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=>{var a,c,l;let s=(c=(a=i.match)==null?void 0:a.path_glob)!=null?c:"";return`${i.name} ${(l=i.display_name_key)!=null?l:""} ${i.filePath} ${s}`.toLowerCase().includes(n)}).slice(0,100):this.typeDefs.slice(0,100)}renderSuggestion(t,n){var o,a;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((o=t.fields)!=null?o:{}).length} fields`}),(a=t.match)!=null&&a.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 AM(r,e){return new Promise(t=>{new _p(r,e,i=>{if(i.type==="selected"){t(i.typeDef);return}t(null)}).open()})}var bp=class extends j.ItemView{constructor(t,n){super(t);this.severityFilter="all";this.query="";this.plugin=n}getViewType(){return Fi}getDisplayText(){return"mdbase issues"}getIcon(){return"shield-alert"}async onOpen(){this.containerEl.empty(),this.containerEl.addClass("mdbase-issues-view"),this.render()}render(){var y;let t=this.containerEl;t.empty(),t.addClass("mdbase-issues-view");let n=t.createDiv({cls:"mdbase-issues-header"});n.createEl("h3",{text:"mdbase Issues"});let s=n.createDiv({cls:"mdbase-issues-header-actions"}).createEl("button",{text:"Refresh"});s.addClass("mod-cta"),s.onclick=()=>{this.plugin.runCollectionValidation(!1)};let o=t.createDiv({cls:"mdbase-issues-controls"}),a=o.createEl("select");a.addClass("mdbase-issues-severity"),a.createEl("option",{value:"all",text:"All severities"}),a.createEl("option",{value:"error",text:"Errors only"}),a.createEl("option",{value:"warn",text:"Warnings only"}),a.value=this.severityFilter,a.onchange=()=>{let h=a.value;(h==="error"||h==="warn"||h==="all")&&(this.severityFilter=h),this.render()};let c=o.createEl("input",{type:"search"});c.addClass("mdbase-issues-query"),c.placeholder="Filter by path, code, message, field",c.value=this.query,c.oninput=()=>{this.query=c.value,this.render()};let l=this.plugin.getIssues(),d=this.query.trim().toLowerCase(),u=l.filter(h=>{var g;return this.severityFilter!=="all"&&h.severity!==this.severityFilter?!1:d?`${h.path} ${h.code} ${h.message} ${(g=h.field)!=null?g:""}`.toLowerCase().includes(d):!0}),f=u.slice(0,500);if(t.createDiv({cls:"mdbase-issues-count",text:u.length>f.length?`Showing ${f.length} of ${u.length} matching issues`:u.length===l.length?`${u.length} issue${u.length===1?"":"s"}`:`${u.length} of ${l.length} issue${l.length===1?"":"s"}`}),u.length===0){t.createDiv({cls:"mdbase-empty",text:l.length===0?"No validation issues.":"No issues match current filters."});return}let p=new Map;for(let h of f){let m=(y=p.get(h.path))!=null?y:[];m.push(h),p.set(h.path,m)}for(let[h,m]of p.entries()){t.createDiv({cls:"mdbase-issue-file",text:h});for(let g of m){let _=t.createDiv({cls:"mdbase-issue-item"});_.setAttr("data-severity",g.severity),_.createDiv({cls:"mdbase-issue-code",text:`${g.severity.toUpperCase()} \xB7 ${g.code}${g.field?` \xB7 ${g.field}`:""}`}),_.createDiv({cls:"mdbase-issue-message",text:g.message});let w=_.createDiv({cls:"mdbase-issue-actions"}),x=w.createEl("button",{text:g.field?"Open field":"Open file"});x.onclick=P=>{P.stopPropagation(),this.plugin.openIssue(g)};let v=this.plugin.getQuickFixLabel(g);if(v){let P=w.createEl("button",{text:v});P.onclick=O=>{O.stopPropagation(),this.plugin.applyQuickFix(g)}}_.onclick=()=>{this.plugin.openIssue(g)}}}}},wp=class extends j.PluginSettingTab{constructor(e,t){super(e,t),this.plugin=t}display(){let{containerEl:e}=this;e.empty(),e.createEl("h2",{text:"mdbase settings"}),new j.Setting(e).setName("Validate on save").setDesc("Run mdbase validation when a markdown file is modified.").addToggle(t=>t.setValue(this.plugin.settings.validateOnSave).onChange(async n=>{this.plugin.settings.validateOnSave=n,await this.plugin.saveSettings()})),new j.Setting(e).setName("Validate on file open").setDesc("Validate the active note when opened.").addToggle(t=>t.setValue(this.plugin.settings.validateOnOpen).onChange(async n=>{this.plugin.settings.validateOnOpen=n,await this.plugin.saveSettings()})),new j.Setting(e).setName("Show notices on save").setDesc("Display a notice when save-time validation finds issues.").addToggle(t=>t.setValue(this.plugin.settings.showNoticeOnSave).onChange(async n=>{this.plugin.settings.showNoticeOnSave=n,await this.plugin.saveSettings()})),new j.Setting(e).setName("Allow local application interoperability").setDesc("Allow installed Obsidian plugins to exchange validated mdbase events and actions in this vault. Contracts establish compatibility; this switch is the separate user grant.").addToggle(t=>t.setValue(this.plugin.settings.interopEnabled).onChange(async n=>{this.plugin.settings.interopEnabled=n,await this.plugin.saveSettings()}))}},zc=class extends j.Plugin{constructor(t,n){super(t,n);this.issueMap=new Map;this.sortedIssuesCache=null;this.schemaCache=null;this.schemaLoadPromise=null;this.pendingSaveValidations=new Map;this.saveValidationDebounceMs=250;this.connectSync=new qc(t,{getMirrorProfile:()=>this.getMirrorProfile(),saveMirrorProfile:async i=>{this.settings.mirrorProfile=i,await this.saveSettings()}}),this.interopBridge=new ga(t,()=>{var i;return((i=this.settings)==null?void 0:i.interopEnabled)===!0}),this.api={apiVersion:1,interop:this.interopBridge,getInteropStatus:()=>{var i;return{enabled:((i=this.settings)==null?void 0:i.interopEnabled)===!0,profileVersion:"0.1"}}}}async onload(){await this.loadSettings(),await this.connectSync.initialize(),(0,j.addIcon)(qi,T0),this.statusBarEl=this.addStatusBarItem(),this.updateStatusBar(),this.registerView(qn,n=>new Bc(n,this)),this.registerView(Fi,n=>new bp(n,this)),this.addSettingTab(new wp(this.app,this)),this.addRibbonIcon(qi,"Open mdbase",()=>void this.openWorkspace()),this.addCommand({id:"mdbase-open",name:"mdbase: Open workspace",callback:()=>void this.openWorkspace()}),this.addCommand({id:"mdbase-initialize-collection",name:"mdbase: Initialize collection",callback:()=>void this.initializeCollectionCommand()}),this.addCommand({id:"mdbase-create-type",name:"mdbase: Create type definition",callback:()=>void this.openWorkspace("types")}),this.addCommand({id:"mdbase-edit-type",name:"mdbase: Edit type definition",callback:()=>void this.openWorkspace("types")}),this.addCommand({id:"mdbase-edit-current-type",name:"mdbase: Edit current type definition",callback:()=>void this.openWorkspace("types")}),this.addCommand({id:"mdbase-create-note-from-type",name:"mdbase: Create note from type",callback:()=>void this.createNoteFromTypeCommand()}),this.addCommand({id:"mdbase-validate-current-note",name:"mdbase: Validate current note",callback:()=>void this.validateCurrentNoteCommand()}),this.addCommand({id:"mdbase-validate-collection",name:"mdbase: Validate collection",callback:()=>void this.runCollectionValidation(!0)}),this.addCommand({id:"mdbase-open-issues-view",name:"mdbase: Open issues view",callback:()=>void this.openWorkspace("issues")}),this.addCommand({id:"mdbase-sync",name:"mdbase: Sync collection authority",callback:()=>void this.syncHostedCollectionCommand()}),this.addCommand({id:"mdbase-open-sync",name:"mdbase: Open sync",callback:()=>void this.openWorkspace("sync")}),this.registerEvent(this.app.vault.on("modify",n=>{n instanceof j.TFile&&this.onVaultModify(n)})),this.registerEvent(this.app.vault.on("rename",(n,i)=>{n instanceof j.TFile&&this.onVaultRename(n,i)})),this.registerEvent(this.app.vault.on("delete",n=>{n instanceof j.TFile&&this.onVaultDelete(n)})),this.registerEvent(this.app.vault.on("create",n=>{n instanceof j.TFile&&this.onVaultCreate(n)})),this.registerEvent(this.app.workspace.on("file-open",n=>{this.settings.validateOnOpen&&(!(n instanceof j.TFile)||n.extension!=="md"||this.validateFileAndStore(n,"open"))}));let t=this.app.workspace.getActiveFile();t&&this.settings.validateOnOpen&&this.validateFileAndStore(t,"open")}async onunload(){await this.interopBridge.dispose(),this.app.workspace.getLeavesOfType(qn).forEach(t=>t.detach()),this.app.workspace.getLeavesOfType(Fi).forEach(t=>t.detach()),this.clearAllPendingSaveValidations()}async loadSettings(){this.settings=Object.assign({},$M,await this.loadData()),SM(this.settings.mirrorProfile)||(this.settings.mirrorProfile=null)}async saveSettings(){await this.saveData(this.settings)}getIssues(){var t;return(t=this.sortedIssuesCache)!=null||(this.sortedIssuesCache=Array.from(this.issueMap.values()).flat().sort((n,i)=>n.path.localeCompare(i.path)||n.severity.localeCompare(i.severity)||n.code.localeCompare(i.code))),this.sortedIssuesCache}getMirrorProfile(){return this.settings.mirrorProfile?{...this.settings.mirrorProfile}:null}async loadWorkspaceSchema(t=!1){return this.getConfigAndTypes(t)}async loadTypeModel(t){var s;let n=this.app.vault.getAbstractFileByPath((0,j.normalizePath)(t));if(!(n instanceof j.TFile))throw new Error(`Type file not found: ${t}`);let i=Pt(await this.app.vault.cachedRead(n));if(!i.hasFrontmatter||i.error)throw new Error(`Invalid type frontmatter: ${(s=i.error)!=null?s:"frontmatter is missing"}`);return Uc(i.frontmatter,i.body,n.basename)}async saveTypeModel(t,n){var a;if(this.connectSync.assertLocalAuthorityWritable(),((a=this.getMirrorProfile())==null?void 0:a.mode)==="read_only")throw new Error("This mirror has read-only access. Re-enroll it with write access before editing types.");let i=await pi(this.app.vault);if(!i)throw new Error("No mdbase.yaml found.");if(!i.spec_version.startsWith("0.3."))throw new Error("mdbase v0.2 type definitions are read-only. Migrate the collection first.");let s=n?this.app.vault.getAbstractFileByPath((0,j.normalizePath)(n)):null;if(s!=null&&!(s instanceof j.TFile))throw new Error(`Type file not found: ${n}`);let o=await this.writeTypeDefinition(i,t,s);return this.refreshWorkspaceViews(!0),o}async initializeCollection(){this.connectSync.assertLocalAuthorityWritable(),await this.initializeCollectionCommand(),this.refreshWorkspaceViews(!0)}async validateCollection(){await this.runCollectionValidation(!1)}analyzeMigration(){if(this.getMirrorProfile())throw new Error("Collection authority resources must be migrated at the collection authority.");return I0(this.app.vault)}async applyMigration(t,n){var s,o;if(this.connectSync.assertLocalAuthorityWritable(),this.getMirrorProfile())throw new Error("Collection authority resources must be migrated at the collection authority.");let i=await O0(this.app.vault,t,{allowLossy:n});if(!i.applied)throw new Error(i.restored?`Migration failed and all writes were rolled back. ${(s=i.error)!=null?s:""}`.trim():`Migration needs manual recovery. See ${i.manifestPath}. ${(o=i.error)!=null?o:""}`.trim());this.invalidateSchemaCache(),new j.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["unknown_field","schema_additional_properties"].includes(t.code)&&t.field?"Remove field":["missing_required","schema_required"].includes(t.code)&&t.field?"Add placeholder":null}async applyQuickFix(t){this.connectSync.assertLocalAuthorityWritable();let n=this.app.vault.getAbstractFileByPath(t.path);if(!(n instanceof j.TFile)){new j.Notice(`File not found: ${t.path}`);return}let i=await this.app.vault.cachedRead(n),s=Pt(i);if(s.error){new j.Notice(`Cannot apply quick fix: invalid frontmatter (${s.error})`);return}if(["unknown_field","schema_additional_properties"].includes(t.code)&&t.field){let o=$a(t.field);if(!(o in s.frontmatter)){new j.Notice(`Field '${o}' not found in frontmatter.`);return}delete s.frontmatter[o],await this.app.vault.modify(n,`${mt(s.frontmatter,s.body)} +`),new j.Notice(`Removed '${o}' from ${n.basename}`),await this.validateFileAndStore(n,"manual");return}if(["missing_required","schema_required"].includes(t.code)&&t.field){let o=$a(t.field);s.frontmatter[o]===void 0&&(s.frontmatter[o]="TODO");let a=s.hasFrontmatter?s.body:i;await this.app.vault.modify(n,`${mt(s.frontmatter,a)} +`),new j.Notice(`Added placeholder '${o}' to ${n.basename}`),await this.validateFileAndStore(n,"manual");return}new j.Notice("No quick fix available for this issue.")}async openFileByPath(t,n){let i=this.app.vault.getAbstractFileByPath(t);if(!(i instanceof j.TFile)){new j.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 j.MarkdownView))return;let s=i.view;if(!(s.file instanceof j.TFile)||s.file.path!==t.path)return;let o=s.editor,a=o.lineCount();if(a<3)return;let c=$a(n),l=new RegExp(`^\\s*${EM(c)}\\s*:`);if(o.getLine(0).trim()==="---")for(let d=1;ds.severity==="error").length,i=t.length-n;if(t.length===0){this.statusBarEl.setText("mdbase: no issues");return}this.statusBarEl.setText(`mdbase: ${n} error${n===1?"":"s"}, ${i} warning${i===1?"":"s"}`)}async openIssuesView(){var i;let t=this.app.workspace.getLeavesOfType(Fi)[0];if(t){this.app.workspace.revealLeaf(t),t.view.render();return}let n=(i=this.app.workspace.getRightLeaf(!1))!=null?i:this.app.workspace.getLeaf(!0);await n.setViewState({type:Fi,active:!0}),this.app.workspace.revealLeaf(n)}async openWorkspace(t="types"){let n=this.app.workspace.getLeavesOfType(qn)[0];if(n){this.app.workspace.revealLeaf(n);let o=n.view;o.showDestination(t),await o.refresh();return}let i=this.app.workspace.getLeaf(!0);await i.setViewState({type:qn,active:!0}),this.app.workspace.revealLeaf(i),i.view.showDestination(t)}refreshWorkspaceViews(t=!1){for(let n of this.app.workspace.getLeavesOfType(qn))n.view.refresh(t)}refreshIssueViews(){this.updateStatusBar();for(let t of this.app.workspace.getLeavesOfType(Fi))t.view.render();this.refreshWorkspaceViews()}setFileIssues(t,n){n.length===0?this.issueMap.delete(t):this.issueMap.set(t,n),this.sortedIssuesCache=null,this.refreshIssueViews()}clearFileIssues(t){this.issueMap.has(t)&&(this.issueMap.delete(t),this.sortedIssuesCache=null,this.refreshIssueViews())}moveFileIssues(t,n){let 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())}clearAllPendingSaveValidations(){for(let t of this.pendingSaveValidations.values())window.clearTimeout(t);this.pendingSaveValidations.clear()}clearPendingSaveValidation(t){let n=this.pendingSaveValidations.get(t);n!=null&&(window.clearTimeout(n),this.pendingSaveValidations.delete(t))}scheduleSaveValidation(t){this.clearPendingSaveValidation(t.path);let n=window.setTimeout(()=>{this.pendingSaveValidations.delete(t.path),this.validateFileAndStore(t,"save")},this.saveValidationDebounceMs);this.pendingSaveValidations.set(t.path,n)}isSchemaRelevantPath(t){let n=(0,j.normalizePath)(t);if(n==="mdbase.yaml")return!0;let i=new Set(["_types"]);this.schemaCache&&i.add((0,j.normalizePath)(this.schemaCache.config.settings.types_folder));for(let s of i)if(n===s||n.startsWith(`${s}/`))return!0;return!1}invalidateSchemaCache(){this.schemaCache=null,this.schemaLoadPromise=null}async getConfigAndTypes(t=!1){if(t&&this.invalidateSchemaCache(),this.schemaCache)return this.schemaCache;if(this.schemaLoadPromise)return this.schemaLoadPromise;this.schemaLoadPromise=(async()=>{let n=await pi(this.app.vault);if(!n)return null;let i=await fb(this.app.vault,n);return{config:n,types:i}})();try{let n=await this.schemaLoadPromise;return n&&(this.schemaCache=n),n}finally{this.schemaLoadPromise=null}}async requireConfigAndTypes(t={}){var s,o;let n=(s=t.background)!=null?s:!1,i=await this.getConfigAndTypes((o=t.forceReload)!=null?o:!1);return i?(i.types.size===0&&!n&&new j.Notice(`No types found in ${i.config.settings.types_folder}`),i):(n||new j.Notice("No mdbase.yaml found. Run 'mdbase: Initialize collection' first."),null)}onVaultModify(t){this.isSchemaRelevantPath(t.path)&&(this.invalidateSchemaCache(),this.refreshWorkspaceViews()),this.settings.validateOnSave&&t.extension==="md"&&this.scheduleSaveValidation(t)}onVaultRename(t,n){(this.isSchemaRelevantPath(n)||this.isSchemaRelevantPath(t.path))&&(this.invalidateSchemaCache(),this.refreshWorkspaceViews()),t.extension==="md"&&(this.clearPendingSaveValidation(n),this.moveFileIssues(n,t.path),this.settings.validateOnSave&&this.scheduleSaveValidation(t))}onVaultDelete(t){this.isSchemaRelevantPath(t.path)&&(this.invalidateSchemaCache(),this.refreshWorkspaceViews()),t.extension==="md"&&(this.clearPendingSaveValidation(t.path),this.clearFileIssues(t.path))}onVaultCreate(t){this.isSchemaRelevantPath(t.path)&&(this.invalidateSchemaCache(),this.refreshWorkspaceViews())}async validateFileAndStore(t,n){let i=await this.requireConfigAndTypes({background:n!=="manual"});if(!i)return n!=="manual"&&this.clearFileIssues(t.path),[];let s=await ef(this.app.vault,t,i.config,i.types);return this.setFileIssues(t.path,s),n==="save"&&this.settings.showNoticeOnSave&&s.length>0&&new j.Notice(`mdbase: ${s.length} issue${s.length===1?"":"s"} in ${t.basename}`),s}async initializeCollectionCommand(){if(this.connectSync.assertLocalAuthorityWritable(),this.getMirrorProfile()){new j.Notice("This vault is configured as a mirror. Sync it instead of initializing a local collection.");return}let{created:t}=await lb(this.app.vault);if(this.invalidateSchemaCache(),t.length===0){new j.Notice("mdbase collection already initialized.");return}new j.Notice(`Initialized mdbase collection: ${t.join(", ")}`)}async syncHostedCollectionCommand(){var t,n,i,s;if(!this.getMirrorProfile()){await this.openWorkspace("sync");return}try{let o=await this.connectSync.preview(),a=await this.connectSync.sync(o),c=await this.connectSync.status();this.invalidateSchemaCache(),this.refreshWorkspaceViews(!0);let l=((t=c==null?void 0:c.conflicts.length)!=null?t:0)+((n=c==null?void 0:c.local_issues.length)!=null?n:0);new j.Notice(a.status==="stale"?"The sync plan changed before it could apply. Review the new plan in the mdbase workspace.":a.status==="failed"||a.status==="blocked"?`mdbase sync stopped safely: ${(s=(i=a.failure)==null?void 0:i.message)!=null?s:a.status}.`:l?`Sync completed with ${l} item${l===1?"":"s"} needing attention.`:"mdbase sync completed.")}catch(o){new j.Notice(`mdbase sync failed: ${o instanceof Error?o.message:String(o)}`),await this.openWorkspace("sync")}}async createNoteFromTypeCommand(){var d,u;this.connectSync.assertLocalAuthorityWritable();let t=await this.requireConfigAndTypes();if(!t)return;if(t.types.size===0){new j.Notice("No type definitions found.");return}let n=await AM(this.app,Array.from(t.types.values()));if(!n)return;let i=mb(n,t.config),s=yb(n,i);for(let[f,p]of s){let y=`Required field: ${f}`,h=await new go(this.app,y,(d=p.type)!=null?d:"string").openAndGetValue();if(h==null)return;if(h.trim().length===0){new j.Notice(`Field '${f}' is required.`);return}try{i[f]=tf(h,p)}catch(m){new j.Notice(`Invalid value for ${f}: ${m instanceof Error?m.message:String(m)}`);return}}let o=(u=n.display_name_key)!=null?u:"title";if(i[o]==null){let f=await new go(this.app,`Optional ${o} (used for filename)`,"").openAndGetValue();f&&f.trim().length>0&&(i[o]=f.trim())}let a=await _b(this.app.vault,n,i),c=await new go(this.app,"Note path","Relative path in vault",a).openAndGetValue();if(c==null)return;let l=(0,j.normalizePath)(c.trim().length>0?c.trim():a);l.endsWith(".md")||(l=`${l}.md`);try{let f=await bb(this.app.vault,l,i);await this.app.workspace.getLeaf(!0).openFile(f),new j.Notice(`Created note: ${f.path}`),await this.validateFileAndStore(f,"manual")}catch(f){new j.Notice(f instanceof Error?f.message:String(f))}}async validateCurrentNoteCommand(){let t=this.app.workspace.getActiveFile();if(!(t instanceof j.TFile)||t.extension!=="md"){new j.Notice("Open a markdown note first.");return}let n=await this.validateFileAndStore(t,"manual");n.length===0?new j.Notice("No issues in current note."):(new j.Notice(`Found ${n.length} issue${n.length===1?"":"s"} in current note.`),await this.openIssuesView())}async runCollectionValidation(t){var o;let n=await this.requireConfigAndTypes({background:!1});if(!n)return;let i=await hb(this.app.vault,n.config,n.types),s=new Map;for(let a of i){let c=(o=s.get(a.path))!=null?o:[];c.push(a),s.set(a.path,c)}if(this.issueMap=s,this.sortedIssuesCache=null,this.refreshIssueViews(),t)if(i.length===0)new j.Notice("Collection validation passed with no issues.");else{let a=i.filter(l=>l.severity==="error").length,c=i.length-a;new j.Notice(`Collection validation: ${a} error(s), ${c} warning(s)`),await this.openIssuesView()}}async ensureFolderExists(t){let n=(0,j.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){let s=n.name.trim();if(!s)throw new Error("Type name is required.");if(!t.spec_version.startsWith("0.3.")||n.specProfile!=="v0.3")throw new Error("mdbase v0.2 type definitions are read-only. Migrate the collection first.");let o=yo(n),a=n.body.trim()||`# ${s} Type definition for ${s}.`,c=`${mt(o,a)} -`,l=(0,L.normalizePath)(t.settings.types_folder),d=(0,L.normalizePath)(`${l}/${s}.md`);if(!i){if(await this.ensureFolderExists(l),await this.app.vault.adapter.exists(d))throw new Error(`Type already exists: ${d}`);let m=await this.app.vault.create(d,c);return this.invalidateSchemaCache(),m}let u=i.path.lastIndexOf("/"),f=u>=0?i.path.slice(0,u):"",y=(0,L.normalizePath)(`${f?`${f}/`:""}${s}.md`)||d;if(y!==i.path&&await this.app.vault.adapter.exists(y))throw new Error(`Cannot rename type file to ${y}; file already exists.`);y!==i.path&&await this.app.fileManager.renameFile(i,y);let h=this.app.vault.getAbstractFileByPath(y);if(!(h instanceof L.TFile))throw new Error(`Unable to access updated type file: ${y}`);return await this.app.vault.modify(h,c),this.invalidateSchemaCache(),h}}; +`,l=(0,j.normalizePath)(t.settings.types_folder),d=(0,j.normalizePath)(`${l}/${s}.md`);if(!i){if(await this.ensureFolderExists(l),await this.app.vault.adapter.exists(d))throw new Error(`Type already exists: ${d}`);let m=await this.app.vault.create(d,c);return this.invalidateSchemaCache(),m}let u=i.path.lastIndexOf("/"),f=u>=0?i.path.slice(0,u):"",y=(0,j.normalizePath)(`${f?`${f}/`:""}${s}.md`)||d;if(y!==i.path&&await this.app.vault.adapter.exists(y))throw new Error(`Cannot rename type file to ${y}; file already exists.`);y!==i.path&&await this.app.fileManager.renameFile(i,y);let h=this.app.vault.getAbstractFileByPath(y);if(!(h instanceof j.TFile))throw new Error(`Unable to access updated type file: ${y}`);return await this.app.vault.modify(h,c),this.invalidateSchemaCache(),h}}; diff --git a/src/workspaceView.ts b/src/workspaceView.ts index 03a5c3f..452ddb7 100644 --- a/src/workspaceView.ts +++ b/src/workspaceView.ts @@ -883,21 +883,28 @@ export class MdbaseWorkspaceView extends ItemView { this.mirrorPreview = await this.host.connectSync.preview(); this.transientMessage = this.mirrorPreview.entries.length ? "Review the engine plan below, then sync when ready." - : "No content effects are needed; confirm the sync checkpoint when ready."; + : this.mirrorPreview.plan.actions.some((action) => action.command === "advance_checkpoint") + ? "No content effects are needed; confirm the sync checkpoint when ready." + : "This mirror is already up to date."; this.render(); }); const plannedOutcomeCount = this.mirrorPreview?.plan.actions .filter((action) => action.command !== "advance_checkpoint").length ?? 0; + const hasCheckpointAction = this.mirrorPreview?.plan.actions + .some((action) => action.command === "advance_checkpoint") ?? false; const hasBlockingIssue = (this.mirrorPreview?.plan.summary.blocking_issues ?? 0) > 0; const sync = actions.createEl("button", { text: this.mirrorPreview ? plannedOutcomeCount ? `Sync ${plannedOutcomeCount} ${plannedOutcomeCount === 1 ? "outcome" : "outcomes"}` - : "Confirm sync checkpoint" + : hasCheckpointAction + ? "Confirm sync checkpoint" + : "Already up to date" : "Review before syncing", }); sync.addClass("mod-cta"); - sync.disabled = this.busy || !this.mirrorPreview || hasBlockingIssue; + sync.disabled = this.busy || !this.mirrorPreview || hasBlockingIssue + || this.mirrorPreview.plan.actions.length === 0; sync.onclick = () => void this.perform(async () => { const outcome = await this.host.connectSync.sync(this.mirrorPreview!, (progress) => { this.mirrorProgress = progress; diff --git a/test/syncPreview.test.ts b/test/syncPreview.test.ts index 659530a..e04ef71 100644 --- a/test/syncPreview.test.ts +++ b/test/syncPreview.test.ts @@ -76,6 +76,18 @@ test("sync preview is a direct projection of the engine-owned plan", () => { assert.equal(preview.upload_files, 1); }); +test("an exact idle plan remains an explicit zero-action preview", () => { + const preview = previewFromPlan(plan({ + base_cursor: 6, + authority_cursor: 6, + })); + + assert.deepEqual(preview.plan.actions, []); + assert.deepEqual(preview.entries, []); + assert.equal(preview.cursor, 6); + assert.equal(preview.remoteHead, 6); +}); + test("plan conflicts and blocking issues are shown as attention without inventing transfers", () => { const preview = previewFromPlan(plan({ actions: [{